Creating And Consuming WCF Services In ASP.NET

Creating WCF Services

Before Creating any WCF service I want to give a brief description about WCF. WCF is a Microsoft technology provided in DotNet Framework for development rich distributed application.

In Visual studio 2008 the first version of WCF was introduced. Before WCF we were mainly using "WEB SERVICES" for communication with diffrent platform applications. Introduction of WCF brings a great revolution in "SOA"(Service Oriented Archicture).

Here I will explain in detail how to create and consume WCF Service in your application. First for Creating WCF service open Visual studio and follow the given steps.

Create a new project of type(WCF) and choose the following template as shown below.

 
 
Now the following things get added into your project in solution Explorer.
 
Now I am adding one model class called "Employee.cs" to my project as follow.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace WCF_REST  
  7. {  
  8.     public class Employee1  
  9.     {  
  10.         public int EmpId { getset; }  
  11.         public string EmpName { getset; }  
  12.         public string CompanyName { getset; }  
  13.         public string Location { getset; }  
  14.         public string Dept { getset; }  
  15.        
  16.     }  
  17. }  
After that I will add a "WCFDAL.cs" class to perform database operations in my service. Here my solution explorer looks like this.
 
Now open the Web.config and write the following connection string in it.
  1. <connectionStrings>  
  2.   <add name="connect" connectionString="Server=Debendra; Database=students; User ID=sa;Password=123;" />  
  3.        
  4. </connectionStrings>  
Now open the IService1.cs and define the following interfaces for operation.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using System.Data;  
  9.   
  10. namespace WCF_REST  
  11. {  
  12.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.  
  13.     [ServiceContract]  
  14.     public interface IService1  
  15.     {  
  16.   
  17.         [OperationContract]  
  18.         bool InsertData(Employee1 obj);  
  19.         [OperationContract(Name = "ShowAll")]  
  20.         [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/ShowAll")]  
  21.         List<Employee1> ShowAll();  
  22.         [OperationContract]  
  23.         [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/showdata/")]  
  24.         List<Employee1> getRecordbyId(int id);  
  25.         [OperationContract]  
  26.         bool UpdateData(Employee1 obj);  
  27.         [OperationContract]  
  28.         bool DeleteData(Employee1 obj);  
  29.   
  30.   
  31.     }  
  32.         [DataContract]  
  33.         public class Employee  
  34.         {  
  35.   
  36.             string _name = "";  
  37.             string _email = "";  
  38.             string _phone = "";  
  39.             string _gender = "";  
  40.             [DataMember]  
  41.             public int EmpId  
  42.             {  
  43.                 get { return EmpId; }  
  44.                 set { EmpId = value; }  
  45.             }  
  46.   
  47.             [DataMember]  
  48.             public string EmpName  
  49.             {  
  50.                 get { return _name; }  
  51.                 set { _name = value; }  
  52.             }  
  53.   
  54.             [DataMember]  
  55.             public string CompanyName  
  56.             {  
  57.                 get { return _email; }  
  58.                 set { _email = value; }  
  59.             }  
  60.   
  61.             [DataMember]  
  62.             public string Location  
  63.             {  
  64.                 get { return _phone; }  
  65.                 set { _phone = value; }  
  66.             }  
  67.   
  68.             [DataMember]  
  69.             public string Dept  
  70.             {  
  71.                 get { return _gender; }  
  72.                 set { _gender = value; }  
  73.             }  
  74.         }  
  75.     }  
Now here is the "Service1.svc.cs" class to implement all these interfaces.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Data.SqlClient;  
  8. using System.Data;  
  9. using System.Configuration;  
  10.   
  11.   
  12. namespace WCF_REST  
  13. {  
  14.     public class Service1 : IService1  
  15.     {  
  16.         WCFDAL myobject = new WCFDAL();  
  17.         public bool InsertData(Employee1 obj)  
  18.         {  
  19.             string query = "insert into Employee(EmpName,CompanyName,Location,Dept) values('" + obj.EmpName + "','" + obj.CompanyName + "','" + obj.Location + "','" + obj.Dept + "')";  
  20.             bool x = myobject.DML(query);  
  21.             return x;  
  22.   
  23.   
  24.   
  25.         }  
  26.         public  bool UpdateData(Employee1 obj)  
  27.         {  
  28.             string query = "update Employee set EmpName='" + obj.EmpName + "',CompanyName='" + obj.CompanyName + "',Location='" + obj.Location + "',Dept='" + obj.Dept + "' where Empid='" + obj.EmpId + "' ";  
  29.             bool x = myobject.DML(query);  
  30.             return x;  
  31.   
  32.   
  33.         }  
  34.        public bool DeleteData(Employee1 obj)  
  35.         {  
  36.             string query = "Delete from Employee where Empid='" + obj.EmpId + "'";  
  37.             bool x = myobject.DML(query);  
  38.             return x;  
  39.   
  40.         }  
  41.   
  42.         public List<Employee1> ShowAll()  
  43.         {  
  44.             List<Employee1> li = new List<Employee1>();  
  45.             string s = "select * from Employee";  
  46.             DataTable dt = new DataTable();  
  47.             dt = myobject.getdata(s);  
  48.             for (int i = 0; i < dt.Rows.Count; i++)  
  49.             {  
  50.                 Employee1 emp = new Employee1();  
  51.                 emp.EmpId = Convert.ToInt32(dt.Rows[i]["EmpId"]);  
  52.                 emp.EmpName = dt.Rows[i]["EmpName"].ToString();  
  53.                 emp.CompanyName = dt.Rows[i]["CompanyName"].ToString();  
  54.                 emp.Dept = dt.Rows[i]["Dept"].ToString();  
  55.                 emp.Location = dt.Rows[i]["Location"].ToString();  
  56.                   
  57.                  
  58.                 li.Add(emp);  
  59.                  
  60.             }  
  61.   
  62.   
  63.             return li;  
  64.   
  65.               
  66.   
  67.         }  
  68.         public List<Employee1> getRecordbyId(int id)  
  69.         {  
  70.             List<Employee1> li = new List<Employee1>();  
  71.             DataTable dt1 = new DataTable();  
  72.             string query="select * from Employee where EmpId='"+id+"'";  
  73.            dt1= myobject.getdata(query);  
  74.             if(dt1.Rows.Count>0)  
  75.             {  
  76.                 for (int i = 0; i < dt1.Rows.Count; i++)  
  77.                 {  
  78.                     Employee1 emp = new Employee1();  
  79.                     emp.EmpId = Convert.ToInt32(dt1.Rows[i]["EmpId"]);  
  80.                     emp.EmpName = dt1.Rows[i]["EmpName"].ToString();  
  81.                     emp.CompanyName = dt1.Rows[i]["CompanyName"].ToString();  
  82.                     emp.Dept = dt1.Rows[i]["Dept"].ToString();  
  83.                     emp.Location = dt1.Rows[i]["Location"].ToString();  
  84.   
  85.   
  86.                     li.Add(emp);  
  87.   
  88.                 }  
  89.                 return li;  
  90.   
  91.             }  
  92.             else  
  93.             {  
  94.                 return li;  
  95.             }  
  96.            
  97.   
  98.         }  
  99.     
  100.     }  
  101. }  
Here for Database operation I am calling to "WCFDAL .cs" here as code for this class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.Configuration;  
  8.   
  9. namespace WCF_REST  
  10. {  
  11.     public class WCFDAL  
  12.     {  
  13.         SqlCommand cmd;  
  14.         SqlDataAdapter da;  
  15.         DataSet ds;  
  16.         public static SqlConnection connection()  
  17.         {  
  18.             string s = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;  
  19.             SqlConnection con = new SqlConnection(s);  
  20.             if (con.State == ConnectionState.Closed)  
  21.             {  
  22.                 con.Open();  
  23.             }  
  24.             else  
  25.             {  
  26.                 con.Open();  
  27.             }  
  28.             return con;  
  29.         }  
  30.         public bool DML(string Query)  
  31.         {  
  32.             cmd = new SqlCommand(Query, WCFDAL.connection());  
  33.             int x = cmd.ExecuteNonQuery();  
  34.             if(x==1)  
  35.             {  
  36.                 return true;  
  37.             }  
  38.             else  
  39.             {  
  40.                 return false;  
  41.             }  
  42.   
  43.   
  44.   
  45.         }  
  46.         public DataTable getdata(string query)  
  47.         {  
  48.             da = new SqlDataAdapter(query, WCFDAL.connection());  
  49.             DataTable dt = new DataTable();  
  50.             da.Fill(dt);  
  51.             return dt;  
  52.               
  53.   
  54.         }  
  55.          
  56.   
  57.     }  
  58. }  
Now that's all from WCF service side to check this service we need the TEST Client. Now Save and Run this project. It will open the test Client as follows.
 
 
 
Now here you can test your individual service seperatly.
 
Consuming WCF Service in ASP DOTNET  Application :
 
Now to Consume this service add a new project in this Solution Explorer Name it as "WCFClient" and add a page(CRUD.aspx) as follow.
 
  
Now Add the Service Referance as follow.
 
 
 Now design the CRUD.aspx as follow to perform CRUD operation.
 
 
Here is the code for the design page. 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CRUD.aspx.cs" Inherits="WCFClient.CRUD" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <table>  
  13.             <tr>  
  14.                  
  15.                 <td>  
  16.                    <asp:Label ID="lbl_id" Visible="false" runat="server"></asp:Label>  
  17.                 </td>  
  18.             </tr>  
  19.             <tr>  
  20.                 <td>  
  21.                     Name:  
  22.                 </td>  
  23.                 <td>  
  24.                     <asp:TextBox runat="server" ID="txt_name" Width="200px"></asp:TextBox>  
  25.                 </td>  
  26.             </tr>  
  27.              <tr>  
  28.                 <td>  
  29.                     Company Name:  
  30.                 </td>  
  31.                 <td>  
  32.                     <asp:TextBox runat="server" ID="txt_company" Width="200px"></asp:TextBox>  
  33.                 </td>  
  34.             </tr>  
  35.              <tr>  
  36.                 <td>  
  37.                     Department:  
  38.                 </td>  
  39.                 <td>  
  40.                     <asp:TextBox runat="server" ID="txt_dept" Width="200px"></asp:TextBox>  
  41.                 </td>  
  42.             </tr>  
  43.              <tr>  
  44.                 <td>  
  45.                     Location:  
  46.                 </td>  
  47.                 <td>  
  48.                     <asp:TextBox runat="server" ID="txt_location" Width="200px"></asp:TextBox>  
  49.                 </td>  
  50.             </tr>  
  51.             <tr>  
  52.                 <td>  
  53.                  <asp:Button runat="server" ID="btn_save" Text="SAVE" OnClick="btn_save_Click" />  
  54.                 </td>  
  55.             </tr>  
  56.               
  57.         </table>  
  58.          
  59.             <asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" Width="700px" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting">  
  60.                <Columns>  
  61.                    <asp:TemplateField HeaderText="EMPLOYEE ID">  
  62.                         
  63.                        <ItemTemplate>  
  64.                            <asp:Label ID="lbl_empid" runat="server" Text='<%# Bind("EmpId") %>'></asp:Label>  
  65.                        </ItemTemplate>  
  66.                        <ItemStyle Width="150px" />  
  67.                    </asp:TemplateField>  
  68.                    <asp:TemplateField HeaderText="EMPLOYEE NAME">  
  69.                         
  70.                        <ItemTemplate>  
  71.                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("EmpName") %>'></asp:Label>  
  72.                        </ItemTemplate>  
  73.                        <ItemStyle Width="150px" />  
  74.                    </asp:TemplateField>  
  75.                    <asp:TemplateField HeaderText="COMPANY NAME">  
  76.                         
  77.                        <ItemTemplate>  
  78.                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>  
  79.                        </ItemTemplate>  
  80.                        <ItemStyle Width="100px" />  
  81.                    </asp:TemplateField>  
  82.                    <asp:TemplateField HeaderText="LOCATION">  
  83.                         
  84.                        <ItemTemplate>  
  85.                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("Location") %>'></asp:Label>  
  86.                        </ItemTemplate>  
  87.                        <ItemStyle Width="150px" />  
  88.                    </asp:TemplateField>  
  89.   
  90.                     <asp:TemplateField HeaderText="DEPARTMENT">  
  91.                       
  92.                        <ItemTemplate>  
  93.                            <asp:Label ID="Label5" runat="server" Text='<%# Bind("Dept") %>'></asp:Label>  
  94.                        </ItemTemplate>  
  95.                        <ItemStyle Width="150px" />  
  96.                    </asp:TemplateField>  
  97.          
  98.                    <asp:TemplateField HeaderText="EDIT" ShowHeader="False">  
  99.                         
  100.                        <ItemTemplate>  
  101.                            <asp:Button ID="Button1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />  
  102.                        </ItemTemplate>  
  103.                    </asp:TemplateField>  
  104.          
  105.                    <asp:TemplateField HeaderText="DELETE">  
  106.                        <ItemTemplate>  
  107.                            <asp:Button ID="Button2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" />  
  108.                        </ItemTemplate>  
  109.                    </asp:TemplateField>  
  110.          
  111.            </Columns>  
  112.                 <FooterStyle BackColor="#CCCCCC" />  
  113.                 <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />  
  114.                 <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />  
  115.                 <RowStyle BackColor="White" />  
  116.                 <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />  
  117.                 <SortedAscendingCellStyle BackColor="#F1F1F1" />  
  118.                 <SortedAscendingHeaderStyle BackColor="#808080" />  
  119.                 <SortedDescendingCellStyle BackColor="#CAC9C9" />  
  120.                 <SortedDescendingHeaderStyle BackColor="#383838" />  
  121.             </asp:GridView>  
  122.   
  123.         </div>  
  124.       
  125.    
  126.     </form>  
  127. </body>  
  128. </html>  
Now write the following logic in the code behind window.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.ServiceModel;  
  8. using System.Data;  
  9. namespace WCFClient  
  10. {  
  11.     public partial class CRUD : System.Web.UI.Page  
  12.     {  
  13.         ServiceReference.Service1Client obj = new ServiceReference.Service1Client();  
  14.         ServiceReference.Employee1 emp = new ServiceReference.Employee1();  
  15.         protected void Page_Load(object sender, EventArgs e)  
  16.         {  
  17.               
  18.             if(!IsPostBack)  
  19.             {  
  20.   
  21.                 BindData();  
  22.   
  23.             }  
  24.   
  25.         }  
  26.         public void BindData()  
  27.         {  
  28.             List<ServiceReference.Employee1> li = new List<ServiceReference.Employee1>();  
  29.   
  30.   
  31.             li = obj.ShowAll();  
  32.   
  33.             GridView1.DataSource = li;  
  34.             GridView1.DataBind();  
  35.              
  36.   
  37.         }  
  38.   
  39.         protected void btn_save_Click(object sender, EventArgs e)  
  40.         {  
  41.             if(btn_save.Text=="SAVE")  
  42.             {  
  43.                 ServiceReference.Employee1 employee = new ServiceReference.Employee1();  
  44.                 emp.EmpName = txt_name.Text;  
  45.                 emp.CompanyName = txt_company.Text;  
  46.                 emp.Dept = txt_dept.Text;  
  47.                 emp.Location = txt_location.Text;  
  48.                 bool x = false;  
  49.                 x = obj.InsertData(emp);  
  50.                 if (x == true)  
  51.                 {  
  52.                     Response.Write("<script LANGUAGE="'JavaScript'" >alert('Data Inserted Successfully.')</script>");  
  53.                     clear();  
  54.                     BindData();  
  55.                 }  
  56.                 else  
  57.                 {  
  58.                     Response.Write("<script LANGUAGE="'JavaScript'" >alert('Please try again.')</script>");  
  59.                 }  
  60.   
  61.             }  
  62.             else  
  63.             {  
  64.                 ServiceReference.Employee1 employee = new ServiceReference.Employee1();  
  65.                 emp.EmpName = txt_name.Text;  
  66.                 emp.CompanyName = txt_company.Text;  
  67.                 emp.Dept = txt_dept.Text;  
  68.                 emp.Location = txt_location.Text;  
  69.                 emp.EmpId = Convert.ToInt32(lbl_id.Text);  
  70.                 bool x = false;  
  71.                 x = obj.UpdateData(emp);  
  72.                 if (x == true)  
  73.                 {  
  74.                     Response.Write("<script LANGUAGE="'JavaScript'" >alert('Data Updated Successfully.')</script>");  
  75.                     btn_save.Text = "SAVE";  
  76.                     GridView1.EditIndex =-1;  
  77.                     clear();  
  78.                     BindData();  
  79.                       
  80.                 }  
  81.                 else  
  82.                 {  
  83.                     Response.Write("<script LANGUAGE="'JavaScript'" >alert('Please try again.')</script>");  
  84.                 }  
  85.   
  86.             }  
  87.              
  88.         }  
  89.         public void clear()  
  90.         {  
  91.             txt_company.Text = "";  
  92.             txt_dept.Text = "";  
  93.             txt_location.Text = "";  
  94.             txt_name.Text = "";  
  95.         }  
  96.   
  97.         protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  98.         {  
  99.             List<ServiceReference.Employee1> li = new List<ServiceReference.Employee1>();  
  100.             Label lbl = (Label)GridView1.Rows[e.NewEditIndex].FindControl("lbl_empid");  
  101.             int userId =Convert.ToInt32(lbl.Text);  
  102.             DataTable dt = new DataTable();  
  103.             li = obj.getRecordbyId(userId);  
  104.             foreach(var x in li)  
  105.             {  
  106.                 txt_company.Text = x.CompanyName;  
  107.                 txt_dept.Text = x.Dept;  
  108.                 txt_location.Text = x.Location;  
  109.                 txt_name.Text = x.EmpName;  
  110.                 lbl_id.Text = (x.EmpId).ToString();  
  111.                 btn_save.Text = "UPDATE";  
  112.                 BindData();  
  113.             }  
  114.   
  115.   
  116.         }  
  117.   
  118.         protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  119.         {  
  120.   
  121.         }  
  122.   
  123.         protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  124.         {  
  125.              Label lbl_delID = (Label)GridView1.Rows[e.RowIndex].FindControl("lbl_empid");  
  126.              ServiceReference.Employee1 obj1 = new ServiceReference.Employee1();  
  127.              obj1.EmpId = Convert.ToInt32(lbl_delID.Text);  
  128.                bool m= obj.DeleteData(obj1);  
  129.             if(m==true)  
  130.             {  
  131.                 Response.Write("<script LANGUAGE="'JavaScript'" >alert('Data Deleted')</script>");  
  132.   
  133.             }  
  134.             else  
  135.             {  
  136.                 Response.Write("<script LANGUAGE="'JavaScript'" >alert('Please try again.')</script>");  
  137.             }  
  138.   
  139.             BindData();  
  140.   
  141.               
  142.         }  
  143.     }  
  144. }  
After this you can run and check your project .
 
It will get added like this.
 
 
Now if you want to Edit you can Edit Like this. 
 
Now after Clicking Update it will update it as follows.
 
So you can update anything by clicking update button.Similarly the delete button will work and delete the record you selected.
 
So in this way we can create WCF service and Consume in our Asp.Net Application. You can check the project sample on gitHub.
Read more articles on ASP.NET:

Up Next
    Ebook Download
    View all
    Learn
    View all