Friday 14 October 2011

step 7&8

Step 6: Create the console client application and name it as DurableServiceClient
Step 7: Add following reference to client application
  • System.ServiceModel
  • System.WorkflowService

How to Create Durable Service( step 2 to 5)

Step 2: Create interface and decorate with Service and Operation contract.
    [ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract]
        int Add(int num);

        [OperationContract]
        int Subtract(int num);

        [OperationContract]
        int Multiply(int num);

        [OperationContract]
        void EndPersistence();
    }
 
Step 3: You need to add [Serializable] And [DurableService()] attribute to the service implementation. Set CanCreateInstance = true property to the operation in which instance state has to be persisted and set CompletesInstance = true when state has to be destroyed. In this implementation, we are going to persist the 'currentValue' variable value to the database.
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Description;
    [Serializable]
    [DurableService()]
    public class SimpleCalculator :ISimpleCalculator 
    {
        int currentValue = default(int);
        [DurableOperation(CanCreateInstance = true)]
        public int Add(int num)
        {
            return (currentValue += num);
        }
        [DurableOperation()]
        public int Subtract(int num)
        {
            return (currentValue -= num);
        }
        [DurableOperation()]
        public int Multiply(int num)
        {
            return (currentValue *= num);
        }
        [DurableOperation(CompletesInstance = true)]
        public void EndPersistence()
        {
        }
Step 4: Before configuring the database information in the durable service, you need to set up DataStore environment. Microsoft provides inbuilt sqlPersistance provider. To set up the database environment, run the these sql query located at following location 'C:\Windows\Microsoft.NET\Framework\v3.5\SQL\EN'
  • SqlPersistenceProviderSchema.sql
  • SqlPersistenceProviderLogic.sql
Step 5: In order to support durable service, you need to use Context binding type. <persistenceProvider> tag is used to configure the persistence provider.
<system.serviceModel>
 <services>
  <service name="SimpleCalculator" behaviorConfiguration="ServiceBehavior">
  <!-- Service Endpoints -->
  <endpoint address="" binding="wsHttpContextBinding" 
  bindingConfiguration="browConfig" contract="ISimpleCalculator">
  <identity>
  <dns value="localhost"/>
  </identity>
  </endpoint>
  <endpoint address="mex" binding="mexHttpBinding" 
  contract="IMetadataExchange"/>
  </service>
 </services>
 <behaviors>
  <serviceBehaviors>
  <behavior name="ServiceBehavior">
  <serviceMetadata httpGetEnabled="true"/>
 <serviceDebug includeExceptionDetailInFaults="true"/>
    <persistenceProvider  
     type="System.ServiceModel.Persistence.SqlPersistenceProviderFactory,
        System.WorkflowServices, Version=3.5.0.0, Culture=neutral,
         PublicKeyToken=31bf3856ad364e35" connectionStringName="DurableServiceStore" 
                               persistenceOperationTimeout="00:00:10"
                               lockTimeout="00:01:00"
                               serializeAsText="true"/>
   </behavior>
   </serviceBehaviors>
  </behaviors>
    <bindings>
      <wsHttpContextBinding >
        <binding name="browConfig" >
          <security mode="None"></security>
        </binding>
      </wsHttpContextBinding>
    </bindings>
</system.serviceModel>
<connectionStrings>
<add name="DurableServiceStore" 
connectionString="Data Source=saravanakumar;Initial Catalog
=DurableServiceStore;Integrated Security=True"/>
</connectionStrings>

How to Create Durable Service

Let us understand more about the durable service by creating Simple Calculator service which persist the instance state in SQL server database.
Step 1: Start the Visual Studio 2008 and click File->New->Web Site. Select the 'WCF Service' as shown below.

Instance Deactivation

In Instance Management System tutorial, you learn how to create sessionful service instance. Basically service instance is hosted in a context. Session actually correlated the client message not to the instance, but to the context that host it. When session starts, context is created and when it closes, context is terminated. WCF provides the option of separating the two lifetimes and deactivating the instance separately from its context.
ReleaseInstanceMode property of the OberationalBehavior attribute used to control the instance in relation to the method call.
Followings are the list Release mode available in the ReleaseInstanceMode
  1. RealeaseInstanceMode.None
  2. RealeaseInstanceMode.BeforeCall
  3. RealeaseInstanceMode.AfterCall
  4. RealeaseInstanceMode.BeforeAndAfterCall
Below code show, how to add the 'ReleaseInstanceMode' property to the operational behavior.
    [ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
   [OperationBehavior(ReleaseInstanceMode=ReleaseInstanceMode.BeforeCall]
    public int Add(int num1, int num2)
    {
        return num1 + num2;            
    }

ReleaseInstanceMode.None

This property means that it will not affect the instance lifetime. By default ReleaseInstanceMode property is set to 'None'.

ReleaseInstanceMode.BeforeCall

This property means that it will create new instance before a call is made to the operation.
If the instance is already exist,WCF deactivates the instance and calls Dispose() before the call is done. This is designed to optimize a method such as Create()

ReleaseInstanceMode.AfterCall

This property means that it will deactivate the instance after call is made to the method.
This is designed to optimize a method such a Cleanup()

ReleaseInstanceMode.BeforeAndAfterCall

This is means that it will create new instance of object before a call and deactivates the instance after call. This has combined effect of using ReleaseInstanceMode.BeforeCall and ReleaseInstanceMode.AfterCall

Explicit Deactivate

You can also explicitly deactivate instance using InstanceContext object as shown below.
   [ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        void MyMethod();
    }

   
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class MyService:IMyService
    {

        public void MyMethod()
        {
           //Do something
           OperationContext.Current.InstanceContext.ReleaseServiceInstance();
            
        }       
    }
 

Singleton Service

When WCF service is configured for Singleton instance mode, all clients are independently connected to the same single instance. This singleton instance will be created when service is hosted and, it is disposed when host shuts down.
Following diagram represent the process of handling the request from client using Singleton instance mode.
Let as understand the Singleton Instance mode using example.
Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to Single as show below.
    [ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        int MyMethod();
    }
Step 2: In this implementation of MyMethod operation, increment the static variable(m_Counter). Each time while making call to the service, m_Counter variable is incremented and return the value to the client
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class MyService:IMyService
    {
        static int m_Counter = 0;

        public int MyMethod()
        {
            m_Counter++;
            return m_Counter;
        }       
    }
Step 3: Client side, create the two proxies for the service and made a multiple call to MyMethod.
static void Main(string[] args)
        {
Console.WriteLine("Service Instance mode: Singleton");
            Console.WriteLine("Client 1 making call to service...");
            //Creating the proxy on client side
            MyCalculatorServiceProxy.MyServiceProxy proxy = 
            new MyCalculatorServiceProxy.MyServiceProxy();
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());

            Console.WriteLine("Client 2 making call to service...");
            //Creating new proxy to act as new client
            MyCalculatorServiceProxy.MyServiceProxy proxy2 =
             new MyCalculatorServiceProxy.MyServiceProxy();
            Console.WriteLine("Counter: " + proxy2.MyMethod());
            Console.WriteLine("Counter: " + proxy2.MyMethod());
            Console.ReadLine();
  }
  
When two proxy class made a request to service, single instance at service will handle it and it return incremented value (1, 2, 3, 4), because instance mode is configured to 'Single'. Service instance is created when it is hosted. So this instance will remain till host is shutdown. Output is shown below.

Per-Session Service

When WCF service is configured for Per-Session instance mode, logical session between client and service will be maintained. When the client creates new proxy to particular service instance, a dedicated service instance will be provided to the client. It is independent of all other instance.
Following diagram represent the process of handling the request from client using Per-Session instance mode.
Let as understand the Per-Session instance mode using example.
Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerSession as show below.
    [ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        int MyMethod();
    }
Step 2: In this implementation of MyMethod operation, increment the static variable (m_Counter). Each time while making call to the service, m_Counter variable will be incremented and return the value to the client.
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
    public class MyService:IMyService
    {
        static int m_Counter = 0;

        public int MyMethod()
        {
            m_Counter++;
            return m_Counter;
        }       
    }
Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time.
        static void Main(string[] args)
        {
            Console.WriteLine("Service Instance mode: Per-Session");
            Console.WriteLine("Client  making call to service...");
            //Creating the proxy on client side
            MyCalculatorServiceProxy.MyServiceProxy proxy = 
            new MyCalculatorServiceProxy.MyServiceProxy();
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.ReadLine();
        }
All request to service return incremented value (1, 2, 3, 4), because we configured the instance mode to Per-Session. Service instance will be created once the proxy is created at client side. So each time request is made to the service, static variable is incremented. So each call to MyMethod return incremented value. Output is shown below.

Per-Call Service

When WCF service is configured for Per-Call instance mode, Service instance will be created for each client request. This Service instance will be disposed after response is sent back to client.
Following diagram represent the process of handling the request from client using Per-Call instance mode.
Let as understand the per-call instance mode using example.
Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerCall as show below.
[ServiceContract()]
    public interface IMyService
    {
        [OperationContract]
        int MyMethod();
    }
Step 2: In this implementation of MyMethod operation, increment the static variable(m_Counter). Each time while making call to the service, m_Counter variable is incremented and return the value to the client.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
    public class MyService:IMyService
    {
        static int m_Counter = 0;

        public int MyMethod()
        {
            m_Counter++;
            return m_Counter;
        }       
    }
 
Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time.
static void Main(string[] args)
        {
            Console.WriteLine("Service Instance mode: Per-Call");
            Console.WriteLine("Client  making call to service...");
            //Creating the proxy on client side
            MyCalculatorServiceProxy.MyServiceProxy proxy =
             new MyCalculatorServiceProxy.MyServiceProxy();
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.WriteLine("Counter: " + proxy.MyMethod());
            Console.ReadLine();
}
Surprisingly, all requests to service return '1', because we configured the Instance mode to Per-Call. Service instance will created for each request and value of static variable will be set to one. While return back, service instance will be disposed. Output is shown below.
Fig: PercallOutput.

Fault Contract

Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific.
In order to support interoperability and client will also be interested only, what wents wrong? not on how and where cause the error.
By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.
Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error accorded in the service to client. This help as to easy identity the what error has accord. Let us try to understand the concept using sample example.
Step 1: I have created simple calculator service with Add operation which will throw general exception as shown below
//Service interface
[ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
//Service implementation
public  class SimpleCalculator : ISimpleCalculator
    {
    
        public int Add(int num1, int num2)
        {
            //Do something
            throw new Exception("Error while adding number");
            
        }

    }

Step 2: On client side code. Exceptions are handled using try-Catch block. Even though I have capture the exception when I run the application. I got the message that exceptions are not handled properly.
try
   {
      MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy
       = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
      Console.WriteLine("Client is running at " + DateTime.Now.ToString());
      Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
      Console.ReadLine();
   }
   catch (Exception ex) 
   {
      Console.WriteLine(ex.Message);
      Console.ReadLine();
   }
Step 3: Now if you want to send exception information form service to client, you have to use FaultException as shown below.
        public int Add(int num1, int num2)
        {
            //Do something
            throw new FaultException("Error while adding number");
            
        }
Step 4: Output window on the client side is show below.
Step 5: You can also create your own Custom type and send the error information to the client using FaultContract. These are the steps to be followed to create the fault contract.
  • Define a type using the data contract and specify the fields you want to return.
  • Decorate the service operation with the FaultContract attribute and specify the type name.
  • Raise the exception from the service by creating an instance and assigning properties of the custom exception.
Step 6: Defining the type using Data Contract
    [DataContract()]
    public class CustomException
    {
        [DataMember()]
        public string Title;
        [DataMember()]
        public string ExceptionMessage;
        [DataMember()]
        public string InnerException;
        [DataMember()]
        public string StackTrace;        
    }
Step 7: Decorate the service operation with the FaultContract
    [ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        [FaultContract(typeof(CustomException))]
        int Add(int num1, int num2);
    }
Step 8: Raise the exception from the service
        public int Add(int num1, int num2)
        {
            //Do something
            CustomException ex = new CustomException();
            ex.Title = "Error Funtion:Add()";
            ex.ExceptionMessage = "Error occur while doing add function.";
            ex.InnerException = "Inner exception message from serice";
            ex.StackTrace = "Stack Trace message from service.";
            throw new FaultException(ex,"Reason: Testing the Fault contract") ;
            
        }
Step 9: On client side, you can capture the service exception and process the information, as shown below.
   try
   {
      MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy 
      = new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
       Console.WriteLine("Client is running at " + DateTime.Now.ToString());
       Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
       Console.ReadLine();
    }
    catch (FaultException<MyCalculatorService.CustomException> ex)
     {
        //Process the Exception
     }

Message Contract

Message

Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination.
WCF uses SOAP(Simple Object Access Protocol) Message format for communication. SOAP message contain Envelope, Header and Body.SOAP envelope contails name, namespace,header and body element. SOAP Hear contain important information which are not directly related to message. SOAP body contains information which is used by the target.
Diagram Soap envelope

Message Pattern

It describes how the programs will exchange message each other. There are three way of communication between source and destination
  1. Simplex - It is one way communication. Source will send message to target, but target will not respond to the message.
  2. Request/Replay - It is two way communications, when source send message to the target, it will resend response message to the source. But at a time only one can send a message
  3. Duplex - It is two way communication, both source and target can send and receive message simultaniouly.

What is Message contract?

As I said earlier, WCF uses SOAP message for communication. Most of the time developer will concentrate more on developing the DataContract, Serializing the data, etc. WCF will automatically take care of message. On Some critical issue, developer will also require control over the SOAP message format. In that case WCF provides Message Contract to customize the message as per requirement.
WCF supports either RPC(Remote Procedure Call) or Message style operation model. In the RPC model, you can develop operation with Ref and out parameter. WCF will automatically create the message for operation at run time. In Message style operation WCF allows to customize the message header and define the security for header and body of the message.

Defining Message Contract

Message contract can be applied to type using MessageContract attribute. Custom Header and Body can be included to message using 'MessageHeader' and 'MessageBodyMember'atttribute. Let us see the sample message contract definition.
[MessageContract]
public class EmployeeDetails
{
    [MessageHeader]
    public string EmpID;
    [MessageBodyMember]
    public string Name;
    [MessageBodyMember]
    public string Designation;
    [MessageBodyMember]
    public int Salary;
    [MessageBodyMember]
    public string Location;
}
When I use this EmployeeDeatils type in the service operation as parameter. WCF will add extra header call 'EmpID' to the SOAP envelope. It also add Name, Designation, Salary, Location as extra member to the SOAP Body.

Rules :

You have to follow certain rules while working with Message contract
  1. When using Message contract type as parameter, Only one parameter can be used in servicie Operation
    [OperationContract]
    void SaveEmployeeDetails(EmployeeDetails emp);
    
  2. Service operation either should return Messagecontract type or it should not return any value
    [OperationContract]
    EmployeeDetails GetEmployeeDetails();
    
  3. Service operation will accept and return only message contract type. Other data types are not allowed.
    [OperationContract]
    EmployeeDetails ModifyEmployeeDetails(EmployeeDetails emp);
     
Note: If a type has both Message and Data contract, service operation will accept only message contract.

Data Contract

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.
Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.
A data contract can be defined as follows:
  • It describes the external format of data passed to and from service operations
  • It defines the structure and types of data exchanged in service messages
  • It maps a CLR type to an XML Schema
  • t defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through deserialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
  • It is a versioning system that allows you to manage changes to structured data
We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute.
Create user defined data type called Employee. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute.
 [ServiceContract]
    public interface IEmployeeService
    {
        [OperationContract]
        Employee GetEmployeeDetails(int EmpId);
    }

    [DataContract]
    public class Employee
    {
        private string m_Name;
        private int m_Age;
        private int m_Salary;
        private string m_Designation;
        private string m_Manager;

        [DataMember]
        public string Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }

        [DataMember]
        public int Age
        {
            get { return m_Age; }
            set { m_Age = value; }
        }

        [DataMember]
        public int Salary
        {
            get { return m_Salary; }
            set { m_Salary = value; }
        }

        [DataMember]
        public string Designation
        {
            get { return m_Designation; }
            set { m_Designation = value; }
        }

        [DataMember]
        public string Manager
        {
            get { return m_Manager; }
            set { m_Manager = value; }
        }

    }
Implementation of the service class is shown below. In GetEmployee method we have created the Employee instance and return to the client. Since we have created the data contract for the Employee class, client will aware of this instance whenever he creates proxy for the service.
public class EmployeeService : IEmployeeService
    {
        public Employee GetEmployeeDetails(int empId)
        {
            
            Employee empDetail = new Employee();

            //Do something to get employee details and assign to 'empDetail' properties

            return empDetail;
        }
    }

Client side

On client side we can create the proxy for the service and make use of it. The client side code is shown below.
protected void btnGetDetails_Click(object sender, EventArgs e)
        {
            EmployeeServiceClient objEmployeeClient = new EmployeeServiceClient();
            Employee empDetails;
            empDetails = objEmployeeClient.GetEmployeeDetails(empId);
//Do something on employee details
        }

Service Contract

Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.
Service Contract can be define using [ServiceContract] and [OperationContract] attribute. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService.
  • It describes the client-callable operations (functions) exposed by the service
  • It maps the interface and methods of your service to a platform-independent description
  • It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern
  • It is analogous to the element in WSDL
To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the OperationContract Attribute.
[ServiceContract()]
    public interface ISimpleCalculator
    {
        [OperationContract()]
        int Add(int num1, int num2);
    }
Once we define Service contract in the interface, we can create implement class for this interface.
public  class SimpleCalculator : ISimpleCalculator
    {
    
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }

    }
With out creating the interface, we can also directly created the service by placing Contract in the implemented class. But it is not good practice of creating the service
[ServiceContract()]
   public class SimpleCalculator 
   {
       [OperationContract()]
       public int Add(int num1, int num2)
       {
           return num1 + num2;
       }

   }
Now you have some fundamental idea on Service contract. Next we will look into Data Contract.

Metadata Exchange Endpoint

Exposing the metadata using HTTP-GET has a disadvantage, such that there is no guarantee that other platforms you interact will support it. There is other way of exposing the using special endpoint is called as Metadata Exchange Endpoint. You can have as many metadata exchange endpoints as you want.

Address

It is basically Uri to identify the metadata. You can specify as address in the endpoint but append with "mex" keyword. For example "http://localhost:9090/MyCalulatorService/mex"

Binding

There are four types of bindings supported for metadata exchange. They are mexHttpBinding, mexHttpsBinding, mexNamedPipesBinding, mexTcpBinding.

Contract

IMetadataExchange is the contract used for MEX endpoint. WCF service host automatically provides the implementation for this IMetadataExcahnge while hosting the service.
You can create the Metadata Exchange Endpoint either Administrative (configuration file) or programmatically.

Administrative (Configuration file):

In the configuration file of the hosting application, you can add metadata exchange endpoint as shown below.
<system.serviceModel>
<services>
 <service name="MyService">
 <endpoint address="http://localhost/IISHostedService/MyService.svc"
 binding="wsHttpBinding" contract="IMyService">
 <identity>
 <dns value="localhost"/>
 </identity>
 </endpoint>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
 </service>
</services>  
</system.serviceModel>

Programming Model:

In the following code I have mention about creating the Metadata Exchange Endpoint through coding. Steps to create the metadata endpoint are
  • Create the ServiceMetadataBehavior object and add to Service host description.
  • ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                host.Description.Behaviors.Add(smb);
  • Create the metadata binding object using MetadataExchangeBinding
  • Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding ();
  • 3. Add the endpoint to the service host with address, binding and contract.
  • host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
Complete code for hosting the service with metadata exchange endpoint is shown below.
//Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
            //Create ServiceHost
            ServiceHost host = new 
            ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
            //Add a service endpoint
            host.AddServiceEndpoint
            (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            host.Description.Behaviors.Add(smb);
            Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding ();
            //Adding metadata exchange endpoint
            host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
            //Start the Service
            host.Open();

            Console.WriteLine("Service is host at " + DateTime.Now.ToString());
            Console.WriteLine("Host is running... Press  key to stop");
            Console.ReadLine();

HTTP_GET Enabled Metadata

We will use ServiceBehaviour to publish the metadata using HTTP-GET. This can be configures either administratively or Programmatically. Http and Https can expose by appending "?wsdl" to the end of the service address. For example service address is http://localhost:9090/MyCalulatorService , HTTP-Get metadata address is given by http://localhost:9090/MyCalulatorService?wsdl.

Administrative (Configuration file):

In the below mention configuration information, you can find the behavior section in the ServiceBehavior. You can expose the metadata using ServiceMetadata node with httpGetEnable='True'.
<system.serviceModel>
   <services>
 <service behaviorConfiguration="ServiceBehavior" name="MyService">
    <endpoint address="http://localhost/IISHostedService/MyService.svc"
     binding="wsHttpBinding" contract="IMyService">
  <identity>
  <dns value="localhost"/>
  </identity>
     </endpoint>
 </service>
  </services>
  <behaviors>
    <serviceBehaviors>
 <behavior name="ServiceBehavior">
   <!-Setting httpGetEnabled you can publish the metadata -->
  <serviceMetadata httpGetEnabled="true"/>
  </behavior>
     </serviceBehaviors>
   </behaviors>
</system.serviceModel>

Progarmming Model:

Using ServiceMetadataBehavior you can enable the metadata exchange. In the following code, I have created the ServiceMetadataBehavior object and assigned HttpGetEnabled property to true. Then you have to add the behavior to host description as shown. This set of code will publish the metadata using HTTP-GET.
 //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
            //Create ServiceHost
            ServiceHost host = new 
            ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
            //Add a service endpoint
            host.AddServiceEndpoint
            (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

            //Enable metadata exchange using HTTP-GET
            smb.HttpGetEnabled = true;

            host.Description.Behaviors.Add(smb);
            //Start the Service
            host.Open();
            Console.WriteLine("Service is host at " + DateTime.Now.ToString());
            Console.WriteLine("Host is running... Press  key to stop");
            Console.ReadLine();

Types of Binding

Let us see more detailed on predefined binding

BasicHttpBinding

  • It is suitable for communicating with ASP.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services.
  • This binding uses HTTP as the transport and text/XML as the default message encoding.
  • Security is disabled by default
  • This binding does not support WS-* functionalities like WS- Addressing, WS-Security, WS-ReliableMessaging
  • It is fairly weak on interoperability.

WSHttpBinding

  • Defines a secure, reliable, interoperable binding suitable for non-duplex service contracts.
  • It offers lot more functionality in the area of interoperability.
  • It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security.
  • It uses HTTP and HTTPS transport for communication.
  • Reliable sessions are disabled by default.

WSDualHttpBinding

This binding is same as that of WSHttpBinding, except it supports duplex service. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback.
In WSDualHttpBinding reliable sessions are enabled by default. It also supports communication via SOAP intermediaries.

WSFederationHttpBinding

This binding support federated security. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization. It supports WS-Federation protocol.

NetTcpBinding

This binding provides secure and reliable binding environment for .Net to .Net cross machine communication. By default it creates communication stack using WS-ReliableMessaging protocol for reliability, TCP for message delivery and windows security for message and authentication at run time. It uses TCP protocol and provides support for security, transaction and reliability.

NetNamedPipeBinding

This binding provides secure and reliable binding environment for on-machine cross process communication. It uses NamedPipe protocol and provides full support for SOAP security, transaction and reliability. By default it creates communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding.

NetMsmqBinding

  • This binding provides secure and reliable queued communication for cross-machine environment.
  • Queuing is provided by using MSMQ as transport.
  • It enables for disconnected operations, failure isolation and load leveling

NetPeerTcpBinding

  • This binding provides secure binding for peer-to-peer environment and network applications.
  • It uses TCP protocol for communication
  • It provides full support for SOAP security, transaction and reliability.

Bindings and Channel Stacks

In WCF all the communication details are handled by channel, it is a stack of channel components that all messages pass through during runtime processing. The bottom-most component is the transport channel. This implements the given transport protocol and reads incoming messages off the wire. The transport channel uses a message encoder to read the incoming bytes into a logical Message object for further processing.
Figure 1: Bindings and Channel Stacks (draw new diagram)
After that, the message bubbles up through the rest of the channel stack, giving each protocol channel an opportunity to do its processing, until it eventually reaches the top and WCF dispatches the final message to your service implementation. Messages undergo significant transformation along the way.
It is very difficult for the developer to work directly with channel stack architecture. Because you have to be very careful while ordering the channel stack components, and whether or not they are compatible with one other.
So WCF provides easy way of achieving this using end point. In end point we will specify address, binding and contract. To know more about end point. Windows Communication Foundation follows the instructions outlined by the binding description to create each channel stack. The binding binds your service implementation to the wire through the channel stack in the middle.

step 9

Step 10: Build the project, we will get the WCFHostedWindowsService.exe. Next we need to install the service using Visual Studio Command Prompt. So open the command prompt by clicking Start->All Programs-> Microsoft Visual Studio 2008-> Visual Studio Tools-> Visual Studio Command Prompt Using installutil utility application, you can install the service as shown below.
 Step 11: Now service is Hosted sucessfully and we can create the proxy class for the service and start using in the client applcaiton.