Windows Communication Foundation (WCF)
Introduction: WCF provides a simple programming model in which multiple applications can communicate with each other seamlessly via SOA. It provides mode reliability, security, scalability and flexible ways for consuming services.
Flow of Message in WCF :
Client >> Message >> Channel Stack (Transport and protocol) >> Dispatcher ( message interceptor and formatter) >> Message validation with XML Schema >> WSDL located >> Protocol validation >> Message formatted >> Service Method >> Method is executed
Every WCF service is associated with an endpoint for communication. It has 3 parts Address, Binding and Contract
It provides a unique location for the Service including following elements:
1. Protocol - Ex... http://, https://, net.tcp://, net.pipe://, net.msmq://
2. Server name or IP address - Ex... localhost, 127.0.0.1, 188.8.131.52
3. Port - Ex... :1024, :90, :8090
4. Service name - Ex... UMS-Server, Fabric-Server
It determines the method of communication for specific scenarios.
Binding can be used in three ways:
1. Use built-in bindings as it is.
2. Configure some of the properties of bindings.
3. Create custom bindings,
Some Standard bindings:
BasicHttpBinding - Expose WCF service as legacy Web services
WsHttpBinding - Http/Https, Reliability, Transactions, Security
NetTCPBinding - TCP, Optimized for WCF-WCF, Reliability, Transactions, Security
NetMSMQBinding - MSMS, including disconnected queued calls
Platform-independent way to represent the Service and Interface is created for the contract
Service Contract - defines specific group (class/type) of operations, exposed by WCF
Operation Contract - defines individual APIs/Methods to be exposed by WCF
Data Contract - defines the data structure exposed by WCF
Message Contract - defines the format of message
Fault Contract - to deal exceptions which are generated in API execution
How it goes:
Each Service Contract has one or more Operation Contracts
Each Operation Contract has one or more Message Contracts
Each Message Contract has one or more Data Contracts
Each Data Contract has some specific Data Structure
A Service Behaviors determines the way the service works in different scenarios to meet some goals like performance and scalability. It WCF internal feature and client should not be aware for the behavior. Service Behavior Attribute affects the service class and decides the service instance context mode mode.
An important feature of SOA architecture for proper call handling
Let's bind specific client request to specific service instance
3 instance management methods
Introduction: Instance allocated to individual client request and destroyed afterwards. Current.SessionId returns null as there is no session.
Pros: Much cheaper and disposed just after call. For some of the services we can maintain state mgmt
Cons: To maintain state across 2 requests some feature needs to be implemented that would cause trade-off to WCF performance.
[Service Behavior (InstanceContextMode = InstanceContextMode.PerCall)]
Introduction: Service instance is allocated to individual client connection. Private Session. Current.SessionId returns Session Id for connection
Pros: Provides persistent state
Cons: Costly to support multiple private sessions in memory due. And client has to some-how notify to service to end its session.
Note: If 2 Contracts are created with SessionMode.Required & SessionMode.NotAllowed then avoid implement both interfaces in one Service as this would create conflict in ServiceBehavious setting
[Service Behavior (InstanceContextMode = InstanceContextMode.PerSession)]
Introduction: Instance shared to all clients & remains alive until host shuts down. Automatically created & hosted as Singleton
Pros: Useful when used as natural singleton like Shared Logbook and Common Result chart etc.
Cons: Scalability cannot be handled easily.
Note: As a general scenario, avoid making Singleton service. Rather try to find some other approach/work-around to provide state sharing.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
Multiple client requests can downgrade WCF performance. In such scenario, if throttling is enabled then WCF automatically moves the pending client requests in queue and serves them in order if service is free. If during this Timeout is expired for some requests then their clients receive a TimeOutException.
<service name="MyService" behaviorConfiguration="MyThrottlingBehavior">
This is achieved by Fault Exception
A client may encounter three types of errors:
1. Host not running or address wrong - In this error client receives CommunicationException.
2. Channel or proxy is closed - In this error client receives ObjectDisposedException
3. If an error appeared during service call by some internal wrong operation/state - In this error Exception should reach to client as soap faults. Soap fault is technology-independent way (not like CLS, JVM or C++ exceptions). To throw a soap faults, a FaultException
class MyService : IContract
public int AverageWorkingbyEmployees(int empIds, int count)
// Perform some sttements..
int totalSalary = GetAllSalaries(empIds);
int avgSalary = totalSalary/count;
throw new FaultException
throw new FaultException
// Handle some other way
throw new FaultException("Some exception occurred …")
By default all the exceptions from a service are reached to the clients as Fault Exception. A Fault Contract is a mechanism that WCF uses to declare types of exception it can throw. And the scope of FaultContract is limited to the method it is mapped with.
double AverageSalaries(int empids, int count);
Once one or more Fault Contracts are mapped with the method signatures, they can be thrown from the actual implementation of methods incase some matching exceptions occur.
Exception at client side
Faults are caught at client in same format FaultException
CommunicationException : Proxy is disconnected.
Exception : Proxy is disconnected
All server side handled exceptions are caught as FaultException at client side and proxy is not disconnected but for unhandled exceptions, proxy is disconnected. To handle such exceptions at server side, we need to throws a base class FaultException() instance as follows…
throw new FaultException("Some unknown exception occured");
At client side…
catch (FaultException ex)
// proxy is still available.
// ex can give a little information about the cause
To let Clients properly analyze the cause of exception, we can also create instance of ExceptionDetail() class and propagate to client with following details …
ExceptionDetail ed = new ExceptionDetail(ex);
throw new FaultException< ExceptionDetail >(ed, ex.Message);
At client side…
// proxy is still available.
// ex. Will give all possible information for the cause
WCF Transaction handling
TransactionScope class provides a way to use transactions in WCF service.
using (TransactopmAbortException tae)
// task 1
// task 2
Security involves two operations; authentication of clients and authorization for specific operations.
Some of the Security aspects are as follows…
This verifies whether the client is added in the user group of the WCF service. There can be many modes of authentication…
1. No Authentication
All clients are assumed as valid users
2. Windows Authentication
Authentication is done through Windows domain credentials
3. Username - Password Authentication
Authentication is done based on some username and password provided by the client. These credentials are queries against some kind of stores.
4. X509 Certificate Authentication
This certificate is know by the service in advance and same is provided to its clients that in-turn is passed by the client back to service for authentication
5. Token based Authentication
This is done through some Secured Token Service like ADFS. A token contains everything like; authentication and authorization information. The client gets the token from ADFS and passes it to WCF service. WCF internally authenticate it against same ADFS service and authentication takes place. Authorization data is also kept in the token as claim rules. Rules can be fetched and used to determine the permissions for that client.
It comes after Authentication and it validates whether the current client has sufficient permissions to consume a service. Authorization is based on the roles. There are many approached used for authorization…
1. Mapping store can be used where credentials and roles are stored
2. STS token (SAML token – security assertion markup language) has claims roles
3. Windows group can be used to map with user names.
4. And so on…
Hope this article provides insight about WCF services.