Click here to Skip to main content
12,761,421 members (32,496 online)
Click here to Skip to main content
Add your own
alternative version

Stats

446.2K views
35.6K downloads
103 bookmarked
Posted 30 Sep 2012

WCF example for inserting and displaying data from a SQL Server database using a WCF Service in ASP.NET

, 30 Sep 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
In this article I will show you a practical example of a WCF service for inserting data into a database using ASP.NET.
This is an old version of the currently published tip/trick.

Introduction

In this article I will show you a practical example of a WCF service for inserting data into a database using ASP.NET.

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
  2. New WCF Service Application.
  3. Give the name for the service as Customer Service.
  4. Press OK.

Open VS 2010

After the new project CustomerService project is created.

Then you will get three files:

  • IService.cs
  • Service.svc
  • Service.svc.cs

IService.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.Runtime.Serialization;
using System.ServiceModel;

[ServiceContract]
public interface IService
{

    [OperationContract]
    List<CustomerDetails> GetCustomerDetails(string CutomerName);

    [OperationContract]
    string InsertCustomerDetails(CustomerDetails customerInfo);
}

 [DataContract]
public class CustomerDetails
{
    string CutomerName = string.Empty;
    string firstname = string.Empty;
    string lastname = string.Empty;
    string address = string.Empty;

    [DataMember]
    public string CutomerName
    {
        get { return CutomerName; }
        set { CutomerName = value; }
    }
    [DataMember]
    public string FirstName
    {
        get { return firstname; }
        set { firstname = value; }
    }
    [DataMember]
    public string LastName
    {
        get { return lastname; }
        set { lastname = value; }
    }
    [DataMember]
    public string Address
    {
        get { return address; }
        set { address = value; }
    }
}

And write the following code in the Service.cs file:

Service.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 Service : IService
{
    SqlConnection con = new SqlConnection(
       "Data Source=Sujeet;Initial Catalog=Register;User ID=sa;Password=123");

    public List<CustomerDetails> GetCustomerDetails(string CutomerName)
    {
        List<CustomerDetails> CustomerDetails = new List<CustomerDetails>();
        {
            con.Open();
            SqlCommand cmd = new SqlCommand(
              "select * from CustomerInfo where CutomerName Like '%'+@Name+'%'", con);
            cmd.Parameters.AddWithValue("@Name", CutomerName);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    CustomerDetails customerInfo = new CustomerDetails();
                    customerInfo.CutomerName = dt.Rows[i]["CutomerName"].ToString();
                    customerInfo.FirstName = dt.Rows[i]["FirstName"].ToString();
                    customerInfo.LastName = dt.Rows[i]["LastName"].ToString();
                    customerInfo.Address = dt.Rows[i]["Address"].ToString();
                    CustomerDetails.Add(customerInfo);
                }
            }
            con.Close();
        }
        return CustomerDetails;
    }

    public string InsertCustomerDetails(CustomerDetails customerInfo)
    {
        string strMessage = string.Empty;
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into CustomerInfo(CutomerName," + 
           "FirstName,LastName,Address) values(@Name,@FName,@LName,@Address)", con);
        cmd.Parameters.AddWithValue("@Name", customerInfo.CutomerName);
        cmd.Parameters.AddWithValue("@FName", customerInfo.FirstName);
        cmd.Parameters.AddWithValue("@LName", customerInfo.LastName);
        cmd.Parameters.AddWithValue("@Address", customerInfo.Address);
        int result = cmd.ExecuteNonQuery();
        if (result == 1)
        {
            strMessage = customerInfo.CutomerName + " inserted successfully";
        }
        else
        {
            strMessage = customerInfo.CutomerName + " not inserted successfully";
        }
        con.Close();
        return strMessage;
    }
}

Build your service and if successful then run your service in your browser and then you will get a URL link like below and copy that URL:

Service

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 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 -> OK.
  6. Open Service Reference

  7. Then automatically a proxy will be created in your client system.
  8. Write the following code in your source code:
  9. <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
       
            <h2  >
                <strong>Cutomer  Form</strong></h2>
       
        </div>
        <table align="center" class="style1">
            <tr>
                <td  >
                    CutomerName</td>
                <td>
                    <asp:TextBox ID="txtCutomerName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                        ControlToValidate="txtCutomerName" ToolTip="CutomerName Required"><imgsrc="delete.png" /></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td  >
                    First Name</td>
                <td>
                    <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                        ControlToValidate="txtfname" ToolTip="Firstname Required"><imgsrc="delete.png" /></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td  >
                    Last Name</td>
                <td>
                    <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
                        ControlToValidate="txtlname" ToolTip="Lastname Required"><imgsrc="delete.png" /></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td  >
                    Address</td>
                <td>
                    <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
                        ControlToValidate="txtAddress" ToolTip="Address Required"><imgsrc="delete.png" /></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td  >
                     </td>
                <td>
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit"
                        onclick="btnSubmit_Click" />
                </td>
            </tr>
        </table>
        <table align="center" class="style3">
            <tr>
                <td>
                    <asp:Label ID="lblResult" runat="server"/>
                    <br />
                    <br />
                    <asp:GridView ID="GridView1" runat="server"BackColor="LightGoldenrodYellow"
                        BorderColor="Tan" BorderWidth="1px" CellPadding="2"ForeColor="Black"
                        GridLines="None" style="text-align: left" Width="304px">
                        <AlternatingRowStyle BackColor="PaleGoldenrod" />
                        <FooterStyle BackColor="Tan" />
                        <HeaderStyle BackColor="Tan" Font-Bold="True" />
                        <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
                            HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite"/>
                        <SortedAscendingCellStyle BackColor="#FAFAE7" />
                        <SortedAscendingHeaderStyle BackColor="#DAC09E" />
                        <SortedDescendingCellStyle BackColor="#E1DB9C" />
                        <SortedDescendingHeaderStyle BackColor="#C2A47B" />
                    </asp:GridView>
                </td>
            </tr>
        </table>
        </form>
        </body>
    </html>
  10. Add your service reference on the top.
  11. using ServiceReference1;
  12. Then create an object for Service Reference and use that object to call the methods from your service.
  13. 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
{
    ServiceReference1.ServiceClient objService = new ServiceReference1.ServiceClient();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindUserDetails();
        }
    }

    protected void BindUserDetails()
    {
        IList<CustomerDetails> objUserDetails = new List<CustomerDetails>();
        objUserDetails = objService.GetCustomerDetails("");

        GridView1.DataSource = objUserDetails;
        GridView1.DataBind();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        CustomerDetails customerInfo = new CustomerDetails();
        customerInfo.CutomerName = txtCutomerName.Text;
        customerInfo.FirstName = txtfname.Text;
        customerInfo.LastName = txtlname.Text;
        customerInfo.Address = txtlocation.Text;
        string result = objService.InsertCustomerDetails(customerInfo);
        lblResult.Text = result;
        BindUserDetails();
        txtCutomerName.Text = string.Empty;
        txtfname.Text = string.Empty;
        txtlname.Text = string.Empty;
        txtAddress.Text = string.Empty;
    }
}

