Friday 2 November 2012

New Features in Windows Communication Foundation (WCF) 4.0


New Features in Windows Communication Foundation (WCF) 4.0



Introduction

There have been quite a few enhancements and new features introduced in WCF 4.0. These new features and enhancements are a major boost to productivity, flexibility and they facilitate seamless development of service oriented applications. This article discusses the new features and enhancements in WCF 4.0 and how one can make use of them in applications.

What is Windows Communication Foundation (WCF)?

Windows Communication Foundation (WCF) is a platform that can be used to design and implement platform independent, scalable services. It is a framework from Microsoft that provides a platform for unification of a number of enterprise technologies under one roof. The MSDN states, "Windows Communication Foundation (WCF) is Microsoft's unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments."
WCF was introduced as part of .NET Framework 3.0 in 2006 and was initially named "Indigo". The forthcoming sections in this article presents the new features and enhancements in WCF 4.0.

Pre-requisites

To work with the concepts and the code examples presented in this article, you should have the following installed on your system: Microsoft Visual Studio 2010 RC or higher

New Features and Enhancements in WCF 4.0

The new and enhanced features in Windows Communication Foundation 4.0 include the following:
  • Support for simplified configuration
  • Support for standard endpoints
  • Support for discovery
  • Support for simplified IIS hosting
  • Enhanced support for REST
  • Support for routing service
  • Support for workflow services
We will discuss each of these new features and enhancements in the sections that follow.


Support for Simplified Configuration

Configuration in WCF 4.0 is much simpler compared to the earlier versions of WCF. WCF 4.0 provides default endpoints, binding, and behavior. Refer to the WCF 4.0 service shown below:
[ServiceContract]
public class CustomerService
{
    [OperationContract]
    public string GetCustomerName(int customerID)
    {
        //Code to search customer name based on customerID and return it.
    }
}
Here's an example of the simple configuration you would use to host the service.
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost serviceHost = new ServiceHost
                 (typeof(CustomerService));
                 serviceHost.AddServiceEndpoint (typeof(CustomerService), new BasicHttpBinding(), "http://localhost:1212/ CustomerService.svc");
            serviceHost.Open();
            Console.WriteLine("The Customer Service has been started");
            Console.ReadLine();
            serviceHost.Close();
        }
    }
To consume the service, you can use the following configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled ="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
 </system.serviceModel>
</configuration>
To specify a more secure wsHttpBinding binding, you can specify the following configuration in your configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled ="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="wsHttpBinding" scheme ="http"/>
    </protocolMapping>
 </system.serviceModel>
</configuration>

Support for Standard Endpoints

WCF 4.0 provides support for standard endpoints--a set of preconfigured endpoints to minimize on the otherwise tedious configuration that is needed to host or consume a WCF service. The standard endpoints available in WCF 4.0 include the following:
  • dynamicEndPoint
  • discoveryEndpoint
  • udpDiscoveryEndpoint
  • announcementEndpoint
  • udpAnnouncementEndpoint
  • mexEndPoint
  • webHttpEndpoint
  • webScriptEndpoint
  • workflowControlEndpoint

Support for Discovery

The ability to dynamically resolve the service endpoints based on some predefined criteria is one of the most striking of all the new features and enhancements in WCF 4.0. The following code snippet is the entire code configuration you need to specify the base addresses and endpoints and other necessary configuration information for a WCF 4.0 service:
<configuration>
    <system.serviceModel>
      <services>
        <service name="CustomerService"
                 behaviorConfiguration="serviceBehavior">
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:1234/CustomerService"/>
            </baseAddresses>
          </host>
          <endpoint address=""
                    binding="basicHttpBinding"
                    contract="ICustomerService" />
          <endpoint name="udpDiscovery" kind="udpDiscoveryEndpoint"/>
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="serviceBehavior">
            <serviceDiscovery />
          </behavior>
        </serviceBehaviors>        
      </behaviors>
    </system.serviceModel>
</configuration>
To consume the customer service using the discovery API at runtime from the client side, you can use this code:
DiscoveryClient discoveryClient = new DiscoveryClient("udpDiscoveryEndpoint");
FindCriteria findCriteria = new FindCriteria(typeof(ICustomerService));
FindResponse findResponse = discoveryClient.Find(findCriteria);
if (findResponse.Endpoints.Count > 0)
{
    EndpointAddress endPointAddress = findResponse.Endpoints[0].Address;
    ChannelFactory<ICustomerServiceChannel> channelFactory = new ChannelFactory<ICustomerServiceChannel>(
        new BasicHttpBinding(), endPointAddress);
    ICustomerServiceChannel serviceClient = new factory.CreateChannel();
    String customerName = client.GetCustomerName(10);    
    serviceClient.Close();
    channelFactory.Close();
}

