Click here to Skip to main content
11,574,473 members (57,868 online)
Click here to Skip to main content

WCF Example for Inserting, Deleting and Displaying Data using a WCF Service in ASP.NET

, 11 Mar 2015 CPOL 486.2K 25.8K 86
Rate this:
Please Sign up or sign in to vote.
A practical example of a WCF service for inserting , Deleting and Displaying Data using a WCF Service in ASP.NET

Introduction 

WCF is more popular now a days and for beginners, I will show you a practical example of a WCF service for inserting, deleting and displaying data using ASP.NET.

Basically, this tip will demonstrate with example the following:

  • Step by step procedure/example to create WCF service
  • How to consume/access WCF service 
  • How to Use Proxy class
  • How to get data from WCF
  • How to bind/Load/Fill gridview from SQL Server database using WCF service
  • How to perform insert, edit, update and delete operation on gridview using WCF service

Using the Code

For inserting data into a database using a WCF service in ASP.NET, we have to do the following steps:

  • Create a WCF service
  • Create a Web based application

Part 1: Create a WCF Service

Open Visual Studio 2010/2012.

Step 1: Open Visual Studio -> Go to File menu -> New -> Project -->  Select the new Empty Solution and give name WCFProject.

Step 2: Then add new Class Library Project and give name SaleClassLibrary.

Step 3: Then add reference of System.ServiceModel and System.Runtime.Serialization into that project.

Step 4: Then add new Interface ISaleService.

//
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.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;

 [ServiceContract]
    interface ISaleService
    {
        [OperationContract]
         bool InsertCustomer(Customer obj);

        [OperationContract]
        List<Customer> GetAllCustomer();

        [OperationContract]
        bool DeleteCustomer(int Cid);

        [OperationContract]
        bool UpdateCustomer(Customer obj);     
    }

  [DataContract]
   public class Customer
    {
        [DataMember]
        public int CustomerID;
        [DataMember]
        public string CustomerName;        
        [DataMember]
        public string Address;
        [DataMember]
        public string EmailId;
    } 

Step 5: And write the following code in the SaleService.cs file:

SaleService.cs page:

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.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public class SaleService : ISaleService
    {
        public bool InsertCustomer(Customer obj)
        {
            cutomerList.Add(obj);
            return true;
        }

        public List<Customer> GetAllCustomer()
        {
            return cutomerList;
        }

        public bool DeleteCustomer(int Cid)
        {
            var item = cutomerList.First(x => x.CustomerID == Cid);

            cutomerList.Remove(item);
            return true;
        }

        public bool UpdateCustomer(Customer obj)
        {
            var list = cutomerList;
            cutomerList.Where(p => p.CustomerID == 
            obj.CustomerID).Update(p => p.CustomerName = obj.CustomerName);
            return true;
        }

      public static  List<Customer> cutomerList = new List<Customer>()
         {
        new Customer {CustomerID = 1, CustomerName="Sujeet", 
        Address="Pune", EmailId="test@yahoo.com" },
        new Customer {CustomerID = 2, CustomerName="Rahul", 
        Address="Pune", EmailId="test@yahoo.com" },
        new Customer {CustomerID = 3, CustomerName="Mayur", 
        Address="Pune", EmailId="test@yahoo.com"}
         };       
    }  
 
 public static class LinqUpdates
    {
        public static void Update<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach (var item in source)
                action(item);
        }
    } 

Step 6: Build your Class library.

Step 7: Add New Empty ASP.NET Project into that Solution, give name SaleServiceHost.

Step 8: Add reference of Classlibrary Project to that SaleServiceHost ASP.NET project.

Step 9: Add new item WCF Service in that SaleServiceHost ASP.NET project and give name SaleService.

Step 10: Right click on that SaleService.svc and select view Markup:

Change the Service Name from that markup:

<%@ ServiceHost Language="C#" Debug="true" 
Service="SaleClassLibrary.SaleService"  %>

Step 11: And build the solution and SaleServiceHost set as startup project and SaleService.svc set as startup page.

In this way, your WCF service builds successfully.

Part 2: Create a Web Based Application (Client)

Now, create your client application in your system:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
      <h2>
        Welcome to Sale Service</h2><table class="style1">
            <tr>
                <td style="text-align: right">
                    Enter name</td>
                <td>
                    <asp:TextBox ID="TextBox1" 
                    runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Address</td>
                <td>
                    <asp:TextBox ID="TextBox2" 
                    runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Email ID</td>
                <td>
                    <asp:TextBox ID="TextBox3" 
                    runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" 
                    onclick="Button1_Click" Text="Save" />
                </td>
            </tr>
        </table>
    
<p>
        <asp:GridView ID="GridView1" runat="server" 
        AllowPaging="True"  DataKeyNames="CustomerID,CustomerName"
            AllowSorting="True" AutoGenerateDeleteButton="True" 
            onrowdeleting="GridView1_RowDeleting">
        </asp:GridView>
</p>
    <p>
        <asp:Label ID="Label1" runat="server" 
        Text="Label"></asp:Label>
    </form>
    </body>
</html>
using SaleService;
  1. Create a Website.
  2. Add Service Reference http://localhost:53544/SaleService.svc?wsdl to a Web Application.
  3. Select your Website.
  4. Right click on it, add Service Reference, then enter your Service URL and click Go.
  5. Give the name for your service SaleService -> OK.
  6. Then automatically a proxy will be created in your client system.
  7. Write the following code in your source code:
  8. Add your service reference on the top.
  9. Then create an object for Service Reference and use that object to call the methods from your service.
  10. Write the following code in your aspx.cs file.
Default.aspx.cs page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using ServiceReference1;

public partial class _Default : System.Web.UI.Page
{
    SaleService.SaleServiceClient proxy;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                 proxy=new SaleService.SaleServiceClient();
                GridView1.DataSource=proxy.GetAllCustomer();
                GridView1.DataBind();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            proxy = new SaleService.SaleServiceClient();
            SaleService.Customer objcust = 
            new SaleService.Customer() { CustomerID=5, CustomerName=TextBox1.Text,
            Address=TextBox2.Text,EmailId=TextBox3.Text  };

            proxy.InsertCustomer(objcust);

            GridView1.DataSource = proxy.GetAllCustomer();
            GridView1.DataBind();
            Label1.Text = "Record Saved Successfully";
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int userid = Convert.ToInt32(GridView1.DataKeys
            [e.RowIndex].Values["CustomerID"].ToString());
            proxy = new SaleService.SaleServiceClient();

            bool check = proxy.DeleteCustomer(userid);
              Label1.Text = "Record Deleted Successfully";
              GridView1.DataSource = proxy.GetAllCustomer();
              GridView1.DataBind();
        }
}

By using this, you have successfully inserted data in the database and you have also shown this in the gridview.

Please take a look at the attached code for more information.

Happy programming!!

Don’t forget to leave your feedback and comments below!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sujit Bhujbal
Software Developer (Senior)
India India
Sujit Bhujbal is Senior Software Engineer having over 6 + years of Experience in Asp.net 3.5,WPF,WCF and has worked on various platforms. He worked during various phases of SDLC such as Requirements and Analysis, Design and Construction, development, maintenance, Testing, UAT.

He is Microsoft Certified Technology Specialist (MCTS) in Asp.net /WCF Applications. He worked at various levels and currently working as a Senior Software Engineer.

His core areas of skill are Web application development using WPF,WCF , C#.Net, ASP.Net 3.5, WCF, SQL Server 2008, CSS, Java script Web design using HTML, AJAX and Crystal Reports

He is proficient in developing applications using SilverLight irrespective of the language, with sound knowledge of Microsoft Expression Blend and exposure to other Microsoft Expression studio tools.


------------------------------------------------------------------------
Blog: Visit Sujit Bhujbal

Personal Website :-Visit sujit Bhujbal Personal Site

Facebook :- Sujit Bhujbal Facebook

