Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Article

A closer look at Windows Communication Foundation

Rate me:
Please Sign up or sign in to vote.
4.44/5 (37 votes)
29 Jan 200713 min read 95K   1.1K   105   7
The article describes details of WCF and also has source code for different types of binding.

Abstract

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

Introduction

To make developer's 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 the 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 mentioned earlier, WCF is the Windows Communication Foundation built on .NET 2.0 framework. It is a type of service execution framework especially made for establishing communication between diverse systems and to 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 that it supports most of the open industry standards hence it can produce the best results across heterogeneous operations systems. Other benefits are that 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 the 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 a WCF service. We will go in the details of each component in the sections below:

  1. Contract definitions
    • Data contracts and data member
    • Service contracts
    • Fault contracts
    • Message contracts
  2. End points
  3. Bindings
    • BasicHttpBinding
    • WSHttpBinding
    • WSDualHttpBinding
    • WSFederationHttpBinding
    • MsmqIntegrationBinding
    • NetMsmqBinding
    • NetNamedPipeBinding
    • NetPeerTcpBinding
    • NetTcpBinding
  4. Hosting environments
    • Windows application
    • Console application
    • Windows service
    • IIS
    • WAS (Windows activation service) comes with IIS 7.0
    • 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 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 outside clients and a remoting or COM+ application for Windows OS. Both these applications are using the same business logic and the same database. Suppose you want to add some new business logic like introducing a 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 a 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 the client and server of available methods, data structures, and message structures. They remain loosely coupled and platform independent. WCF contains the following contracts. As SOAP is the native protocol of WCF for communication, interfaces, classes are translated to SOAP types by CLR.

Service contract

  • 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.
  • Each service contract contains method that are exposed outside and annotated with [OperationContract]attribute.
  • Service contract can also specify the requirements that should be satisfied by the endpoint.
    E.g. session required should satisfied by endpoints.
  • Example:

    C#
    [ServiceContract
        (ProtectionLevel=System.Net.Security.ProtectionLevel.None)]
            public interface IWCFService
            {
                    [OperationContract]
                    string GetSystemIPAddress();
    
                    [OperationContract]
                    List<employee /> GetEmpolyeeArray();
    
                    [OperationContract]
                    Employee CreateNewEmployee();
            }
  • Usually we can use service contract over a class too. 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 the client outside the application domain.
  • Services are of three types:
    1. Typed: Used for simple communication. It can accept or return simple or complex data objects.
      E.g. CreateNewEmployee() method in the above class
    2. UnTyped: It allows developers to work at message level.
      E.g. Message ParseRequest(Message myRequestMessage)
    3. Typed message: Falls between typed and untyped services.
      Uses custom message classes defined with Message contracts.
      MyMessage ProcessedRequest(MyRequestMessage msg)

Data contract

  • 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 do not change the name of the existing members, name of the namespace to maintain compatibility.
  • 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.
  • [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.
  • Here also access modifiers do not play any role.
  • 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 the 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<iwcfservice /> and implement the WCF service (IWCFService). In such a case, the operation contract method will call base.Channel.GetSystemIPAddress() and it will be routed to the 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 that namespace must have same names as that of server. Also method names and data member names should remain the same.

Fault contract

  • 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 to want to document. Custom exception should be marked as serializable.

Message contract

  • Translated to SOAP messages. It describes the structure of the message like what goes where. WCF allows the developer to control what goes 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 the [MessageContract] attribute. Members participating in the SOAP message can be defined and placed at the appropriate place using [MessageHeader] and [MessageBodyMember] attribute.
  • Example:

    C#
    [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 the 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 binding 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 applications. The exceptions can be: RSS feed of a site or SMTP protocol.

1BasicHttpBinding:Basic web service communication with no security by default
2WSHttpBinding:Web services with WS-* standards, supports transactions
3WSDualHttpBinding:Web services with duplex contract and transaction support
4WSFederationHttpBinding:Web services with federated security with transaction support
5MsmqIntegrationBinding:Direct communication with MSMQ, supports transaction
6NetMsmqBinding:Communication between WCF applications using queuing with transaction support
7NetNamedPipeBinding:Communication between WCF applications on the same computer with duplex contracts support and transaction support
8NetPeerTcpBinding:Communication between computers across peer-to-peer services with duplex contracts support
9NetTcpBinding: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 a URI which are exposed to the outside world and from where the client can connect to the WCF service.
Each end point consists 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 requires. 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 the WPF client will communicate and an end point with basic HTTP binding where JAVA client will communicate. We can control and configure the behavior of an end point programmatically and using application configuration file.

Hosting environments

The architecture of an 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 a 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:

  1. Windows application: Simple winform application
  2. Console application: Simple console application
  3. Windows service: WCF service can be controlled by the Service control manager
  4. IIS: Can be hosted in IIS provided the service exposes at least one HTTP end point
  5. WAS (Windows Activation Service) comes with IIS 7.0: Removes dependability upon HTTP
  6. Windows Presentation Foundation

Security in WCF

When you go for a distributed application, the most important aspect is security. As mentioned 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 for the development of secured applications. WCF service can be secured using four ways:

  1. Authentication
  2. Message integrity
  3. Message confidentiality
  4. 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 a distributed application.
    Service behavior can also control a transaction using the parameters in the [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. Queuing: Using NetMsmqBinding or MsmqIntegrationBinding, WCF supports queuing of messages.

    C#
    [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

The attached application solution contains six projects:

  1. Console client: It calls the WCF service without creating a proxy. Contract and data members are created manually at client side. It uses simple TCP binding.
  2. MsmqClient: As the 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 implementer class which implements service contracts. Most of the code is self explanatory. Your suggestions are always welcome.

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior) Symantec Services, Pune
India India
Dear Friends,
I'm from Pune and currently working with Symantec. I'm having 7+ yrs of software development experience and I'm working on .NET since 6+ years.
I'm a Brainbench Certified Software Engineer in C#, ASP.NET, .NET Framework and ADO.NET.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Hitesh.D.Patel16-Aug-10 2:44
Hitesh.D.Patel16-Aug-10 2:44 
GeneralWCF Events to windows form Pin
mohit.raghav4-Jun-08 11:02
mohit.raghav4-Jun-08 11:02 
GeneralRe: WCF Events to windows form Pin
jdkulkarni9-Jun-08 5:11
jdkulkarni9-Jun-08 5:11 
GeneralAbout interactive window station under non-System account.. Pin
masaniparesh29-Nov-07 4:00
masaniparesh29-Nov-07 4:00 
GeneralGood Pin
akshayswaroop15-Feb-07 22:42
akshayswaroop15-Feb-07 22:42 
GeneralGeneral comments Pin
bachnpham6-Feb-07 11:43
bachnpham6-Feb-07 11:43 
GeneralRe: General comments Pin
jdkulkarni6-Feb-07 17:14
jdkulkarni6-Feb-07 17:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.