CRUD Operations Using WCF in ASP.Net

This article explains the following topics:

  • How to create a WCF service
  • How to consume the WCF service in your ASP.Net application
  • How to bind a GridView using the WCF service
  • How to do insert, edit, update and delete operations on the GridView using the WCF service

The Database

Set up your database depending on the requirements. In the following WCF CRUD example I use the following tables and Stored Procedures.

Mas_Employee table

 

Figure 1: Mas_Employee table

Mas_Department table

 

Figure 2: Mas_Department table

To get the emplyees by am optional parameter:

  1. Create Procedure Get_AllEmployees  
  2. @Id int = null  
  3. AS  
  4. Begin  
  5. Select E.Id, E.Name, E.Salary,E.DeptID,D.DeptName  
  6. From Mas_Employee E  
  7. Join Mas_Department D  
  8. On E.DeptId = D.DeptId  
  9. where D.Status = 1  
  10. And Id = Isnull(@Id, Id)  
  11. End  

To Insert emplyee details into the Mas_Employee table:

  1. Create Procedure USP_Emp_Insert  
  2. @Name varchar(50),  
  3. @Salary int,  
  4. @DeptId int  
  5. AS  
  6. Begin  
  7. Insert into Mas_Employee  
  8. (Name,Salary,DeptId) Values  
  9. (@Name,@Salary,@DeptId)  
  10. End  

To update the emplyee details in the Mas_Employee table:

  1. Create Procedure USP_Emp_Update  
  2. @Id int,  
  3. @Name varchar(50),  
  4. @Salary int,  
  5. @DeptId int  
  6. AS  
  7. Begin  
  8. update Mas_Employee Set  
  9. Name=@Name,  
  10. Salary=@Salary,  
  11. DeptId=@DeptId  
  12. where Id=@Id  
  13. End  

To delete emplyee details in the Mas_Employee table:

  1. Create Procedure USP_Emp_Delete  
  2. @Id int  
  3. AS  
  4. Begin  
  5. Delete From Mas_Employee  
  6. where Id=@Id  
  7. End  

WCF Service and Application

Open Visual Studio then go to "File" -> "New" -> "Project..." then select WCF Service Application and provide it the name " WCF_Crud" as shown in the following image.

 

Figure 3: Create WCF Service Application

Two files, IService1.cs and Service1.svc, will be added under the project in the Solution Explorer as shown in the following image.

Figure 4: Solution Explorer

In the web.config.

Here you have seen some predefined code that is automatically generated when the WCF Service Application is created.

Figure 5: Web Config

Next make a ConnectionString in the Wb.Config as in the following:

  1. <connectionStrings>  
  2. <add name="conStr" connectionString="Password=1234; User ID=sa; Database=DB_WCF; Data Source=." providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  

Next open the Iservices1.cs file and remove all the default code and declare the Service Contracts, Operation Contracts and Data Contracts.

Add the following namespace first:

  1. using System.Data;  
  2. namespace WCF_Crud  
  3. {  
  4.     [ServiceContract]  
  5.     public interface IService1  
  6.     {  
  7.         [OperationContract]  
  8.         string InsertEmpDetails(EmpDetails eDatils);  
  9.         [OperationContract]  
  10.         DataSet GetEmpDetails(EmpDetails eDatils);  
  11.         [OperationContract]  
  12.         DataSet FetchUpdatedRecords(EmpDetails eDatils);  
  13.         [OperationContract]  
  14.         string UpdateEmpDetails(EmpDetails eDatils);  
  15.         [OperationContract]  
  16.         bool DeleteEmpDetails(EmpDetails eDatils);  
  17.     }  
  18.     // Use a data contract as illustrated in the sample below to add composite types to service operations.  
  19.     [DataContract]  
  20.     public class EmpDetails  
  21.     {  
  22.         int ? eId;  
  23.         string eName = string.Empty;  
  24.         string eSalary = string.Empty;  
  25.         string eDeptId = string.Empty;  
  26.         string eDeptName = string.Empty;  
  27.         [DataMember]  
  28.         public int ? Id  
  29.         {  
  30.             get {  
  31.                 return eId;  
  32.             }  
  33.             set {  
  34.                 eId = value;  
  35.             }  
  36.         }  
  37.         [DataMember]  
  38.         public string Name  
  39.         {  
  40.             get {  
  41.                 return eName;  
  42.             }  
  43.             set {  
  44.                 eName = value;  
  45.             }  
  46.         }  
  47.         [DataMember]  
  48.         public string Salary  
  49.         {  
  50.             get {  
  51.                 return eSalary;  
  52.             }  
  53.             set {  
  54.                 eSalary = value;  
  55.             }  
  56.         }  
  57.         [DataMember]  
  58.         public string DeptId  
  59.         {  
  60.             get {  
  61.                 return eDeptId;  
  62.             }  
  63.             set {  
  64.                 eDeptId = value;  
  65.             }  
  66.         }  
  67.         [DataMember]  
  68.         public string DeptName  
  69.         {  
  70.             get {  
  71.                 return eDeptName;  
  72.             }  
  73.             set {  
  74.                 eDeptName = value;  
  75.             }  
  76.         }  
  77.     }  
  78. }  

