Friday, December 28, 2012

WCF 4.0 Features - Four

So in WCF 4.0 Features - Threewe discussed Routing service. Now let's move to next...

Improved REST Support...

WCF 4 comes with several Improved REST Support like  an automatic help page that describes the RESTful service to consumers, simplified HTTP caching etc. 

Help page lists a description of each operation, request and response formats.This functionality is turned off by default. When a user browses to a WCF WEB HTTP service and appends "/Help" on to the end of the URL, for example http://localhost:8000/Customers/Help, a help page like the following is displayed.

 
The user can then click any method listed in the help page and detailed page for that operation is displayed showing more information about the method, including message formats and example responses. The following image is an example of a help page for a method.
 We have to add <webHttp helpEnabled="true" /> in Cconfiguration behaviors.

HTTP Caching...

  One of the primary potential benefits of REST is HTTP caching to leverage the various HTTP caching header, apply the [AspNetCacheProfile] attribute to a [WebGet] operation as follows:

[AspNetCacheProfile("CacheFor60Seconds")]

With this in place, you’ll need to define an ASP.NET output caching profile named “CacheFor60Seconds” within your web.config file. The following web.config shows how this can be done:

<configuration>
  <system.web>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="CacheFor60Seconds" duration="60" varyByParam="format" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
</configuration> 

Same Can be achieved programmatically as follows :

using (WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/Customers")))
{
   host.AddServiceEndpoint(typeof(ICustomerCollection), new WebHttpBinding(), "");            
   host.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { EnableHelp = true });
}

  

So in WCF 4.0 Features series we discussed some basic new features thanks for reading...

Courtesy: Random Web Images, MSDN, Microsoft .NET 4.0 WCF Book, Several online resources     

Thursday, December 27, 2012

WCF 4.0 Features - Three

So in WCF 4.0 Features - Two we discussed Dynamic Service and 
End Point discovery. Now let's move to next.

Routing service


This new feature introduces routing service between client and actual business service. This intermediate service Act as broker or gateways to the actual business services and provides features for content based routing, protocol bridging and error handling

 In the above figure,the Client application have knowledge of WCF Routing Service which further routes request to the specific services WCF Service1 or WCF Service2 or WCF Service3.

Understanding the Routing Service

 The Routing Service is implemented as a Windows Communication Foundation (WCF) service in the System.ServiceModel.Routing namespace.In order to implement the WCF Routing Service .NET framework 4.0 offers a few in-build contracts as follows
  1. ISimplexDatagramRouter: It is a one way model for which session is not mandatory. Ideal for performing tasks like logging, message queuing, etc.
  2. ISimplexSessionRouter: It is one way but works on a session.
  3. IRequestReplyRouter: It is the usual client message request and service response model.
  4. IDuplexSessionRouter: It works over session and supports performing callbacks to the client
Message Filters are used by the WCF routing service to consider which part of the message has to be matched in order to perform the routing to the respective service. Below are some of the available message filters.

  1. Action 
  2. EndpointName
  3. EndpointAddress 
  4. XPATH
  5. Even a Custom one can be created

Sample Code …Create a WCF service project, delete all the .cs files and add the reference to the library System.ServiceModel.Routing and add following configuration file :

<system.serviceModel>
    <services>
        <service name="DemoRoutingService" behaviorConfiguration="MyRoutingServiceBehavior">
        <host>
            <baseAddresses>
                <add baseAddress="http://localhost:5555/RoutingService/DemoRouter"/>
            </baseAddresses>
        </host>
        <endpoint name="RequestReplyBindingEP" address="http://localhost:5555/RoutingService/DemoRouter" binding="wsHttpBinding" contract="System.ServiceModel.Routing.IRequestReplyRouter"></endpoint>
       </service>
    </services>

    <behaviors>
        <serviceBehaviors>
            <behavior name="MyRoutingServiceBehavior">
            <serviceMetadata httpsGetEnabled="True"/>
            <routing filterTableName="routingFilterTable"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <client>
        <endpoint name="GreetingService" address="http://localhost:6666/GreetingService/Greeting" binding="wsHttpBinding" contract="IGreetingService"></endpoint>
        <endpoint name="CalculatorService" address="net.tcp://localhost:6666/CalculatorService/Calculator" binding="netTcpBinding" contract="ICalculatorService"></endpoint>
    </client>
    <routing>
        <filters>
         <filter name="EPFilter" filterType="EndpointName" filterData="RequestReplyBindingEP"/>
          <filter name="EPAddressFilter" filterType="EndpointAddress" filterData="http://localhost:5555/RoutingService/DemoRouter"/>
        </filters>
        <filterTables>
            <filterTable name="routingFilterTable">
            <add filterName="EPFilter" endpointName="GreetingService"/>
            <add filterName="EPAddressFilter" endpointName="CalculatorService"/>
            </filterTable>
        </filterTables>
    </routing>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>

Below is detailed the sequence for the routing service configuration

1.Add routing service endpoints.

2.Add the routing service behavior along with a filter table name.

