Looking at the WCF Windows Communication Foundation

Introduction

To make your life as a developer easy, Microsoft continuously brings new technologies to the market. Sometimes, these technologies are similar to existing technologies, and at other times large enhancements are made in the current technologies. As a result, at times you see the processing architecture of a web page totally change, as was done in .NET 2.0.

.NET 2.0 does not, however, bring significant enhancements in Winform application development. So, how can you build a Windows application that can be distributed across diverse operating systems and that will gain a performance benefit when used on the same OS? The answer is Windows Communication Foundation (WCF), which had previously been code named "Indigo."

This article will cover the basic components of WCF and dive into some of the details of its components. It will address the issues faced in previous technologies as well as show why you should use WCF.

What Is WCF?

As said earlier, WCF is a part of the .NET 3.0 framework. It is a type of service execution framework made especially to establish 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 that it supports most open industry standards; therefore, it can produce the best results across heterogeneous operations systems.

It is also beneficial that it was developed using managed code and that it uses the power and features of .NET 2.0. Because it supports WS-* standards, it supports transaction, security, and reliability. WCF uses SOAP as its native protocol for communication.

Prerequisites

You need the following to develop a WCF service:

OS: Windows VISTA, Windows XP SP2, or Windows 2003 Server SP1

Visual Studio 2005 professional Edition with SP1 (or better)

Microsoft Windows SDK

.NET 3.0 runtime

WCF extensions (while working on the VS 2005 editor)

Key Components of WCF

WCF is based upon the following key components that are used to build a WCF service. Each component is covered in detail in the following sections.

Contract definitions

Data contracts and data member

Service contracts

Fault contracts

Message contracts

End points

Bindings

BasicHttpBinding

WSHttpBinding

WSDualHttpBinding

WSFederationHttpBinding

MsmqIntegrationBinding

NetMsmqBinding

NetNamedPipeBinding

NetPeerTcpBinding

NetTcpBinding

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

To understand the power of WCF, you really need to understand what issues it addresses.

Imagine you are developing an enterprise application for a bank. When you start designing the system, the requirements are very complex and critical. Consider, for example, that the application is used by bank staff, outside customers, and by payment gateway systems. You are not sure that what operating system and what type of clients will be used by outside customers. You want the system to have performance with security and reliability when used on an intranet. You want security and reliability when used from outside as well. Previously you could have gone for creating web services exposing web methods for outside clients and a remoting or COM+ application for Windows OS.

Both the web service and the remoting/COM+ based applications us the same business logic and the same database. Suppose you want to add some new business logic, such as 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 the business logic or add 3-4 additional schemes in the span of six months?

The current design will not scale. You might start wondering: What if you had a single application exposing multiple endpoints for diverse and similar clients—an application that will give me all the benefits of industry-wide open standards.

That's it. WCF is the answer to your question.

WCF with managed code, using the 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 the following:

Web services

.NET—.NET communication

Distributed transactions

Support for WS-* specifications

Queued messaging

Key Subsystems of WCF

Service model

Connector framework

Hosting environment

System services

Messaging services

Key Components in WCF

The following are key components of WCF. Each of these is covered in the following sections.

Contracts

Bindings

End point definitions

Hosting environment

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 the following contracts. Because SOAP is the native protocol of WCF for communication, interfaces and classes are translated to SOAP types by CLR.

1. Service contract

This is translated to WSDL. Service contract defines the operations that a service can perform. This is why a WCF service must contain at least one. It also can have more than one service contract. It is defined by using the [ServiceContract] attribute. The implementer of the service contract is managed code. Hence, the service contract also maps the interface and methods to a platform-independent description. By using the attribute feature of .NET, you can extend the behavior of the service like is it one way or two way, the exception handling behavior, and so forth.

Each service contract contains methods that are exposed outside and annotated with the [OperationContract] attribute.

A service contract also can specify the requirements that should be satisfied by the endpoint; a required session should be satisfied by endpoints. For example:

Usually, you also can use a service contract over a class. However, it is not a good practice because interfaces allow separation from the implementation logic. When using ServiceContract and OperationContract over a method or a class, access modifiers do not make any sense. Everything that is marked with ServiceContract or OperationContract will be exposed to a client outside the application domain.

Services are of three types.

Typed

Uses for the simple communication. It can accept or return simple or complex data objects.

For example, you can use the CreateNewEmployee() method in the above class.

UnTyped

It allows developers to work at the message level.

For example, you can use Message ParseRequest(Message myRequestMessage).

Typed message

Falls between typed and untyped services.

Uses custom message classes defined with Message contracts.

For example, you can use MyMessage ProcessedRequest(MyRequestMessage msg).

2. Data contract

This is translated to XML schema (XSD). It basically describes the data structure. When you want to pass or return more values, you 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; instead, name the namespace to maintain compatibility.