And next open the Service.svc.cs file and remove the default code and define the methods declared in the IService1.cs above.

Add the following namespaces:

  1. using System.Data;  
  2. using System.Data.SqlClient;  
  3. using System.Configuration;  
  4. namespace WCF_Crud  
  5. {  
  6.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.  
  7.     public class Service1: IService1  
  8.     {  
  9.         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);  
  10.         public string InsertEmpDetails(EmpDetails eDetails)  
  11.         {  
  12.             string Status;  
  13.             SqlCommand cmd = new SqlCommand("USP_Emp_Insert", con);  
  14.             cmd.CommandType = CommandType.StoredProcedure;  
  15.             cmd.Parameters.AddWithValue("@Name", eDetails.Name);  
  16.             cmd.Parameters.AddWithValue("@Salary", eDetails.Salary);  
  17.             cmd.Parameters.AddWithValue("@DeptId", eDetails.DeptId);  
  18.             if (con.State == ConnectionState.Closed)  
  19.             {  
  20.                 con.Open();  
  21.             }  
  22.             int result = cmd.ExecuteNonQuery();  
  23.             if (result == 1)  
  24.             {  
  25.                 Status = eDetails.Name + " " + eDetails.Salary + " registered successfully";  
  26.             }   
  27.             else  
  28.             {  
  29.                 Status = eDetails.Name + " " + eDetails.Salary + " could not be registered";  
  30.             }  
  31.             con.Close();  
  32.             return Status;  
  33.         }  
  34.         public DataSet GetEmpDetails(EmpDetails eDetails)  
  35.         {  
  36.             SqlCommand cmd = new SqlCommand("Get_AllEmployees", con);  
  37.             cmd.CommandType = CommandType.StoredProcedure;  
  38.             cmd.Parameters.AddWithValue("@Id", eDetails.Id);  
  39.             if (con.State == ConnectionState.Closed)  
  40.             {  
  41.                 con.Open();  
  42.             }  
  43.             SqlDataAdapter da = new SqlDataAdapter(cmd);  
  44.             DataSet ds = new DataSet();  
  45.             da.Fill(ds);  
  46.             cmd.ExecuteNonQuery();  
  47.             con.Close();  
  48.             return ds;  
  49.         }  
  50.         public DataSet FetchUpdatedRecords(EmpDetails eDetails)  
  51.         {  
  52.             SqlCommand cmd = new SqlCommand("Get_AllEmployees", con);  
  53.             cmd.CommandType = CommandType.StoredProcedure;  
  54.             cmd.Parameters.AddWithValue("@Id", eDetails.Id);  
  55.             if (con.State == ConnectionState.Closed)  
  56.             {  
  57.                 con.Open();  
  58.             }  
  59.             SqlDataAdapter da = new SqlDataAdapter(cmd);  
  60.             DataSet ds = new DataSet();  
  61.             da.Fill(ds);  
  62.             cmd.ExecuteNonQuery();  
  63.             con.Close();  
  64.             return ds;  
  65.         }  
  66.         public string UpdateEmpDetails(EmpDetails eDetails)  
  67.         {  
  68.             string Status;  
  69.             SqlCommand cmd = new SqlCommand("USP_Emp_Update", con);  
  70.             cmd.CommandType = CommandType.StoredProcedure;  
  71.             cmd.Parameters.AddWithValue("@Id", eDetails.Id);  
  72.             cmd.Parameters.AddWithValue("@Name", eDetails.Name);  
  73.             cmd.Parameters.AddWithValue("@Salary", eDetails.Salary);  
  74.             cmd.Parameters.AddWithValue("@DeptId", eDetails.DeptId);  
  75.             if (con.State == ConnectionState.Closed)  
  76.             {  
  77.                 con.Open();  
  78.             }  
  79.             int result = cmd.ExecuteNonQuery();  
  80.             if (result == 1)  
  81.             {  
  82.                 Status = "Record updated successfully";  
  83.             }   
  84.             else  
  85.             {  
  86.                 Status = "Record could not be updated";  
  87.             }  
  88.             con.Close();  
  89.             return Status;  
  90.         }  
  91.         public bool DeleteEmpDetails(EmpDetails eDetails)  
  92.         {  
  93.             SqlCommand cmd = new SqlCommand("USP_Emp_Delete", con);  
  94.             cmd.CommandType = CommandType.StoredProcedure;  
  95.             cmd.Parameters.AddWithValue("@Id", eDetails.Id);  
  96.             if (con.State == ConnectionState.Closed)  
  97.             {  
  98.                 con.Open();  
  99.             }  
  100.             cmd.ExecuteNonQuery();  
  101.             con.Close();  
  102.             return true;  
  103.         }  
  104.     }  
  105. }  

