1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Service Contract in WCF

Discussion in 'ASP.NET' started by MinalS, Nov 5, 2014.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    30
    Trophy Points:
    0
    Service Contract describes the operations implemented by the service. The contract maps the class methods of the .NET type to WSDL services, port types, and operations. The message format is referred and describes how the messages are exchanged. They are later described as data contract and message contracts.

    Service Contract is used at design time for identifying the classes in the code. The class is marked as [ ServiceContract ] and the methods in it are marked as
    [ OperationContract ].

    Synchronous Request – Response Operations

    The synchronous request – response message exchange is used widely in the service functions. The pattern is useful in both local and remote procedure calls.

    The following diagram shows the request response communication, the proxy from the client side send a request to the service and the service responds synchronously back to the client.

    [​IMG]

    WCF service provides user with the request – response communication between the client and the service. The user uses the Add Service Reference to call the endpoint and generate the client side proxy. The proxy serializes the method name and parameters into a SOAP message, forwards the message to the service, listens the message and creates a .NET type representing the message response from the service.

    The following code defines the service contract definition. The service contract and the operation contract are defined in the code. The operation contract represents the method that can be called by a client.

    The following code represents the service created by the application.
    Code:
    using System;
    using System.ServiceModel;
    
    namespace WCFapplication1
    {
    	[ ServiceContract ]
    	public interface ISaleInfo
    	{
    		[ OperationContract ]
    		double Price ( string ProductName );
    	}
    	public class SaleInfo: ISaleInfo
    	{
    		public double Price ( string ProductName )
    		{
    			return 1200.50;
    		}
    	}
    }
    
    The client code contains the proxy generated after creating the AddServiceReference. The following code demonstrates the client application for the service.
    Code:
    using System;
    using System.ServiceModel;
    
    namespace client
    {
    	class client
    	{
    		static void Main ( string[] args )
    		{
    			localhost.SaleInfoClient proxy=new localhost.SaleInfoClient();
    			double price=proxy.GetPrice(“Books”);
    			Console.WriteLine (“ Books: {0}”, price );
    			proxy.Close();
    		}
    	}
    }
    
    Asynchronous Request – Response Operations

    In WCF, the request response operations the client waits while the service operation is executing. The svcutil.exe uses the blocking call for the WCF channel. The client application is blocked for time duration. The freezing time for the client is the time required for the service to response.

    The .NET framework asynchronous pattern is used with the proxy generated by the util file. The following figure demonstrates the asynchronous request response communication.

    [​IMG]

    The code to demonstrate the request response client using the asynchronous pattern is as shown below:
    Code:
    using System;
    using System.Threading;
    
    namespace asynchronous1
    {
    	class Program
    	{
    		static int a = 0;
    	static void Main ( string[ ] args )
    	{
    		Clientdata proxy = new Clientdata();
    		IAsyncResult GetValue;
    		for ( int i =0; i<10; i++ )
    		{
    			GetValue=proxy.BeginPrice(“ Books”, GetPriceCallBack, proxy );
    			Interlocked.Increment ( ref x );
    		}
    		while ( x > 0 )
    		{
    			Thread.Sleep ( 1000 );
    			Console.WriteLine ( “Waiting …. “);
    		}
    		proxy.Close();
    		Console.WriteLine(“Completed”);
    	}
    
    	static void GetPriceCallback ( IAsyncResult ar )
    	{
    		double d = (( ServiceClient ) ar.AsyncState).EndGetPrice (ar);
    		Interlocked.Decrement ( ref i );
    	}
    	}
    }
    
    One Way Operations

    The one way communication states that the client sends the information to a service. The response is not received by the client. The client gets the acknowledgement of the delivery but it does not wait for the response from the server.

    The one way operation is supported by the WCF service. The [ OperationContract ] attribute is added to the code. The attribute IsOneWay = true modifier is used for one way operations.

    The following code demonstrates the one way operation in WCF.
    Code:
    [ ServiceContract ]
    public interface IStudentData
    {
    	[ OperationContract ( IsOneWay = true ) ]
    	void StudName ( string name )
    	
    	[ OperationContract ]
    	void StudCourse( string cousename )
    	
    }
    
    public class StudentData : IStudentData
    {
    	public void StudName ( string name )
    	{
    		Thread.Sleep(15000);
    	}
    	public void StudCourse ( string coursename )
    	{
    		Thread.Sleep ( 20000);
    	}
    }
    
    In the above code, there are two service operations in the service contract. The code implementation is similar but the one is marked as one way operation. The client application calls the StudName, the client proxy returns immediately. There is no waiting time even if the service is in Thread.Sleep statement.

    When the client calls the StudCourse, the client proxy call blocks for twenty seconds when the service executes the Thread.Sleep statement.

    Duplex Operations

    Request response communication is the widely used communication pattern between the client and the service. The client initiates the communication, the request message is send to the service, and then the response message is sent back to the client. User can implement synchronously if the response is expected quickly. If there is a delay between the client and the response, the request – response pattern is implemented asynchronously.

    The bidirectional communication is enabled through duplex service contract. The messages can be sent in any direction after the channel is established between the client and the server. As it is bidirectional communication, both the client and the server need the address, binding, and contract defining where, how and what messages can be sent.

    WCF creates a second channel through the same protocol when the initial channel does not support bidirectional communication.

    The following figure shows the duplex communication in WCF.

    [​IMG]

    To overcome the problem of two way messaging, user can use the pair of one way contract or single duplex contract. In one way contract both the client and the service are independent WCF hosts. Multiple endpoints are implemented using several bindings and contracts.

    In duplex service contract, the client does not become a WCF service. It does not contain the bindings or endpoints. The channel factory is used to when the duplex communication is initiated by the client.

    The comparison of the two ways contract and duplex contract is as shown below:

    1. 1) In a Paired one way contracts, the contracts can be versioned independently. In Duplex contract, the client side callback contract is determined by the service.
    2. 2) For every one way contract, the binding is defined using different protocols, encoding or encryption in each direction. In Duplex contract, the communication protocol is same in both the directions as it is defined by the service binding.

    Server portion of Duplex Service Contract

    The duplex contract contains the specifications of the interface for client and service endpoints.

    In a duplex communication the client registers for the updates and the service send the periodical updates to the client. The service creates a thread that will periodically send updates to the client.

    The server side implementation of the duplex contract is as shown below:
    Code:
    [ ServiceContract ( CallbackContract = typeof( IClientCallback) ) ]
    public interface IServerData
    {
    	[ OperationContract (IsOneWay = true ) ]
    	void AddForUpdates ( string value );
    }
    
    public interface IClientCallback
    {
    	[ OperationContract ( IsOneWay = true ) ]
    	void CostUpdate ( string value, double cost );
    }
    
    public class ServerData: IServerData
    {
    	public void AddForUpdates ( string value )
    	{
    		Update datavalue=new Update();
    		Datavalue.callback = OperationContext.Current.GetCallbackChannel <IClientCallback>();
    		Thread t = new Thread ( new ThreadStart ( datavalue.SendUpdateToClient ) );
    		t.Start();
    	}
    }
    
    public class Update
    {
    	public IClientCallback callback = null;
    	public void SendUpdateToClient ()
    	{
    		Random r= new Random ();
    		for ( int i=0; i<10; i++)
    		{
    			Thread.Sleep(10000);
    		try
    		{
    			callback.CostUpdate (“xyz”, 2000+r.NextDouble());
    		}
    		catch ( Exception e )
    		{
    			Console.WriteLine ( “ Error sending cache to the client: {0}”, ex.Message);
    		}
    	}
    }
    
    The configuration file for the service is as shown below:

    Code:
    <?xml version = “1.0” encoding = “utf-8” ?>
    <configuration>
    	<system.ServiceModel>
    	<services>
    	<service behaviorConfiguration = “MEXServiceTypeBehavior” 
    	name=”Essantial.WCF.ServerData”>
    	<endpoint address=”” binding=”wsDualHttpBinding” 
    	contract=”IMetadataExchange” />
    	</service>
    	</services>
    	<behaviors>
    	<serviceBehaviors>
    		<behavior name=”MEXServiceTypeBehavior”>
    		<serviceMetadata httpGetEnabled=”true” />
    		</behavior>
    	</serviceBehaviors>
    	</behaviors>
    	</system.ServiceModel>
    </configuration>
    
    Client code of the Duplex Contract

    The client must implement the ABC of the WCF that is the address on the client to send messages, the binding to direct the messages sent to the client, and how the service sends messages to the client.

    The code for the duplex contract is as shown below:
    Code:
    using System;
    using System.ServiceModel;
    
    namespace Client
    {
    	public class CallbackHandler: IServerStockCallback
    	{
    		static InstanceContext IC = new InstanceContext ( new CallbackHandler());
    		static ServerStockClient proxy = new ServerStockClient (site);
    		
    	public void CostUpdates( string value, double cost )
    	{
    		Console.WriteLine (“ The alert is : {0}. {1}:{2}”, value,cost);
    	}
    
    class Program
    {
    	static void Main ( string[] args )
    	{
    		proxy.AddForUpdates(“xyz”);
    		Console.ReadLine();
    	}
    }
    }
    }
    
    Multiple Contracts and Endpoints in a service

    A service is defined as an endpoint. The endpoint contains the address, binding and contract. The contract is used to expose the capabilities of an endpoint. The address is used to specify where the applications are in the network. The binding states how they are used.

    The following code demonstrates the multiple contracts in an endpoint.
    Code:
    namespace WCFApp
    {
    	[ ServiceContract ]
    	public interface IStudInfo
    	{
    		[ OperationContract ]
    		string GetName ( string name );
    	}
    	
    	[ ServiceContract ]
    	public interface IEmpInfo
    	{
    		[ OperationContract ]
    		int GetAge ( int age );
    	}
    
    	[ ServiceContract ]
    	public interface IStudData: IEmpInfo, IStudInfo { };
    	public class StudData : IStudData
    	{
    		public string GetName ( string name )
    		{
    			Thread.Sleep(10000);
    			return “xyz”;
    		}
    		public int GetAge ( int age )
    		{
    			return 20;
    		}
    	}
    }
    
    The configuration file exposes the multiple endpoints for the three contracts. The endpoints are IStudData, IEmpInfo,and IStudInfo. These endpoints share the scheme, address for each endpoint.
    Code:
    <?xml version = “1.0” encoding=”utf-8” ?>
    <configuration>
    	<system.serviceModel>
    	<services>
    	<service name=”WCFApp.StudData”   behaviorConfiguration=”mexServiceBehavior”>
    	<host>
    		<baseAddresses>
    		<add baseaddress=”http://MyComputer/WCFApp/”/>
    		</baseAddresses>
    	</host>
    	<endpoint name=”StudInfo”
    binding=”basichttpBinding”
    contract=”WCFApp.IStudInfo” />
    	<endpoint name=”EmpInfo”
    		address=”Emp”
    binding=”basichttpBinding”
    contract=”WCFApp.IEmpInfo” />
    	<endpoint name=”StudData”
    		address=”Stud”
    binding=”basichttpBinding”
    contract=”WCFApp.IStudData” />
    	<endpoint name=”mex”
    binding=”mexHttpBinding”
    contract=”IMetadataExchange” />
    	</service>
    	</services>
    	<behaviors>
    	<serviceBehaviors>
    	   <behavior name=”mexServiceBehavior”>
    	   <serviceMetadata httpGetEnabled=”True” />
    	   </behavior>
    	</serviceBehaviors>
    	</behaviors>
    	</system.ServiceModel>
    </configuration>
    
     

Share This Page