3.Add client service endpoints

4.Add the MessageFilters with filterType and filterData

5.Link the message filter with respective client endpoints through filterTable.

There is also an interesting concept called back up endpoints. The messages are routed to these back up endpoints when the main client WCF service endpoint routing fails for some reason. There can be multiple backup endpoints specified and the fail over will happen in the provided order. This is same what is mentioned in WCF 4.0 Features.

In this article, We discussed routing service.In later articles, I will cover in detail other features as well. Till then, thanks for reading...



Courtesy: Random Web Images, MSDN, Microsoft .NET 4.0 WCF Book, Several online resources 
 

Saturday, December 22, 2012

WCF 4.0 Features - Two

So in WCF 4.0 Featurewe discussed Simplified Configuration , Standard End Points, File-less Activation and Protocol bridging and Fault tolerance. Now let's move to next.

Dynamic Service and End Point discovery 

The next major WCF 4 feature we’re going to discuss is service discovery. In some specialized service oriented environments, there are services whose run-time location is dynamic and constantly changing. Even if Binding need to change at the service side from basic to WS over HTTP, This is very basic change but to accommodate this client has to update the service again. 

WS-Discovery defines two primary modes of operation: ad hoc mode and managed mode. In ad hoc mode, clients probe for services by sending multicast messages. The framework provides UDP multicast mechanism for this ad-hoc mode. Services that match the probe respond directly to the client. In order to minimize the need for client polling, services can also "announce" themselves when joining or leaving the network by sending a multicast message to clients who may be "listening". Ad hoc discovery is limited by the protocol used for multicasting messages, in the case for UDP only the services listening in on the local subnet will be able to receive the messages.


With managed service discovery, you provide a discovery proxy on the network that “manages” the discoverable service endpoints. Clients talk directly to the discovery proxy to locate services based on probing criteria. The discovery proxy needs a repository of services that it can match against the query. How the proxy is populated with this information is an implementation detail. Discovery proxies can easily be connected to an exisiting service repository, they can be pre-configured with a list of endpoints, or a discovery proxy can even listen for announcements to update its cache. In managed mode, announcements can be unicast directly to a recipient, potentially by a discovery proxy.



Simple Service Discovery 

The easiest way to enable service discovery is through the ad hoc mode.To configure your service for discovery, simply add the standard “udpDiscoveryEndpoint” endpoint and then enable the <serviceDiscovery> behavior on the service. 

Here’s a complete example illustrating how to do this:

<configuration>
    <system.serviceModel>
      <services>
        <service name="Service1">
          <endpoint binding="wsHttpBinding" contract="IService1" />
          <!-- add a standard UDP discovery endpoint-->
          <endpoint name="udpDiscovery" kind="udpDiscoveryEndpoint"/>
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior>
            <serviceDiscovery/> <!-- enable service discovery behavior -->
          </behavior>
        </serviceBehaviors>
      </behaviors>
    </system.serviceModel>
</configuration>

By doing this, your service becomes discoverable over UDP on the local subnet. Clients can then take advantage of WS-Discovery at runtime to “discover” the actual address of the running service. WCF 4 makes it easy for clients to accomplish this through the dynamicEndpoint standard endpoint.

Simply take your existing client endpoint that you were using to connect to the service, remove the address and add a kind=”dynamicEndpoint” tag.
<configuration>
    <system.serviceModel>
        <client>
          <endpoint
              name="ServiceEndpoint"
              kind="dynamicEndpoint"
              binding="wsHttpBinding"
              contract="IService1">
          </endpoint>
        </client>
    </system.serviceModel>
</configuration>
When the first service call is made, the client will send out a multicast query looking for services that match the ICalculatorService contract and attempt to connect to one. Various settings allow you to fine tune your serach, adjust the discovery bindings and control the discovery process.At Client side :-

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DiscoveryClient discoverclient = new DiscoveryClient(new UdpDiscoveryEndpoint());
            FindResponse response = discoverclient.Find(new FindCriteria(typeof(IService1)));
            EndpointAddress address = response.Endpoints[0].Address;
            Service1Client client = new Service1Client(new  WSHttpBinding(), address);
            string str= client.GetMessage("Hello WCF 4 ");
            Console.WriteLine(str);
            Console.ReadKey(true);
        }
    }
}

In this article, We discussed Dynamic Service and End Point Discovery. In later articles, I will cover in detail other features as well. Till then, thanks for reading...


Courtesy: Random Web Images, MSDN, Microsoft .NET 4.0 WCF Book, Several online resources  

Wednesday, December 12, 2012

WCF 4.0 Features

After being unavailable for such a long time I am back with The Windows Communication Foundation (WCF) 4.0 Features. Let’s Begin with enlisting few new features of WCF 4.0
  •         Simplified Configuration
  •         Standard End Points
  •         Fileless Activation
  •         Protocol bridging and Fault tolerance
  •         Dynamic Service and End Point discovery
  •         Routing Services
  •         Improved REST Support
I will discuss details of each feature in subsequent articles

 

