Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

how to consume (or) use wcf service in web application | how to consume (or) use wcf service in asp.net | wcf tutorial with examples for beginners

Jul 5, 2011
Introduction:

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

 


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

45 comments :

Anonymous said...

great example dude

Anonymous said...

great work .. keep going ....

Anonymous said...

Hi Suresh,

Nice Work.. However, i am unable to consume WCF Service in my application. Its giving me following error,

he HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'Negotiate,NTLM'.

Can u pls tell solution on this ?

Regards,

Rohit Pundlik

Anonymous said...

Very nice indeed..... keep it up !!!!!!

Santosh said...

very nice example...after abt 1 hour googling i got this example...

http://aspdotnetcode.blogspot.com/

Vijay Negi said...

Suresh your blog seems extremly awsome,but could you please tell me when u are coming with MVC in your blog with your teaching style?

ASHOK said...

Hi Suresh,

IList userdetails = new List();
userdetails = objService.GetUserDetails("as");

In that following code objService.GetUserDetails("as");
is throwing some error like "Can't implicit convert type..."

Can you give me solution please...

ASHOK said...

Hi Suresh,

IList userdetails = new List();
userdetails = objService.GetUserDetails("as");

In that following code objService.GetUserDetails("as");
is throwing some error like "Can't implicit convert type..."

Can you give me solution please...

Simerdeep Singh said...

Good job bro
Simerdeep Singh from Canada

www.cosmicdatainc.com

binapani.deori said...

this is a very useful example sir.....but m beginner of mvc application..so can u pls tell me how to consume this same wcf service using an mvc applicaion..?

Pratik said...

Perfect!!!! Point to point

ramessh said...

very good example

ramessh said...

very good example

shahid said...

HI suresh

the code is giving error objService.GetUserDetails("as");
is throwing some error like "Can't implicit convert type..."

shahid said...

thank you so much your collection is really helpfull

Mohan said...

Thank u so much for kind inf..abt the WCF..its help me a lot ........

Anonymous said...

Nice work... keep up the good work

Anonymous said...

Very good example. Thank you Suresh

ANIL BABU Mandla said...

Greate,Tell me UPDATE,DELETE also pls

shivm said...

hi suresh,
is apply css in window application using C#

Anonymous said...

Great work

Anonymous said...

very good example. can i know how can we consume a WCF Service in MVC 3 Application?

Anonymous said...

http:\\yahoo.com

sravan kumar said...

good one very useful information...

Anonymous said...

very good

Anonymous said...

Lovely...Thanks...

Santosh Pal said...

hi suresh sir
while doing this im getting this error
Plz help me to solve this error

The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.

Anonymous said...

Hi,
Thanks for making us understand WCF clearly with examples
Am getting below error
plz helpme out

The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.

Thanks
Archana

Marees said...
This comment has been removed by the author.
Marees said...

Nice article .Will you pls explain how to make MVC 4 ?

Anonymous said...

when i type h in text box in location field i need to get all the values starting with 'h' in database as shown above..evrything is working fine except that i am not getting that

Anonymous said...

Thanks a lot for wonderful example

Vinayak Deshpande said...

hi suresh sir

nice example
but when i am trying to insert
time out error given.

sir please tell me the solution for this.

thanks
Vinayak

Anonymous said...

thanks a lot for great example.

anupam suman said...

hi suresh

thnx for the post,if you will post some REAL TIME scene with code than WCF will be more easy to understand so plz ost some real time scene on wcf

Sandip Roy said...

thanks yaar..

Raghavender Balasani said...

Your Explanation simply nice...

Anonymous said...

Hi suresh
I used the same example.i am getting this error

" The Address property on ChannelFactory.Endpoint was null. The ChannelFactory's Endpoint must have a valid Address specified."

00MANN00 said...

is throwing some error like "Can't implicit convert type..."

Anonymous said...

Good Explanation

Anonymous said...

hey i tried this with vs2010,but i couldnt host it in IIS, can you explain me how to deploy this WCF service in IIS. your link abo ut deploy only deals with website not WCF deployment

Anonymous said...

can you provide with details how to deploy it in IIS , i am using VS2010.I need this example in VS2010 with creation and deployment. Thanks

Anonymous said...

Sathish - Very sueful

Bhagwat Prasad Sharma said...

very great articles posted by you...

SS.GOWTHAMAN S.SRIRAM said...

Hi

i am getting error while accessing your application as
The HTTP service located at

http://localhost/sampleuserservice/Service.svc is too busy.

can you provide me some solution

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.