articles

Home / DeveloperSection / Articles / Creating a Self-Hosted WCF Service

Creating a Self-Hosted WCF Service

priyanka kushwaha5360 18-Mar-2015

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.

Creating a Self-Hosted WCF Service

 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]
    publicinterfaceIService2
    {
 
        [OperationContract]
 
        int InsertEmployee(Employee emp);
        [OperationContract]
     
        int DeleteEmployee(string EmpNo);
        [OperationContract]
        Employee[] GetAllEmployee();
    }
    [DataContract(Name = "Employee", Namespace = "")]
    publicclassEmployee
    {
 
        [DataMember]
        publicstring EmpNo { get; set; }
        [DataMember]
        publicstring EmpName { get; set; }
        [DataMember]
        publicstring DeptNo { get; set; }
        [DataMember]
        publicstring Salary { get; set; }
    }
}

 

Step 3: Write Web.Config



  <connectionStrings>
    <addname="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.
 
    publicclassService2 : IService2
    {
        SqlConnection conn = newSqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString);
        #region IService Members
      
        publicint InsertEmployee(Employee emp)
        {
            int result = 0;
 
            conn.Open();
            SqlCommand cmd = newSqlCommand();
            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;
        }
        publicint DeleteEmployee(string EmpNo)
        {
            int Delete = 0;
            conn.Open();
            SqlCommand cmd = newSqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "Delete  from Employee Where EmpNo=@EmpNo";
           cmd.Parameters.AddWithValue("@EmpNo",EmpNo);
            Delete = cmd.ExecuteNonQuery();
            conn.Close();
            return Delete;
        }
        publicEmployee[] GetAllEmployee()
        {
            List<Employee> EmpList = newList<Employee>();
            conn.Open();
            SqlCommand cmd = newSqlCommand("select * from Employee", conn);
            SqlDataReader dr = cmd.ExecuteReader();
 
            while (dr.Read())
            {
                EmpList.Add(newEmployee()
                {
                    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.

Creating a Self-Hosted WCF Service

 

Step 7:  Create a EmployeeInformation.aspx

 

<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="EmployeeInformation.aspx.cs"Inherits="EmployeeDetail.EmployeeInformation"%>
 
<!DOCTYPEhtml>
 
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
    <title></title>
    <linkhref="css/bootstrap.min.css"rel="stylesheet"/>
    <linkhref="css/bootstrap.css"rel="stylesheet"/>
</head>
<body>
    <formid="form1"runat="server">
        <divclass="container">
            <divclass="row">
                <divclass="col-md-6">
                   
                    <divclass="row well well-sm">
                        <divclass="col-md-4">
                            <labelfor="recipient-name"class="control-label">Employee No</label>
 
                        </div>
                        <divclass="col-md-4">
                            <asp:TextBoxID="txtEmpNo"runat="server"CssClass="form-control"></asp:TextBox>
                        </div>
                    </div>
                    <divclass="row well well-sm">
                        <divclass="col-md-4">
                            <labelfor="recipient-name"class="control-label">Employee Name</label>
 
                        </div>
                        <divclass="col-md-4">
                            <asp:TextBoxID="txtEmpName"runat="server"CssClass="form-control"></asp:TextBox>
                        </div>
                    </div>
                    <divclass="row well well-sm">
                        <divclass="col-md-4">
                            <labelfor="recipient-name"class="control-label">Salary</label>
 
                        </div>
                        <divclass="col-md-4">
                            <asp:TextBoxID="txtSalary"runat="server"CssClass="form-control"></asp:TextBox>
                        </div>
                    </div>
                    <divclass="row well well-sm">
                        <divclass="col-md-4">
                            <labelfor="recipient-name"class="control-label">Dept No</label>
 
                        </div>
                        <divclass="col-md-4">
                            <asp:TextBoxID="txtDeptNo"runat="server"CssClass="form-control"></asp:TextBox>
                        </div>
                    </div>
                    <divclass="row well well-sm">
 
 
                        <divclass="col-md-12">
                            <asp:ButtonID="btnInsert"runat="server"Text="Insert"CssClass="form-control"OnClick="btnInsert_Click"/>
                        </div>
                       
                    </div>
                      <divclass="row well well-sm">
                          <divclass="col-md-12">
                              <asp:LabelID="lblmsg"runat="server"Text=""CssClass="glyphicon-certificate"></asp:Label>
                          </div>
                      </div>
                </div>
                <divclass="col-md-6">
                    <asp:GridViewID="GridView1"runat="server"CellPadding="4"ForeColor="#333333"GridLines="None"OnRowDeleting="GridView1_RowDeleting"  >
                        <AlternatingRowStyleBackColor="White"ForeColor="#284775"/>
                        <Columns>
                            <asp:CommandFieldHeaderText="Delete"ShowDeleteButton="True"/>
                        </Columns>
                        <EditRowStyleBackColor="#999999"/>
                        <FooterStyleBackColor="#5D7B9D"Font-Bold="True"ForeColor="White"/>
                        <HeaderStyleBackColor="#5D7B9D"Font-Bold="True"ForeColor="White"/>
                        <PagerStyleBackColor="#284775"ForeColor="White"HorizontalAlign="Center"/>
                        <RowStyleBackColor="#F7F6F3"ForeColor="#333333"/>
                        <SelectedRowStyleBackColor="#E2DED6"Font-Bold="True"ForeColor="#333333"/>
                        <SortedAscendingCellStyleBackColor="#E9E7E2"/>
                        <SortedAscendingHeaderStyleBackColor="#506C8C"/>
                        <SortedDescendingCellStyleBackColor="#FFFDF8"/>
                        <SortedDescendingHeaderStyleBackColor="#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
{
    publicpartialclassEmployeeInformation : System.Web.UI.Page
    {
        Service2Client inst;
        void bindGrid()
        {
            inst = newService2Client();
            GridView1.DataSource = inst.GetAllEmployee();
            GridView1.DataBind();
        }
        protectedvoid Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindGrid();
            }
        }
 
        protectedvoid btnInsert_Click(object sender, EventArgs e)
        {
         
            inst = newService2Client();
            Employee emp = newEmployee() { 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();
        }
     
        protectedvoid GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string  index =GridView1.Rows[e.RowIndex].Cells[3].Text;
            inst = newService2Client();
          int res = inst.DeleteEmployee(index);
            bindGrid();
            if (res > 0)
            {
                lblmsg.Text = "Successfully deleted";
            }
        }
 
    }
}

 

Output:

Creating a Self-Hosted WCF Service

 

 


Updated 07-Sep-2019

Leave Comment

Comments

Liked By