Thursday 27 February 2014

Insert Edit Update Delete using wcf service in asp.net c#

Hello Friends !!
In this Post I will Explain WCF Service (Window Communication Foundation) in Asp .net c#.
In this post I will show you how to create WCF Service and how to consume it within an aspx page to perform CRUD operation using  WCF Service.For the CRUD (Create,Read,Update,Delete) operation using WCF service in asp with C#, I have use the one Stored procedure using in linq to sql.

First I have created one table in database :-


After creating table I have make one stored procedure with multiple queries when I execute this stored procedure using linq to sql it will give different result on condition to perform CRUD operation.
Here I am using also Resource file for set condition on stored procedure.
In the below stored procedure you can see parameter @Dboperation that condition value set by resource file.

CREATE PROCEDURE [dbo].[usp_WCF_CRUD]
@Dboperation varchar(50),
@empid int,
@name nvarchar(50),
@department nvarchar(50),
@desigination nvarchar(50),
@salary nvarchar(50),
@address nvarchar(50),
@contactno nvarchar(50),
AS
BEGIN
begin try
if(@Dboperation='ReadAll')
begin
select * from dsh_WCF_CRUD
end
else if(@Dboperation='ReadSpecific')
begin
select * from dsh_WCF_CRUD where empid=@empid
end
else if(@Dboperation='Create')
begin
INSERT INTO [Demo].[dbo].[dsh_WCF_CRUD]
           ([name],[department],[desigination],[salary],[address],[contactno])
VALUES
           (@name,@department,@desigination,@salary,@address,@contactno)
select * from dsh_WCF_CRUD where empid=scope_identity();
end
else if(@Dboperation='Update')
begin
UPDATE [Demo].[dbo].[dsh_WCF_CRUD]
    SET [name] = @name,
      [department] = @department,
     [desigination] = @desigination,
      [salary] =@salary,
      [address] = @address,
      [contactno] =@contactno
    WHERE empid=@empid
end
else if(@Dboperation='Delete')
begin
DELETE FROM [Demo].[dbo].[dsh_WCF_CRUD]
    WHERE empid=@empid
end
end try
begin catch
end catch
END
After Creating Stored Procedure 
1 Open Visual Studio 
2 Create a new Project (ASP.NET Web Application) name it (DataEntity)
3  Next step is to add a new item “LINQ to SQL Classes”.
   See figure below after drag and drop stored procedure.



After that ,
4 Add New Project (ASP.NET Web Application)  name it(ReasourceFile)
5 next step is to add a new item “Resources File”. Name it(Dboperation.resx).
Add the following value in resource file  in from the below figure.
This resource file use for database operation to set value into stored procedure.


Then after
6 Add New Project  (WCF Service Application) name it (WCF-CRUD)
Once you created project you will get default class files including Service.cs and IService.cs. But I am adding one new wcf service. 
7 next step is to add a new item “WCF Service”. Name it (empservice.svc).
After adding all this ,the whole solution look like in the below figure.


Now open Iempservice.cs and write following code.
Iempservice.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using DataEntity;
namespace WCF_CRUD
{
    // NOTE: If you change the interface name "Iempservice" here, you must also update the reference to "Iempservice" in Web.config.
    [ServiceContract]
    public interface Iempservice
    {
        [OperationContract]
        void DoWork();
        [OperationContract]
        List<usp_WCF_CRUDResult> InsertEmployee(usp_WCF_CRUDResult empobj);
        [OperationContract]
        List<usp_WCF_CRUDResult> ReadAllEmployee();
        [OperationContract]
        List<usp_WCF_CRUDResult> ReadSpecific(int ID);
        [OperationContract]
        List<usp_WCF_CRUDResult> UpdateEmployee(usp_WCF_CRUDResult updateemp);
        [OperationContract]
        List<usp_WCF_CRUDResult> DeleteEmployee(int ID);
    }
}
After that open empservice.cs and write the following code.
empservice.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using DataEntity;
using System.Data.Linq;
using System.Data.SqlClient;
using ReasourceFile;

