Monday, 1 October 2012

WCF Example for Inserting and Displaying Data from SQL Server Database Using WCF Service in ASP.NET

Introduction

In this article I will show you a practical example of a WCF service for inserting,deleting and displyaing data  using ASP.NET. 

Download Source Code



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
  1. Open Visual Studio 2010 
Step 1 : 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.Serailization in to 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"}
         };

      
    }
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:
  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.

  1. Then automatically a proxy will be created in your client system.
  2. Write the following code in your source code:
<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>
  1. Add your service reference on the top.
using SaleService;
  1. Then create an object for Service Reference and use that object to call the methods from your service.
  2. 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 grid view.

Please find attached code for more information.

!! Happy Programming !!
 Don’t forget to leave your feedback and comments below! If you have any query,

Thanks
Sujeet


13 comments :

Anonymous said...

nice :) appreciate the work :)

Sujit Bhujbal said...

Thanks Dude...

follow my blog :(

Anonymous said...

Very nice explaination dude. Thanks for sharing your excellent knowledge.

ANIL BABU Mandla said...

Hi,
This is my table

CustId(PK) ID Email PhoneNO
1 101 a@gmail.com 22222222
2 201 b@hotmail.com 33333333
3 301 c@yahoo.com 44444444
I want Create wcf service to take ID + email/phone number and send back CustId

How can i do this?
Pls give the code for sample for this

Anonymous said...

hello plzzz guide how to do this------------

Create a DB having Price & Currency table. Price & Currency tables will be linked using referential constraint for the key CurrencyID (PK in Currency table). Price table will have Prices (Bid rate & Offer rate) of currencies for the different time stamps. For this, write a window service that will insert random prices for all the currencies in every 60 secs

Anonymous said...

Thanks Sujit your examples was very helpful for me who is new to WCF...

Sujit Bhujbal said...

Thanks friends

pantham lakshmaiah said...

very nice-----------------!~:~!

ANIL BABU Mandla said...

I ha two classes
[DataContract]
public class Employee
{
[DataMember]
public int EmpNo { get; set; }

[DataMember]
public string EmpName { get; set; }

[DataMember]
public List AllDepart { get; set; }


//[DataMember]
//public List AllSales { get; set; }

[DataMember]
public string DeptName { get; set; }

}

[DataContract]
public class Department
{
[DataMember]
public int DeptNo { get; set; }

[DataMember]
public string Dname { get; set; }

[DataMember]
public string Location { get; set; }
//public List Allempl { get; set; }
[DataMember]
public List AllSales { get; set; }

public Employee Employee { get; set; }
}
Method like this
[WebGet(UriTemplate = "Employee", ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
List GetAllEmployeeDetails();
Getting data from two classes output like below
How can i get that type of output?

I want to output like this

DEV
Anil
101



1
Sales
Vij



please help me

ANIL BABU Mandla said...

I am writing the update statement,
the below Update method not comming the list
What is that Update method?
Update(p => p.CustomerName = obj.CustomerName);

ANIL BABU Mandla said...

{
[DataContract]
public class Employee
{
[DataMember]
public int EmpNo { get; set; }

[DataMember]
public string EmpName { get; set; }



//[DataMember]
//public List AllSales { get; set; }

[DataMember]
public string DeptName { get; set; }

[DataMember]
public List AllDepart { get; set; }
[DataMember]
public List AllSales { get; set; }

[DataMember]
public List Purchages { get; set; }

}
[DataContract]
public class Order
{
[DataMember]
public int Oid { get; set; }

[DataMember]
public string OName { get; set; }

//[DataMember]
//public List Sa { get; set; }
}

[DataContract]
public class Purchage
{
[DataMember]
public int Id { get; set; }

[DataMember]
public string IName { get; set; }
}

[DataContract]
public class Department
{
[DataMember]
public int DeptNo { get; set; }

[DataMember]
public string Dname { get; set; }

[DataMember]
public string Location { get; set; }
}
[DataContract]
public class Sales
{
[DataMember]
public string SName { get; set; }

[DataMember]
public string Sloc { get; set; }

[DataMember]
public List Orders { get; set; }


}

public partial class EmployeeData
{
private static readonly EmployeeData _instance = new EmployeeData();

private EmployeeData() { }

public static EmployeeData Instance
{
get
{
return _instance;
}
}

List empList = new List
{

new Employee() { EmpNo=101,EmpName="Anil",
AllDepart=new List { new Department (){ DeptNo=1,Dname="Sales",Location="Vij"}},
DeptName="DEV",
AllSales=new List { new Sales (){ SName="jjj",Sloc="ban",Orders=new List{new Order (){Oid=200,OName="ebay"}}}},
Purchages=new List {new Purchage () {Id=200,IName="Mobiles"}


}}
};
public List EmployeeList
{
get
{
return empList;
}
}

public void Add(Employee newEmployee)
{
empList.Add(new Employee
{
EmpNo = newEmployee.EmpNo,
EmpName = newEmployee.EmpName,
DeptName = newEmployee.DeptName,

});
}

public void UpdateEmp(Employee obj)
{

empList.Where(p => p.EmpNo == obj.EmpNo).Update(p => p.EmpName = obj.EmpName);

}
}

public static class LinqUpdates
{

public static void Update(this IEnumerable source, Action action)
{
foreach (var item in source)
action(item);
}

}

}
Actually this is my total code,

The using this update method ,i want to update and Insert total List of data,

The below list data i want to update and Insert
please give me that two methods for multiple classes

gimish said...

Getting Error : The type 'SaleClassLibrary.SaleService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.

Anonymous said...

where is the database connection???

Post a Comment