Exploring WCF programming model

MinalS's Avatar author of Exploring WCF programming model
WCF service the communication occurs through the service endpoint which is the gateway for communication of different applications..
An endpoint is formed by address, binding, and a contract known as ABC. The following figure shows the endpoint of the programming model.



Address



To access a WCF service, a client application needs to confirm the address of the service. It is the location where the service resides. The address is represented in the form of the URL. The URL has the following components.
  1. The protocol to be used for sending and receiving messages
  2. The system name where the service is executed
  3. The port number at which the client request is listened
  4. The path where the service resides and the service name
The following sample demonstrates how the user can specify the address of the service in a WCF application.

address=http://MyComputer:2497/Service1.svc

Where, http is the communication protocol, MyComputer is the computer name. 2497 is the port number where the service listens the request from the client. Service1.svc is the name of the service.

Binding



In WCF service communication, the binding describes how the communication is done with the client application. The communication details are specified in it. It contains two elements as message encoder binding element and protocol binding element. The message encoder binding element serializes and deserializes the message. The protocol binding element specifies the protocol such as HTTP for exchanging the messages.

There are several binding types to enable the client application for communication with the WCF service. Different protocols are used for the purpose. Some of them are as mentioned below:
  1. basicHttpBinding: It is used to configure the endpoints and expose the WCF service to communicate with the web service or client application.
  2. wsHttpBinding: The features like transactions, security and reliable messaging are possible through the binding
  3. netTcpBinding: It is used to enable the communication between a WCF service and a .Net client application over an intranet. The features like reliable messaging and Windows security are provided.
  4. netNamedPipeBinding: The communication between the WCF service and .NET client application on the same computer but in different process is possible through the binding.
  5. netMsmqBinding: It is used to implement the message queuing in a WCF service. It uses the MSMQ to implement the message queuing
  6. netPeerTcpBinding: It is used for peer to peer communication. The TCP protocol is used for sending and receiving messages
User defined bindings can be created for some specific bindings. Add the <customBinding> element in the Web.Config file. It is created through the combination of the existing bindings.

The following code snippet demonstrates the user- defined binding.
Code:
<system.serviceModel>
   <bindings>
          <customBinding>
	    <binding name=”Binding1”>
	        <reliableSession ordered=”true” />
	        <httpsTransport />
	    </binding>
	</customBinding>
    </bindings>
</system.serviceModel>
In the above code, Binding1 is the custom binding. It implements the reliable session using the httpstransport protocol to send and receive messages.

Contract



The declaration of functionality in a WCF service is done through Contract. It exposes the class, methods, interfaces, and variables to enable the service. It contains various contract types for exposing the class and its members. The different contracts are as follows:

1) Service Contract

It is the entry point for the service access in WCF. The contracts are implemented at interfaces. To define a service contract, declare the [ServiceContract] attribute in a WCF service. The following code snippet demonstrates the service contract.

Code:
[ServiceContract]
public interface IService
{
}
In the above code, the service contract is defined by using the [ServiceContract] attribute present in the System.ServiceModel namespace. It exposes the IService interface. An interface is declared with the [ServiceContract] attribute and it can be accessed by the clients.

2) Operation Contract

It is used to expose the operations that can be performed by the service. The methods of the WCF service and the parameters and return type of the methods are defined.
The operation contract is sued to define the operation contract in the service. The [OperationContract] attribute is used. The following code snippet demonstrates the operation contract.

Code:
[ServiceContract]
public interface IService
{
	[OperationContract]
	DataSet GetDetails( int Stud_ID)
}
In the above code, the operation contract is defined. It is available in the System.ServiceModel namespace. The attribute uses the method, GetDetails and DataSet as the return type. The Stud_ID parameter is used to enable the client application to expose the service.

3) Data Contract

It is used to expose the user defined data types in the WCF service. It serializes the defined data type in an XML format. When the service is exposed to the client the service data is represented in the form of XML Schema Definition (XSD).

The [DataContract] attribute is used to define the WCF service. The [DataMember] attribute is used to expose the variables of the user defined type.