By using this you have successfully inserted data in the database and you have also shown this in the grid view.

!! Happy Programming !!

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
Technical Lead
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.


Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

------------------------------------------------------------------------
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: Stac

You may also be interested in...

Pro
Pro

Comments and Discussions


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
QuestionOne of the most confusing tutorials I've ever tried to follow Pin
Member 1274969820-Sep-16 1:48
memberMember 1274969820-Sep-16 1:48 
AnswerRe: One of the most confusing tutorials I've ever tried to follow Pin
Member 1274969820-Sep-16 2:04
memberMember 1274969820-Sep-16 2:04 
QuestionDB Connection Pin
svassilianski28-Jan-16 10:44
membersvassilianski28-Jan-16 10:44 
GeneralMy vote of 4 Pin
Member 1206058129-Oct-15 22:07
memberMember 1206058129-Oct-15 22:07 
GeneralMy Vote Of 5 Pin
Sanket Bankar28-Oct-15 2:13
memberSanket Bankar28-Oct-15 2:13 
GeneralRe: My Vote Of 5 Pin
Sujit Bhujbal28-Oct-15 2:15
memberSujit Bhujbal28-Oct-15 2:15 
QuestionThere was no endpoint listening at http://localhost:53544/SaleService.svc that could accept the message Pin
Member 1207934022-Oct-15 6:50
memberMember 1207934022-Oct-15 6:50 
AnswerRe: There was no endpoint listening at http://localhost:53544/SaleService.svc that could accept the message Pin
Sujit Bhujbal27-Oct-15 4:47
memberSujit Bhujbal27-Oct-15 4:47 
GeneralMy vote of 5 Pin
Santhakumar Munuswamy @ Chennai8-Aug-15 5:43
professionalSanthakumar Munuswamy @ Chennai8-Aug-15 5:43 
GeneralRe: My vote of 5 Pin
Sujit Bhujbal27-Oct-15 4:43
memberSujit Bhujbal27-Oct-15 4:43 
GeneralMy Vote of 5 Pin
Math08avan12-Jul-15 1:39
memberMath08avan12-Jul-15 1:39 
GeneralRe: My Vote of 5 Pin
Sujit Bhujbal27-Oct-15 4:42
memberSujit Bhujbal27-Oct-15 4:42 
QuestionThank you Pin
Member 1168587712-May-15 16:27
memberMember 1168587712-May-15 16:27 
AnswerRe: Thank you Pin
Sujit Bhujbal18-Jun-15 21:02
memberSujit Bhujbal18-Jun-15 21:02 
QuestionThanks Sujit Bhujbal Pin
Nguyên Hoàng Nguyễn Đức8-May-15 0:00
memberNguyên Hoàng Nguyễn Đức8-May-15 0:00 
AnswerRe: Thanks Sujit Bhujbal Pin
Sujit Bhujbal18-Jun-15 21:03
memberSujit Bhujbal18-Jun-15 21:03 
QuestionGetting error in VS2012 Pin
JomyK7-May-15 14:15
memberJomyK7-May-15 14:15 
AnswerRe: Getting error in VS2012 Pin
Sujit Bhujbal18-Jun-15 21:18
memberSujit Bhujbal18-Jun-15 21:18 
GeneralCongrats Pin
Member 111054606-Apr-15 23:43
memberMember 111054606-Apr-15 23:43 
GeneralRe: Congrats Pin
Sujit Bhujbal18-Jun-15 21:09
memberSujit Bhujbal18-Jun-15 21:09 
QuestionAdnan Pin
Member 1151696711-Mar-15 8:13
memberMember 1151696711-Mar-15 8:13 
AnswerRe: Adnan Pin
Sujit Bhujbal15-Mar-15 20:41
memberSujit Bhujbal15-Mar-15 20:41 
QuestionLink not working Pin
Humayun Kabir Mamun10-Mar-15 21:22
memberHumayun Kabir Mamun10-Mar-15 21:22 
AnswerRe: Link not working Pin
Sujit Bhujbal11-Mar-15 1:09
memberSujit Bhujbal11-Mar-15 1:09 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-Mar-15 21:19
memberHumayun Kabir Mamun10-Mar-15 21:19 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170217.1 | Last Updated 30 Sep 2012
Article Copyright 2012 by Sujit Bhujbal
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid