CRUD Operations in ASP.Net Using WCF Service

Overview

In this article we will do Create, Retrieve, Update and Delete (CRUD) operations using the Windows Communication Foundation (WCF) services. In other words, in this article we will create two applications, the first for the WCF Service and the second to use the service. So before starting anything with it we should be familiar with WCF. So let's learn about it.

WCF is a framework for building service-oriented applications. So using WCF services, we can send data asynchronously from one service endpoint to another. Where endpoint can be part of a continuously available service hosted by IIS. In WCF services three important things are necessary to understand. We commonly callthem the ABCs of WCF Services, in other words:

  • Address
     
  • Binding
     
  • Contract 

Where address specifies where the service is, binding specifies what type of binding mode we want to use (where binding mode may be HTTP, TCP, MSMQ and so on) and contract specifies what service you want to provide. Let's learn about it, how we will do it.

Application I: WCF Service

Step 1

First we will create a WCF Service Application.

In Visual Studio 2010 select "File" -> "New" -> "Project..." and select "WCF" -> "WCF Service Application". For more see Figure 1.

Figure1

NewProjectWCF1

Step 2
 
Now watch in Solution Explorer, there will be the three files there IService1.cs, Service1.svc and Web.config. It is unnecessary to rename the file. For increased convenience, IService1 -> IEmployeeService and Service1 -> EmployeeService. After renaming the file your Solution Explorer will look like Figure 2.

Figure 2

SolutionExp1

Step 3

Some default lines of code we will see in all these three files. So we can change it depending on our requirements. So in this article we will create a service for Employee Records that can add an employee, update employee information, search for an employee, display an employee and delete an employee.

IEmployeeService.cs: Replace the default code of this file with the following code. 

  1. namespace EmployeeServices  
  2. {  
  3.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.  
  4.     [ServiceContract]  
  5.     public interface IEmployeeService   
  6.     {  
  7.   
  8.         [OperationContract]  
  9.         string GetData(int value);  
  10.   
  11.         [OperationContract]  
  12.         string AddEmployyeeRecord(Employee emp);  
  13.   
  14.         [OperationContract]  
  15.         DataSet GetEmployeeRecords();  
  16.   
  17.         [OperationContract]  
  18.         string DeleteRecords(Employee emp);  
  19.   
  20.         [OperationContract]  
  21.         DataSet SearchEmployeeRecord(Employee emp);  
  22.   
  23.         [OperationContract]  
  24.         string UpdateEmployeeContact(Employee emp);    
  25.   
  26.          
  27.     }  
  28.   
  29.   
  30.     // Use a data contract as illustrated in the sample below to add composite types to service operations.  
  31.     [DataContract]  
  32.     public class Employee  
  33.     {  
  34.           
  35.         string _empID = "";  
  36.         string _name = "";  
  37.         string _email = "";  
  38.         string _phone = "";  
  39.         string _gender = "";          
  40.           
  41.         [DataMember]  
  42.         public string EmpID  
  43.         {  
  44.             get { return _empID; }  
  45.             set { _empID = value; }  
  46.         }  
  47.   
  48.         [DataMember]  
  49.         public string Name  
  50.         {  
  51.             get { return _name; }  
  52.             set { _name = value; }  
  53.         }  
  54.   
  55.         [DataMember]  
  56.         public string Email  
  57.         {  
  58.             get { return _email; }  
  59.             set { _email = value; }  
  60.         }  
  61.   
  62.         [DataMember]  
  63.         public string Phone  
  64.         {  
  65.             get { return _phone; }  
  66.             set { _phone = value; }  
  67.         }  
  68.   
  69.         [DataMember]  
  70.         public string Gender  
  71.         {  
  72.             get { return _gender; }  
  73.             set { _gender = value; }  
  74.         }  
  75.     }  
  76. }  

Basically in the preceding code we have declared the four methods for CRUD operations. Now we will implement these methods in EmployeeService.cs.

Step 4