The following code snippet demonstrates the attributes.

Code:
[DataContract]
public class Student
{
	[DataMember]
	public int StudID;
	[DataMember]
	public int stud_name;
}
In the above code, the Student is a user defined class. The [DataContract] attribute is used to declare attributes that are exposed to the clients. The variables are declared with the [DataMember] attribute.

4) Message Contract

The structure of the message exchange between the client and the WCF service is described through the message contract. It enables the user to control the information in the message.

The message transfer is in the form of SOAP messages through the SOAP protocol. The contract allows the user to use the user defined classes, variables, and data types for defining the exact content of the message.

The [MessageContract] is used to define the contract, the [MessageBodyMember] and [MessageHeader] attributes are used.

The following code snippet demonstrates the use of the message contract.

Code:
[MessageContract]
public class MessageData
{
	[MessageHeader]
	public string messagetype;
	[MessageBodyMember]
	public Student StudID;
}
In the above code, the user defined class MessageData is created. The [MessageContract] attribute is used to control the information of the message. The [MessageHeader] contains the value of messageType of string data type. The [MessageBodyMember] attribute contains the variable StudID of the Student datatype.

5) FaultContract

It is used to send the customized error message to a client by creating the user defined class. The contract helps to control the situation when the service encounters an error.
A fault contract can be defined through the [FaultContract] attribute as shown in the following code snippet.

Code:
[ServiceContract]
public interface IService
{
	[OperationContract]
	[FaultContract ( typeof( MyException))]
	DataSet GetDetails ( int StudID);
	[DataContract]
	public class MyException
	{
		[DataMember]
		public string message;
	}
}
In the above code, the user defined class MyException is created. It contains a variable as message. The [FaultContract] attribute takes the user defined class as a parameter. At the occurrence of an exception, the customized message is sent to the client application.

Creating a WCF Service



1) Open Visual Studio application and click ‘File’, select ‘New Project’ option. Select the ‘WCF Service Application’ from the list.



2) The WCF file consists of an interface service and service class. Add the following code in the IService1.cs class of the application.

Code:
[ServiceContract]
public interface IService1
{
	[OperationContract]
	int add ( int a, int b);

	[OperationContract]
	int sub ( int c, int d);
}
3) Open the Service1.svc.cs class and add the following code

Code:
public class Service1: IService1
{
	int IService1.add( int a, int b)
	{
		return a+b;
	}
	int IService1.sub( int c, int d)
	{
		if ( c>=d)
		{
			return c-d;
		}
		else
		{ 
			return d-c;
		}
	}
}
4) Create a web application as the client application where the service is accessed. The source code file of the web application consists the following code.

Code:
<form id=”form1” runat=”server”>
<div>
	Number1: <asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox><br/>
	Number2: <asp:TextBox ID=”TextBox2” runat=”server”></asp:TextBox><br/>
<asp:Button ID=”btn1” runat=”server” Text=”Add”  OnClick=”btn1_Click” />
		      <br/>
<asp:Button ID=”btn2” runat=”server” Text=”Sub”   OnClick=”btn2_Click” />
		     <br/>
		     <asp:Label ID=”Label1” runat=”server” Text=”Label> </asp:Label>
</div>
</form>
5) Add the service reference to the application.

6) In the code behind file, add the following code.

Code:
public partial class WebForm1: System.Web.UI.Page
{
	ServiceReference1.ServiceClient obj=new ServiceReference1.ServiceClient();
	int a,b;
	protected void btn1_Click (object sender, EventArgs e)
	{
		a=Convert.ToInt32( TextBox1.Text);
		b=Convert.ToInt32( TextBox2.Text);
		int add=obj.add(2,3);
		Label1.Text=add.ToString();
	}
	int c,d;
		protected void btn2_Click (object sender, EventArgs e)
	{
		c=Convert.ToInt32( TextBox1.Text);
		d=Convert.ToInt32( TextBox2.Text);
		int sub=obj.sub(3,1);
		Label1.Text=sub.ToString();
	}
}
The output for the add operation is as shown below:



The output for the sub operation is as shown below: