Windows Communication Foundation (WCF): The Little Things

Introduction

There are numerous articles on the web that talk about OperationContracts, MessageContracts, ServiceContracts, Bindings, endpointand other topics. This article talks about some of the smaller things that will help beginner .NET developers.

Let’s start with a little insight to help us start.

Windows Communication Foundation (WCF) in simple terms offers communication between processes. True, irrespective of the location of the process.

As you have already known, WCF replaces the ASMX, Removing, DCOM, Enterprise Services, Messaging and Sockets technology in communication with its flexible features.

Windows Communication Foundation (WCF) is a cohesive programming model targeted at the ASMX , .NET Remoting, Message Oriented Programming, Enterprise Services and many more. It all started with the design of COM that helped us communicate between two applications. A step further took us to DCOM enabling us to interact with applications over a network. They were followed by COM + , Enterprise Services and the .NET Framework.

Windows Communication Foundation (WCF) provides a unified model around all these technologies with backward compatibility. It is a streamlined implementation procedure to provide access to various types of connection. The most fundamental concept that upholds WCF is the ABC – address, binding and the contract as you are already aware.

WCF is extensible through the enormous set of configurable parameters. This is achieved through the configurable elements in the configuration files.

The two ends of configuration of a WCF component are,


  1. The Client Configuration (this is done in the host app.config file)

  2. The Service Configuration (this is done in the web.config file)

WCF Services Can Be Setup Using the Simple Steps

The Service, per se, consists of several endpoints. And is governed by predefined “Service Behaviors” and “Binding Configurations” You start off with an Interface and Contract. Since it follows the Contract-first design, it is very easy for anyone to grasp.


  • Create a Service Contract

  • Add Operation Contracts to Service Contracts

  • Create Service implementation for the Operation Contracts.

  • Configure a Service Host that provides a wrapper to the implementation to the contract through an Endpoint.

The Endpoint is a portal for communicating with the clients who consume it. It provides the details of the Service to the clients. It is comprised of Address, Binding, and a Contract , popularly known as ABC of Endpoint.

The binding supports the service and shows how the client connects to the service.

Microsoft Service Configuration Editor

This is a nifty editor that allows us to configure the WCF Service. You would also be happy to know that this editor can be launched from our Editor – the Visual Studio itself. Right-click on the Web.config configuration file, and you should find the “Edit WCF Configuration” option in the context menu options.

The editor would launch and by setting few properties your configuration file would be ready.

The WCF Service can be invoked in “One Way” mode so that the caller need not wait for the response of the request. This is particularly useful when the user makes a request to database for Logging, Storing computation results…and much more scenarios where the user would just initiate the calls to the service and does not necessarily require waiting for the response. For the purpose, we need to use the IsOneWay attribute of the Operation Contract.


[ServiceContract]
Public Interface IMyService
{
[OperationContext(IsOneWay=true)]
Void LogMessage(Log l);
}

Exception Handling in Windows Communication Foundation (WCF)

WCF does not thrown to the client by default unlike any other medium. It makes the channel Faulted. This behavior is obviously an extension to the Custom Errors default behavior. But this can be overridden , for development or debugging purposes through Service Behaviors.

When WCF service throws such a FaultException, a SOAP fault message is generated and send to the Calling Client. FaultExceptions can also be Strongly typed.

Modify the includeExceptionDetailInFaults to true in the Service behavior that you create.


<Config Entry>
<serviceBehaviors>
  <behavior name=”Debug”>
   <serviceDebug includeExceptionDetailInFaults=”true” />
  </behavior>
</serviceBehaviors>
</Config Entry>

ASPNETCompatibility

WCF does not support storage for Session State. The workaround that I figured out a few days back was to use the ASP.Net Compatibility mode. The attribute is called AspNetCompatibilityRequirements and takes one of the below mentioned three values. (Below is an excerpt from MSDN)


  • NotAllowed – Indicates that your services may never be run in the ASP.NET compatibility mode. You have to set this in scenarios where your service implementation doesn’t work in ASP.NET compatibility mode, such as in scenarios where your services are not built for HTTP.
  • Allowed – Indicates that your services may run in the ASP.NET compatibility mode. Pick this value only when you know your service may work in this mode.
  • Required – Indicates that your service must run in the ASP.NET compatibility mode. Pick this value when your service requires persistent session storage.

You would need to use this attribute when you decorate your class as shown in sample below:



<CODE>
[AspNetCompatibilityRequirements(
RequirementsMode=AspNetCompatibilityRequirementsMode.Required)]
public class myWCFService : IMyService
</CODE>