In EmployeeService.cs we will define the body of all these four methods. So replace the default line of code with the following code. 

  1. namespace EmployeeServices  
  2. {  
  3.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.  
  4.     public class EmpService : IEmployeeService   
  5.     {  
  6.   
  7.   
  8.         public string GetData(int value)  
  9.         {  
  10.             return string.Format("You entered: {0}", value);  
  11.         }  
  12.   
  13.         //C- Add Employee Record  
  14.         public string AddEmployyeeRecord(Employee emp)   
  15.         {  
  16.             string result = "";  
  17.             try  
  18.             {  
  19.   
  20.                 SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP35\\SQLEXPRESS;Initial Catalog=EmployeeDb;User ID=sa;Password=Password$2;");  
  21.                 SqlCommand cmd = new SqlCommand();                  
  22.   
  23.                 string Query = @"INSERT INTO tblEmployee (EmpID,Name,Email,Phone,Gender)  
  24.                                                Values(@EmpID,@Name,@Email,@Phone,@Gender)";  
  25.   
  26.                 cmd = new SqlCommand(Query, con);  
  27.                 cmd.Parameters.AddWithValue("@EmpID", emp.EmpID);  
  28.                 cmd.Parameters.AddWithValue("@Name", emp.Name);  
  29.                 cmd.Parameters.AddWithValue("@Email", emp.Email);  
  30.                 cmd.Parameters.AddWithValue("@Phone", emp.Phone);  
  31.                 cmd.Parameters.AddWithValue("@Gender", emp.Gender);  
  32.                 con.Open();  
  33.                 cmd.ExecuteNonQuery();  
  34.                 con.Close();  
  35.                 result = "Record Added Successfully !";  
  36.             }  
  37.             catch (FaultException fex)  
  38.             {  
  39.                 result = "Error";  
  40.             }  
  41.   
  42.              return result;               
  43.         }  
  44.   
  45.         //Retrieve Data  
  46.         //Retrive Record  
  47.         public DataSet GetEmployeeRecords()  
  48.         {  
  49.             DataSet ds = new DataSet();  
  50.             try  
  51.             {  
  52.                 SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP35\\SQLEXPRESS;Initial Catalog=EmployeeDb;User ID=sa;Password=Password$2;");  
  53.                 string Query = "SELECT * FROM tblEmployee";  
  54.   
  55.                 SqlDataAdapter sda = new SqlDataAdapter(Query, con);  
  56.                 sda.Fill(ds);  
  57.             }  
  58.             catch (FaultException fex)  
  59.             {  
  60.                 throw new FaultException<string>("Error: "+fex);  
  61.             }  
  62.               
  63.             return ds;  
  64.         }  
  65.   
  66.         //Delete Record  
  67.         public string DeleteRecords(Employee emp)  
  68.         {  
  69.             string result = "";  
  70.             SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP35\\SQLEXPRESS;Initial Catalog=EmployeeDb;User ID=sa;Password=Password$2;");  
  71.             SqlCommand cmd = new SqlCommand();  
  72.             string Query = "DELETE FROM tblEmployee Where EmpID=@EmpID";   
  73.             cmd = new SqlCommand(Query, con);  
  74.             cmd.Parameters.AddWithValue("@EmpID", emp.EmpID);  
  75.             con.Open();  
  76.             cmd.ExecuteNonQuery();  
  77.             con.Close();  
  78.             result = "Record Deleted Successfully!";  
  79.             return result;  
  80.         }  
  81.   
  82.         //Search Employee Record  
  83.         public DataSet SearchEmployeeRecord(Employee emp)  
  84.         {  
  85.             DataSet ds = new DataSet();  
  86.             try  
  87.             {  
  88.                 SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP35\\SQLEXPRESS;Initial Catalog=EmployeeDb;User ID=sa;Password=Password$2;");  
  89.                 string Query = "SELECT * FROM tblEmployee WHERE EmpID=@EmpID";  
  90.   
  91.                 SqlDataAdapter sda = new SqlDataAdapter(Query, con);  
  92.                 sda.SelectCommand.Parameters.AddWithValue("@EmpID", emp.EmpID);  
  93.                 sda.Fill(ds);  
  94.             }  
  95.             catch (FaultException fex)  
  96.             {  
  97.                 throw new FaultException<string>("Error:  " + fex);  
  98.             }  
  99.             return ds;          
  100.         }  
  101.   
  102.         //UPDATE RECORDS  
  103.         //Update by Phone Roll   
  104.         public string UpdateEmployeeContact(Employee emp)   
  105.         {  
  106.             string result = "";  
  107.             SqlConnection con = new SqlConnection("Data Source=MCNDESKTOP35\\SQLEXPRESS;Initial Catalog=EmployeeDb;User ID=sa;Password=Password$2;");  
  108.             SqlCommand cmd = new SqlCommand();  
  109.   
  110.             string Query = "UPDATE tblEmployee SET Email=@Email,Phone=@Phone WHERE EmpID=@EmpID";  
  111.   
  112.             cmd = new SqlCommand(Query, con);  
  113.             cmd.Parameters.AddWithValue("@EmpID", emp.EmpID);  
  114.             cmd.Parameters.AddWithValue("@Email", emp.Email);  
  115.             cmd.Parameters.AddWithValue("@Phone", emp.Phone);  
  116.             con.Open();  
  117.             cmd.ExecuteNonQuery();  
  118.             result = "Record Updated Successfully !";  
  119.             con.Close();  
  120.   
  121.             return result;  
  122.         }  
  123.           
  124.           
  125.     }  
  126. }  

Step 5

Now configure the Web.config file using the following code. 

  1. <?xml version="1.0"?>  
  2. <configuration>  
  3.   
  4.   <system.web>  
  5.     <compilation debug="true" targetFramework="4.0" />  
  6.   </system.web>  
  7.     
  8.   <system.serviceModel>  
  9.     <bindings>  
  10.       <wsHttpBinding>  
  11.         <binding name="wsHttpBinding_IService1" />  
  12.       </wsHttpBinding>  
  13.     </bindings>  
  14.     <client>  
  15.       <endpoint address=""  
  16.                 binding="wsHttpBinding"  
  17.                 contract="EmployeeServices.IEmployeeService"  
  18.                 bindingConfiguration="wsHttpBinding_IEmployeeService" />  
  19.     </client>  
  20.       
  21.     <behaviors>  
  22.       <serviceBehaviors>  
  23.         <behavior>  
  24.           <serviceMetadata httpGetEnabled="true"/>  
  25.           <serviceDebug includeExceptionDetailInFaults="true"/>  
  26.         </behavior>  
  27.       </serviceBehaviors>  
  28.     </behaviors>      
  29.   
  30.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  31.   </system.serviceModel>  
  32.     
  33.  <system.webServer>  
  34.     <modules runAllManagedModulesForAllRequests="true"/>  
  35.   </system.webServer>  
  36.     
  37. </configuration>  

 

WebconfigImage

Note:

Now build your application and run the service (F5), then you will see the following in the web browser.

ServiceRun

Now copy the URL from the browser, the URL will look like the following: http://localhost:5530/EmpService.svc. To use this service we will create another application.

Application II: Web Application

We can use this service in any type of application but for this example article we will create a web application.

Step I

In Visual Studio 2010 select "File" -> "New" -> "Project..." and select "Web" -> "ASP.NET Web Application".

*WebApplication

So for doing the CRUD operations we will create four aspx pages in this applciation. First create a master page.

  1. AddNewEmployee.aspx
     
  2. DisplayEmployeeRecord.aspx
     
  3. UpdateEmployee.aspx
     
  4. DeleteEmployee.aspx 

MasterPage: Employee.Master 

  1. <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Employee.master.cs" Inherits="Application.Employee" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <asp:ContentPlaceHolder ID="head" runat="server">  
  9.     </asp:ContentPlaceHolder>  
  10.     <style>  
  11.       body{width:100%; background-color:Silver;}  
  12.       .page-wrapper{width:700px; background-color:Orange; padding:0px; height:auto; overflow:hidden;}  
  13.       .header{height:50px; width:99%; padding:1%; background-color:Green; color:White; font-family:Segoe UI; font-size:30px;}  
  14.       .menu{height:30px; width:99%; padding:1%; background-color:White; color:White; font-family:Segoe UI; font-size:14px; clear:both; float:left; text-align:left;}  
  15.       .footer{height:30px; width:99%; padding:1%; background-color:Black; color:White; font-family:Segoe UI; font-size:12px; text-align:left; vertical-align:bottom; clear:both;}  
  16.       .button{width:110px; height:30px; border-style:none; background-color:Green; font-family:Verdana; font-size:15px; color:White;}  
  17.       .button:hover{background-color:Black;}  
  18.       .textBox{width:400px; background-color:White; border:1px Solid Navy; padding:5px; color:Black; font-family:Segoe UI; }  
  19.       .linkbutton{width:120px; padding:7px; background-color:Green;color:White; font-family:Verdana; font-size:16px; margin-right:1px; margin-top:2px; text-decoration:none;}  
  20.       .linkbutton:hover{background-color:Orange;}  
  21.     </style>  
  22. </head>  
  23. <body>  
  24.     <form id="form1" runat="server">  
  25.     <center>  
  26.     <div class="page-wrapper">  
  27.     <div class="header">  
  28.     CRUD Operation Using WCF Service  
  29.     </div>  
  30.     <div class="menu">  
  31.     <table style="float:left">  
  32.     <tr>  
  33.     <td><a href="AddNewEmployee.aspx" class="linkbutton" >Add New</a></td>  
  34.     <td><a href="UpdateEmployee.aspx" class="linkbutton" >Update</td>  
  35.     <td><a href="DeleteEmployee.aspx" class="linkbutton" >Delete</td>  
  36.     <td><a href="DissplayEmployeeRecord.aspx" class="linkbutton" >Display</td>  
  37.     </tr>  
  38.     </table>  
  39.     </div>  
  40.         <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">  
  41.           
  42.         </asp:ContentPlaceHolder>  
  43.         <div class="footer">  
  44.         By C# Corner 2014  
  45.         </div>  
  46.     </div>  
  47.     </center>  
  48.     </form>  
  49. </body>  
  50. </html>  
Step II

To use the CRUD services, we need to make reference to this current service that is running on IIS. To make the reference use the following procedure.

In Solution Explorer, right-click on the application name and move to "Add Service Reference...". For more see the following Figure 3.

Figure 3:

ServiceReference

Step III

First create a SQL database and table in which we will do CRUD operations.
 
EmployeeDb (Database) tblEmployee (table).
  1. Create database EmployeeDb;  
  2.   
  3. CREATE TABLE tblEmployee  
  4. (  
  5.   EmpId int NOT NULL PRIMARY KEY,  
  6.   Name nvarchar(50),  
  7.   Email nvarchar(50),  
  8.   Phone nvarchar(10),  
  9.   Gender char(10)  
  10. );  
Provide the following code for AddNewEmployee.aspx 
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Employee.Master" AutoEventWireup="true" CodeBehind="AddNewEmployee.aspx.cs" Inherits="Application.AddNewEmployee" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">  
  3.   
  4. </asp:Content>  
  5. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">  
  6.     <table style="width:100%; color:Black; font-family:Segoe UI; font-size:14px; float:left; text-align:left;">  
  7. <tr>  
  8. <td colspan="2"><asp:Label ID="lblMsg" runat="server" Font-Size="Medium" ></asp:Label></td>  
  9. </tr>  
  10. <tr>  
  11. <td>Employee ID</td>  
  12. <td><asp:TextBox ID="txtEmpID" runat="server" CssClass="textBox" ></asp:TextBox></td>  
  13. </tr>  
  14. <tr>  
  15. <td>Name</td>  
  16. <td><asp:TextBox ID="txtName" runat="server" CssClass="textBox" ></asp:TextBox></td>  
  17. </tr>  
  18. <tr>  
  19. <td>Email</td>  
  20. <td><asp:TextBox ID="txtEmail" runat="server" CssClass="textBox" ></asp:TextBox></td>  
  21. </tr>  
  22. <tr>  
  23. <td>Phone</td>  
  24. <td><asp:TextBox ID="txtPhone" runat="server" CssClass="textBox" ></asp:TextBox></td>  
  25. </tr>  
  26. <tr>  
  27. <td>Gender</td>  
  28. <td>  
  29. <asp:RadioButtonList ID="rbtnGender" runat="server" RepeatColumns="2" CssClass="textBox" >  
  30.     <asp:ListItem Selected="True">Male</asp:ListItem>  
  31.     <asp:ListItem>Female</asp:ListItem>  
  32. </asp:RadioButtonList></td>  
  33. </tr>  
  34. <tr>  
  35. <td colspan="2">  
  36. <asp:Button ID="btnSave" runat="server" Text="Save" CssClass="button"   
  37.         onclick="btnSave_Click" />  
  38. <asp:Button ID="bntReset" runat="server" Text="Reset" CssClass="button"   
  39.         onclick="bntReset_Click" />  
  40. </td>  
  41. </tr>  
  42. </tr>  
  43. </table>  
  44. </asp:Content>  

Provide the following code for AddNewEmployee.aspx.cs 

  1. namespace Application  
  2. {  
  3.     public partial class AddNewEmployee : System.Web.UI.Page  
  4.     {  
  5.         protected void Page_Load(object sender, EventArgs e)  
  6.         {  
  7.             if (!Page.IsPostBack)  
  8.             {  
  9.                 txtEmpID.Text = "";  
  10.                 txtName.Text = "";  
  11.                 txtEmail.Text = "";  
  12.                 txtPhone.Text = "";  
  13.                 lblMsg.Text = "";  
  14.                 txtEmpID.Focus();  
  15.             }  
  16.               
  17.         }  
  18.   
  19.         protected void btnSave_Click(object sender, EventArgs e)  
  20.         {  
  21.             //Adding New Employee Records  
  22.               
  23.             if ((txtEmpID.Text != "") || (txtName.Text != "") || (txtEmail.Text != "") || (txtPhone.Text != ""))  
  24.             {  
  25.                 try  
  26.                 {  
  27.                     MyService.Employee employee = new MyService.Employee();  
  28.                     employee.EmpID = txtEmpID.Text;  
  29.                     employee.Name = txtName.Text;  
  30.                     employee.Email = txtEmail.Text;  
  31.                     employee.Phone = txtPhone.Text;  
  32.                     employee.Gender = rbtnGender.SelectedItem.Text;  
  33.   
  34.                     MyService.EmployeeServiceClient client = new MyService.EmployeeServiceClient();  
  35.                     lblMsg.Text = "Employee ID: " + employee.EmpID + ", " + client.AddEmployyeeRecord(employee);  
  36.                 }  
  37.                 catch (Exception ex)  
  38.                 {  
  39.                     lblMsg.Text = "Employee ID must be unique! ";  
  40.                 }  
  41.   
  42.   
  43.             }  
  44.             else  
  45.             {  
  46.   
  47.                 lblMsg.Text = "All fields are mandatory! ";  
  48.                 lblMsg.ForeColor = System.Drawing.Color.Red;  
  49.             }           
  50.   
  51.   
  52.         }  
  53.   
  54.         protected void bntReset_Click(object sender, EventArgs e)  
  55.         {  
  56.             ClearForm();  
  57.         }  
  58.   
  59.         private void ClearForm()  
  60.         {  
  61.            txtEmpID.Text = "";  
  62.             txtName.Text = "";  
  63.             txtEmail.Text = "";  
  64.             txtPhone.Text = "";  
  65.             lblMsg.Text = "";  
  66.             txtEmpID.Focus();  
  67.         }  
  68.     }  
  69. }  

Step IV

Provide the following code for DisplayEmployeeRecord.aspx 

  1. <asp:GridView ID="grdEmployees" runat="server">  
  2.        <AlternatingRowStyle BackColor="White" />  
  3.        <HeaderStyle BackColor="#003300" Font-Bold="True" ForeColor="White" />  
  4.    </asp:GridView>  

Provide the following code for DisplayEmployeeRecord.aspx.cs

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.            if (!Page.IsPostBack)  
  4.            {  
  5.                DataSet ds = new DataSet();  
  6.                MyService.EmployeeServiceClient client = new MyService.EmployeeServiceClient();  
  7.                ds = client.GetEmployeeRecords();  
  8.                grdEmployees.DataSource = ds;  
  9.                grdEmployees.DataBind();  
  10.            }  
  11.  }  

Step V

Provide the following code for UpdateEmployee.aspx 

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Employee.Master" AutoEventWireup="true" CodeBehind="UpdateEmployee.aspx.cs" Inherits="Application.UpdateEmployee" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">  
  3. </asp:Content>  
  4. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">  
  5.   
  6. <table id="panSearch" runat="server" style="width:auto; color:Black; font-family:Segoe UI; font-size:14px; float:right; text-align:left; padding:10px; padding-bottom:20px;" >  
  7. <tr>  
  8. <td>Enter Employee ID</td>  
  9. <td><asp:TextBox ID="txtSearch" runat="server" CssClass="textBox" Placeholder="Enter Employee ID e.g 201" ></asp:TextBox></td>  
  10. <td><asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="button"   
  11.         onclick="btnSearch_Click" ></asp:Button></td>  
  12. </tr>  
  13. <tr>  
  14.   
  15. <td colspan="3" ><asp:Label ID="lblSearchResult" runat="server" Font-Size="Medium" ></asp:Label></td></tr>  
  16. </table>  
  17.   
  18.  <table id="panUpdate" runat="server" style="width:100%; color:Black; font-family:Segoe UI; font-size:14px; float:left; text-align:left;">  
  19. <tr>  
  20. <td colspan="2"><asp:Label ID="lblMsg" runat="server" Font-Size="Medium" ></asp:Label></td>  
  21. </tr>  
  22. <tr>  
  23. <td>Employee ID</td>  
  24. <td><asp:Label ID="lblEmpID" runat="server" ></asp:Label></td>  
  25. </tr>  
  26. <tr>  
  27. <td>Email</td>  
  28. <td><asp:TextBox ID="txtEmail" runat="server" CssClass="textBox" ></asp:TextBox></td>  
  29. </tr>  
  30. <tr>  
  31. <td>Phone</td>  
  32. <td><asp:TextBox ID="txtPhone" runat="server" CssClass="textBox" ></asp:TextBox></td>  
  33. </tr>  
  34. <tr>  
  35. <td colspan="2">  
  36. <asp:Button ID="bntUpdated" runat="server" Text="Update" CssClass="button" onclick="bntUpdated_Click"    
  37.          />  
  38. <asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="button" onclick="btnCancel_Click"   
  39.         />  
  40. </td>  
  41. </tr>  
  42. </table>  
  43. </asp:Content>  

Provide the following code for UpdateEmployee.aspx.cs 

  1. namespace Application  
  2. {  
  3.     public partial class UpdateEmployee : System.Web.UI.Page  
  4.     {  
  5.         MyService.Employee employee = new MyService.Employee();  
  6.         MyService.EmployeeServiceClient client = new MyService.EmployeeServiceClient();  
  7.   
  8.         DataSet ds;  
  9.   
  10.         protected void Page_Load(object sender, EventArgs e)  
  11.         {  
  12.             if (!Page.IsPostBack)  
  13.             {  
  14.                 SetPanel(true, false);  
  15.             }  
  16.         }  
  17.   
  18.         protected void btnSearch_Click(object sender, EventArgs e)  
  19.         {  
  20.             if (txtSearch.Text != "")  
  21.             {  
  22.                 employee.EmpID = txtSearch.Text.Trim();  
  23.                 ds = new DataSet();  
  24.                dsclient.SearchEmployeeRecord(employee);  
  25.   
  26.                if (ds.Tables[0].Rows.Count > 0)  
  27.                {  
  28.                    lblEmpID.Text = ds.Tables[0].Rows[0]["EmpID"].ToString();  
  29.                    txtEmail.Text = ds.Tables[0].Rows[0]["Email"].ToString();  
  30.                    txtPhone.Text = ds.Tables[0].Rows[0]["Phone"].ToString();  
  31.                    SetPanel(false, true);  
  32.   
  33.                }  
  34.                else  
  35.                {  
  36.                    lblSearchResult.Text = "Please Enter Employee ID !";  
  37.                    lblSearchResult.ForeColor = System.Drawing.Color.White;  
  38.                }  
  39.   
  40.             }  
  41.             else  
  42.             {  
  43.                 lblSearchResult.Text = "Please Enter Employee ID !";  
  44.             }  
  45.         }  
  46.   
  47.         private void SetPanel(bool pSearch, bool pUpdate)  
  48.         {  
  49.             panSearch.Visible = pSearch;  
  50.             panUpdate.Visible = pUpdate;  
  51.         }  
  52.   
  53.         protected void bntReset_Click(object sender, EventArgs e)  
  54.         {  
  55.             SetPanel(true, false);  
  56.         }  
  57.   
  58.         protected void btnCancel_Click(object sender, EventArgs e)  
  59.         {  
  60.             SetPanel(true, false);  
  61.             lblMsg.Text = "";  
  62.         }  
  63.   
  64.         protected void bntUpdated_Click(object sender, EventArgs e)  
  65.         {  
  66.             employee.EmpID = lblEmpID.Text.Trim();  
  67.             employee.EmailtxtEmail.Text;  
  68.             employee.Phone = txtPhone.Text;  
  69.   
  70.            string resultclient.UpdateEmployeeContact(employee);  
  71.            lblSearchResult.Text = result;  
  72.            SetPanel(true, false);  
  73.            txtPhone.Text = "";  
  74.            txtEmail.Text = "";  
  75.            lblEmpID.Text = "";  
  76.              
  77.         }  
  78.   
  79.           
  80.     }  
  81. }  

Step VI

Provide the following code for DeleteEmployee.aspx 

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Employee.Master" AutoEventWireup="true" CodeBehind="DeleteEmployee.aspx.cs" Inherits="Application.DeleteEmployee" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">  
  3. </asp:Content>  
  4. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">  
  5. <table id="panSearch" runat="server" style="width:auto; color:Black; font-family:Segoe UI; font-size:14px; float:left; text-align:left; padding:10px; padding-bottom:20px;" >  
  6. <tr>  
  7. <td>Employee ID</td>  
  8. <td><asp:TextBox ID="txtSearch" runat="server" CssClass="textBox" Placeholder="Enter employee id to delete it" ></asp:TextBox></td>  
  9. <td><asp:Button ID="btnDelete" runat="server" Text="Delete" CssClass="button" onclick="btnDelete_Click"   
  10.         ></asp:Button></td>  
  11. </tr>  
  12. <tr>  
  13. <td colspan="3" ><asp:Label ID="lblSearchResult" runat="server" Font-Size="Medium" ></asp:Label></td></tr>  
  14. </table>  
  15.  <hr />  
  16.  <div style="float:left" >  
  17.  <asp:GridView ID="grdEmployees" runat="server">  
  18.         <AlternatingRowStyle BackColor="White" />  
  19.         <HeaderStyle BackColor="#003300" Font-Bold="True" ForeColor="White" />  
  20.     </asp:GridView>  
  21.     </div>  
  22. </asp:Content>  

Provide the following code for DeleteEmployee.aspxcs 

  1. namespace Application  
  2. {  
  3.     public partial class DeleteEmployee : System.Web.UI.Page  
  4.     {  
  5.         protected void Page_Load(object sender, EventArgs e)  
  6.         {  
  7.             if (!Page.IsPostBack)  
  8.             {  
  9.                 BindGridData();  
  10.             }  
  11.         }  
  12.   
  13.         //Bind Grid  
  14.         public void BindGridData()  
  15.         {  
  16.             DataSet ds = new DataSet();  
  17.             MyService.EmployeeServiceClient client = new MyService.EmployeeServiceClient();  
  18.             ds = client.GetEmployeeRecords();  
  19.             grdEmployees.DataSource = ds;  
  20.             grdEmployees.DataBind();  
  21.         }  
  22.   
  23.          
  24.         protected void btnDelete_Click(object sender, EventArgs e)  
  25.         {  
  26.             MyService.EmployeeServiceClient client = new MyService.EmployeeServiceClient();  
  27.   
  28.             MyService.Employee employee = new MyService.Employee();  
  29.             employee.EmpID = txtSearch.Text.Trim();  
  30.             string result = client.DeleteRecords(employee);  
  31.   
  32.             if (result == "Record Deleted Successfully!")  
  33.             {  
  34.                 BindGridData();  
  35.                 lblSearchResult.Text = "Employee ID: " + txtSearch.Text.Trim() + "Deleted Successfully!";  
  36.             }  
  37.             else  
  38.             {  
  39.                 lblSearchResult.Text = "Employee ID: " + txtSearch.Text.Trim() + "Not Found!";  
  40.             }  
  41.         }  
  42.     }  
  43. }  

Now run this web applciation to test it; it will look like the following.

ADD NEW RECORD into tblEmployee (SQL).

AddNewRecord

DISPLAY ALL RECORDS

DisplayAllRecords

UPDATE RECORD BY EMP ID

UpdateRecords

DELETE RECORD BY EMP ID

DeleteRecords

Summary

In this article we learned about WCF services to do CRUD operations.

Up Next
    Ebook Download
    View all
    Learn
    View all