The data contract can be defined by annotating the [DataContract] attribute on a class, structure, or enum. The data members that are to be exposed outside are annotated with the [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, it uses binary serialization over SOAP to optimize the performance. In the 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 a proxy generated for the given service. This may be the case when the WCF service uses only TCP endpoints to allow interaction. In that case, WSDL will not be available unless and until it is explicitly defined in the service behavior with an HTTP end point. Even if client does not have WSDL with you, you can create the same WCF dummy class or proxy class at the client side. The 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 the foundation. In this case, you can have data contract members defined in the same way. The only thing—and the most important thing—is that the namespace must have the same names as that of server. Also, method names and data member names should remain the same.

3. Fault contract

These are translated to SOAP faults. The allow the developer to document the errors that a service can produce. You can define a service contract only on [OperationContract] by annotating with the [FaultContract(typeof(System.Exception))] attribute. Here, the exception type can be a exception to what you want to document. A custom exception should be marked as serializable.

4. Message contract

This is translated to a SOAP message. It describes the structure of the message, such as what goes where. WCF allows the 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 by using the [MessageContract] attribute. Members participating in the SOAP message can be defined and placed at appropriate place by using the [MessageHeader] and [MessageBodyMember] attributes. For example:

Looking at the WCF Windows Communication Foundation

Bindings

Bindings are communication channels between a WCF service and client. They decide how a WCF service will communicate with the client. Depending upon the different protocols like HTTP, TCP, MSMQ, there are different types of binding. Binding supports the 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 64 Kb). Because WCF supports all industry open standards, it supports security by using SSL and WS-Security (schema defined security) standards.

If you want a session-enabled service, binding determines whether the service is session enabled or not. Not all binding supports sessions. Because WCF is extendible, you can define your own custom bindings. However, this is very rare case because WCF has nine built-in bindings that are sufficient for most applications. The exceptions can be the RSS feed of a site or SMTP protocol.

Binding Type

Description

BasicHttpBinding

Basic web service communication with no security by default

WSHttpBinding

Web services with WS-* standards; supports transactions

WSDualHttpBinding

Web services with duplex contract and transaction support

WSFederationHttpBinding

Web services with federated security with transaction support

MsmqIntegrationBinding

Direct communication with MSMQ; supports transaction

NetMsmqBinding

Communication between WCF applications using queuing with transaction support

NetNamedPipeBinding

Communication between WCF applications on same computer with duplex contracts support and transaction support

NetPeerTcpBinding

Communication between computers across peer-to-peer services with duplex contracts support

Here is the mapping of base address schemes to the transport protocols.

Scheme

Maps To

http

HTTP

net.tcp

TCP

net.pipes

Names pipes

net.msmq

MSMQ

End Points

End points are nothing but URIs that are exposed to the outside world and from where a client can connect to the WCF service. Each end point consists of the following:

Base address: Where to send message (A)

Type of binding: How to send message (B)

Contract: What to send in a message (C)

You 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, you can expose an endpoint with TCP binding where the WPF client will communicate and an end point with basic HTTP binding where the Java client will communicate. You can control and configure the behavior of end point programmatically and use ab application configuration file.

Hosting Environments

As the diagram shows, you 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:

Windows application: Simple winform application

Console application: Simple console application

Windows service: WCF service can be controlled by the Service control manager

IIS: Can be hosted in IIS provided the service exposes at least one HTTP end point

Security in WCF

When you go for a distributed application, the most important aspect is security. As said earlier, WCF uses binding to support security. Binding supports security by using SSL and WS-Security standards. You also can use Windows authentication. One of the primary goals behind WCF development was to make the development of secured applications easy. A WCF service can be secured in four ways:

Authentication

Message integrity

Message confidentiality

Authorization

There are some guidelines about using security mechanisms. Depending upon the application need and requirement, you easily can select the suitable one and implement it with little effort. 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. Although 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 that are present in WCF and can be used to achieve reliable communication. They are as follows:

Transactions: WCF uses System.Transactions to control the transaction in a distributed application. Service behavior can also control transactions by using the parameters in the [ServiceBehavior] attribute. An operation contract can force a transaction by using the [OperationBehavior] attribute if the operation is very critical. If the client also supports WS-AutomicTransaction, a Java client and WCF service can share the same transaction. Some binding, such as WsHttpBinding and NetTcpBiinding, also allows configuring the transaction flow. For example:

Queuing:WCF uses NetMsmqBinding or MsmqIntegrationBinding to support the queuing of messages.

Extensibility: WCF allows creating custom channels and 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. Most of the code is self explanatory. Your suggestions are always welcome.

Console client: It calls WCF service without creating a proxy. Contract and data members are created manually at the client side. It uses simple TCP binding.

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.

SystemInfo: Simple data access class. It does nothing special. The WCF service calls methods of this class.

WCFClient: Simple Windows application to demonstrate the working of WSDL created using svcutil. Uses Basichttp binding.

WCFHost: A simple console application acting as a host for WCF service.

WCFservice: Actual WCF service with service contract and data contract. Also contains a .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 that implements service contracts.

Conclusion

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. Because it offers explicit support for a service-oriented approach, WCF gives developers a natural environment for building modern software.

About the Author

Jayant Kulkarni

Dear Friends,
I'm from Pune and curently working with Symantec Corp. I'm having more than 7 years of exp in software field and have worked on areas like ASP.NET, C#, .NET remoting, web services, pocket pc applciations. I'm a brainbench certified software engineer in .NET framework, C#, ADO.NET and ASP.NET.
If you like any of my articles or you want to suggest some changes and improve the way I code, write articles feel free to mail me at: jayantdotnet@gmail.com

Top White Papers and Webcasts

When individual departments procure cloud service for their own use, they usually don't consider the hazardous organization-wide implications. Read this paper to learn best practices for setting up an internal, IT-based cloud brokerage function that service the entire organization. Find out how this approach enables you to retain top-down visibility and control of network security and manage the impact of cloud traffic on your WAN.

U.S. companies are desperately trying to recruit and hire skilled software engineers and developers, but there is simply not enough quality talent to go around. Tiempo Development is a nearshore software development company. Our headquarters are in AZ, but we are a pioneer and leader in outsourcing to Mexico, based on our three software development centers there. We have a proven process and we are experts at providing our customers with powerful solutions. We transform ideas into reality.