CodeProject:- Sujit Bhujbal codeproject

DotNetHeaven:- DotNetHeaven

CsharpCorner:-CsharpCorner

Linkedin :-Linkedin

Stack-Exchange: Stack-Exchange

Twitter :-Twitter

JavaTalks :-JavaTalk

------------------------------------------------------------------------

You may also be interested in...

Comments and Discussions

 
QuestionThank you Pin
Member 1168587712-May-15 15:27
memberMember 1168587712-May-15 15:27 
AnswerRe: Thank you Pin
Sujit Bhujbal18-Jun-15 20:02
memberSujit Bhujbal18-Jun-15 20:02 
QuestionThanks Sujit Bhujbal Pin
Nguyên Hoàng Nguyễn Đức7-May-15 23:00
memberNguyên Hoàng Nguyễn Đức7-May-15 23:00 
AnswerRe: Thanks Sujit Bhujbal Pin
Sujit Bhujbal18-Jun-15 20:03
memberSujit Bhujbal18-Jun-15 20:03 
QuestionGetting error in VS2012 Pin
JomyK7-May-15 13:15
memberJomyK7-May-15 13:15 
AnswerRe: Getting error in VS2012 Pin
Sujit Bhujbal18-Jun-15 20:18
memberSujit Bhujbal18-Jun-15 20:18 
GeneralCongrats Pin
Member 111054606-Apr-15 22:43
memberMember 111054606-Apr-15 22:43 
GeneralRe: Congrats Pin
Sujit Bhujbal18-Jun-15 20:09
memberSujit Bhujbal18-Jun-15 20:09 
QuestionAdnan Pin
Member 1151696711-Mar-15 7:13
memberMember 1151696711-Mar-15 7:13 
AnswerRe: Adnan Pin
Sujit Bhujbal15-Mar-15 19:41
memberSujit Bhujbal15-Mar-15 19:41 
QuestionLink not working Pin
Humayun Kabir Mamun10-Mar-15 20:22
memberHumayun Kabir Mamun10-Mar-15 20:22 
AnswerRe: Link not working Pin
Sujit Bhujbal11-Mar-15 0:09
memberSujit Bhujbal11-Mar-15 0:09 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-Mar-15 20:19
memberHumayun Kabir Mamun10-Mar-15 20:19 
GeneralRe: My vote of 5 Pin
Sujit Bhujbal11-Mar-15 0:08
memberSujit Bhujbal11-Mar-15 0:08 
QuestionBug In App Pin
snehal newase10-Feb-15 19:59
membersnehal newase10-Feb-15 19:59 
AnswerRe: Bug In App Pin
Sujit Bhujbal10-Mar-15 1:46
memberSujit Bhujbal10-Mar-15 1:46 
Questiongood article Pin
brijesh vaidya23-Jun-14 20:57
memberbrijesh vaidya23-Jun-14 20:57 
AnswerRe: good article Pin
Sujit Bhujbal27-Oct-14 20:01
memberSujit Bhujbal27-Oct-14 20:01 
Questionwhat is the use of using wcf service for insertion,deletion,updation in real time projects ? Explain ? Pin
CHAITANYA KIRAN KASANI5-Jun-14 1:30
memberCHAITANYA KIRAN KASANI5-Jun-14 1:30 
AnswerRe: what is the use of using wcf service for insertion,deletion,updation in real time projects ? Explain ? Pin
Sujit Bhujbal27-Oct-14 20:00
memberSujit Bhujbal27-Oct-14 20:00 
QuestionNice Articles Pin
P.Venkatachalam26-Feb-14 2:37
memberP.Venkatachalam26-Feb-14 2:37 
AnswerRe: Nice Articles Pin
Sujit Bhujbal24-Mar-14 20:38
memberSujit Bhujbal24-Mar-14 20:38 
GeneralSuperb Pin
mcdubey17-Feb-14 2:48
membermcdubey17-Feb-14 2:48 
GeneralRe: Superb Pin
Sujit Bhujbal24-Mar-14 20:37
memberSujit Bhujbal24-Mar-14 20:37 
GeneralHelpful Pin
itrywhatic#13-Feb-14 10:56
memberitrywhatic#13-Feb-14 10:56 
GeneralRe: Helpful Pin
Sujit Bhujbal24-Mar-14 20:36
memberSujit Bhujbal24-Mar-14 20:36 
QuestionHelpful site Pin
Mohit Jain6-Feb-14 4:57
memberMohit Jain6-Feb-14 4:57 
AnswerRe: Helpful site Pin
Sujit Bhujbal24-Mar-14 20:36
memberSujit Bhujbal24-Mar-14 20:36 
Questiongood article Pin
Member 96549963-Jan-14 17:51
memberMember 96549963-Jan-14 17:51 
AnswerRe: good article Pin
Sujit Bhujbal8-Jan-14 20:56
memberSujit Bhujbal8-Jan-14 20:56 
QuestionGood One ! Pin
venkatesun4-Dec-13 4:21
membervenkatesun4-Dec-13 4:21 
AnswerRe: Good One ! Pin
Sujit Bhujbal4-Dec-13 6:17
memberSujit Bhujbal4-Dec-13 6:17 
QuestionPrintable version Pin
sthabisod4-Nov-13 1:54
membersthabisod4-Nov-13 1:54 
AnswerRe: Printable version Pin
Sujit Bhujbal4-Nov-13 5:37
memberSujit Bhujbal4-Nov-13 5:37 
QuestionZakas Article Pin
Nandakishor Arun Gaikwad28-Oct-13 2:50
memberNandakishor Arun Gaikwad28-Oct-13 2:50 
AnswerRe: Zakas Article Pin
Sujit Bhujbal28-Oct-13 4:20
memberSujit Bhujbal28-Oct-13 4:20 
AnswerRe: Zakas Article Pin
Sujit Bhujbal11-Mar-15 0:26
memberSujit Bhujbal11-Mar-15 0:26 
QuestioneRROR dISPLAYING Pin
vijay.cs99@gmail.com23-Oct-13 8:08
membervijay.cs99@gmail.com23-Oct-13 8:08 
AnswerRe: eRROR dISPLAYING Pin
Member 1035615823-Oct-13 16:43
memberMember 1035615823-Oct-13 16:43 
GeneralRe: eRROR dISPLAYING Pin
Sujit Bhujbal24-Oct-13 20:34
memberSujit Bhujbal24-Oct-13 20:34 
QuestionRun time error Pin
Member 1034473918-Oct-13 6:06
memberMember 1034473918-Oct-13 6:06 
AnswerRe: Run time error Pin
Sujit Bhujbal19-Oct-13 5:03
memberSujit Bhujbal19-Oct-13 5:03 
GeneralRe: Run time error Pin
Member 1034473919-Oct-13 19:18
memberMember 1034473919-Oct-13 19:18 
GeneralRe: Run time error Pin
Sujit Bhujbal20-Oct-13 4:24
memberSujit Bhujbal20-Oct-13 4:24 
QuestionThank you for the article Pin
Pendragon100025-Sep-13 5:58
memberPendragon100025-Sep-13 5:58 
AnswerRe: Thank you for the article Pin
Sujit Bhujbal25-Sep-13 6:39
memberSujit Bhujbal25-Sep-13 6:39 
QuestionAbout Article Pin
Manohar_manu19-Sep-13 19:21
groupManohar_manu19-Sep-13 19:21 
Questionwcf tutorial Pin
Member 102366829-Sep-13 21:29
memberMember 102366829-Sep-13 21:29 
GeneralRe: wcf tutorial Pin
Sujit Bhujbal9-Sep-13 22:54
memberSujit Bhujbal9-Sep-13 22:54 
GeneralNice demo Pin
Member 1024375531-Aug-13 6:10
memberMember 1024375531-Aug-13 6:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150624.2 | Last Updated 11 Mar 2015
Article Copyright 2012 by Sujit Bhujbal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid