Search This Blog

Thursday 3 March 2016

Create WCF Service in Visual Studio 2013 Step by Step

We are going to create simple Insert, Update, Delete and Select features WCF Service. 

Use the following table.

Table Script

Create table tblEmployee
(
       Id int primary key identity(1,1),
       Name nvarchar(50),
       Email nvarchar(50),
       Age int,
       Gender nvarchar(50)
)

Insert into tblEmployee values('Sara Nan', 'Sara.Nani@test.com', 30, 'Female')
Insert into tblEmployee values('James Histo', 'James.Histo@test.com', 33, 'Male' )
Insert into tblEmployee values('Mary Jane', 'Mary.Jane@test.com', 28, 'Female' )
Insert into tblEmployee values('Paul Sensit', 'Paul.Sensit@test.com', 29, 'Male' )


Id
Name
Email
Age
Gender
1
Sara Nan
Sara.Nani@test.com
30
Female
2
James Histo
James.Histo@test.com
33
Male
3
Mary Jane
Mary.Jane@test.com
28
Female
4
Paul Sensit
Paul.Sensit@test.com
29
Male


Let's Start


Step 1:- Open Visual Studio 2013


Step 2:- Go to File => New => Project...


Step 3:- Expand Left Pane Templates => Visual C# => Select WCF => Select WCF Service Application from Middle pane


Step 4:- Give Name EmployeeWcfService => Click OK


Step 5:- Delete default Service1.cs and Service1.svc file from project

Step 6:- Right Click on Project Root Folder => Add => New Item...


Step 7:- Select WCF Service from Middle pane


Step 8:-Give name EmployeeService => Click OK


Step 9:- Open Web.config file from Solution Explorer


Step 10:- Add following code under <configuration> section

  <connectionStrings>
    <add name="EmployeeContext" connectionString="Data Source=192.168.1.1; Initial Catalog=WCF;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Note: - Data Source required Server IP or Server Name or Localhost Name



Step 11:- Open IEmployeeService.cs file from Solution Explorer


Step 12:- Copy Past following code in the IEmployeeService.cs file

    [ServiceContract]
    public interface IEmployeeService
    {
        [OperationContract]
        List<Employee> GetData();

        [OperationContract]
        List<Employee> GetDataById(int Id);

        [OperationContract]
        int AddEmployee(Employee employee);

        [OperationContract]
        int UpdateEmployee(Employee employee);

        [OperationContract]
        int DeleteEmployee(int Id);
    }

    [DataContract]
    public class Employee
    {
        [DataMember]
        public int Id { getset; }
        [DataMember]
        public string Name { getset; }
        [DataMember]
        public string Email { getset; }
        [DataMember]
        public int Age { getset; }
        [DataMember]
        public string Gender { getset; }
    }


We have created the service contract for Employee.

Step 13:- Open IEmployeeService.svc file from Solution Explorer


Step 14:- Copy Past following code in the IEmployeeService.svc file

