Wednesday, January 13, 2010

How to Use WCF Service in Web Application


Wcf Service:
There is new baby of microsoft  in the world.  called WCF service. But there is huge Question how to call it in webapplication. thoug it is as easy as we are doing with webservice.
there is a huge differance in the plateform on which webservice is built and on which WCF is service in built.
Differance:
The Main differance bet'n this two services (WebService/WCF) is   With WCF Service  SOAP messages can be transmitted over a variety of supported protocols including IPC (named pipes), TCP, HTTP and MSMQ. Like any distributed messaging platform,on the other hand in WebService SOAP message can only transmitted via HTTP.
How To Create WCF Service:
To Create WCF service Create 
1).Create  blank website 
2).Right-Click  > Add Item >WCF Service
 3). Add referance to
System.ServiceModel.
Three files will be created in solution .
A)  App_Code/IService.cs
Content:
using System.ServiceModel;// NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
[ServiceContract]
public interface IService
{
    [OperationContract]
    string DoWork();

}

B)  App_Code/Service.cs
Content:
using System;
using System.ServiceModel.Activation;
// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
   public string DoWork()
    {

        return DateTime.Now.ToString();
    }
}
C) Service.svc
Content:
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

And Following lines of Configuration will automatically added to Web.Config file of your web site.
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="" binding="wsHttpBinding" contract="IService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />   
  </system.serviceModel>
This are the steps to create WCF service.To call  WCF service in our application we have to Add bindings  in web.Config file & also have to create a class which acts  as proxy of WCF  service in our application.
How to Consume WCF service in WebApplication:
to call WCF service we have to add following service contract in our web.config file. please copy and paste below configuration tags  between  <system.serviceModel> </system.serviceModel> elements.
Service binding configuration:
 <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IService" closeTimeout="00:01:00">
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:54464/SVCTest/Service.svc"
          binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"
          contract="IService" name="WSHttpBinding_IService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
Now we have done with configuration of WCF service configuration.now we have to create ClassLibrary which contains proxy class to call WCF service methods.
Steps to create  proxy is:
1) on solution Right-Click >Add New Project >Class Library.
2) Add Class and name it  ServiceCaller.cs.
3) Add Referance to  System.ServiceModel  in Class Library project.
4 ) Add following code in that class file.
namespace WCFServices
{
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName = "IService")]
    public interface IService
    {

        [System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IService/DoWork", ReplyAction = "http://tempuri.org/IService/DoWorkResponse")] //This line is must
        string DoWork();
    }
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class ServiceClient : System.ServiceModel.ClientBase<IService>, IService
    {

        public ServiceClient(){}
        public string DoWork()
        {

            return base.Channel.DoWork();
        }
    }
}
Finally now we are done with creating WCF service caller class.I have given sample code for service proxy and configuration elements.But you can also create configuration Using Command line Called svcutil.exe Automatically.
Steps to create configuration and proxy class using Command-line(svcutil.exe):
1) Open Visual Studio 2008 Command Prompt.
Service.cs and output.config will be automaticall create at
Program Files (x86)\Microsoft Visual Studio 9.0\VC.
you can use this Service.cs  as ServiceCaller and elements inside output.config as configuration elements for web.config file.
To call WCF service in our application is very easy now.
Just Create object of ServiceClient Class. and you will be able to call methos in WCF service.
Eg.
 protected void Page_Load(object sender, EventArgs e)
 {

        WCFServices.ServiceClient sc = new WCFServices.ServiceClient();
        string currentTime = sc.DoWork();
        Response.Write(currentTime);
        sc.Close();
        //Response.Write(DateTime.Now.ToString());

 }
Here we GO.
you can find more details of each and every class and terms and Namespace used here in following links.also can find more about making WCF service more secure from the referances given here.
Performance Comparision:
Consuming Wcf Service:
Hosting WCF Service in IIS:
Securing WCF Service:

Hope this will help you.

Thanks.