You are on page 1of 6

10/20/12 Asp.net WebService or Creating and Consuming WebService in asp.

net or Create and call webservice


1/11 www.aspdotnet-suresh.com/2011/05/aspnet-web-service-or-creating-and.html
Like 2.7k Follow Follow @aspdotnetsuresh @aspdotnetsuresh 1,662 f ollowers
ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL
Server,Ajax,SSRS, XML examples
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
HOME ASP.NET AJAX GRIDVIEW JAVASCRIPT SQL JQUERY OOPS CONCEPTS INTERVIEW QUESTIONS TRACE MOBILE NUMBER CONTACT
Asp.net WebService or Creating and Consuming WebService in
asp.net or Create and call webservice in asp.net or how to create
webservice and how to use webservice in asp.net
By: Suresh Dasari May 17, 2011
Categories: Asp.net, WebService
Introduction:
Here I will explain what webservice is, uses of webservice and how to create webservice and how to
consume webservice in asp.net.
Description:
Today I am writing article to explain about webservices. First we will see what is webservice is and uses
of webservice and then we will see how to use webservice in our applications.
What is Web Service?
Web Service is an application that is designed to interact directly with other applications over the
internet. In simple sense, Web Services are means for interacting with objects over the Internet. The
Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over
the Web. WebService is language independent and Web Services communicate by using standard web
protocols and data formats, such as
HTTP
XML
SOAP
Advantages of Web Service
Web Service messages are formatted as XML, a standard way for communication between two
incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the
internet without being blocked by firewall.
Examples for Web Service
Weather Reporting: You can use Weather Reporting web service to display weather information in your
personal website.
Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
News Headline: You can display latest news update by using News Headline Web Service in your
website.
In summary you can any use any web service which is available to use. You can make your own web
service and let others use it. Example you can make Free SMS Sending Service with footer with your
advertisement, so whosoever use this service indirectly advertise your company... You can apply your
ideas in N no. of ways to take advantage of it.
Frequently used word with web services
What is SOAP?
SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on
Remote machine and translate the object communication into XML format. In short, SOAP are way by
which method calls are translate into XML format and sent via HTTP.
What is WSDL?
WSDL stands for Web Service Description Language, a standard by which a web service can tell clients
what messages it accepts and which results it will return.
WSDL contains every detail regarding using web service and Method and Properties provided by web
service and URLs from which those methods can be accessed and Data Types used.
Search This Site
Search
About Me
SURESH DASARI
TENALI, ANDHRA PRADESH, INDIA
Hi i am suresh dasari,software
engineer working on
asp.net,c#.net,SQL Server.
VIEW MY COMPLETE PROFILE
Follow Follow @aspdotnetsuresh @aspdotnetsuresh 1,662 f ollowers
Like 2.7k