Simplified Configuration …

The programming model offered by WCF in 3.x simplifies writing service logic for a variety of different communication scenarios, however it also increases the complexity on the configuration side of things because it provides so many different underlying communications options that you’re forced to understand before you can get started...

WCF 4 comes with a new “default configuration” model that completely removes the need for any WCF configuration. If you don’t provide any WCF configuration for a particular service, the WCF 4 run time automatically configures your service with some standard endpoints and default binding/behavior configurations. This makes it much easier to get a WCF service up and running, especially for those who aren’t familiar with the various WCF configuration options and are happy to accept the defaults, at least to get started. Let’s see how this works
   1) Service Contract :-   [ServiceContract]
                           public interface IService1
                           {
                            [OperationContract]
                             string GetData(int value);
                           }
              
S   2) Service :-   public string GetData(int value)
                           {
            return string.Format("You entered: {0}", value);                                 }
    3) Now add ConsoleApplication1 in the Solution. 
        ServiceHost serviceHost = new ServiceHost(
        typeof(WcfService1.Service1), new Uri("http://localhost:8080/Service1"));
        
        serviceHost.Open();
        System.Console.WriteLine("The Service has started");
        foreach (ServiceEndpoint se in  serviceHost.Description.Endpoints)
        {
        System.Console.WriteLine("Address:{0}, Binding:{1}, Contract:{2}", se.Address, se.Binding.Name, se.Contract.Name);
        }
    System.Console.WriteLine("Please, press any key to finish");
    System.Console.ReadLine();
    serviceHost.Close();
   4) Add following in App.config.

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled ="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="wsHttpBinding" scheme ="http"/>
    </protocolMapping>
  </system.serviceModel>
</configuration>


Output Window

When you run this program, you will see that the IService1 service contract can be accessed from the http://localhost:808/Service1 using WSHttpBinding as shown in image…

Standard endpoints in WCF 4…
Related to default endpoints is another new WCF 4 feature known as “standard endpoints”.  We can think of a standard endpoint as a common preconfigured endpoint definition built into the WCF 4 framework that we can simply use. Enlisting few of them:-
  •         mexEndpoint
  •         dynamicEndpoint
  •         discoveryEndpoint
  •         udpDiscoveryEndpoint
  •         webHttpEndpoint
Although the standard endpoints shield us from most of the configuration details and we can use them as follows 
  
<system.serviceModel>
   <services>
      <service name="GreetingService">
        <endpoint binding="basicHttpBinding" contract="IHello"/>
        <endpoint kind="mexEndpoint" address="mex“/>
      </service>
   </services>
</system.serviceModel>


Fileless Activation of WCF Service …
Every WCF service needs to have a host process. It can be a windows service, IIS or any other .NET program. This host process will create an instance of the System.ServiceModel.ServiceHost class or any custom class deriving from ServiceModel.ServiceHostBase.

This host class will manage the service configurations, behaviors, channels and make it accessible to the outside world. When a service is hosted in IIS it behaves a little bit differently. Here we need to create a physical file with .svc extension in the virtual directory of the web server. This file actually points to the service class implementing the Service Contract and System.ServiceModel.Activation.ServiceHostFactory or a derived class ServiceModel.Activation.ServiceHostFactoryBase. 

When IIS receives a request with that .svc file in URI the corresponding ServiceHostFactory creates an instance of the Service Host. The mark-up contained in a .svc file is shown below:-
<%@ ServiceHost Language="C#" Debug="true" Factory="System.ServiceModel.Activation.ServiceHostFactory" Service="TestService" CodeBehind="TestService.svc.cs" %>

In WCF 4.0 we can create and deploy services in IIS without a physical file in the virtual directory. This can be done using the serviceActivations configuration in the system.serviceModel configuration in web.config as shown below:-
<serviceHostingEnvironment > 
  <ServiceActivations>
    <add factory="System.ServiceModel.Activation.ServiceHostFactory"   
     relativeAddress="/Payment" service="PaymentService"/>
  </ServiceActivations >
</serviceHostingEnvironment>

There is no physical file named Payment.svc but still we’ll able to access the service at http://localhost/Payment.svc , This is the new Fileless Activation feature introduced in .NET 4.0.

Protocol bridging and Fault tolerance …
Protocol bridging is basically used for transportation. Client sends message to Routing Service via HTTP .Routing Service will send the message to Back end WCF Service via TCP/IP. Here we are using Protocol bridging between HTTP AND TCP/IP.


The Routing Service also provides a built-in mechanism to deal with run time communication errors and to support a basic level of fault tolerance. When defining your filter table, you can define different lists of alternate endpoints that will be used by the Routing Service if communicating with the initial target endpoint results in an error. This essentially makes it possible to have lists of “backup” endpoints. 
I’ll try to explain these more when discussing Routing Service. In Next article we will discus more about routing service, Rest Improvements & End Point discovery etc.... 

Courtesy: Random Web Images, MSDN, Microsoft .NET 4.0 WCF Book, Several online resources