Monday 4 November 2013

How to create and consume WCF Services in asp.net ?

WCF allows sending data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages that can be sent can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.

WCF Hosting
Web services that was used earlier was hosted inside web server such as IIS using http or wsHttp protocols. But WCF (Windows Communication Foundation) supports four types of hosting.
  •  IIS 
  •  WAS (Windows process activation services) 
  •  Self-hosting 
  •  Windows services

What is ABC in WCF 
We had gone through the feature of WCF and understood why its termed as advanced version of web services. Now it’s time to answer a very basic question related to WCF i.e., what is ABC of WCF?

When we say WCF, we came across end points. Service endpoint can be a part of continuously hosted service hosted in IIS or service hosted in an application.
ABC where "A"stands for Address,"B" stands for Binding and "C" stands for Contract are the three elements which constitutes and Service Endpoint.
  • Address - Where the Service is residing (URL of the service.) i..e. where the service is?
  • Binding – Way to talk to the service? Example – basicHttpBinding, wsHttpBinding, webHttpBinding etc. 
  • Contract – What can the service do for me?
Advantages:
  • WCF is interoperable with other services when compared to .Net Remoting where the client and service have to be .Net. 
  • WCF services provide better reliability and security in compared to ASMX web services. 
  • In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Instead it requires small changes in the configuration. 
  • WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
Let's create WCF application and its consuming application:
    • Open visual studio ->File -> New ->Website -> select Visual C# language from the left pane and WCF Service from the right pane and Name it WcfSample or whatever you want.
    • Now it will create a file Service.svc and two files IService.cs and Service.cs under App_Code folder in Solution Explorer
    •  In the IService.cs interface remove all existing sample code that is placed in the interface IService and let’s declare our own functions as:
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        int GetEmpId(int id);
        [OperationContract]
        string GetEmpName(string name);
        [OperationContract]
        string GetDept(string dept);
        [OperationContract]
        int GetBasicSalary(int BasicSal);
        [OperationContract]
        int GetPF(int BasicSal);
        [OperationContract]
        int GetHRA(int BasicSal);
        [OperationContract]
        int GetGrossSalary(int BasicSal);
    }
    • Similarly remove all existing sample code that is placed inside the Service class in the Service.cs file and write define the function. Our Service.cs file will look like as:
    public class Service : IService
    {   
        public int GetEmpId(int id)
        {
            return id;
        }

        public string GetEmpName(string name)
        {
            return name;
        }

        public string GetDept(string dept)
        {
            return dept;
        }

        public int GetBasicSalary(int BasicSal)
        {
            return BasicSal;
        }

        public int GetPF(int BasicSal)
        {
            return (BasicSal * 7) / 100;
        }

        public int GetHRA(int BasicSal)
        {
            return (BasicSal * 4) / 100;
        }

        public int GetGrossSalary(int BasicSal)
        {
            return BasicSal + GetPF(BasicSal) + GetHRA(BasicSal);
        }
    }
    • Now in web.config file write as:  
    <system.serviceModel>
                                    <services>
                                                    <service name="Service" behaviorConfiguration="ServiceBehavior">
                                                                    <endpoint address="" binding="wsHttpBinding"contract="IService">
                                                                                    <identity>
                                                                                                    <dns value="localhost"/>
                                                                                    </identity>
                                                                    </endpoint>
                                                                    <endpoint address="mex" binding="mexHttpBinding"contract="IMetadataExchange">
                                                                    </endpoint>
                                                    </service>
                                    </services>
                                    <behaviors>
                                                    <serviceBehaviors>
                                                                    <behavior name="ServiceBehavior">
                                                                                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                                                                                    <serviceMetadata httpGetEnabled="true"/>
                                                                                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                                                                                    <serviceDebugincludeExceptionDetailInFaults="false"/>
                                                                    </behavior>
                                                    </serviceBehaviors>
                                    </behaviors>
                                    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
                    </system.serviceModel>

    • Congratulations you have created a Wcf service. Now make Service.svc file as startup page by right clicking on the Service.svc file in the solution explorer and select “set as start up page” and run the website. If everything is fine then it will look like as shown in the image below:

    WCF example in asp.net
    Click on image to enlarge

    • Copy the URL of the service. Here in our example it is “http://localhost:1416/WcfSample/Service.svc”
    Note: Leave the Wcf application  running.

    Consuming WCF Service

    Now it’s time to create a consuming application that will consume the service provided by WcfSample service we just created.

    Create a new website as:
    Open visual studio ->File -> New ->Website -> select Visual C# language from the left pane and ASP.NET Empty website from the right pane and Name it "ConsumingWcfSample" or whatever you want.
    Add a new page as: Website menu-> Add new item ->Web Form-> default.aspx

    Now add the service reference of the WCF service we created as:
    Right click on the ConsumingWcfSample website and select Add Service Reference and paste the WCF service address (“http://localhost:1416/WcfSample/Service.svc”) that we copied earlier in the address box. Notices that ServiceReference is the namespace that is to be included on the page where we want to consume the WCF service .You can also rename it as per your choice. But we have not changed the default name. Click on GO button
    WCF example in asp.net
    Click on image to enlarge


    You can also view all the functions declared in the IService by clicking on the Service-> IService in the  Add Service Reference box as shown in image below:

    WCF example in asp.net
    Click on image to enlarge
    • Now In the design page default.aspx create the structure as:
    <table>
            <tr>
                    <td>
                        Employee ID</td>
                    <td>
                        <asp:TextBox ID="txtEmpID" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        Employee Name</td>
                    <td>
                        <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        Department</td>
                    <td>
                        <asp:TextBox ID="txtDept" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        Basic Salary</td>
                    <td>
                        <asp:TextBox ID="txtBasicSal" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        &nbsp;</td>
                    <td>
                        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
                            onclick="btnSubmit_Click"/>
                    </td>
                </tr>
            </table>
    • In the code behind file default.aspx.cs
    Add the following required namespace:

    Using ServiceReference;
    • In the submit button click event write the code as:
    protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
            Response.Write("Employee ID: " + obj.GetEmpId(Convert.ToInt32(txtEmpID.Text.Trim())));
            Response.Write("<BR/>Employee Name: " + obj.GetEmpName(txtEmpName.Text.Trim()));
            Response.Write("<BR/>Employee Department: " + obj.GetDept(txtDept.Text.Trim()));
            Response.Write("<BR/>Basic Salary: " + obj.GetBasicSalary(Convert.ToInt32(txtBasicSal.Text.Trim())));
            Response.Write("<BR/>PF: " + obj.GetPF(Convert.ToInt32(txtBasicSal.Text.Trim())));
            Response.Write("<BR/>HRA: " + obj.GetHRA(Convert.ToInt32(txtBasicSal.Text.Trim())));
            Response.Write("<BR/>Gross Salary: " + obj.GetGrossSalary(Convert.ToInt32(txtBasicSal.Text.Trim())));
        }

    • Now run the default page and enter the details as:
    WCF example in asp.net
    Click on image to enlarge
    • And click on submit. It will call the WCF service methods and process the data and return the Output as :
    WCF example in asp.net
    Click on image to enlarge


    Now suppose you want to add another function or make modification in the existing functions then how it is possible?
    In fact it’s very easy. What you need to do is to add another function or modify existing function in the WCF service and then run the service.
    Now open your ConsumingWcfSample application and right click on the App_WebReferences folder under solution explorer and click on Update Web/Service References as:

    WCF example in asp.net
    Click on image to enlarge

    No comments:

    Post a Comment