9
Select Language
Powered by Translate
Tweet Tweet
2
9
StumbleUpon
1
14
Like
Share Share
V enkatesh SE Arun Niv as
Datta Md Ziaullah V inod
Aspdotnetsuresh on
Facebook
2,701 people like Aspdotnetsuresh.
Like
Facebook social plugin
10/20/12 Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice
2/11 www.aspdotnet-suresh.com/2011/05/aspnet-web-service-or-creating-and.html
What is UDDI?
UDDI allows you to find web services by connecting to a directory.
What is Discovery or .Disco Files?
Discovery files are used to group common services together on a web server. Discovery files .Disco and
.VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery
information for a web service. Disco File contains URL for the WSDL, URL for the documentation and URL
to which SOAP messages should be sent.
Before start creating web service first create one table in your database and give name UserInformation
in my code I am using same name and enter some dummy data for our testing purpose
Column Name Data Type Allow Nulls
UserId Int(Set Identity=true) No
UserName Varchar(50) Yes
FirstName Varchar(50) Yes
LastName Varchar(50) Yes
Location Varchar(50) Yes
Now we will see how to create new web service application in asp.net
Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Service
Now our new web service ready our webservice website like this
Now open your Service.cs file in web service website to write the code to get the user details from
database
Before writing the WebMethod in Service.cs first add following namespaces
using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After adding namespaces write the following method GetUserDetails in Service.cs page
[WebMethod]
public XmlElement GetUserDetails(string userName)
{
Recent Posts
Asp.net Cross Page Postback Example in 2.0,
3.0, 3.5, 4.0
More
11 Best jQuery Countdown Timer Script Plugin
Examples/Tutori...
More
Print Asp.net Gridview Data using C# VB.NET
JavaScript
More
jQuery Countdown Timer Script Example in
Asp.net
More
jQuery Redirect to Another Page After 5
seconds or Some Time...
More
JavaScript Redirect to Another Page After 5
seconds or Some ...
More
JavaScript Display Current Time on Webpage
or Website withou...
More
jQuery Display Current Time on Webpage
using Asp.net
More
Asp.net Pass Multiple Parameters in Query
String or URL
More
Asp.net Query String Example in C#, VB.NET
More
We're on
+251
Follow
Find us on Facebook
Sradhanjali Md Om Ziaullah Qaiser
Aspdotnetsuresh
2,701 people like Aspdotnetsuresh.
Like
Facebook social plugin
Get Latest articles in your inbox for free.
Enter your email address:
Subscribe
10/20/12 Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice
3/11 www.aspdotnet-suresh.com/2011/05/aspnet-web-service-or-creating-and.html
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like
@userName+'%'", con);
cmd.Parameters.AddWithValue("@userName", userName);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
// Return the DataSet as an XmlElement.
XmlDataDocument xmldata = new XmlDataDocument(ds);
XmlElement xmlElement = xmldata.DocumentElement;
return xmlElement;
}
Here we need to remember one point that is adding [WebMethod] before method definition because we
need to access web method pulically otherwise its not possible to access method publically. If you
observe above code I converted dataset to XmlElement t because sometimes we will get error like return
type dataset invalid type it must be either an IListSource, IEnumerable, or IDataSource to avoid
this error I converted dataset to XmlElement.
Here we need to set the database connection in web.config because here I am getting database
connection from web.config
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial
Catalog=MySampleDB"/>
</connectionStrings>
Now run your web service it would be like this
Our web service is working fine now we need to know how we can use webservice in our application?
Before to know about using web service in application first Deploy your webservice application in your
local system if you want to know how to deploy application in your local system check this link deploy
application in local system
How to Use Web service in web application?
By using this webservice we can get the user details based on username. For that first create one new
web application
Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Site
Categories
Asp.net (316)
General (195)
JQuery (84)
Gridview (60)
SQL Server (59)
Code Snippets (56)
Errors (34)
Javascript (32)
Ajax (29)
Interview Questions (26)
C#.Net (25)
DropdownList (16)
VB.NET (15)
Authentication (14)
Membership (14)
Crystal Reports (11)
Fileupload (11)
IISServer (11)
validations (10)
DatePicker (8)
JSON (8)
AutoComplete (7)
JQuery Plugins (7)
AjaxModalPopupExtender (6)
SQL Joins (6)
SendMail (6)
Windows Application (6)
DataList (5)
ExcelSheet (5)
InternetTips (5)
Dynamic Controls (4)
ExportGridviewData (4)
ToolTip (4)
WCF (4)
Windows Service (4)
XML (4)
CheckBox (3)
EncryptionandDecryption (3)
Facebook (3)
Twitter (3)
WebService (3)
web.config (3)
AjaxAsyncFileUpload (2)
AjaxAutoCompleteExtender (2)
AjaxTabContainer (2)
CSS (2)
Global.asax (2)
LightBoxEffect (2)
MultilineTextbox (2)
OOPS Concepts (2)
Progressbar (2)
10/20/12 Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice
4/11 www.aspdotnet-suresh.com/2011/05/aspnet-web-service-or-creating-and.html
After creation of new website right click on solution explorer and choose Add web reference that would
be like this
After select Add Web reference option one window will open like this
Now enter your locally deployed web service link and click Go button after that your web service will
found and window will looks like this
SSRS (2)
Session Timeout (2)
ThumbnailsGeneration (2)
UserName Check (2)
Visual Studio (2)
3-TierArchitecture (1)
ADO.NET (1)
AbstractVsInterface (1)
ActiveDirectory (1)
Ajax Calendarextender (1)
Ajax ConfirmbuttonExtender (1)
AjaxAccordionControl (1)
AjaxCalendarExtender (1)
AjaxCollapsiblePanelControl (1)
AjaxDragPanelExtender (1)
AjaxPasswordStrength (1)
AjaxRatingControl (1)
AjaxSlideshowExtender (1)
Arraylist (1)
Assembly (1)
Authorization (1)
Average rating (1)
CheckBoxList (1)
CodingStandards (1)
DataGrid (1)
Generic List (1)
ImportContacts (1)
ListBox (1)
MCC Award (1)
QueryString (1)
RSSFeeds (1)
RadioButtonList (1)
Read/Write text file (1)
ReadOnlyValues (1)
Repeater (1)
Resize Image (1)
RichTextBox (1)
SQL Constraints (1)
SiteMap (1)
SlideShow (1)
Testing (1)
Trace Mobile Number (1)
UpdatePanel (1)
VBScript (1)
WPF (1)
Blog Archive
2012 (219)
2011 (131)
December (24)
November (15)
October (17)
July (8)
June (7)
May (15)
how to show the tooltip for gridview header
column...
Invalid length for a base-64 char array error
duri...
The requested page cannot be accessed
because the ...
System.Data.SqlClient.SqlException: Login failed
f...
how to add Global.asax.cs file in asp.net or how
10/20/12 Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice
5/11 www.aspdotnet-suresh.com/2011/05/aspnet-web-service-or-creating-and.html