Support for Simplified IIS Hosting

WCF 4.0 provides support for simplified configuration for hosting services in the IIS. Refer to the code listing below that illustrates a WCF 4.0 Service:
<!-- StudentService.svc -->
<%@ ServiceHost Language="C#" Debug="true" Service="StudentService
CodeBehind="~/App_Code/StudentService.cs" %>
[ServiceContract]
public class StudentService
{
    [OperationContract]
    public string GetStudentName(int studentID)
    {
        //Code to search student name based on student ID and return it.
    }
}
You can easily enable the service metadata in the application's web.config file by specifying the following:
<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>
To eliminate the need of a .svc file, you would like to define virtual service activation endpoints for the service as shown below:
<configuration>
  <system.serviceModel>
    <serviceHostingEnvironment>
      <serviceActivations>
        <add relativeAddress="StudentService.svc" service="StudentService"/>
      </serviceActivations>
    </serviceHostingEnvironment>
  </system.serviceModel>
</configuration>

Enhanced Support for REST

Representational State Transfer (REST) is an architectural paradigm that can be used for designing and developing scalable, interoperable, platform and protocol independent services. WCF 4.0 provides seamless support for design and development of REST-based services. Note that support for REST-based services was also provided as part of the earlier version of WCF, but, now with WCF 4.0, designing, implementing and managing REST-based services has become much simpler.
You can design and implement REST-based services in WCF 4.0 using a new binding calledWebHttpBinding. To make a service RESTful, you need to use the WebGet attribute as shown in the code listing below:
[ServiceContract]
public interface IStudentDataService
{
[OperationContract]
[WebGet]
int GetStudentCount(string courseCode);
}
The following code snippet illustrates how you can specify the binding information for the RESTful service:
<service name ="StudentService" behaviorConfiguration="Default">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:1212/StudentService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding ="webHttpBinding"
          contract="IStudentService" />
</service>
In WCF 4.0, you can configure an automatic help page that describes the REST-based services. To do this, here's all you need to specify in your application's configuration file:
<configuration>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <behaviors>
      <endpointBehaviors>
        <behavior name="TestHelpBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="TestWCFService">
        <endpoint behaviorConfiguration="TestHelpBehavior"
                  binding="webHttpBinding"
                  contract="TestWCFService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

Support for Routing Service

WCF 4.0 provides support for routing through the usage of the RoutingService class. Hosting a routing service is similar to hosting a WCF service. Routing Service provides versioning, protocol bridging, transaction, error handling support. Here's what theRoutingService class looks like:
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any,
    InstanceContextMode = InstanceContextMode.PerSession,
    UseSynchronizationContext = false, ValidateMustUnderstand = false)]
public sealed class RoutingService : ISimplexDatagramRouter, ISimplexSessionRouter,
    IRequestReplyRouter, IDuplexSessionRouter
{
    //Class members
}

Support for Workflow Services

WCF 4.0 provides support for integrating WCF and WF to implement declarative long running workflow services seamlessly. In the earlier version of .NET Framework, i.e., .NET Framework 3.5, you were restricted to using workflow services to asynchronous long running processes only. In .NET 4.0, the performance for the workflow services have been improved to a considerable extent and you can now use WCF and WF in conjunction to design and implement declarative high performant services with ease. In WF 4.0, you have powerful messaging capabilities to achieve close integration with WCF 4.0. Also, .NET Framework 4.0 provides a much improved infrastructure for hosting workflow services in IIS.
The following code snippet illustrates how you can configure a workflow service:
<configuration>
  <system.serviceModel>
    <services>
      <service name="TestWorkflowService">
        <endpoint binding="basicHttpContextBinding" contract="ITestWorkflowService"/>
      </service>
</services>
</system.serviceModel>
</configuration>

Summary

WCF 4.0 has eliminated the pain of specifying tedious configuration details to host WCF services. With enhancements to configuration, tracing, serialization, message queuing, service discovery, routing, and workflow services, WCF 4.0 promises to be the technology of choice for building scalable, service oriented, REST-based services. In this article we have had a look at the new features and enhancements in WCF 4.0 and how they can be used in applications.

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...