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
- CREATE TABLE [dbo].[Mas_Employee](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [varchar](50) NOT NULL,
- [Salary] [varchar](50) NOT NULL,
- [DeptId] [int] NOT NULL,
- [Status] [int] NULL,
- CONSTRAINT [PK_Mas_Employee] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
-
-
- CREATE TABLE [dbo].[Mas_Department](
- [DeptId] [int] IDENTITY(1,1) NOT NULL,
- [DeptName] [varchar](50) NOT NULL,
- [Status] [int] NULL,
- CONSTRAINT [PK_Mas_Department] PRIMARY KEY CLUSTERED
- (
- [DeptId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
Step2
Enter dummy data in Mas_Department table. That will be needed during inner join, with first table to fetch records.
- SET IDENTITY_INSERT [dbo].[Mas_Department] ON
-
- GO
- INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (1, N'IT', 1)
- GO
- INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (2, N'HR', 1)
- GO
- INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (3, N'ACCOUNTS', 1)
- GO
- SET IDENTITY_INSERT [dbo].[Mas_Department] OFF
- GO
Step3
Create list of procedures to perform operations.
- IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Insert')
- DROP PROCEDURE USP_Emp_Insert
- GO
-
-
-
-
-
-
- Create Procedure [dbo].[USP_Emp_Insert]
- @Name varchar(50),
- @Salary int,
- @DeptId int
- AS
- Begin
- Insert into Mas_Employee
- (Name,Salary,DeptId) Values
- (@Name,@Salary,@DeptId)
- End
- GO
-
-
-
- IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Update')
- DROP PROCEDURE USP_Emp_Update
- GO
-
-
-
-
-
-
- Create Procedure [dbo].[USP_Emp_Update]
- @Id int,
- @Name varchar(50),
- @Salary int,
- @DeptId int
- AS
- Begin
- update Mas_Employee Set
- Name=@Name,
- Salary=@Salary,
- DeptId=@DeptId
- where Id=@Id
- End
- GO
-
-
-
- IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Delete')
- DROP PROCEDURE USP_Emp_Delete
- GO
-
-
-
-
-
-
- Create Procedure [dbo].[USP_Emp_Delete]
- @Id int
- AS
- Begin
- Delete From Mas_Employee
- where Id=@Id
- End
- GO
-
-
-
- IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'Get_AllEmployees')
- DROP PROCEDURE Get_AllEmployees
- GO
-
-
-
-
-
-
- Create Procedure [dbo].[Get_AllEmployees]
- @Id int = null
- AS
- Begin
- Select E.Id, E.Name, E.Salary,E.DeptID,D.DeptName
- From Mas_Employee E
- Join Mas_Department D
- On E.DeptId = D.DeptId
- where D.Status = 1
- And Id = Isnull(@Id, Id)
- End
- GO
-
-
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
- <connectionStrings>
- <add name="conStr" connectionString="Put Connection string here...." providerName="System.Data.SqlClient"/>
- </connectionStrings>
Step6
In Iservices1.cs file, remove all the default code and declare the Service Contracts, Operation Contracts, and Data Contracts.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using System.Data;
- namespace WCF_Crud
- {
- [ServiceContract]
- public interface IService1
- {
- [OperationContract]
- string InsertEmpDetails(EmpDetails eDatils);
- [OperationContract]
- DataSet GetEmpDetails(EmpDetails eDatils);
- [OperationContract]
- DataSet FetchUpdatedRecords(EmpDetails eDatils);
- [OperationContract]
- string UpdateEmpDetails(EmpDetails eDatils);
- [OperationContract]
- bool DeleteEmpDetails(EmpDetails eDatils);
- }
-
- [DataContract]
- public class EmpDetails
- {
- int? eId;
- string eName = string.Empty;
- string eSalary = string.Empty;
- string eDeptId = string.Empty;
- string eDeptName = string.Empty;
- [DataMember]
- public int? Id
- {
- get
- {
- return eId;
- }
- set
- {
- eId = value;
- }
- }
- [DataMember]
- public string Name
- {
- get
- {
- return eName;
- }
- set
- {
- eName = value;
- }
- }
- [DataMember]
- public string Salary
- {
- get
- {
- return eSalary;
- }
- set
- {
- eSalary = value;
- }
- }
- [DataMember]
- public string DeptId
- {
- get
- {
- return eDeptId;
- }
- set
- {
- eDeptId = value;
- }
- }
- [DataMember]
- public string DeptName
- {
- get
- {
- return eDeptName;
- }
- set
- {
- eDeptName = value;
- }
- }
- }
- }
Code Description
Under [ServiceContract] attribute, I have defined some functions to perform operations using [OperationContract] attribute.
- [OperationContract]
- string InsertEmpDetails(EmpDetails eDatils);
- [OperationContract]
- DataSet GetEmpDetails(EmpDetails eDatils);
- [OperationContract]
- DataSet FetchUpdatedRecords(EmpDetails eDatils);
- [OperationContract]
- string UpdateEmpDetails(EmpDetails eDatils);
- [OperationContract]
- bool DeleteEmpDetails(EmpDetails eDatils);
Use a data contract, as illustrated in the sample below, to add composite types to service operations using [DataMember] attribute.
- public class EmpDetails
- {
- int? eId;
- string eName = string.Empty;
- string eSalary = string.Empty;
- string eDeptId = string.Empty;
- string eDeptName = string.Empty;
- [DataMember]
- public int? Id
- {
- get
- {
- return eId;
- }
- set
- {
- eId = value;
- }
- }
- [DataMember]
- public string Name
- {
- get
- {
- return eName;
- }
- set
- {
- eName = value;
- }
- }
- [DataMember]
- public string Salary
- {
- get
- {
- return eSalary;
- }
- set
- {
- eSalary = value;
- }
- }
- [DataMember]
- public string DeptId
- {
- get
- {
- return eDeptId;
- }
- set
- {
- eDeptId = value;
- }
- }
- [DataMember]
- public string DeptName
- {
- get
- {
- return eDeptName;
- }
- set
- {
- eDeptName = value;
- }
- }
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- namespace WCF_Crud
- {
-
- public class Service1 : IService1
- {
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
- public string InsertEmpDetails(EmpDetails eDetails)
- {
- string Status;
- SqlCommand cmd = new SqlCommand("USP_Emp_Insert", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Name", eDetails.Name);
- cmd.Parameters.AddWithValue("@Salary", eDetails.Salary);
- cmd.Parameters.AddWithValue("@DeptId", eDetails.DeptId);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- int result = cmd.ExecuteNonQuery();
- if (result == 1)
- {
- Status = eDetails.Name + " " + eDetails.Salary + " Is Registered Successfully";
- }
- else
- {
- Status = eDetails.Name + " " + eDetails.Salary + " could not be registered";
- }
- con.Close();
- return Status;
- }
- public DataSet GetEmpDetails(EmpDetails eDetails)
- {
- SqlCommand cmd = new SqlCommand("Get_AllEmployees", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Id", eDetails.Id);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- DataSet ds = new DataSet();
- da.Fill(ds);
- cmd.ExecuteNonQuery();
- con.Close();
- return ds;
- }
- public DataSet FetchUpdatedRecords(EmpDetails eDetails)
- {
- SqlCommand cmd = new SqlCommand("Get_AllEmployees", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Id", eDetails.Id);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- DataSet ds = new DataSet();
- da.Fill(ds);
- cmd.ExecuteNonQuery();
- con.Close();
- return ds;
- }
- public string UpdateEmpDetails(EmpDetails eDetails)
- {
- string Status;
- SqlCommand cmd = new SqlCommand("USP_Emp_Update", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Id", eDetails.Id);
- cmd.Parameters.AddWithValue("@Name", eDetails.Name);
- cmd.Parameters.AddWithValue("@Salary", eDetails.Salary);
- cmd.Parameters.AddWithValue("@DeptId", eDetails.DeptId);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- int result = cmd.ExecuteNonQuery();
- if (result == 1)
- {
- Status = "Record Is Updated successfully";
- }
- else
- {
- Status = "Record could not be updated";
- }
- con.Close();
- return Status;
- }
- public bool DeleteEmpDetails(EmpDetails eDetails)
- {
- SqlCommand cmd = new SqlCommand("USP_Emp_Delete", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Id", eDetails.Id);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- cmd.ExecuteNonQuery();
- con.Close();
- return true;
- }
- }
- }
Code Description
Add the namespace lists.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
Here, Service1 class inherits some properties from IService1.
- public class Service1 : IService1
Then, I have added the name of connection string.
- 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
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
Code Description
Some important namespaces are added here.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- 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.