Wednesday, August 28, 2013

Creating and Deploying a Simple WCF service (VS'10-C#)

WCF (Windows Communication Foundation) services supports more protocols for transporting messages between software entities (including protocols: HTTP,TCP,MSMQ{Microsoft Message Queuing}).But ASP.NET Web Services only supports HTTP protocol.

STEP I 

Creating a table


  • Open MS SQL Server, Goto Object Explorer tab , Select your Database and Create a table.
  • Here I'm creating a table 'productTable ' in DREAMTECH (data source) -> allTest (Database) and Fill it as shown below:
   
Fig: productTable

STEP II

Creating a WCF Service

  • Open Visual studio and Create File -> New Website-> WCF Service
  • Expand App_Code Folder in Solution Explorer.
  • Open IService.cs file and Comment all code which is inside public interface IService and rewrite (include namespace = using System.Data; ) :
            [ServiceContract]
            public interface IService{
            [OperationContract]
            DataSet queryInventoryById(int productId);
            }
  • Open Service.cs file and Comment all code inside public class Service : IService and rewrite (include namespace =  using System.Data; and  using System.Data.SqlClient; ) :
         public class Service : IService
         {       
        public DataSet queryInventoryById(int productId){
        SqlConnection sc = new SqlConnection("data source=DREAMTECH; Initial Catalog=allTest;
         User id =sa;  Password=sushil47");
        SqlDataAdapter sa = new SqlDataAdapter("Select * from productTable where                                             productId="+productId+"",sc);
        DataSet ds = new DataSet();
        sa.Fill(ds);
        return ds;
                  }
            }

  • Build it (F5) and copy "http://localhost:9715/WCFServiceTest/Service.svc?singleWsdl" .

STEP III

Creating a WCF application

  •  Open Visual studio and Create File -> New Website-> ASP.NET Website
  •  Open Default.aspx in designer mode and Drag a textbox(id=txtProductId), button(id=btnProcess) and gridview(id=GridView1).
  •  Now Goto Solution Explorer and on root website path -> Add Service Reference.

  •  Copy the previous link in the Address section and Press OK.
  • On button event write the following code (Default.aspx.cs):
       protected void btnProcess_Click(object sender, EventArgs e)

    {
        int productId = Convert.ToInt32(txtProductId.Text);
        ServiceReference1.ServiceClient objServiceProxy = new ServiceReference1.ServiceClient();
        GridView1.DataSource = objServiceProxy.queryInventoryById(productId).Tables[0];
        GridView1.DataBind();
    }
  •    Build it and Result will be:





No comments:

Post a Comment