[refers to http://www.codeproject.com/useritems/WCF_in_details.asp]

Abstract:

In this article I am going to take you little bit in depth of (Windows Communication Foundation) WCF, the latest technology
and framework introduced by Microsoft to make developer life easy in distributed applications.

Introduction:

To make developers life easy Microsoft continuously brings new technologies in the market. Sometimes those are similar to their predecessors and sometimes they bring large enhancements in the current technologies. As a result we can see the
processing architecture of web page is totally changed in .NET 2.0. Now .NET 2.0 does not bring significant enhancements in winform application development. So how can we go with a windows application that can be distributed across
diverse operating systems and that will gain the performance benefit while used on same OS? The answer is WCF i.e. Windows Communication Foundation (WCF) code name INDIGO.
In this article we will learn the basic components of WCF and also dive into some of the details of these components.
We will try to address the issues faced in previous versions and find out why to use WCF.

WHAT IS WCF

As said earlier, WCF is the Windows Communication Foundation built on .NET 2.0 framework. It is type of service execution  framework especial made for establishing communication between diverse systems and gain performance benefits on similar systems. It consolidates the best features of web service, remoting, MSMQ, System.Messaging and Microsoft enterprise services. One of the biggest advantages of WCF is, it supports most of the open industry standards hence it can produce the best results across heterogeneous operations systems. Other benefits are like it is developed using managed code and uses the power and features of .NET 2.0. As it supports WS-* standards, it supports transaction, security, reliability.WCF uses SOAP as its native protocol for communication.

PREREQUISITE

You need following to develop a WCF service.
1. OS: Windows VISTA, Windows XP SP2, Windows 2003 Server SP1,
2. VS 2005 professional edition with SP1
3. Microsoft Windows Software Development KIT
4. .NET 3.0 runtime
5. WCF extensions (while working on VS 2005 editor)

KEY COMPONENTS OF WCF

WCF is based upon the following key components that are used to build WCF service. We will go in details of each component in coming sections.
1.Contract definitions
     a.Data contracts and data member
     b.Service contracts
     c.Fault contracts
     d.Message contracts
2.End points
3.Bindings
     a.BasicHttpBinding
     b.WSHttpBinding
     c.WSDualHttpBinding
     d.WSFederationHttpBinding
     e.MsmqIntegrationBinding
     f.NetMsmqBinding
     g.NetNamedPipeBinding
     h.NetPeerTcpBinding
     i.NetTcpBinding
4.Hosting environments
     a.Windows application
     b.Console application
     c.Windows service
     d.IIS
     e.WAS (windows activation service) comes with IIS 7.0
     f.Windows presentation foundation

PROBLEMS ADDRESSED BY WCF

Till now we have seen what WCF is and what WCF components are. But unless and until we come to know the issues addressed by WCF, we will never come to know the power of WCF. Imagine you are developing an enterprise application for a bank. Now when you start designing the system, the requirements are very complex and critical. Say for example, the application is used by bank staff, outside customers, some of payment gateway systems. You are not sure that what operating system and what type of clients will be used by outside customers. You want performance with security, reliability when used on intranet and security, reliability when used from outside. Previously you could have gone for web services exposing web methods for out side clients and a remoting or COM+ application for windows OS. Both these application are using same business  logic and same database. Suppose you want to add some new business logic like introducing new loan system, imagine how much it will take to change all the systems. This is perhaps the simplest example. What if you are going to modify business logic or add 3-4 additional schemes in the span of 6 months? The current design will not scale. You will start thinking, what if I would have a single application exposing multiple endpoints for diverse and similar clients and will give me all benefits of industry wide open standards. That’s it. WCF is the answer to your question. WCF, with managed code, using power and features of .NET 2.0, giving all the benefits of performance, security, transaction, reliability by supporting all open industry standards makes life easy for the developer and the organization by unifying the programming model with the best features from all available technologies. WCF is interoperable with
1. Web services
2. .NET - .NET communication
3. Distributed transactions
4. Support for WS-* specifications
5. Queued messaging

Key subsystems of WCF

1. Service model
2. Connector framework
3. Hosting environment
4. System services
5. Messaging services

Key components in WCF

1. Contracts
2. Bindings
3. End point definitions
4. Hosting environment
We will go in details of each component in the coming sections.

Contracts:

Contracts are one of the most important components of WCF. Contracts make developing interoperable services possible. It is a common understanding between client and server of available methods, data structures, and message structures. They remain loosely coupled and platform independent. WCF contains following contracts. As SOAP is the native protocol of  WCF for communication, interfaces, classes are translated to SOAP types by CLR
1.Service contract:
     a.Translated to WSDL. Service contract defines the operations that a service can perform. This is what a WCF service must contain at least one. It can have more than one service contract also. It is defined using [ServiceContract]attribute. The implementer of the service contract is managed code. Hence, service contract also maps the interface and methods to platform independent description. Using the attribute feature of .NET, we can extend the behavior of the service like is it one way or two way, the exception handling behavior etc.
     b.Each service contract contains method that are exposed outside and annotated with [OperationContract]attribute.
     c.Service contract can also specify the requirements that should be satisfied by the endpoint.  
E.g. session required should satisfied by endpoints.
     d. E.g.
[ServiceContract(ProtectionLevel=System.Net.Security.ProtectionLevel.None)]
public interface IWCFService
{
[OperationContract]
string GetSystemIPAddress();
[OperationContract]
List GetEmpolyeeArray();
[OperationContract]
Employee CreateNewEmployee();
}

     e. Usually we can use service contract over a class also. But it is not a good practice as interfaces allows separation from the implementation logic. While using ServiceContract and OperationContract over a method or a class, access modifiers does not make any sense. Everything that is marked with ServiceContract or OperationContract will be exposed to client outside the application domain.
     f. Services are of three types.
         1. Typed
             1. Uses for the simple communication. It can acceptor return simple or complex data objects.
             2. E.g. CreateNewEmployee() method in the above class
         2. UnTyped
            1. It allows developers to work at message level.
            2. E.g. Message ParseRequest(Message myRequestMessage)
         3. Typed message
            1. Falls between typed and untyped services.
            2. Uses custom message classes defined with Message contracts.
            3. MyMessage ProcessedRequest(MyRequestMessage msg)
2.Data contract:
    a. Translated to XML schema (XSD). Basically describes data structure. When we want to pass or return more values then we go for data contract. It is a serializable object that can be passed or returned to or from a service. It supports versioning provided you should not change the name of the existing members, name of the namespace to maintain compatibility.
    b. Data contract can be defined annotating [DataContract] attribute on a class, structure or enum. The data members that are to be exposed outside are annotated with [DataMember] attribute for class and structure and [EnumMember] attribute for enum.
    c. [DataContract] tells WCF how to serialize the object. Depending upon the client WCF serializes the members. If the communication is between WCF and WCF then it uses binary serialization over SOAP to optimize the performance. While in case of WCF to Non-Windows client, it uses SOAP serialization.
    d. Here also access modifiers do not play any role.
    e. There are some cases when you do not have proxy generated for the given service. This may be the case when the WCF service using only TCP endpoints to allow interaction. In that case WSDL will not be available unless and until it is explicitly defined in service behavior with HTTP end point. Even if client does not have WSDL with us, we can create the same WCF dummy class or proxy class at client side. WCF service will remain as it is, the implementer will derive from ClientBase and implement WCF service
(IWCFService). In such case, operation contract method will call base.Channel.GetSystemIPAddress() and it will be routed to server by foundation. In this case we can have data contract members defined in the same way. The only thing and most important thing is namespace must have same names as that of server. Also method names and data member names should remain the same.
3. Fault contract:
    a. Translated to SOAP faults. Allows developer to document the errors that a service can produce. We can define service contract only on [OperationContract] by annotating with [FaultContract(typeof(System.Exception))] attribute. Here the exception type can be exception toy want to document. Custom exception should be marked as serializable.
4. Message contract:
    a. Translated to SOAP messages. It describes the structure of message like what goes where. WCF allows developer to control what to go where in a message for interoperability issues. Message contracts allow you to match the expectations of other systems concerning the SOAP message. Message contracts can be defined using [MessageContract] attribute. Members participating in the SOAP message can be defined and placed at appropriate place using [MessageHeader] and [MessageBodyMember] attribute.
    b. E.g.
[MessageContract]
public class MyMessage
{
[MessageHeader]
public string myHeader;
[MessageBodyMember]
public Employee myMessageBody;
}

Bindings

Bindings are communication channels between a WCF service and client. They decide how WCF service will communicate with the client. Depending upon the different protocols like HTTP, TCP, MSMQ there are different types of binding.Binding supports encoding of messages using text encoding, binary encoding and Message Transmission Optimization mechanism (MTOM, interoperable message format used for effective transmission of large attachments greater than 64K) As WCF supports all industry open standards, it supports security using SSL and WS-Security (schema defined security) standards.If we want
session enabled service then biding determines whether the service is session enabled or not. Not all binding supports sessions. As WCF is extendible, we can define our own custom bindings. But this is very rare case because WCF has nine in built bindings that are sufficient for most of the application. The exceptions can be: RSS feed of a site or SMTP protocol
1 BasicHttpBinding : Basic web service communication with no security by default
2 WSHttpBinding : Web services with WS-* standards, supports transactions
3 WSDualHttpBinding : Web services with duplex contract and transaction support
4 WSFederationHttpBinding : Web services with federated security with transaction support
5 MsmqIntegrationBinding : Direct communication with MSMQ, supports transaction
6 NetMsmqBinding : Communication between WCF applications using queuing with transaction support
7 NetNamedPipeBinding : Communication between WCF applications on same computer with duplex contracts support and transaction support
8 NetPeerTcpBinding : Communication between computers across peer-to-peer services with duplex contracts support
9 NetTcpBinding : Communication between WCF applications across computers supports duplex contracts and transactions

Here is the mapping of base address schemes to the transport protocols.
http : HTTP
net.tcp : TCP
net.pipes : Names pipes
net.msmq : MSMQ

End points

End points are nothing but an URI which are exposed to outside world and from where client can connect to WCF service.
Each end point consist of
    • Base address: Where to send message (A)
    • Type of binding: How to send message (B)
    • Contract: What to send in a message (C)
We can define as many end points as the application require. For example, if the application is to be used by a JAVA client and WPF client then we can expose an endpoint with TCP binding where WPF client will communicate and end point with basic HTTP binding where JAVA client will communicate. We can control and configure the behavior of end point programmatically and using application configuration file.

Hosting environments

The architecture of WCF application is usually like this.
Database layer => Business logic layer => WCF service => Hosting environment
As the diagram shows, we need a host to run WCF service. Fortunately there are many options that can be used for hosting a WCF service. This actually depends upon the application requirement.Following is the list of hosts:
    a. Windows application: Simple winform application
    b. Console application: Simple console application
    c. Windows service: WCF service can be controlled by Service control manager
    d. IIS: Can be hosted in IIS provided the service exposes at least one HTTP end point
    e. WAS (windows activation service) comes with IIS 7.0: Removes dependability upon HTTP
    f. Windows presentation foundation

Security in WCF

When you go for a distributed application, the most important aspect is security. As said earlier WCF supports security using binding. Binding supports security using SSL, WS-Security standards. You can also use windows authentication. One of the primary goals behind WCF development was to make it easy the development of secured applications. WCF service can be secured using four ways:
    • Authentication
    • Message integrity
    • Message confidentiality
    • Authorization
There are some guidelines about using security mechanisms. Depending upon the application need and requirement we can easily select the suitable one and implement with few efforts.Here are the guidelines:
    • Use a standard binding that directly supports security. For example, applications that
require end-to-end security for messages that go through multiple SOAP intermediaries can use a binding that supports WS-Security, such as WsHttpBinding.
    • Use a standard binding that optionally supports security, and then configure it as needed. For example, applications that need only transport-based security can choose BasicHttpBinding, configuring it to use HTTPS rather than HTTP. It’s also possible to customize other more-advanced security behaviors. For example, the authentication mechanism used by a binding such as WsHttpBinding can be changed if desired.
    • Create a custom binding that provides exactly the security behavior a developer needs. Doing this is
not for the faint of heart, but it can be the right solution for some advanced scenarios.
    • Use a standard binding that provides no support for security, such as BasicHttpBinding. While using
no security is a risky thing to do, it can be the only option in some situations.

Other important features

There are many other features which are present in WCF and can be used to achieve reliable communication.
Those are as follows
    • Transactions: WCF uses System.Transactions to control the transaction in distributed application.
Service behavior can also control transaction using the parameters in [ServiceBehavior] attribute. An operation contract can force a transaction using [OperationBehavior] attribute if the operation is very critical. If the client also supports WS-AutomicTransaction then a JAVA client and WCF service can share the same transaction. Some binding like WsHttpBinding and NetTcpBiinding also allows configuring the transaction flow. e.g.
    [OperationContract]
[OperationBehavior(TransactionScopeRequired=true, TransactionAutoComplete=true)]
public void TransferMoney(Account creditor, Account debitor)
{
// 
}
    • Queuing: Using NetMsmqBinding or MsmqIntegrationBinding, WCF supports queuing of messages.
    • Extensibility: WCF allows creating custom channels, bindings as per the application requirements.
For example you can create a channel for communicating with SMTP protocol or RSS protocol.

Application outline

Attached application solution contains six projects.
1. Console client: It calls WCF service without creating a proxy. Contract and data members are created manually at client side. It uses simple TCP binding.
2. MsmqClient: As name says, it uses MSMQ binding. The MSMQ must be installed and the private queue with the given name should be created before running this application.
3. SystemInfo: Simple data access class. It does nothing special. WCF service calls methods of this class.
4. WCFClient: Simple windows application to demonstrate working of WSDL created using svcutil. Uses Basichttp binding.
5. WCFHost: A simple console application acting as a host for WCF service.
6. WCFservice: Actual WCF service with service contract and data contract. Also contains .SVC file so that it can be hosted in IIS directly. It also contains other details required for MSMQ binding. There is one implmenter class which implements service contracts. Most of the code is self explanatory. Your suggestions are always wel-come.

Conclusion

We can conclude that WCF simplifies the creation of distributed applications on Windows. Because it implements SOAP and the most important WS-* specifications, WCF provides full-featured interoperability with other Web services platforms. And because it offers explicit support for a service-oriented approach, WCF gives developers a natural environment for building modern software.