public List<Employee> GetData()
        {
            string strConnection = ConfigurationManager.ConnectionStrings["EmployeeContext"].ToString();
            SqlConnection sqlConnection = new SqlConnection(strConnection);
            sqlConnection.Open();

            string strQuery = "select * from tblEmployee";
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.CommandText = strQuery;
            sqlCommand.Connection = sqlConnection;

            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

            List<Employee> employees = new List<Employee>();

            while (sqlDataReader.Read())
            {
                Employee employee = new Employee();

                employee.Id = Convert.ToInt32(sqlDataReader["Id"]);
                employee.Name = Convert.ToString(sqlDataReader["Name"]);
                employee.Email = Convert.ToString(sqlDataReader["Email"]);
                employee.Age = Convert.ToInt32(sqlDataReader["Age"]);
                employee.Gender = Convert.ToString(sqlDataReader["Gender"]);

                employees.Add(employee);
            }

            sqlDataReader.Close();
            sqlConnection.Close();

            return employees;
        }

        public List<Employee> GetDataById(int Id)
        {
            string strConnection = ConfigurationManager.ConnectionStrings["EmployeeContext"].ToString();
            SqlConnection sqlConnection = new SqlConnection(strConnection);
            sqlConnection.Open();

            string strQuery = "select * from tblEmployee where Id = @Id";
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.CommandText = strQuery;
            sqlCommand.Connection = sqlConnection;
            sqlCommand.Parameters.AddWithValue("@Id", Id);

            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

            List<Employee> employees = new List<Employee>();

            while (sqlDataReader.Read())
            {
                Employee employee = new Employee();

                employee.Id = Convert.ToInt32(sqlDataReader["Id"]);
                employee.Name = Convert.ToString(sqlDataReader["Name"]);
                employee.Email = Convert.ToString(sqlDataReader["Email"]);
                employee.Age = Convert.ToInt32(sqlDataReader["Age"]);
                employee.Gender = Convert.ToString(sqlDataReader["Gender"]);

                employees.Add(employee);
            }

            sqlDataReader.Close();
            sqlConnection.Close();

            return employees;
        }

        public int AddEmployee(Employee employee)
        {
            string strConnection = ConfigurationManager.ConnectionStrings["EmployeeContext"].ToString();
            SqlConnection sqlConnection = new SqlConnection(strConnection);
            sqlConnection.Open();

            string strQuery = "insert into tblEmployee(Name, Email, Age, Gender) values(@Name, @Email, @Age, @Gender)";
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.CommandText = strQuery;
            sqlCommand.Connection = sqlConnection;
            sqlCommand.Parameters.AddWithValue("@Name", employee.Name);
            sqlCommand.Parameters.AddWithValue("@Email", employee.Email);
            sqlCommand.Parameters.AddWithValue("@Age", employee.Age);
            sqlCommand.Parameters.AddWithValue("@Gender", employee.Gender);

            int result = sqlCommand.ExecuteNonQuery();

            sqlConnection.Close();

            return result;
        }

        public int UpdateEmployee(Employee employee)
        {
            string strConnection = ConfigurationManager.ConnectionStrings["EmployeeContext"].ToString();
            SqlConnection sqlConnection = new SqlConnection(strConnection);
            sqlConnection.Open();

            string strQuery = "update tblEmployee set Name = @Name , Email = @Email, Age = @Age, Gender = @Gender where Id = @Id";
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.CommandText = strQuery;
            sqlCommand.Connection = sqlConnection;
            sqlCommand.Parameters.AddWithValue("@Id", employee.Id);
            sqlCommand.Parameters.AddWithValue("@Name", employee.Name);
            sqlCommand.Parameters.AddWithValue("@Email", employee.Email);
            sqlCommand.Parameters.AddWithValue("@Age", employee.Age);
            sqlCommand.Parameters.AddWithValue("@Gender", employee.Gender);

            int result = sqlCommand.ExecuteNonQuery();

            sqlConnection.Close();

            return result;
        }

        public int DeleteEmployee(int id)
        {
            string strConnection = ConfigurationManager.ConnectionStrings["EmployeeContext"].ToString();
            SqlConnection sqlConnection = new SqlConnection(strConnection);
            sqlConnection.Open();

            string strQuery = "delete from tblEmployee where Id = @Id";
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.CommandText = strQuery;
            sqlCommand.Connection = sqlConnection;
            sqlCommand.Parameters.AddWithValue("@Id", id);

            int result = sqlCommand.ExecuteNonQuery();

            sqlConnection.Close();

            return result;
        }


We have successfully created the WCF Service.

Step 15:- Build Solution


Step 16:- Your Solution successfully build




Testing the Service


Step 1:- Right click on IEmployeeService.svc file from Solution Explorer => Click on Set As Start Page


Step 2:- Press F5 to run the service. A WCF Test Client Window will be displayed and it will load the service.



Step 3:- Double click on GetData() function => Click on Invoke Button


You will see all Employee Results in Response Header


Step 4:- Expand Name Column 0 position item, you will see results details


Step 5:- Double click on GetDataById() function => In Request Header give 2 in Value field => Click on Invoke Button


You will see particular Employee Result in Response Header


Step 6:- Expand Name Column 0 position item, you will see results details



Like that you will invoke or test all remaining methods

Step 7:- Double click on Config File => Copy highlighted Address URL

URL = http://localhost:52923/EmployeeService.svc


Important Note:-
This copied URL we can use when we create client to consume our Service.

No comments:

Post a Comment