When you set the AspNetCompatibilityRequirementsMode to Required, you have to also specify the aspNetCompatibilityEnabled mode. This is done under the serviceHostingEnvironment Node with the aspNetCompatibilityEnabled attribute.


<Config Entry>
<system.serviceModel>
      <serviceHostingEnvironment aspNetCompatibilityEnabled=”true”/>
</system.serviceModel>
</Config Entry>

Simple Windows Authentication in Binding

You can define and configure the existing binding, or even extend it to your needs. You could also create custom bindings that cater to custom solutions.

The first thing that is easy to implement is the basic HTTP Binding. It is also powerful. Check out the below sample that configures the binding with Windows Authentication. The Client Credential Type is set to Windows.


<Config Entry>
<Bindings>
     <basicHttpBinding>
          <binding name=”MyBinding”>
              <security mode=”TransportCredentialOnly”>
                  <transport clientCredentialType=”Windows” />
              </security>
          </binding>
     </basicHttpBinding>
</bindings>
</Config Entry>

IExtensibleDataObject

Let’s say we have a DataContract with few attributes and a Client adds a reference to a service that has these attributes. What if the Attribute names change over a course of time? The client would get an unexpected behavior. In such cases , we need to do two things:


  • Implement the IExtensibleDataObject interface

  • Change the inner implementation of the Attribute


<CODE>
public class MyClass: IExtensibleDataObject
{
   private string _property1 = string.Empty;
   private ExtensionDataObject _extensionData;

   [DataMember (Name=” Property1″)]
   public string Property1
   {
       get { return _ property1; }
       set { _ property1 = value; }
   }

   public ExtensionDataObject ExtensionData
   {
       get { return _extensionData; }
       set { _extensionData = value; }
   }
}
</CODE>


If we had to change the Property1 name, ensure that you only change the internal application.


<CODE>
[DataMember(Name=” Property1″)]
   public string Property1
   {
       get { return _ property2; }
       set { _ property2= value; }
   }
</CODE>

The extensionDataField field (look at the above example) serves as a repository for undefined data items. It does not delete them.

Hosting Windows Communication Foundation (WCF) services in IIS

IIS needs information on how to help communicate the client with the service. This is achieving thru Binding.


The Windows Communication Foundation (WCF) Service files end with a SVC extension. This is not enabled by default. You may have to go to IIS (type “Inetmgr” without quotes in your run menu and hit the Enter key) and configure it. Here are the steps:

Go to the appropriate web site – and see its properties.


If not present, add the following attributes to the WebServer Extensions:

Path   &nbsp:     c:windowsmicrosoft.netframeworkv2.0.50727aspnet_isapi.dll

Limit to    :    GET,HEAD,POST,DEBUG

Migrating ASMX to Windows Communication Foundation (WCF)

First, you would need to figure out what is the current version that the ASMX version of the web service handles. It could be either SOAP 1.1 or SOAP 1.2. As a provision, you should ideally start with two bindings that facilitate serving of either version.

The basicHTTPBinding that servers the SOAP 1.1 version, and the CustomBinding that is a replica of basicHTTPBinding but the MessageVersion set to SOAP 1.2.

Recommendations

Check out the WCFLoadTest project from CodePlex.

As it describes “This tool takes a WCF trace file and a WCF client proxy, or a WCF interface contract, and generates a unit test that replays the same sequence of calls found in the trace file. The code generated is easily modifiable so that data variation can be introduced for the purpose of doing performance testing.

The tool generates code for both Microsoft Visual Studio 2005 and Visual Studio 2008. It also installs a wizard into both editions of Visual Studio for creating the trace and processing it from inside Visual Studio. If both editions are present the tool is installed into both editions. The source code is a Visual Studio 2005 project.”

Web Service Software Factory: is an integrated collection of resources designed to help you quickly and consistently build Web services that adhere to well-known architecture and design patterns. These resources consist of patterns and architecture topics in the form of written guidance and models with code generation in the form of tools integrated with Visual Studio 2008. Refer MSDN for more help.

The article titled “A Performance Comparison of Windows Communication Foundation (WCF) with Existing Distributed Communication Technologies” at MSDN compares it with:


  • Message Encoders

  • Message Formatters

  • Message Filters

  • Message Formatter

  • Parameter Inspectors

  • Operation Selectors

  • Operation Invokers

That should be an interesting read.

References

http://msdn.microsoft.com/en-us/library/bb310550.aspx

http://msdn.microsoft.com/en-us/library/cc487895.aspx

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read