WCF example for inserting and displaying data from a 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 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
- Open Visual Studio 2010
- New WCF Service Application
- Give the name for service Customer Service
- Press ok
After that a new project is created, the CustomerService project.
Then you will get 3 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 successfully first, then run your service in your browser, then you will get one URL link as in the following (copy that URL):
In this way your WCF service builds successfully.
Part 2: Create a Web Based Application (Client)
Now create your Client Application in your system in the following way:
-
Create one Website
-
Add a Service Reference to the Web Application
-
Select Your Website
-
Right-click on it, add a Service Reference, then enter your Service URL and click Go
-
Give the name for your service then click the OK buton
-
Then a Proxy will be created automatically in your client system.
-
Write the following code in your source code:
Source Code
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" 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>
- <usercontrol x:class="SilverlightRIAInsert.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d"
- d:designheight="300" d:designwidth="543">
- <Grid x:Name="LayoutRoot" ><TextBlock Height="23" HorizontalAlignment="Left" Margin="152,29,0,0" Name="textBlock1" Text="FirsName" FontFamily="Verdana" FontSize="15" VerticalAlignment="Top" /><TextBox Height="23" HorizontalAlignment="Left" Margin="252,25,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /><TextBlock Height="23" HorizontalAlignment="Left" Margin="150,72,0,0" Name="textBlock2" Text="LastName" FontFamily="Verdana" FontSize="15" VerticalAlignment="Top" /><TextBox Height="23" HorizontalAlignment="Left" Margin="252,68,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" /><TextBlock Height="23" HorizontalAlignment="Left" Margin="150,113,0,0" Name="textBlock3" Text="Age" FontFamily="Verdana" FontSize="15" VerticalAlignment="Top" /><TextBox Height="23" HorizontalAlignment="Left" Margin="252,113,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" /><Button Content="Insert" FontFamily="Verdana" FontSize="19" Background="DeepSkyBlue" Height="44" HorizontalAlignment="Left" Margin="252,156,0,0" Name="button1" VerticalAlignment="Top" Width="120" Click="button1_Click" /></Grid>
- </usercontrol>
8. Add your service reference on the top:
9. Then create one Object for Service Reference and use that object to call 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
- {
- 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 are also shown this in a grid view.
Happy Programming!