February 5, 2011

Code Sample to write and consume WCF Service

Below are 3 major steps in WCF
  1. Create the Service.(Creating) 
  2. Binding an address to the service and host the Service. (Hosting) 
  3. Consuming the Service.(Consuming) 
Creating the Service
define below 3 contracts(describes all the available operations that a client can perform on the service.)
ServiceContract:
define the service contract. We can apply this attribute on class or interface

OperationContract:
indicate explicitly which method is used to expose as part of WCF contract. We can apply OperationContract attribute only on methods

Data Contract



defines the custom data types that are passed into and out of the service.


Steps To Create WCF Service
1.) Select WCF service Application Template Project
2.)In the solution explorer, under the App_code folder you can find the two files: "IService.cs" and "Service.cs". 

"IService.cs" class file defines the contracts.
 "Service.cs" implements the contracts defined in the "IService.cs". 
  Contracts defined in the "IService.cs" are exposed in the service.  



App_Code/Iservice.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;


// 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 GetData(int value);


    //written by Tanvi
    [OperationContract]
    string GetString(String theString);


[OperationContract]
Student GetStudentUsingDataContract(Student obj);



}


// To add composite types to service operations.
[DataContract]
public class Student
{
string   name ;
int  age ;


[DataMember]
    public int Age
{
        get { return age; }
        set { age = value; }
}


[DataMember]
public string Name
{
        get { return name; }
        set { name = value; }
}
}

App_Code/service.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;


// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class Service : IService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}


    public Student GetStudentUsingDataContract(Student obj)
{


        return obj;
}




    public string GetString(String theString)
    {
        return "Hello First WCF Service" + theString;
    }
}


service.svc
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>






3.) Build The soultion




Hosting the Service

Host this serivce by creating the virtual directory in IIS and browse the *.SVC file
Now the http://tanvi/TestWCFService/Service.svc is the address of the created web service

Consuming the Service
1.) Create New ASP.NET web application
2.)In the solution explorer click on "Add service Reference" and add the service created in the STEP1.  
3.) Once The Reference is added we can use it as we use WebService.
     By Using the namespace and Creating the object of the class

     Below is the code in ASP.NET application to consume the above created service

Default2 .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     Service Call from Code-Behind:<br />
            <asp:TextBox ID="fld_String" runat="server" />
<asp:RegularExpressionValidator ID="rv" ErrorMessage="Enter Number" runat="server" ControlToValidate ="fld_String" SetFocusOnError ="true" ForeColor="Red"  ValidationExpression="^\d*$"></asp:RegularExpressionValidator><br />
            <asp:Button ID="btn_Submit" runat="server" Text="Submit" 
                    onclick="btn_Submit_Click" /><br />
            <asp:Literal ID="lit_Display" runat="server" /><br />
             <asp:Literal ID="lt_studnet" runat="server" />
    </div>
    </form>
</body>
</html>

Default2 .aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
        lit_Display.Text = obj.GetData(int.Parse (fld_String.Text));
        Response.Write ("<br/>");
        //
        ServiceReference1.Student obj1 = new ServiceReference1.Student();
        obj1.Name = "Test";
        obj1.Age = 32;
        ServiceReference1.Student obj2 = obj.GetStudentUsingDataContract(obj1);
       // Response.Write(obj2.Name);
       // Response.Write("<br/>");
        //Response.Write(obj2.Age.ToString ());
        lt_studnet.Text = obj2.Name + " is" + obj2.Age.ToString() + " years old";
    }
}


Below is the o/p



1 comment: