Introduction

WCF refers to Windows Communication Foundation and is a part of .NET 3.0 Framework, a product developed by Microsoft.

To get more details, visit my blog.

http://www.c-sharpcorner.com/blogs/key-notes-to-wcf


Description

We will be going through the following steps.
  • Create a WCF service.
  • Using WCF service in your ASP.Net application.
  • Bind a GridView using the WCF Service.
  • CRUD operations on the GridView using the WCF service in ASP.NET.
  • Textbox Validation using JavaScript.
Steps to be followed
Step1

Create two tables, as mentioned below.

Scripts
  1. CREATE TABLE [dbo].[Mas_Employee](
  2. [Id] [int] IDENTITY(1,1) NOT NULL,
  3. [Name] [varchar](50) NOT NULL,
  4. [Salary] [varchar](50) NOT NULL,
  5. [DeptId] [int] NOT NULL,
  6. [Status] [int] NULL,
  7. CONSTRAINT [PK_Mas_Employee] PRIMARY KEY CLUSTERED
  8. (
  9. [Id] ASC
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  11. ) ON [PRIMARY]
  12. GO
  13. CREATE TABLE [dbo].[Mas_Department](
  14. [DeptId] [int] IDENTITY(1,1) NOT NULL,
  15. [DeptName] [varchar](50) NOT NULL,
  16. [Status] [int] NULL,
  17. CONSTRAINT [PK_Mas_Department] PRIMARY KEY CLUSTERED
  18. (
  19. [DeptId] ASC
  20. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  21. ) ON [PRIMARY]
  22. GO
Step2

Enter dummy data in Mas_Department table. That will be needed during inner join, with first table to fetch records.
  1. SET IDENTITY_INSERT [dbo].[Mas_Department] ON
  2. GO
  3. INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (1, N'IT', 1)
  4. GO
  5. INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (2, N'HR', 1)
  6. GO
  7. INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (3, N'ACCOUNTS', 1)
  8. GO
  9. SET IDENTITY_INSERT [dbo].[Mas_Department] OFF
  10. GO
Step3

Create list of procedures to perform operations.
  1. IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Insert')
  2. DROP PROCEDURE USP_Emp_Insert
  3. GO
  4. -- =============================================
  5. -- Author:Satyaprakash Samantaray
  6. -- Opearion : To Insert emplyee details
  7. -- =============================================
  8. Create Procedure [dbo].[USP_Emp_Insert]
  9. @Name varchar(50),
  10. @Salary int,
  11. @DeptId int
  12. AS
  13. Begin
  14. Insert into Mas_Employee
  15. (Name,Salary,DeptId) Values
  16. (@Name,@Salary,@DeptId)
  17. End
  18. GO
  19. ----------------------------------------------------------------------------------------------------------------
  20. IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Update')
  21. DROP PROCEDURE USP_Emp_Update
  22. GO
  23. -- =============================================
  24. -- Author:Satyaprakash Samantaray
  25. -- Opearion : To update the emplyee details
  26. -- =============================================
  27. Create Procedure [dbo].[USP_Emp_Update]
  28. @Id int,
  29. @Name varchar(50),
  30. @Salary int,
  31. @DeptId int
  32. AS
  33. Begin
  34. update Mas_Employee Set
  35. Name=@Name,
  36. Salary=@Salary,
  37. DeptId=@DeptId
  38. where Id=@Id
  39. End
  40. GO
  41. ----------------------------------------------------------------------------------------------------------------
  42. IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Delete')
  43. DROP PROCEDURE USP_Emp_Delete
  44. GO
  45. -- =============================================
  46. -- Author:Satyaprakash Samantaray
  47. -- Opearion : To delete emplyee details
  48. -- =============================================
  49. Create Procedure [dbo].[USP_Emp_Delete]
  50. @Id int
  51. AS
  52. Begin
  53. Delete From Mas_Employee
  54. where Id=@Id
  55. End
  56. GO
  57. ----------------------------------------------------------------------------------------------------------------
  58. IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'Get_AllEmployees')
  59. DROP PROCEDURE Get_AllEmployees
  60. GO
  61. -- =============================================
  62. -- Author:Satyaprakash Samantaray
  63. -- Opearion : To get the emplyees details
  64. -- =============================================
  65. Create Procedure [dbo].[Get_AllEmployees]
  66. @Id int = null
  67. AS
  68. Begin
  69. Select E.Id, E.Name, E.Salary,E.DeptID,D.DeptName
  70. From Mas_Employee E
  71. Join Mas_Department D
  72. On E.DeptId = D.DeptId
  73. where D.Status = 1
  74. And Id = Isnull(@Id, Id)
  75. End
  76. GO
  77. ----------------------------------------------------------------------------------------------------------------
Step4

Create a WCF Service Application named "WCF_Crud".



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

Step5

Then, in WEB.CONFIG file, add connection string and check some system generated codes.

Code Ref
  1. <connectionStrings>
  2. <add name="conStr" connectionString="Put Connection string here...." providerName="System.Data.SqlClient"/>
  3. </connectionStrings>
Step6

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

Code Ref
  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. namespace WCF_Crud
  10. {
  11. [ServiceContract]
  12. public interface IService1
  13. {
  14. [OperationContract]
  15. string InsertEmpDetails(EmpDetails eDatils);
  16. [OperationContract]
  17. DataSet GetEmpDetails(EmpDetails eDatils);
  18. [OperationContract]
  19. DataSet FetchUpdatedRecords(EmpDetails eDatils);
  20. [OperationContract]
  21. string UpdateEmpDetails(EmpDetails eDatils);
  22. [OperationContract]
  23. bool DeleteEmpDetails(EmpDetails eDatils);
  24. }
  25. [DataContract]
  26. public class EmpDetails
  27. {
  28. int? eId;
  29. string eName = string.Empty;
  30. string eSalary = string.Empty;
  31. string eDeptId = string.Empty;
  32. string eDeptName = string.Empty;
  33. [DataMember]
  34. public int? Id
  35. {
  36. get
  37. {
  38. return eId;
  39. }
  40. set
  41. {
  42. eId = value;
  43. }
  44. }
  45. [DataMember]
  46. public string Name
  47. {
  48. get
  49. {
  50. return eName;
  51. }
  52. set
  53. {
  54. eName = value;
  55. }
  56. }
  57. [DataMember]
  58. public string Salary
  59. {
  60. get
  61. {
  62. return eSalary;
  63. }
  64. set
  65. {
  66. eSalary = value;
  67. }
  68. }
  69. [DataMember]
  70. public string DeptId
  71. {
  72. get
  73. {
  74. return eDeptId;
  75. }
  76. set
  77. {
  78. eDeptId = value;
  79. }
  80. }
  81. [DataMember]
  82. public string DeptName
  83. {
  84. get
  85. {
  86. return eDeptName;
  87. }
  88. set
  89. {
  90. eDeptName = value;
  91. }
  92. }
  93. }
  94. }
Code Description

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

Now, open the Service.svc.cs file and add the below code. Also, define the methods declared in the IService1.cs above.

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

Add the namespace lists.
  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. using System.Data.SqlClient;
  10. using System.Configuration;
Here, Service1 class inherits some properties from IService1.
  1. public class Service1 : IService1
Then, I have added the name of connection string.
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
In code ref. section, I have commented some code with "//" for better information.
Go to the Solution Explorer and then right click on Service1.svc. Click on "View in Browser" as shown in the following diagram.

You will get a service link like this : http://localhost:58209/Service1.svc.

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 call/consume this Service in your ASP.NET application.
Step8

Create your ASP.NET application named "ConsumeWcfCrud" and consume the preceding new WCF service.



Next, add a webform to your project and name it as Sample.aspx.



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



A new window will appear.



Paste the copied Service URL, localhost:58209/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. Then, click on the OK button.

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

Add some code in "Samle.aspx".

Code Ref
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Samle.aspx.cs" Inherits="ConsumeWcfCrud.Samle" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>Satyaprakash Samantaray</title>
  6. <%--added css to asp.net server controls--%>
  7. <style>
  8. .button {
  9. background-color: #4CAF50;
  10. border: none;
  11. color: white;
  12. padding: 15px 32px;
  13. text-align: center;
  14. text-decoration: none;
  15. display: inline-block;
  16. font-size: 16px;
  17. margin: 4px 2px;
  18. cursor: pointer;
  19. }
  20. .DataGridFixedHeader {
  21. color: White;
  22. font-size: 13px;
  23. font-family: Verdana;
  24. background-color:yellow
  25. }
  26. .grid_item {
  27. background-color: #E3EAEB;
  28. border-width: 1px;
  29. font-family: Verdana;
  30. border-style: solid;
  31. font-size: 12pt;
  32. color: black;
  33. border: 1px solid black;
  34. }
  35. .grid_alternate {
  36. border-width: 1px;
  37. font-family: Verdana;
  38. border-style: solid;
  39. font-size: 12pt;
  40. color: black;
  41. background-color: White;
  42. }
  43. .button4 {
  44. border-radius: 9px;
  45. }
  46. input[type=text], select {
  47. width: 50%;
  48. padding: 12px 20px;
  49. margin: 10px 0;
  50. display: inline-block;
  51. border: 1px solid #ccc;
  52. border-radius: 4px;
  53. box-sizing: border-box;
  54. font-family: 'Montserrat', sans-serif;
  55. text-indent: 10px;
  56. color: blue;
  57. text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  58. font-size: 20px;
  59. }
  60. </style>
  61. <%--added css to asp.net server controls--%>
  62. <%--added script file for asp.net server controls validations--%>
  63. <script language="javascript" src="../Scripts/Validation.js" type="text/javascript"></script>
  64. <script language="javascript" type="text/javascript">
  65. function Validation() {
  66. if (Required('<%=txtName.ClientID%>', 'Name'))
  67. if (Required('<%=txtSalary.ClientID%>', 'Salary'))
  68. if (Required('<%=txtDeptId.ClientID%>', 'Dept ID'))
  69. return true;
  70. return false;
  71. }
  72. </script>
  73. <%--added script file for asp.net server controls validations--%>
  74. </head>
  75. <body>
  76. <form id="form1" runat="server">
  77. <fieldset>
  78. <legend style="font-family: Arial Black;background-color:yellow; color:red; font-size:larger;font-style: oblique">Satyaprakash's WCF Real-Time Project</legend>
  79. <table align="center">
  80. <tr>
  81. <td style="text-align:center">
  82. <asp:TextBox ID="txtName" runat="server" placeholder="Enter Name.." ></asp:TextBox>
  83. </td>
  84. </tr>
  85. <tr>
  86. <td style="text-align:center">
  87. <asp:TextBox ID="txtSalary" runat="server" placeholder="Enter Salary.."></asp:TextBox>
  88. </td>
  89. </tr>
  90. <tr>
  91. <td style="text-align:center">
  92. <asp:TextBox ID="txtDeptId" runat="server" placeholder="Enter DeptID.."></asp:TextBox>
  93. </td>
  94. </tr>
  95. <tr>
  96. <td align="center">
  97. <asp:Button ID="btnSubmit" runat="server" class="button button4" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="javascript:return Validation();"/>
  98. <asp:Button ID="btnCancel" runat="server" class="button button4" Text="Cancel" OnClick="btnCancel_Click" />
  99. </td>
  100. </tr>
  101. <tr>
  102. <td align="center">
  103. <asp:Label ID="lblStatus" runat="server"></asp:Label>
  104. </td>
  105. </tr>
  106. <tr>
  107. <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">
  108. <span style="font-family: Arial Black;color:red;background-color:yellow;font-size:larger;font-style: oblique">EMPLOYEE SUMMARY</span>
  109. <br />
  110. </td>
  111. </tr>
  112. <tr>
  113. <td colspan="2">
  114. <%--added gridview style layout and functionality here--%>
  115. <asp:GridView ID="grdWcfTest" runat="server" AllowPaging="true" CellPadding="2" EnableModelValidation="True"
  116. ForeColor="red" GridLines="Both" ItemStyle-HorizontalAlign="center" EmptyDataText="There Is No Records In Database!" AutoGenerateColumns="false" Width="1100px"
  117. HeaderStyle-ForeColor="blue">
  118. <HeaderStyle CssClass="DataGridFixedHeader" />
  119. <RowStyle CssClass="grid_item" />
  120. <AlternatingRowStyle CssClass="grid_alternate" />
  121. <FooterStyle CssClass="DataGridFixedHeader" />
  122. <Columns>
  123. <asp:TemplateField HeaderText="Name">
  124. <HeaderStyle HorizontalAlign="Left" />
  125. <ItemStyle HorizontalAlign="Left" />
  126. <ItemTemplate>
  127. <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'>
  128. </asp:Label>
  129. <asp:Label ID="lblId" runat="server" Visible="false" Text='<%#Eval("Id")%>'>
  130. </asp:Label>
  131. </ItemTemplate>
  132. </asp:TemplateField>
  133. <asp:TemplateField HeaderText="Salary">
  134. <HeaderStyle HorizontalAlign="Left" />
  135. <ItemStyle HorizontalAlign="Left" />
  136. <ItemTemplate>
  137. <asp:Label ID="lblSalary" runat="server" Text='<%#Eval("Salary") %>'>
  138. </asp:Label>
  139. </ItemTemplate>
  140. </asp:TemplateField>
  141. <asp:TemplateField HeaderText="DeptId">
  142. <HeaderStyle HorizontalAlign="Left" />
  143. <ItemStyle HorizontalAlign="Left" />
  144. <ItemTemplate>
  145. <asp:Label ID="lblDeptId" runat="server" Text='<%#Eval("DeptId") %>'>
  146. </asp:Label>
  147. </ItemTemplate>
  148. </asp:TemplateField>
  149. <asp:TemplateField HeaderText="Edit">
  150. <HeaderStyle HorizontalAlign="Left" />
  151. <ItemStyle HorizontalAlign="Left" />
  152. <ItemTemplate>
  153. <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CausesValidation="false"
  154. CommandArgument='
  155. <%#Eval("Id") %>' OnCommand="lnkEdit_Command" ToolTip="Edit" />
  156. </ItemTemplate>
  157. </asp:TemplateField>
  158. <asp:TemplateField HeaderText="Delete">
  159. <HeaderStyle HorizontalAlign="Left" />
  160. <ItemStyle HorizontalAlign="Left" />
  161. <ItemTemplate>
  162. <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CausesValidation="false"
  163. CommandArgument='
  164. <%#Eval("Id") %>' CommandName="Delete" OnCommand="lnkDelete_Command"
  165. OnClientClick="return confirm('Are you sure you want to delete?')" ToolTip="Delete" />
  166. </ItemTemplate>
  167. </asp:TemplateField>
  168. </Columns>
  169. </asp:GridView>
  170. <%--added gridview style layout and functionality here--%>
  171. </td>
  172. </tr>
  173. </table>
  174. </fieldset>
  175. </form>
  176. </body>
  177. <br />
  178. <br />
  179. <%--added footer related information here--%>
  180. <footer>
  181. <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>
  182. </footer>
  183. <%--added footer related information here--%>
  184. </html>
Code Description

I have added some description with commented lines using "<%-- --%>" to describe the above code.
Step10

Add the following code in "Samle.aspx.cs".

Code Ref
  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.Data;
  8. using System.Data.SqlClient;
  9. using System.Configuration;
  10. using ConsumeWcfCrud.WcfCrudRef;
  11. namespace ConsumeWcfCrud
  12. {
  13. public partial class Samle : System.Web.UI.Page
  14. {
  15. #region Variable Declaration
  16. WcfCrudRef.Service1Client obj = new WcfCrudRef.Service1Client(); //WCF SERVICE REFERENCE ADDED HERE.
  17. #endregion
  18. #region User Define Methods
  19. private void ClearControls() //Defined a function to reset asp.net server controls.
  20. {
  21. txtName.Text = string.Empty;
  22. txtSalary.Text = string.Empty;
  23. txtDeptId.Text = string.Empty;
  24. btnSubmit.Text = "Submit";
  25. txtName.Focus();
  26. }
  27. private void BindEmpDetails(int? Id) //This function defined for bind to grid view.
  28. {
  29. EmpDetails eDetails = new EmpDetails();
  30. DataSet ds = new DataSet();
  31. ds = obj.GetEmpDetails(eDetails);
  32. grdWcfTest.DataSource = ds;
  33. grdWcfTest.DataBind();
  34. }
  35. private void SaveEmpDetails() //This function defined for save data.
  36. {
  37. EmpDetails eDetails = new EmpDetails();
  38. eDetails.Name = txtName.Text.Trim();
  39. eDetails.Salary = txtSalary.Text.Trim();
  40. eDetails.DeptId = txtDeptId.Text.Trim();
  41. lblStatus.Text = obj.InsertEmpDetails(eDetails);
  42. lblStatus.ForeColor = System.Drawing.Color.Blue;
  43. ClearControls();
  44. BindEmpDetails(null);
  45. }
  46. private void UpdateEmpDetails() //This function defined for update data.
  47. {
  48. EmpDetails eDetails = new EmpDetails();
  49. eDetails.Id = Convert.ToInt32(ViewState["Id"].ToString());
  50. eDetails.Name = txtName.Text.Trim();
  51. eDetails.Salary = txtSalary.Text.Trim();
  52. eDetails.DeptId = txtDeptId.Text.Trim();
  53. obj.UpdateEmpDetails(eDetails);
  54. lblStatus.Text = obj.UpdateEmpDetails(eDetails);
  55. lblStatus.ForeColor = System.Drawing.Color.Maroon;
  56. ClearControls();
  57. BindEmpDetails(null);
  58. }
  59. #endregion
  60. #region Page Event HandlersBindEmpDetailsBindEmpDetails
  61. protected void Page_Load(object sender, EventArgs e) //In page load event the function " BindEmpDetails()" for bind to gridview.
  62. {
  63. if (!Page.IsPostBack)
  64. {
  65. BindEmpDetails(null);
  66. ClearControls();
  67. lblStatus.Text = String.Empty;
  68. }
  69. }
  70. protected void btnSubmit_Click(object sender, EventArgs e) //In submit button click event i added "SaveEmpDetails()" to insert new records
  71. {
  72. if (btnSubmit.Text == "Update")
  73. {
  74. UpdateEmpDetails(); //for update existing records.
  75. }
  76. else
  77. {
  78. SaveEmpDetails(); //for insert new records
  79. }
  80. }
  81. protected void lnkEdit_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
  82. {
  83. EmpDetails eDetails = new EmpDetails(); //By clicking edit link button in gridview all existing data will come to respected controls.
  84. eDetails.Id = int.Parse(e.CommandArgument.ToString());
  85. ViewState["Id"] = eDetails.Id; //Viewstate variable helps to pass id of respected data.
  86. DataSet ds = new DataSet();
  87. ds = obj.FetchUpdatedRecords(eDetails); //this function will help you fetch updated records.
  88. if (ds.Tables[0].Rows.Count > 0)
  89. {
  90. txtName.Text = ds.Tables[0].Rows[0]["Name"].ToString();
  91. txtSalary.Text = ds.Tables[0].Rows[0]["Salary"].ToString();
  92. txtDeptId.Text = ds.Tables[0].Rows[0]["DeptId"].ToString();
  93. btnSubmit.Text = "Update"; //The button text will be changed to "Update".
  94. }
  95. }
  96. protected void lnkDelete_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
  97. {
  98. EmpDetails eDetails = new EmpDetails(); //This part helps us to delete records using Delete link button.
  99. eDetails.Id = int.Parse(e.CommandArgument.ToString());
  100. if (obj.DeleteEmpDetails(eDetails) == true) //Here the function defined.
  101. {
  102. lblStatus.Text = "Record Is Deleted Successfully";
  103. lblStatus.ForeColor = System.Drawing.Color.Red;
  104. }
  105. else
  106. {
  107. lblStatus.Text = "Record couldn't be deleted";
  108. lblStatus.ForeColor = System.Drawing.Color.OrangeRed;
  109. }
  110. BindEmpDetails(null); //As soon as any change in records the fast action will be happened in gridview using this function.
  111. }
  112. protected void btnCancel_Click(object sender, EventArgs e)
  113. {
  114. ClearControls(); //This function helps to reset control's values.
  115. lblStatus.Text = string.Empty;
  116. }
  117. #endregion
  118. }
  119. }
Code Description

Some important namespaces are added here.
  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.Data;
  8. using System.Data.SqlClient;
  9. using System.Configuration;
  10. using ConsumeWcfCrud.WcfCrudRef;
The label text color will be changed for each operation. For example, for deleting records, I have assigned the red color to be shown to the end user. lblStatus.ForeColor = System.Drawing.Color.Red;
OUTPUT

No records.



For Insert.



For Update.



For Delete.




For Text Validation.




For Chrome View.



That's it. I hope you understood the process very well. For any query or suggestions, please comment below.