Now click on Add Reference button web service will add successfully. Now open your Default.aspx page
and design like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Getting Data from WebService</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<b>Enter UserName:</b>
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvUserDetails" runat="server" EmptyDataText="No Record Found">
<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" />
</asp:GridView>
</div>
</form>
</body>
</html>
Now in code behind add following namespaces
using System.Data;
using System.Xml;
After adding namespaces write the following code in code behind
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindUserDetails("");
}
}
protected void BindUserDetails(string userName)
t...
What is the use of Global.asax file events in
asp....
Asp.net WebService or Creating and Consuming
WebSe...
How To Set a Date Format In GridView Using
ASP.NET...
Ajax AutoCompleteExtender example or sample
withou...
Ajax rating control example with database or
how t...
RichTextbox example or sample in asp.net or
how to...
how to resize image without losing image quality
o...
Asp.net Create/generate thumbnails from
images
Microsoft Community Contributor Award - 2011
or I ...
how to bind or display images from folder to
datal...
April (9)
March (17)
February (9)
January (10)
2010 (77)
Tags
Asp.net General JQuery Gridview
Server Code Snippets Errors Javascript
Interview Questions C#.Net DropdownList
Authentication Membership Crystal Reports Fileupload
IISServer validations DatePicker JSON AutoComplete
JQuery Plugins AjaxModalPopupExtender SQL Joins
Windows Application DataList ExcelSheet InternetTips
Dynamic Controls ExportGridviewData ToolTip WCF Windows
Service XML CheckBox EncryptionandDecryption Facebook
Twitter WebService web.conf ig Aj axAsyncFi l eUpl oad
Aj axAutoCompl eteExtender Aj axTabContai ner
Gl obal .asax Li ghtBoxEffect Mul ti l i neTextbox OOPS Concepts
Progressbar SSRS Sessi on Ti meout Thumbnai l sGenerati on
UserName Check Vi sual Studi o 3-Ti erArchi tecture ADO.NET
AbstractVsInterface Acti veDi rectory Aj ax Cal endarextender
Confi rmbuttonExtender Aj axAccordi onControl
Aj axCal endarExtender Aj axCol l apsi bl ePanel Control
Aj axDragPanel Extender Aj axPasswordStrength
Aj axRati ngControl Aj axSl i deshowExtender Arrayl i st Assembl y
Authori zati on Average rati ng CheckBoxLi st Codi ngStandards
DataGri d Generi c Li st ImportContacts Li stBox MCC Award
QueryStri ng RSSFeeds Radi oButtonLi st Read/Wri te text fi l e
ReadOnl yVal ues Repeater Resi ze Image Ri chTextBox
Constrai nts Si teMap Sl i deShow Testi ng Trace Mobi l e Number
UpdatePanel VBScri pt WPF
10/20/12 Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice
6/11 www.aspdotnet-suresh.com/2011/05/aspnet-web-service-or-creating-and.html
{
localhost.Service objUserDetails = new localhost.Service();
DataSet dsresult = new DataSet();
XmlElement exelement = objUserDetails.GetUserDetails(userName);
if(exelement!=null)
{
XmlNodeReader nodereader = new XmlNodeReader(exelement);
dsresult.ReadXml(nodereader, XmlReadMode.Auto);
gvUserDetails.DataSource = dsresult;
gvUserDetails.DataBind();
}
else
{
gvUserDetails.DataSource = null;
gvUserDetails.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindUserDetails(txtUserName.Text);
}
Now run your application and check output
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.
Like 2.7k

9
Subscribe by RSS Subscribe by Email
Follow Follow @aspdotnetsuresh @aspdotnetsuresh 1,662 f ollowers
Introduction to WCF -
WCF tutorial | WCF
Tutorial - ...
Ajax
AutoCompleteExtend
er sample without
using webse ...
Asp.net login control
to check user details
using Me ...
ASP.Net Create,
manage and delete
roles in membership
CreateUserWizard
control to create
user accounts in ...
Assign roles to user Recover forgot Crystal reports Edit,update,delete Programmatically
You might also like:

You might also like