namespace WCF_CRUD
{
    // NOTE: If you change the class name "empservice" here, you must also update the reference to "empservice" in Web.config.
    public class empservice : Iempservice
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        public void DoWork()
        {
        }
        #region Iempservice Members
        List<usp_WCF_CRUDResult> Iempservice.InsertEmployee(usp_WCF_CRUDResult empobj)
        {
            List<DataEntity.usp_WCF_CRUDResult> empdata = new List<DataEntity.usp_WCF_CRUDResult>();
         
                using (DataClasses1DataContext db = new DataClasses1DataContext())
                {
                    empdata = db.usp_WCF_CRUD(Dboperation.CreateRecord, null, empobj.name, empobj.department, empobj.desigination, empobj.salary, empobj.address, empobj.contactno, null).ToList();
                }
               
            return empdata;
        }
        #endregion
        #region Iempservice Members

        public List<usp_WCF_CRUDResult> ReadAllEmployee()
        {
            List<usp_WCF_CRUDResult> EmplList = new List<usp_WCF_CRUDResult>();
         
                using (DataClasses1DataContext db = new DataClasses1DataContext())
                {
                    EmplList = db.usp_WCF_CRUD(Dboperation.ReadAllRecord, null, null, null, null, null, null, null, null).ToList();
                }
         
         
            return EmplList;
        }
        #endregion
        #region Iempservice Members
        #endregion
        #region Iempservice Members

        public List<usp_WCF_CRUDResult> ReadSpecific(int ID)
        {
            List<usp_WCF_CRUDResult> empobj = new List<usp_WCF_CRUDResult>();
            using (DataClasses1DataContext db = new DataClasses1DataContext())
            {
                empobj = db.usp_WCF_CRUD(Dboperation.ReadSpecificRecord, ID, null, null, null, null, null, null, null).ToList();
            }
            return empobj;
        }
        #endregion
        #region Iempservice Members

        public List<usp_WCF_CRUDResult> UpdateEmployee(usp_WCF_CRUDResult updateemp)
        {
            List<usp_WCF_CRUDResult> empobj = new List<usp_WCF_CRUDResult>();
            using (DataClasses1DataContext db = new DataClasses1DataContext())
            {
                empobj = db.usp_WCF_CRUD(Dboperation.UpdateRecord,updateemp.empid,updateemp.name,updateemp.department,updateemp.desigination,updateemp.salary,updateemp.address,updateemp.contactno,null).ToList();
            }
            return empobj;
        }
        #endregion
        #region Iempservice Members

        public List<usp_WCF_CRUDResult> DeleteEmployee(int ID)
        {
            List<usp_WCF_CRUDResult> deleteemp = new List<usp_WCF_CRUDResult>();
            using (DataClasses1DataContext db = new DataClasses1DataContext())
            {
                deleteemp = db.usp_WCF_CRUD(Dboperation.DeleteRecord, ID, null, null, null, null, null, null, null).ToList();
            }
            return deleteemp;
        }
        #endregion
    }
}
Now copy connection string from DataEntity config file to WCF-CRUD config file.
See below figure.



After that Add Client side Project.
8 Add New Project (ASP.NET Web Application)  name it(ClientApp)
After adding project the whole solution look like below figure.


