Introduction:
Here I will explain how to use or consume WCF (windows communication foundation) service in web application using asp.net.
Description:
Create new website from visual studio select New---> Website and give some name as you like.
Here I will explain how to use or consume WCF (windows communication foundation) service in web application using asp.net.
Description:
In previous articles explained clearly what WCF (windows communication foundation) is and how to create and consume WCF service in c#(windows application) and I also explained clearly uses of WCF Service. Now in this article I will explain how to consume WCF service in web application.
Creating simple application using WCF
Here I am going to do WCF sample to insert new userdetails and display Userdetails based on UserName for that first create table in your database like this
Column Name | Data Type | Allow Nulls |
UserId | Int(Set Identity=true) | No |
UserName | nvarchar(MAX) | Yes |
FirstName | varchar(50) | Yes |
LastName | varchar(50) | Yes |
Location | varchar(50) | Yes |
After that First open Visual Studio and click file ---> Select New ---> Website Under that select WCF Service and give name for WCF Service and click OK
Once you created application you will get default class files including Service.cs and IService.cs
Here IService.cs is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.
Now open IService.cs add the following namespaces
using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; |
After that write the following code in IService.cs file
[ServiceContract] public interface IService { [OperationContract] List<UserDetails> GetUserDetails(string Username); [OperationContract] string InsertUserDetails(UserDetails userInfo); } // Use a data contract as illustrated in the sample below to add composite types to service operations. [DataContract] public class UserDetails { string username = string.Empty; string firstname = string.Empty; string lastname = string.Empty; string location = string.Empty; [DataMember] public string UserName { get { return username; } set { username = value; } } [DataMember] public string FirstName { get { return firstname; } set { firstname = value; } } [DataMember] public string LastName { get { return lastname; } set { lastname = value; } } [DataMember] public string Location { get { return location; } set { location = value; } } } |
After that open Service.cs class file and add the following namespaces
using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; |
After that write the following code
public class Service : IService { private string strConnection = ConfigurationManager.ConnectionStrings["dbconnection"].ToString(); public List<UserDetails> GetUserDetails(string Username) { List<UserDetails> userdetails = new List<UserDetails>(); using (SqlConnection con=new SqlConnection(strConnection)) { con.Open(); SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName Like '%'+@Name+'%'", con); cmd.Parameters.AddWithValue("@Name", Username); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dtresult = new DataTable(); da.Fill(dtresult); if(dtresult.Rows.Count>0) { for(int i=0;i<dtresult.Rows.Count;i++) { UserDetails userInfo = new UserDetails(); userInfo.UserName = dtresult.Rows[i]["UserName"].ToString(); userInfo.FirstName = dtresult.Rows[i]["FirstName"].ToString(); userInfo.LastName = dtresult.Rows[i]["LastName"].ToString(); userInfo.Location = dtresult.Rows[i]["Location"].ToString(); userdetails.Add(userInfo); } } con.Close(); } return userdetails; } public string InsertUserDetails(UserDetails userInfo) { string strMessage = string.Empty; using (SqlConnection con=new SqlConnection(strConnection)) { con.Open(); SqlCommand cmd = new SqlCommand("insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)", con); cmd.Parameters.AddWithValue("@Name", userInfo.UserName); cmd.Parameters.AddWithValue("@FName", userInfo.FirstName); cmd.Parameters.AddWithValue("@LName", userInfo.LastName); cmd.Parameters.AddWithValue("@Location", userInfo.Location); int result= cmd.ExecuteNonQuery(); if(result==1) { strMessage = userInfo.UserName+ " Details inserted successfully"; } else { strMessage = userInfo.UserName + " Details not inserted successfully"; } con.Close(); } return strMessage; } } |
Now set the database connection string in web.config file because in above I am getting the connection string from web.config file
<connectionStrings> <add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/> </connectionStrings> |
Our WCF service ready to use with basicHttpBinding. Now we can call this WCF Service method console applications
After completion of WCF service creation publish or deploy your WCF Service in your system. If you don’t’ have idea on deploy check this post publish or deploy website
After completion of deploy webservice now we can see how to use WCF Service in our console application
Calling WCF Service using Web Application
To call WCF service we have many ways like using console app, windows app and web app in previous post I explained how to call (or) consume WCF service in console application. Now I will explain how to consume WCF service in web application.
Create new website from visual studio select New---> Website and give some name as you like.
After Creation Website now we need to add WCF reference to our web application for that right click on your web application and select Add Service Reference
Now one wizard will open in that give your WCF service link and click Go after add your service click OK button.
After completion of adding WCF Service first open Default.aspx page and write the following code
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { height: 26px; } </style> </head> <body> <form id="form1" runat="server"> <div> <table align="center"> <tr> <td colspan="2" align="center"> <b>User Registration</b> </td> </tr> <tr> <td> UserName: </td> <td> <asp:TextBox ID="txtUserName" runat="server"/> </td> </tr> <tr> <td> FirstName: </td> <td> <asp:TextBox ID="txtfname" runat="server"/> </td> </tr> <tr> <td> LastName: </td> <td> <asp:TextBox ID="txtlname" runat="server"/> </td> </tr> <tr> <td class="style1"> Location: </td> <td class="style1"> <asp:TextBox ID="txtlocation" runat="server"/> </td> </tr> <tr> <td> </td> <td> <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /> </td> </tr> <tr> <td colspan="2"> <asp:Label ID="lblResult" runat="server"/> </td> </tr> <tr> <td colspan="2"> <asp:GridView runat="server" ID="gvDetails" AutoGenerateColumns="false"> <RowStyle BackColor="#EFF3FB" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:BoundField HeaderText="UserName" DataField="UserName" /> <asp:BoundField HeaderText="FirstName" DataField="FirstName" /> <asp:BoundField HeaderText="LastName" DataField="LastName" /> <asp:BoundField HeaderText="Location" DataField="Location" /> </Columns> </asp:GridView> </td> </tr> </table> </div> </form> </body> </html> |
Now open Default.aspx.cs file and add following namespaces
using System; using System.Collections.Generic; using ServiceReference1; |
After adding namespaces write the following code in codebehind
ServiceReference1.ServiceClient objService = new ServiceClient(); protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { BindUserDetails(); } } protected void BindUserDetails() { IList<UserDetails> objUserDetails = new List<UserDetails>(); objUserDetails = objService.GetUserDetails(""); gvDetails.DataSource = objUserDetails; gvDetails.DataBind(); } protected void btnSubmit_Click(object sender, EventArgs e) { UserDetails userInfo = new UserDetails(); userInfo.UserName = txtUserName.Text; userInfo.FirstName = txtfname.Text; userInfo.LastName = txtlname.Text; userInfo.Location = txtlocation.Text; string result= objService.InsertUserDetails(userInfo); lblResult.Text = result; BindUserDetails(); txtUserName.Text = string.Empty; txtfname.Text = string.Empty; txtlname.Text = string.Empty; txtlocation.Text = string.Empty; } |
After completion of adding code check your endpoint connection for WCF Service reference that should be like this
<endpoint address=" http://localhost/WCFServiceSample/Service.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService" contract="ServiceReference1.IService" name="WSHttpBinding_IService"> <identity> <dns value="localhost" /> </identity> </endpoint> |
Now everything is ready run your application that output should be like this
4 comments:
This is simple.
Try to insert data using silverlight wcf ria service...
Inserting into database will create problem when multiple clients e.g 200-250 will access the service at a time? Will that create problem? Is there any other way to do so.?
Thanks man it works for me ....I m start learning WCF Thanks Soo much for this article.
Thanks
Sambhaba
Thanks for sharing such a valuable information.This post is very useful for me.Jobs in Asp.net
Post a Comment