Go to the Solutions Explorer then right-click on Service1.svc then click on "View in Browser" as shown in the following diagram.

Figure 6: View in Browser

It will appear as shown in the following image:

Figure 7: Service1

Copy the URL. Keep it in a Notepad instance. Why? Because it will be used later when consuming this WCF service in your application. You have now created your WCF service successfully. And the next thing is to to call/consume this service in your ASP.Net application.

Create your ASP.Net application and consume the preceding new WCF service

Open Visual Studio then go to "File" -> "New" -> "Project..." then select Web -> ASP.Net Empty Web Application and name it "ConsumeWcfCrud" as shown in the following image:

Figure 8: ASP.NET Empty Application

Next add a webfrom to your project and name it Samle.aspx.

To consume/call the WCF service and its methods we need to add the service reference. For that go to Solution Explorer then right-click on the project then select add Service Reference as shown in the following image.

Figure 9: Add Service Reference

A new window will appear as shown in the following image:

Figure 10: Add Address

Paste the copied Service URL, http://localhost:53561/Service1.svc, as shown in the following image. Next click on the GO Button. Expand the Services and click on Iservice1. It will list all the functions/methods created in Services. Change the namespace ServiceReference1 to WcfCrudRef or you can use your own namespace and then click on the OK button.

Figure 11: Change namespace

References have been added to the Solution Explorer as shown in the following image.

Figure 12: Reference Added

Now it's time to design the .aspx. Copy the following code into your aspx.

  1. <form id="form1" runat="server">  
  2.     <div style="width:100%;" align="center">  
  3.         <fieldset style="width:40%;">  
  4.             <legend>Perform CRUD Operations using WCF</legend>  
  5.             <table style="width:100%;">  
  6.                 <tr>  
  7.                     <td>Name</td>  
  8.                     <td>  
  9.                         <asp:TextBox ID="txtName" runat="server" ></asp:TextBox>  
  10.                     </td>  
  11.                 </tr>  
  12.                 <tr>  
  13.                     <td>Salary</td>  
  14.                     <td>  
  15.                         <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>  
  16.                     </td>  
  17.                 </tr>  
  18.                 <tr>  
  19.                     <td>DeptId</td>  
  20.                     <td>  
  21.                         <asp:TextBox ID="txtDeptId" runat="server"></asp:TextBox>  
  22.                     </td>  
  23.                 </tr>  
  24.                 <tr>  
  25.                     <td></td>  
  26.                     <td class="style1">  
  27.                         <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />  
  28.                         <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />  
  29.                     </td>  
  30.                 </tr>  
  31.                 <tr>  
  32.                     <td colspan="2">  
  33.                         <asp:Label ID="lblStatus" runat="server"></asp:Label>  
  34.                     </td>  
  35.                 </tr>  
  36.                 <tr>  
  37.                     <td colspan="2">  
  38.                         <br />  
  39.                     </td>  
  40.                 </tr>  
  41.                 <tr>  
  42.                     <td colspan="2">  
  43.                         <asp:GridView ID="grdWcfTest" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"  
  44. CellPadding="5" Width="100%">  
  45.                             <AlternatingRowStyle BackColor="White" ForeColor="#284775" />  
  46.                             <Columns>  
  47.                                 <asp:TemplateField HeaderText="Name">  
  48.                                     <ItemTemplate>  
  49.                                         <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'>  
  50.                                         </asp:Label>  
  51.                                         <asp:Label ID="lblId" runat="server" Visible="false" Text='<%#Eval("Id")%>'>  
  52.                                         </asp:Label>  
  53.                                     </ItemTemplate>  
  54.                                 </asp:TemplateField>  
  55.                                 <asp:TemplateField HeaderText="Salary">  
  56.                                     <ItemTemplate>  
  57.                                         <asp:Label ID="lblSalary" runat="server" Text='<%#Eval("Salary") %>'>  
  58.                                         </asp:Label>  
  59.                                     </ItemTemplate>  
  60.                                 </asp:TemplateField>  
  61.                                 <asp:TemplateField HeaderText="DeptId">  
  62.                                     <ItemTemplate>  
  63.                                         <asp:Label ID="lblDeptId" runat="server" Text='<%#Eval("DeptId") %>'>  
  64.                                         </asp:Label>  
  65.                                     </ItemTemplate>  
  66.                                 </asp:TemplateField>  
  67.                                 <asp:TemplateField HeaderText="Edit">  
  68.                                     <ItemTemplate>  
  69.                                         <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CausesValidation="false"  
  70. CommandArgument=' <%#Eval("Id") %>OnCommand="lnkEdit_Command" ToolTip="Edit" />  
  71.                                         </ItemTemplate>  
  72.                                     </asp:TemplateField>  
  73.                                     <asp:TemplateField HeaderText="Delete">  
  74.                                         <ItemTemplate>  
  75.                                             <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CausesValidation="false"  
  76.   
  77. CommandArgument='  
  78.                                                 <%#Eval("Id") %>CommandName="Delete" OnCommand="lnkDelete_Command"  
  79.   
  80. OnClientClick="return confirm('Are you sure you want to delete?')" ToolTip="Delete" />  
  81.                                             </ItemTemplate>  
  82.                                         </asp:TemplateField>  
  83.                                     </Columns>  
  84.                                 </asp:GridView>  
  85.                             </td>  
  86.                         </tr>  
  87.                 </table>  
  88.         </fieldset>  
  89.     </div>  
  90. </form>  

CodeBehind

