In this post, I’m going to explain how to create a simple WCF Service. 


Step 1: Open VS 2012-> file->new -> project-> visual c# ->WCF, Name the project as ServiceOperation and Click Ok.

 Step 2: Add new Interface IService2.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
 
namespace WCFCURDEXample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService2" in both code and config file together.
    [ServiceContract]
    public interface IService2
    {
 
        [OperationContract]
 
        int InsertEmployee(Employee emp);
        [OperationContract]
     
        int DeleteEmployee(string EmpNo);
        [OperationContract]
        Employee[] GetAllEmployee();
    }
    [DataContract(Name = "Employee", Namespace = "")]
    public class Employee
    {
 
        [DataMember]
        public string EmpNo { get; set; }
        [DataMember]
        public string EmpName { get; set; }
        [DataMember]
        public string DeptNo { get; set; }
        [DataMember]
        public string Salary { get; set; }
    }
}

 

Step 3: Write Web.Config



  <connectionStrings>
    <add name="cons"  connectionString="Data Source=ServerName;Initial Catalog=PriyankaDB; User Id=sa;&#xD;&#xA;Password=Password;"
                       providerName="System.Data.SqlClient"/>
  </connectionStrings>

 

Step 4: Then Write in Service2.svc.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace WCFCURDEXample
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service2" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service2.svc or Service2.svc.cs at the Solution Explorer and start debugging.
 
    public class Service2 : IService2
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString);
        #region IService Members
      
        public int InsertEmployee(Employee emp)
        {
            int result = 0;
 
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "insert into Employee values(@EmpNo,@EmpName,@salary,@deptNo)";
            cmd.Parameters.AddWithValue("@EmpNo", emp.EmpNo);
            cmd.Parameters.AddWithValue("@EmpName",emp.EmpName);
            cmd.Parameters.AddWithValue("@Salary", emp.Salary);
            cmd.Parameters.AddWithValue("@deptNo", emp.DeptNo);
            result = cmd.ExecuteNonQuery();
            conn.Close();
            return result;
        }
        public int DeleteEmployee(string EmpNo)
        {
            int Delete = 0;
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "Delete  from Employee Where EmpNo=@EmpNo";
           cmd.Parameters.AddWithValue("@EmpNo",EmpNo);
            Delete = cmd.ExecuteNonQuery();
            conn.Close();
            return Delete;
        }
        public Employee[] GetAllEmployee()
        {
            List<Employee> EmpList = new List<Employee>();
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from Employee", conn);
            SqlDataReader dr = cmd.ExecuteReader();
 
            while (dr.Read())
            {
                EmpList.Add(new Employee()
                {
                    EmpNo = Convert.ToString(dr["EmpNo"]),
                    EmpName = Convert.ToString(dr["EmpName"]),
                    Salary = Convert.ToString(dr["EmpSalary"]),
                    DeptNo = Convert.ToString(dr["DeptNo"])
                });
            }
 
            dr.Close();
            conn.Close();
            return EmpList.ToArray();
        }
        #endregion
    }
}

 

 

Step 5: Create a Web client



Create a New Web Site using the file -> New project-> web-> ASP.NET Empty Web


Application -> OK

 

Step 6: Select References ->Add Service Reference->select Service2.svc->OK.

 

Step 7:  Create a EmployeeInformation.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmployeeInformation.aspx.cs" Inherits="EmployeeDetail.EmployeeInformation" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="css/bootstrap.min.css" rel="stylesheet" />
    <link href="css/bootstrap.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                   
                    <div class="row well well-sm">
                        <div class="col-md-4">
                            <label for="recipient-name" class="control-label">Employee No</label>
 
                        </div>
                        <div class="col-md-4">
                            <asp:TextBox ID="txtEmpNo" runat="server" CssClass="form-control"></asp:TextBox>
                        </div>
                    </div>
                    <div class="row well well-sm">
                        <div class="col-md-4">
                            <label for="recipient-name" class="control-label">Employee Name</label>
 
                        </div>
                        <div class="col-md-4">
                            <asp:TextBox ID="txtEmpName" runat="server" CssClass="form-control"></asp:TextBox>
                        </div>
                    </div>
                    <div class="row well well-sm">
                        <div class="col-md-4">
                            <label for="recipient-name" class="control-label">Salary</label>
 
                        </div>
                        <div class="col-md-4">
                            <asp:TextBox ID="txtSalary" runat="server" CssClass="form-control"></asp:TextBox>
                        </div>
                    </div>
                    <div class="row well well-sm">
                        <div class="col-md-4">
                            <label for="recipient-name" class="control-label">Dept No</label>
 
                        </div>
                        <div class="col-md-4">
                            <asp:TextBox ID="txtDeptNo" runat="server" CssClass="form-control"></asp:TextBox>
                        </div>
                    </div>
                    <div class="row well well-sm">
 
 
                        <div class="col-md-12">
                            <asp:Button ID="btnInsert" runat="server" Text="Insert" CssClass="form-control" OnClick="btnInsert_Click" />
                        </div>
                       
                    </div>
                      <div class="row well well-sm">
                          <div class="col-md-12">
                              <asp:Label ID="lblmsg" runat="server" Text="" CssClass="glyphicon-certificate"></asp:Label>
                          </div>
                      </div>
                </div>
                <div class="col-md-6">
                    <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="GridView1_RowDeleting"  >
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        <Columns>
                            <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
                        </Columns>
                        <EditRowStyle BackColor="#999999" />
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#E9E7E2" />
                        <SortedAscendingHeaderStyle BackColor="#506C8C" />
                        <SortedDescendingCellStyle BackColor="#FFFDF8" />
                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                    </asp:GridView>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

 

 

Step 6: Write EmployeeInformation.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EmployeeDetail.ServiceReference1;
using System.Net;
using System.IO;
using System.Text;
namespace EmployeeDetail
{
    public partial class EmployeeInformation : System.Web.UI.Page
    {
        Service2Client inst;
        void bindGrid()
        {
            inst = new Service2Client();
            GridView1.DataSource = inst.GetAllEmployee();
            GridView1.DataBind();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindGrid();
            }
        }
 
        protected void btnInsert_Click(object sender, EventArgs e)
        {
         
            inst = new Service2Client();
            Employee emp = new Employee() { EmpNo = txtEmpNo.Text, EmpName = txtEmpName.Text, Salary = txtSalary.Text, DeptNo = txtDeptNo.Text };
            int res = inst.InsertEmployee(emp);
            if (res > 0)
                lblmsg.Text = "Successfully saved";
            txtDeptNo.Text = "";
            txtEmpName.Text = "";
            txtEmpNo.Text = "";
            txtSalary.Text = "";
            bindGrid();
        }
     
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string  index =GridView1.Rows[e.RowIndex].Cells[3].Text;
            inst = new Service2Client();
          int res = inst.DeleteEmployee(index);
            bindGrid();
            if (res > 0)
            {
                lblmsg.Text = "Successfully deleted";
            }
        }
 
    }
}

 

Output:

 

 

  Modified On Mar-24-2018 06:48:49 AM

Leave Comment