Friday, August 21, 2009

WCF a Developers look

Service Orientation has changed the way the software is being developed now. It's not just the change in the development; it has brought out an out change in the way the applications are used. Now we can communicate with any system in any island using the Service Oriented Communication…well well if the applications are SOA complaint

What is a Service?

Services are autonomous applications which can expose some functionality to other systems through standard protocols. A service can be consumed in a host application by abiding the contract provided by the service.

Lets try to understand what it is.

What do we do if we have to subscribe to a Mobile communication service?

We abide a contract with the service provider. The contract may include

  1. Type of the service
  2. The usage plan
  3. The extra usage plan
  4. The defaulting penalty
Once we sign the contract, we start getting the service and it continues until we follow the contract. We use the service, but are not known with the intricacies of the operation of the service provider.

Like this in Service Orientation, if we are in need of a particular service; we agree with the contract provided by the service. The service might be running at a remote location, but still it would be the part of our system and the actions are hidden from the host.

Service Orientation is implemented using public standards if the applications are in different platforms or proprietary standards if the applications are of the same platforms. Web Service implemented using SOAP protocol is an example for public standards. And Remoting, CORBA etc are examples for proprietary standards.

The concepts are the same, but based on our choice we have to opt among public / proprietary techniques. The implementation and the development are different for both the techniques. How would it be, if we are given with single development method but multiple options (public / proprietary) for implementation? Windows Communication Foundation does exactly that. The development for the services is unified but WCF provides us the multiple options for consumption using the configuration.

The service oriented application development goes this way

  1. Service Contract Creation
  2. Service Implementation
  3. Service Hosting
  4. Service Consumption
Let's now write a WCF service. The steps to be followed are

  1. Define a service Contract
  2. Implement the service contract
  3. A host process to run the services
  4. Endpoint configuration in the client to access the service
We are going to create a simple arithmetic operation service, which would be hosted as normal webservice

The Service Contract






using System;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace SampleService
{
    [ServiceContract]
    public interface IArithematicOperation
    {
        [OperationContract]
        int add(int first, int second);
        [OperationContract]
        int Substract(int first, int second);
    }
}



In Object Orientated programming, the Interfaces are used for defining the contracts. The contract definition using the interfaces and the implementation using the concrete classes is referred to as contact-first style.

When we mark a class with 'ServiceContract' and the methods as 'OperationContract', the service contract definitions is automatically generated in WSDL.

Now we have to implement the contract.

The Service Implementation







using System;
using System.ServiceModel;
namespace SampleService
{
    public class ArithematicOperationService : IArithematicOperation
    {
        public int add(int first, int second)
        {
            return first + second;
        }
        public int Substract(int first, int second)
        {
            return first - second;
        }
    }
}

The service implementation is straight forward and the class implements all the methods mentioned in the service contract

Hosting Options in WCF

Windows Communication Foundation again gives us choices for hosting the services. The services could be hosted in any of these

  1. IIS
  2. Windows Process Activation Services (WAS) – In Windows Vista or Windows Server 2008
  3. Self Hosting (Any managed .NET application, including WWF, winForm application, Windows Process, Console Applications)
We are now going to host our service in IIS. The IIS hosting is quite simple.

We need to have a virtual directory created in the IIS. Copy the dlls to the virtual directory (Bin folder). We now have to create the host. Open note pad and type the following

<%@ServiceHost language=c# Service="SampleService.ArithematicOperationService" %>

Save the file as ArithematicOperation.svc in the virtual directory

The hosted services have to be exposed through the endpoints in the configuration file. The endpoints are referred as the ABC of the WCF. The endpoint defines

The Address: URLs that identify the machine and the endpoint

The Binding: Determines how these endpoints are accessed. Depending upon the binding the schema of the URL also would be changed.

The Contract: The name of the class/interface which this endpoint exposes. The class/interface should be the one which is decorated with ServiceContract attribute.

In the beginning I mentioned, WCF provides single way of development and multiple ways for hosting and accessing. The endpoint bindings allows us to consume the same service in different protocols viz, webservices, Message Queues and Remoting. Moreover we could also develop our own custom bindings.

Among the WCF bindings most important are the following:

  • BasicHttpBinding: Conforms to the Web Services Interoperability Organization (WS-I) Basic Profile 1.0, which specifies SOAP over HTTP. This binding can also be configured to use HTTPS as specified by the WS-I Basic Security Profile 1.0. It can also be configured to send either standard text or the optimized form defined by MTOM.
  • WsHttpBinding: Uses SOAP over HTTP, like BasicProfileBinding, but also supports reliable message transfer with WS-ReliableMessaging, security with WS-Security, and transactions with WS-AtomicTransaction. This binding allows interoperability with other Web services implementations that also support these specifications.
  • NetTcpBinding: Sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. This binding can be used only for WCF-to-WCF communication.
  • WebHttpBinding: Sends information directly over HTTP or HTTPS—no SOAP envelope is created. This binding is new with the .NET Framework 3.5 version of WCF, and it's the right choice for RESTful communication and other situations where SOAP isn't required. The binding offers three options for representing content: text-based XML encoding, JavaScript Object Notation (JSON) encoding, and opaque binary encoding.
  • NetNamedPipesBinding: Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.
  • NetMsmqBinding: Sends binary-encoded SOAP over MSMQ, as described later in this paper. This binding can only be used for WCF-to-WCF communication.
Lets define the endpoints in the web.config file



<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service  name="SampleService.ArithematicOperationService" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint
          contract="SampleService.IArithematicOperation"
          binding="basicHttpBinding"
          address=
            "http://localhost/wcfSampleService/ArithematicOperation.svc"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors" >
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

We have developed the service and hosted it in IIS with required endpoint access. Now we will develop a client to consume the service.

Create a console application, add the service reference as http://localhost/wcfSampleService/ArithematicOperation.svc and specify the service namespace as 'ArithematicOperation'. This activity would create the necessary proxy classes for the service. In the Main() method write the following code






namespace ServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ArithematicOperations.ArithematicOperationClient obj = new ServiceTest.ArithematicOperations.ArithematicOperationClient();
            Console.WriteLine("The Service result for Add={0}" ,obj.add(10, 20));
            Console.WriteLine("The Service result for Substarction={0}",obj.Substract(20, 10));
            Console.Read();
        }
    }
}

Voilaaa!!! We've done with our service consumption also.

We just covered the basics of the WCF services. In the future post I would cover the some more basics and advanced topics related to the WCF services.

No comments:

Post a Comment