Sunday, September 7, 2008

WCF Sample

WINDOWS COMMUNICATION FOUNDCATION

WCF enables the applications to communicate whether they are in the same computer, difference Computer, across internet, or across different platforms (like J2EE, .NET)

The Basic tasks to be performed to create a WCF are,
1. Create a Service Contract – It defines what the operation the service can support. It may be interface or Class .
The Class/ Interface must have the ‘ServiceContract’ attribute set. And the Each method in the Class / Interface must have ‘OperationContract’ attribute set.
The method without ‘OperationContract’ attribute cannot be accessed by Client

[ServiceContract()]
public interface IString
{
[OperationContract]
String StringReverse(String str);
[OperationContract]
Int32 StringLength(String str);
}

2. Implementing the Service Contract
The Service Contract created in the Step1 is implemented here
public class StringOpertion : IString
{
public String StringReverse(String str)
{
Char[] strChar = str.ToCharArray();
Array.Reverse(strChar);
return new String(strChar);
}

public Int32 StringLength(String str)
{
return Convert.ToInt32(str.Length);
}

}

3. Host And Run the WCF

Create a base URI for the Service
Create a host for the Service
Create a End Point - It provides the access client to the functionality offered by WCF service

static void Main(string[] args)
{
//Create a base URI for the Service
Uri BaseURI = new Uri("http://localhost:8000/Sample/WCFService");

//Create Service Host for the Service
ServiceHost serviceHost = new ServiceHost(typeof(StringOpertion), BaseURI);

//Create an End Point
//Bindings ‘WSHttpBinding’ – used to specify the type of transport/ protocol required for the clients and service to communicate
serviceHost.AddServiceEndpoint(typeof(IString), new WSHttpBinding(), "StringOpertion");

ServiceMetadataBehavior ServiceMDB = new ServiceMetadataBehavior();
ServiceMDB.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(ServiceMDB);
serviceHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press ENTER Key to Close the service.");
Console.WriteLine();
Console.ReadLine();
serviceHost.Close();
}

4. Create Proxy
Using svcutil, generate the proxy and add to the client
Svcutil /language:cs /out:wcfservice.cs /config:app.config http://localhost:8000/sample/WCFService

5. Create Client Application and add the proxy to it.

static void Main(string[] args)
{
StringClient objStringOp = new StringClient();
Console.WriteLine("The Reverse of the String Hello is :" + objStringOp.StringReverse("Hello"));
Console.WriteLine("");
Console.WriteLine("The Length of String Hello is :" + objStringOp.StringLength("Hello"));
objStringOp.Close();
Console.ReadLine();

}

No comments: