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

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

May 17, 2011
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.

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)
{
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 it’s 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


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


 

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)
{
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.

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

210 comments :

«Oldest   ‹Older   1 – 200 of 210   Newer›   Newest»
Khaled Samir. said...

Thank you very much , Suresh I really understood Web Service now.

Greetings from Egypt.

Anonymous said...

Thank you

Unknown said...

Thank you very much, It is very helpful.

vinay_289 said...

very good article for novice in creating and using WebService.....!

Anonymous said...

How to use this code in windows form to display in datagridview? Please replay.

Anonymous said...

Thanks...:)

Anonymous said...

nice article easy to understand for beginers.......

Anonymous said...

Thanks...good one

Anonymous said...

thank you very much suresh .

Anonymous said...

Sir This Artical Is very important to me and my project big problem to solve this artical thanks suresh sir.
rahul shimpi

Anonymous said...

it is realy useful for me....

Jeelani506 said...

Hi good article buddy thank.

sundaram choudhary said...

Ultimate,sir ji.A lot of thanks for every blog.

Anonymous said...

U r Superb man

Anonymous said...

how i use other web services like(cricket score,weather report,new headlines) in my web site

thanx for your post

Anonymous said...

how to access this webservice via internet

Anonymous said...

It is very helpful
thank u

Anonymous said...

I have created the above service & web application now my requirement is to insert user details from Web application to oracle database through web service created above

Anonymous said...

My Emailid is swapnilnalbalwar05@gmail.com

Anonymous said...

Good Example, Very Helpful, thanks

Anonymous said...

how to access this web service via internet

Anonymous said...

very nice example

Jahabar Sathik Hakeem

Anonymous said...

Article is very nice.

Chandrasekar said...

Nice Article Suresh, Very Clear descriptions..

Kunaal said...

hi Suresh...
Thanks for such breif explanation.
I like the article and would like to share it with my frnds as well.

Cheers

Anonymous said...

good one...

Help said...

Give the example How to use Weather report on my asp.net website

Help said...

Thank you,
Plz give me complete example on WEBSERVICE Perform All DML operations AND also consume this service in ASP.NET pages perform all operations
help me

Anonymous said...

hi
getting error on line

localhost.Service objUserDetails = new localhost.Service();

(for localhost)

kindly suggest solution.

pawan Sharma said...

thanks sir..i want more example if possible so please share...

Anonymous said...


hi
sir..

i want to more details about WCF & WEB SERVICE.

Braj Kishor said...

hi,
Dear Sir,
Thank in Advanced, i want to more details about WCF if it possible then plz shared...........


braj from Noida.

Shrikant said...

can you tell me why we use [] in web service .
Please Mail me at shrikantkhode@gmail.com

Unknown said...

Such a Good Article

Hir bavisi said...

Nice Article.

But i want to call the servicemethod from the aspx page it self by Servicemethod="GetUserdetail"

But the created method for the GetUserdetail is taking one argument.

How can i solve this?

Gavidi Srinivas said...

Fine

GAVIDI SRINIVAS 8886164458

Gavidi Srinivas said...

FINE

GAVIDI SRINIVAS

9393087430
8886174458

PremNath said...

Easy Understandable

Unknown said...

So Easy Understandable

Anonymous said...


hi
can you pls tell me for where this obj created
"localhost". below line:
localhost.Service objUserDetails = new localhost.Service();

I think this is an object!!





koti said...

Very Nice Article

Saleem said...

Good very useful blog

Anonymous said...

'localhost.Service' does not contain a definition for 'GetUserDetails' ERROR OCCUR using this can you help

Unknown said...

Very Nice Article....

baliablog said...

Vary Nice Article and easy to understand also well explain...

Anonymous said...

when i use web service that time Error display like
"Unable to connect to the remote server"
please give me solution

Anonymous said...

Fabulous work Sir..
Really your articles are so helpful,,amazing ..
Please keep it up Sir ..
Thanks .....

Anonymous said...

I understood what is websevice. Thank u very much Suresh

S RAMESH KUMAR said...

its easy to understand

Anonymous said...

It is very excellent.
Easy to understand for beginners also.
I am really thanks Suresh.
I am so happy, I had a feared of asp.net.Now I am very clear about it. I know within a few months I am also a programmer in one of the biggest concern. Suresh I never forget you till I die!.

Anonymous said...

Thanks......

Anonymous said...

thanks .it was of great help.

jassi said...

Thanks a lot..suresh now i clear the concept of web services...and your site is so good and nice artical your website is so so so good ...god bless you.

raushan said...

thanks.its a great example to understand websevices.

selvi said...

i have one error like this


Error is
CS0029: Cannot implicitly convert type 'System.Xml.XmlElement' to 'string'

Anonymous said...

can any one clear this error


CS0029: Cannot implicitly convert type 'System.Xml.XmlElement' to 'string'

iDontKnowProgramming said...
This comment has been removed by the author.
Anonymous said...

You are rocking
....awsm
i created my webservice by reading this article
tooo good

-Snehal

Anonymous said...

Really i understood web service from first trial itself.ITS TOO HELPFUL.thanks your nice guidance...

Anonymous said...

it is very useful for beginners. thanks.

--Srinivas

poonam said...

Thank u...

Unknown said...

Very Nice Article to start with WCF

Jatin said...

Again i need to say, kya baat kya baat, excellent... :)

Anonymous said...

Very nice Article ,Thanks...

Bikash Panigrahi said...

I am doing a project OpenKm documentation version 6.2.I am having some problem.Can you help me...

Shashikant Patil said...

Just absolutely brillient!!! You are the man!!!


Cheers,
Shashikant Patil, Pune

Unknown said...

This code is very helpful for the beginners

Unknown said...

Greate Sir.

Please Add Advance topic MVC,WPF in details

Anonymous said...

Superb boss, one time recap for web serice

Amit Sharma said...

please send me a code for showing Exception message using java script alert message

Unknown said...

Nice And Very Good Show code PRoject
thanks agin other web Servies here

Anonymous said...

Hey Thanks Suresh It's really usefull

Love Makes Life Beautifull said...

Thank you friend i have to implement this web service in wpf using VB.net if you don't mine teach me how to write web service in vb.net using Data set....

Anonymous said...

Thank you very much for good explaination.

Anonymous said...

nyc...

Anonymous said...

Superb Article

Anonymous said...

it is really interesting.. i have worked out ur sample. thank u so much.... keep doing this kind of artcle.. all the best

Anonymous said...

thanks.. it seems easy and i did perfectly.. the reson is that u tought us perfectly... thanking you... Shyam Sharma

Anonymous said...

Great Article for beginner level superb

Anonymous said...

superb article.....

Anonymous said...

Thanks a lot....

Rams said...

Very useful.
Thank you sir..

Anonymous said...

great

Rajakumari said...

Thank you very much for this.

Unknown said...

Thanks a lot very simple,understandable.

Anonymous said...

Indeed It was Good.But Suppose if we use edmx model in place of manual sql use. For that if you can give tutorial it will be great..


Thanks

Anonymous said...

Thanks very much suresh.

Anonymous said...

i did not find asp.net web service in vstudio 2010.

Madhusudhan V said...

Really superb boss...and very easy to understand....great job...
Carry on

Anonymous said...

very nice article

Unknown said...

good job sir. u make it easy

sravan said...

nice example.........

Unknown said...

Can you guide me how to code/use web services in vb.net.thanks

Anonymous said...

Hello Sir ,
Its Very Very Important about for this article i would very thanks to say with pleasure

Rahul said...

Getting time out exception when consuming external web service for the second time. I am consuming it in asp.net web application(c#). Any Help...?

Anonymous said...

It is Really Very helpful to Understand the WEBSERVICES. Its COOL

Gokul said...

Really cool article..

Sindhu said...

Thank you, it help alot

Anonymous said...

Thank You..Its good article, anyone can understand web service easily..

Unknown said...

Great blog...for beginners...thanks guru garu...

Anonymous said...

good............

Ashish said...

Nice one.Its very Useful

Unknown said...

Very nice article..

Anonymous said...

Awesome, Great sample article, post as like this articles, Keep up the good Job.

Thanks
Govindaraj

Unknown said...

nice

Anonymous said...

very good article

Kush said...

great buddy, you explained each and everything in a very simple language and Non Technical person also can understand this...great buddy & Thank You so Much

Anonymous said...

very nice sir thnaks

Anonymous said...

very nice

Anonymous said...

VERY NICE..........

Anonymous said...

Unable to automatically step into the server.Attaching to the server process failed.Access is denied.



i am getting above error...please help me to solve the problem

Anonymous said...

I think it is not .Disco file.. It is Disco.exe .. any way good article

Anonymous said...

Wonderful Suresh ! Every time you are describing in this way that's a newly born child also learn. Keep it Up. Also writes articles on WPF,WCF, MVC etc.

Anonymous said...

Nice article easy to understand .............

Raju Patil said...

Nice article easy to understand .............

Anonymous said...

Very good article for the beginners to study about webservice...good work

sns said...

XML Parsing Error: not well-formed

i getting above mentioned error when i run my default page in inetmgr

Unknown said...

Thanks for giving good example

Raju said...

how to generate http error code 100 if nodata


and http error code if data is successfully recieved

and 102 is other errors
...



Pls Respond me

Unknown said...

its helpfull budddy........

Gaurav said...

Thanks for giving good example

Unknown said...

its very helpful...thank u

Anonymous said...

Hi suresh,
I copied my webservice published folder in C:\inetpub\wwwroot folder..But in inetmgr m not getting any default website...wat i can do???

Anonymous said...

nice

KiranK said...

Thank you very much for your all articles.

Anonymous said...

Informative..

Anonymous said...

Thank you so much sir. I really thought that web services is a hard topic but your way of explaining web services really helps me a lot.

Thanking you once again.
Rajesh Tiwari(Pune)

Unknown said...

thank you so much suresh...

Anonymous said...

Thank you Suresh its really gd & easy after taking this example.Pls explain about WCF, WPF, Link & MVC.....etc

seo said...

Thanks. Web service have ultimate performance

Anonymous said...

10q Very Much Mr.Suresh

Unknown said...
This comment has been removed by the author.
Unknown said...
This comment has been removed by the author.
Anonymous said...

Defenitely a standard example. Thanks

Anonymous said...

Very good tuto!

Anonymous said...

Very Helpful for Web Service concept.Thnx Suresh.
Plz post simple ASP.Net web login with ms sql data.
From
Soumen R

Chetan Patil said...

Nice article , very helpful to me.

vali said...

Awesome

Anonymous said...

excellent

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

Nice Article.....

Unknown said...

Hi Sir,

I'm Raghavendra. I've following your blog from many days and it helped me a lot in my daily project routines.

Recently I've got an error in a windows application that I've worked on it earlier.

Coming to the point I've developed a windows application in which client has asked to make it demo version for 30 days and later user should buy it from the site. I've did the same. On installing the exe I've created a registry with my application name along with date of installation. Later every time when clicked on exe it will check with the server data to the installed date and checks whether it has crossed 30days. For getting the date I've used a php service and added it as reference.


This worked very fine earlier. I've added the web reference in my winforms and accessed the method and checked in my application.

But now itsn't running. I've removed service reference and tried to add the same wsdl link again but it says

"The HTML document does not contain Web service discovery information."

Here is the service reference link:

http://projects.santabantathegreat.com/PSMan/license/LicenseService.php?class=licenseService.wsdl

Please help me in this issue ASAP and let me know the source of the problem whether it is the code or the service??

.NET version: VS 2008

Anonymous said...

Nice article and Thanks

Bhemakkagari Satish said...

its clear

vasanth said...

Its Very Nice Blog.

Thank u So much.......!!!!!!!!1

Unknown said...

simple explanation throughout the article.

http://facemekan.blogspot.com/ said...

great:)

Anonymous said...

sukriya Suresh Saab

Unknown said...

bad one

Anonymous said...

ravi

naqash zaheer said...

thanks it's helpful

anusha k said...

where we will get username in service.asmx.cs file . can u please tell me ?

Unknown said...

Sir its really good article. Very helpfull to me.

Unknown said...
This comment has been removed by the author.
Unknown said...
This comment has been removed by the author.
Unknown said...
This comment has been removed by the author.
Anonymous said...

Thank you sir, it's very helpfull

Anonymous said...

How to add web service in android application named. Mobile banking

Anonymous said...

Excellent artical...

Anonymous said...

it is very useful for me.. thnq u sir...

Anonymous said...

getting problem with localhost how to salve that problem

localhost.Service obj = new localhost.Service();

Unknown said...

Thanks, i got cleared idea about web services....

Anonymous said...

Thanks a lot ,,, It helped me a lot Madarchod

Bhavesh Bhuva said...

Very Useful Example.

Gedzi said...

Its really useful for me to understand the basic concept of web service. Thank you so much.

Unknown said...

thanks sir.....such a great work.

Anonymous said...

Hi suresh i calling my wevservice through ajax call in javascript in which i have return string in which 3 different condition in javascript like
if(data.d="1")
{}
else if(data.d="2")
{}
else
{}
in which local host it give proper return value but in live site it return always 1 then how can i solved it its emergency pls give me a reply

angel prit said...

it was really helpful thanks

Anonymous said...

Thanx.....

Unknown said...

thanks...great explanation...its really helped me lot

Anonymous said...

Thanks........... It is good for learn

arun baskar said...

Super Explaination.Thanks.

Unknown said...

Very useful information!!!!

Anonymous said...

It's a really good helpful article.

thomas taw said...

thanks admin nice shares..

kemal sunal said...

Thanks........... It is good for learn

Anonymous said...

very informative and good tutorial

gizli çekim türk said...

Super Explaination.Thanks.

Anonymous said...

good

Unknown said...

Easy example.

Unknown said...

Thank you sir..

Anonymous said...

its nice article for begginers

Anonymous said...

Demonstrate authentication and authorization as well please!

Unknown said...

Thank you ......
really helpful to understand create and consume webservice

Harsha said...

Super Article Suresh, Very Clear descriptions.Thanks for updating .

Harsha Sarnad said...

Nice Article Suresh, Very Clear descriptions

Unknown said...

Really nice article, easy to understand.. Thanks

Please can you post articles on MVC concept..

Really Thanks..

Anonymous said...

nice...

Anonymous said...

for the error: type or namespace name localhost could not be found....
in vs 2012, we didn't get direct option as "add web reference" but we can have "add service reference".
In such cases just click on add service reference.. click on advanced button (under the namespace textbox) then click ok. Next window will come then click add service reference. specify URL address of your service.

Unknown said...

thanku

Unknown said...

nice article , MVC Sample available?

Anonymous said...

Hi Suresh

Can u explain what is localhost in the above code.
Plz any one help me. i was stuck their.

Unknown said...

Hello sir,

Can you help me, after making web service how can use that service

Anonymous said...

Superb article ...............

Anonymous said...

Nice

Anonymous said...

mmmm

Unknown said...

it is very good article provided by you .

Unknown said...

Good article .........Able to grab it easily ..Thanks Man

Anonymous said...

Ur articles are very nice ,easy to understand Thanq

Unknown said...

small and sweet understandable format. thanks

«Oldest ‹Older   1 – 200 of 210   Newer› Newest»

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 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.