Thursday, March 8, 2012

Guidelines for writing WCF Services.

There are two parts in the development of WCF Services.
1) Creating a Service.
2) Consuming a Service.

1. Creating a Service:

In this example we are implementing service for CostCalculation which takes ProductName, ProductCost and ProductQuantity.
And it multiplies the ProductQuantity with ProductCost and gives us a TotalCost.

To create WCF service, open Visual Studio 2010àFileàNewàProject à Select 'WCF' under Visual C# in Installed Template pane on left à Select "WCF Service Application" in content pane à Give Project Name à Click OK
In Solution explorer you can see the files called IService1.cs and Service1.svc. Rename them to IServiceCalculateCost.cs and ServiceCalculateCost.svc.

Creating a WCF service is a 3 step process.
a) Define Interface
b) Define DataType
c) Write the Core Implementation Logic

A. Define Interface:
Now we need to define ServiceContract interface called IServiceCalculateCost in IServiceCalculateCost.cs file which contains the OperationContract method getTotalCost()
by which we can communicate with the service. So, delete the default generated interface and write the interface as below:

[ServiceContract]
public interface IServiceCalculateCost
{
    [OperationContract]   
    string getTotalCost(ProductData objProd);
}

B. Define DataType:
The second step is to define DataType called ProductData in IServiceCalculateCost.cs file which helps us to pass three values called Product Name,Cost & Quantity into the Service. So, remove default
DataContract and define new DataContract which contains Product Name,Quantity & Cost as DataMembers as below :

[DataContract]
public class ProductData
{
 private int quantity;
 private float cost;
 private string name;

 [DataMember]
 public int Qty {
     get { return quantity; }
     set { quantity = value; }
 }
 [DataMember]
 public float Cost {
     get { return cost; }
     set { cost = value; }
 }
 [DataMember]
 public string Name {
     get { return name; }
     set { name = value; }
 }
}

C. Write the Core Implementation Logic:

In third step, we are defining Implementation logic or the Business logic in ServiceCalculation.svc.cs file where we are going to calculate the TotalCost.
So, delete the default class and write the new class as below: 


public class ServiceCalculateCost : IServiceCalculateCost
    {
        public string GetData(int value)
        {  
            return string.Format("You entered: {0}", value);
        }
        string IServiceCalculateCost.getTotalCost(ProductData obj)
        {
            float totCost = obj.Cost * obj.Qty;
            return "Total Cost of " + obj.Name + " is :" + totCost.ToString();
        }
    }

Here we are creating a class ServiceCalculateCost which implements the interface IServiceCalculateCost which we have defined as ServiceContract. In this class we implemented the getTotalCost() method which defined in IServiceCalculateCost interface. This method contains the logic for TotalCost calculation by multiplying Quantity and Cost.

Right click on ServiceCalculateCost.svc à Open With... à Source Code(Text) Editor à OK à Make sure that Service and CodeBehind as,
Service="<ProjectName>.ServiceCalculateCost" CodeBehind="ServiceCalculateCost.svc.cs"

Host this WCF service in IIS. For information about hosting look at this page.


2. Consuming a Service:

After you hosted WCF service, next step is to consume the hosted service in your application.
For that you need to create a small web application. 


  • Open Visual Studio 2010 à File à New à Project à Select 'Web' under Visual C# in Installed Template pane on left à Select "ASP .NET Empty Web Application" in content pane à Give Project Name à Click OK
  • Right click on your project in solution Explorer à Add à New Item à Select 'Web' under Visual C# in Installed Template pane on left à Select "Web Form" in content pane à Give File Name à Click OK
  • Now go to IIS à Right Click on your hosted application à Manage Web Site à Browse à Click ServiceCalculateCost.svc from the list in browser and copy that URL.
  • Right Click on References under your project à Add Service Reference à Paste URL in Address à Click Go à Select your service under Services à Give Namespace(say, MyService) à OK

Give reference of MyService in your C# code. And create a service instance to call Service method as below.

using WebApplication1.MyService;
namespace WebApplication1{
    public partial class WebForm1 : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e){
            IServiceCalculateCost service = new ServiceCalculateCostClient();
            ProductData data = new ProductData();
            data.Cost = 500;
            data.Name = "Shirts";
            data.Qty = 3;
            Label1.Text = service.getTotalCost(data);
        }
    }
}
Now Run the application and you will get the output as:
Total Cost of Shirts is :1500.


Leave your valuable comments if you get any Issues or Errors...

No comments:

Post a Comment