After that open ClienApp Project and open Default.aspx and design Default.aspx as I done in following code.
Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ClientApp._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
        }
        .style3
        {
            width: 94px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table class="style1">
            <tr>
                <td colspan="2">
                    Register
                </td>
            </tr>
            <tr>
                <td class="style3">
                    EmployeeName:
                </td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Desigination:
                </td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Department:
                </td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Salary:
                </td>
                <td>
                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Address:
                </td>
                <td>
                    <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    ContactNo:
                </td>
                <td>
                    <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2" colspan="2">
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
                    &nbsp;
                    <asp:Label ID="Label1" runat="server" ForeColor="Red" Text="Data is not available"
                        Visible="False"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White"
        BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" OnRowCommand="GridView1_RowCommand"
        DataKeyNames="empid" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing">
        <RowStyle BackColor="White" ForeColor="#003399" />
        <Columns>
            <asp:TemplateField HeaderText="EmpId" Visible="false">
                <ItemTemplate>
                    <asp:Label ID="lblempid" runat="server" Text='<%#Eval("empid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="EmpName">
                <ItemTemplate>
                    <asp:Label ID="lblname" runat="server" Text='<%#Eval("name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Department">
                <ItemTemplate>
                    <asp:Label ID="lbldepartment" runat="server" Text='<%#Eval("department") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Desigination">
                <ItemTemplate>
                    <asp:Label ID="lbldesigination" runat="server" Text='<%#Eval("desigination") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="salary">
                <ItemTemplate>
                    <asp:Label ID="lblsalary" runat="server" Text='<%#Eval("salary") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Address">
                <ItemTemplate>
                    <asp:Label ID="lbladdress" runat="server" Text='<%#Eval("address") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ContactNo">
                <ItemTemplate>
                    <asp:Label ID="lblcontactno" runat="server" Text='<%#Eval("contactno") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    <asp:ImageButton ID="EditImage" runat="server" CommandName="Edit" ImageUrl="img/editimage.jpg"
                        Height="33px" Width="36px" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Delete">
                <ItemTemplate>
                    <asp:ImageButton ID="ImageButton1" runat="server" Height="31px" CommandName="Delete"
                        ImageUrl="~/img/images (1).jpg" Width="36px" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
        <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
        <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
    </asp:GridView>
    </form>
</body>
</html>
Default.aspx look like below figure.



After that move to WCF-CUD project and run empservice.svc .



after run service you get web service url (http://localhost:49994/empservice.svc) that show in below figure.


Now move to ClienApp project ,right click on project and select  “Add Service Reference” from context menu.


After enter your service url and click on GO button to see a list of available services and all the available web method (service method) will appear on the pane below.
Note give the specific reference name. I am using default service reference namespace as “ServiceReference1”.


Now observ the solution explorer, you will find ServiceReference1 is added in solution.


After open  Default.aspx.cs and write following code.
Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel;
using System.Data.Linq;
using DataEntity;
using ReasourceFile;
using WCF_CRUD;
using ClientApp.ServiceReference1;
namespace ClientApp
{
    public partial class _Default : System.Web.UI.Page
    {
        static int PK_id;
        ServiceReference1.IempserviceClient ss1 = new ServiceReference1.IempserviceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        private void BindGrid()
        {
            List<usp_WCF_CRUDResult> empdata = ss1.ReadAllEmployee();
            GridView1.DataSource = empdata;
            GridView1.DataBind();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Button1.Text == "Update")
            {
                List<usp_WCF_CRUDResult> emplist1 = ss1.UpdateEmployee(GetControlData());
            }
            else
            {
                List<usp_WCF_CRUDResult> emplist = ss1.InsertEmployee(GetControlData());
            }
            BindGrid();
            ClearControl();
        }
        private void ClearControl()
        {
            TextBox1.Text = string.Empty;
            TextBox2.Text = string.Empty;
            TextBox3.Text = string.Empty;
            TextBox4.Text = string.Empty;
            TextBox5.Text = string.Empty;
            TextBox6.Text = string.Empty;
        }
        private usp_WCF_CRUDResult GetControlData()
        {
            usp_WCF_CRUDResult uspobj = new usp_WCF_CRUDResult()
            {
                name = TextBox1.Text,
                department = TextBox2.Text,
                desigination = TextBox3.Text,
                salary = TextBox4.Text,
                address = TextBox5.Text,
                contactno = TextBox6.Text,
                empid = PK_id
            };
            return uspobj;
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (GridView1.Rows.Count == 0)
            {
                Label1.Visible = true;
            }
            else
            {
                if (e.CommandName == "Edit")
                {
                    GridViewRow index = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
                    PK_id = Convert.ToInt32(GridView1.DataKeys[index.RowIndex].Value);
                    List<usp_WCF_CRUDResult> emplist = ss1.ReadSpecific(PK_id);
                    TextBox1.Text = emplist[0].name;
                    TextBox2.Text = emplist[0].department;
                    TextBox3.Text = emplist[0].desigination;
                    TextBox4.Text = emplist[0].salary;
                    TextBox5.Text = emplist[0].address;
                    TextBox6.Text = emplist[0].contactno;
                    Button1.Text = "Update";
                }
                else if (e.CommandName == "Delete")
                {
                    GridViewRow index = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
                    PK_id = Convert.ToInt32(GridView1.DataKeys[index.RowIndex].Value);
                    List<usp_WCF_CRUDResult> deleteemp = ss1.DeleteEmployee(PK_id);
                    BindGrid();
                }
            }
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
        }
    }
}
Run the application and see the output as below.










3 comments:

Popular Posts

Recent Posts

Sample Text

Stats

Powered by Blogger.

Popular Posts

Popular Posts

Join US on Facebook