First add the following namespaces:

  1. using System.Data;  
  2. using System.Data.SqlClient;  
  3. using System.Configuration;  
  4. using ConsumeWcfCrud.WcfCrudRef;  
  5. namespace ConsumeWcfCrud  
  6. {  
  7.     public partial class WebForm1: System.Web.UI.Page  
  8.     {  
  9.         #region Variable Declaration  
  10.         WcfCrudRef.Service1Client obj = new WcfCrudRef.Service1Client();  
  11.         #endregion  
  12.         #region User Define Methods  
  13.         private void ClearControls()  
  14.         {  
  15.             txtName.Text = string.Empty;  
  16.             txtSalary.Text = string.Empty;  
  17.             txtDeptId.Text = string.Empty;  
  18.             btnSubmit.Text = "Submit";  
  19.             txtName.Focus();  
  20.         }  
  21.         private void BindEmpDetails(int ? Id)  
  22.         {  
  23.             EmpDetails eDetails = new EmpDetails();  
  24.             DataSet ds = new DataSet();  
  25.             ds = obj.GetEmpDetails(eDetails);  
  26.             grdWcfTest.DataSource = ds;  
  27.             grdWcfTest.DataBind();  
  28.         }  
  29.         private void SaveEmpDetails()  
  30.         {  
  31.             EmpDetails eDetails = new EmpDetails();  
  32.             eDetails.Name = txtName.Text.Trim();  
  33.             eDetails.Salary = txtSalary.Text.Trim();  
  34.             eDetails.DeptId = txtDeptId.Text.Trim();  
  35.             lblStatus.Text = obj.InsertEmpDetails(eDetails);  
  36.             ClearControls();  
  37.             BindEmpDetails(null);  
  38.         }  
  39.         private void UpdateEmpDetails()  
  40.         {  
  41.             EmpDetails eDetails = new EmpDetails();  
  42.             eDetails.Id = Convert.ToInt32(ViewState["Id"].ToString());  
  43.             eDetails.Name = txtName.Text.Trim();  
  44.             eDetails.Salary = txtSalary.Text.Trim();  
  45.             eDetails.DeptId = txtDeptId.Text.Trim();  
  46.             obj.UpdateEmpDetails(eDetails);  
  47.             lblStatus.Text = obj.UpdateEmpDetails(eDetails);  
  48.             ClearControls();  
  49.             BindEmpDetails(null);  
  50.         }  
  51.         #endregion  
  52.         #region Page Event Handlers  
  53.         protected void Page_Load(object sender, EventArgs e)  
  54.         {  
  55.             if (!Page.IsPostBack)  
  56.             {  
  57.                 BindEmpDetails(null);  
  58.                 ClearControls();  
  59.                 lblStatus.Text = String.Empty;  
  60.             }  
  61.         }  
  62.         protected void btnSubmit_Click(object sender, EventArgs e)  
  63.         {  
  64.             if (btnSubmit.Text == "Update")  
  65.             {  
  66.                 UpdateEmpDetails();  
  67.             }   
  68.             else  
  69.             {  
  70.                 SaveEmpDetails();  
  71.             }  
  72.         }  
  73.         protected void lnkEdit_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)  
  74.         {  
  75.             EmpDetails eDetails = new EmpDetails();  
  76.             eDetails.Id = int.Parse(e.CommandArgument.ToString());  
  77.             ViewState["Id"] = eDetails.Id;  
  78.             DataSet ds = new DataSet();  
  79.             ds = obj.FetchUpdatedRecords(eDetails);  
  80.             if (ds.Tables[0].Rows.Count > 0)  
  81.             {  
  82.                 txtName.Text = ds.Tables[0].Rows[0]["Name"].ToString();  
  83.                 txtSalary.Text = ds.Tables[0].Rows[0]["Salary"].ToString();  
  84.                 txtDeptId.Text = ds.Tables[0].Rows[0]["DeptId"].ToString();  
  85.                 btnSubmit.Text = "Update";  
  86.             }  
  87.         }  
  88.         protected void lnkDelete_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)  
  89.         {  
  90.             EmpDetails eDetails = new EmpDetails();  
  91.             eDetails.Id = int.Parse(e.CommandArgument.ToString());  
  92.             if (obj.DeleteEmpDetails(eDetails) == true)  
  93.             {  
  94.                 lblStatus.Text = "Record deleted Successfully";  
  95.             }   
  96.             else  
  97.             {  
  98.                 lblStatus.Text = "Record couldn't be deleted";  
  99.             }  
  100.             BindEmpDetails(null);  
  101.         }  
  102.         protected void btnCancel_Click(object sender, EventArgs e)  
  103.         {  
  104.             ClearControls();  
  105.             lblStatus.Text = string.Empty;  
  106.         }  
  107.         #endregion  
  108.     }  
  109. }  

Run the Applicatin and perform CRUD operations.

Output

Figure 13: Output

I hope you enjoyed it. Please provide your valuable suggestions and feedback if you found this article is helpful.


Similar Articles