Saturday, September 22, 2007

All About Web Service in .Net

This article will explain you everything about Web Services in .Net, so lets get started with Web Service

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.
  • Web Service is
    • Language Independent
    • Protocol Independent
    • Platform Independent
    • It assumes a stateless service architecture.
  • We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.

History of Web Service or How Web Service comes into existence?
  • As i have mention before that Web Service is nothing but means for Interacting with objects over the Internet.
  • 1. Initially Object - Oriented Language comes which allow us to interact with two object within same application.
  • 2. Than comes Component Object Model (COM) which allows to interact two objects on the same computer, but in different applications.
  • 3. Than comes Distributed Component Object Model (DCOM) which allows to interact two objects on different computers, but within same local network.
  • 4. And finally the web services, which allows two object to interact internet. That is it allows to interact between two object on different computers and even not within same local network.
Example of 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 companies 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.

Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
  • HTTP
  • XML
  • SOAP
Advantages of Web Service Communication
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.

Terms which are frequently used with web services
  • What is SOAP?
    • SOAP are 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 details regarding using web service
      • Method and Properties provided by web service
      • URLs from which those method can be accessed.
      • Data Types used.
      • Communication Protocol 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 (static)
      • .Disco File contains
        • URL for the WSDL
        • URL for the documentation
        • URL to which SOAP messages should be sent.
      • A static discovery file is an XML document that contains links to other resources that describe web services.
    • .VsDisco File (dynamic)
      • A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
  • What is difference between Disco and UDDI?
    • Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
  • What is Web Service Discovery Tool (disco.exe) ?
    • The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
  • What is Proxy Class?
    • A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
    • A proxy class object allows a client to access a web service as if it were a local COM object.
    • The Proxy must be on the computer that has the web application.
  • What is Web Service Description Language Tool (wsdl.exe)?
    • This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
    • Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
    • Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
  • Testing a Web Service?
    • You can test web service without building an entire client application.
      • With Asp.net you can simply run the application and test the method by entering valid input paramters.
      • You can also use .Net Web Service Studio Tool comes from Microsoft.

Example of Creating Web Service in .Net

This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.

Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"

Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"

Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"

After three steps your solution explorer looks as shown in figure




Step4: Create a Logic for Web Service
  • Create a Method "GetCustomerCountryWise"
  • Note: You need to specify [WebMethod] before method definition, if you want it to be accessible public, otherwise the method would not be accessible remotely.
  • Specify proper argument and return type for method in web service.
  • It is also good practise to specify the use "Description" attribute to tell what method is meant for.
For example, here i need to access data of northwind customers and want to return customer list country wise, so add namespace for

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

[WebMethod(Description="It will generate Customer List, Country Wise")] public System.Xml.XmlElement GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();

string sSQL = "select CustomerId, CompanyName, ContactTitle, City " +
" from Customers where country = '" + sCountry + "'";

SqlConnection connCustomer = new SqlConnection(sConn);

DataSet dsCustomer = new DataSet();

SqlDataAdapter daCustomer = new SqlDataAdapter(sSQL, sConn);

daCustomer.Fill(dsCustomer,"Customers");

//Known bug while return "DataSet" is "Data source is an invalid type.
It must be either an IListSource, IEnumerable, or IDataSource."
//For more details on Error: http://support.microsoft.com/kb/317340

//So to access data we need to make use of XmlElement.

// Return the DataSet as an XmlElement.
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}


Step5: Build Web Service and Run the Web Service for testing by pressing F5 function key.






By pressing "Invoke" button will generate XML File.

So you are done creating web service application.

Example of Testing Web Service in .Net

This Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".

Step1: Create a Test Web Site by File > New > Web Site > Asp.net Web Site
Named the web site, for example here i have choosen name "TestGetCustomerCountryWise"

Step2: Displaying data in gridview, so drag the gridview on to the form.

Step3: Right Click Solution Explorer and Choose "Add Web Reference"



Step4: Choose the option Web Service on the local machine or you can enter the .WSDL File address directly in URL space and press Go button.




Step5: Press "Add Reference button"


Step6: Writing Code for Displaying data in GridView
Here note: I have Pass "USA" as parameter in Country Field.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();

DataSet dsCustomer = new DataSet();

// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");

// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);

GridView1.DataSource = dsCustomer;

GridView1.DataBind();
}
}


Step7: Output as data displayed in GridView.




Few Facts about Web Service in .Net
  • Each Response from web service is a new object, with a new state.
  • Web Service are asynchronous because the request object from the client application and the response object from the web service are unique SOAP envelopes that do not require shared connection.
  • This allow client application and the web service to continue processing while the interaction is ongoing.
  • Instead of a user interface, it provides a standard defined interface called a contract.

45 comments:

zubin said...

It's a good article
Basic Funda of WebService.
should read............

shalini said...

It's really gud article for begginers about web services.

shalini said...

Yes Zubin U r right.
Its really gud artilce

Sujitha said...

Very good article, Simple and informative

Luv said...

Nice article for beginers.
Thank you

nv said...

hi, its nice article...i learned a lot using this article,thank you so much..

cher said...

great article..


http://www.uscontactpoint.com/

Anonymous said...

Great Article.....
Also include some tips and traps

Sneha Gupta said...

Hi,
Congratulations for this nice looking blog.
Keep it up!
Regards,

Anonymous said...

This is great! Thank you so much. I don't believe how many stupid mistakes, I made in past few weeks.
Thanks again

pajko83 said...

Great blog. Help me a lot. Thank you.

Anonymous said...

Cannot implicitly convert type 'TN_Sample_WebService.tnwebservices.Event[]' to 'System.Xml.XmlElement'

How could you overcome this error?

The web service result (i.e., XML file could not stored in the XMLElement.

as here coded
"// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");"
throws error as mentioned above.

can anyone give me a solution.
Thanks in advance.

-rose.

DotNetGuts said...

You should not receive xml error, could you please write your exact code, so that it helps in answering. Also try replacing XmlElement with XmlDocument, still its not answer as above code is tested.

rose said...

Thanks DotNetGuts,

Here is my code

public void tnwebservices()
{
tnwebservices_test.TNWebService tn = new tnwebservices_test.TNWebService();
XmlDocument myServiceDoc = new XmlDocument();
System.Xml.XmlNode neNode;
//Adding the resulting XML from WebMethod to a user created XmlNode
neNode = TN.GetEvents(****, 1000, 942396, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
//Creating a Dataset
DataSet myDataSet = new DataSet();
//The XmlNode is added to a byte[]
byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(neNode.OuterXml);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buf);
//The XML is readed from the MemoryStream
myDataSet.ReadXml(ms);

Gridview1.DataSource = myDataSet.Tables[0];
Gridview1.DataBind();

}

i've included my we reference into my solution.

still i get the "cannot implicitly convert..."

where i did mistake.

DotNetGuts said...

Hi Rose,

it is difficult to identify which line is creating problem.

Two Pointers:
1) Change XmlDocument with XmlElement.
2) Rather than using XmlNode use, XmlNodeReader.

If possible try to follow following way it will help, also try to debug the problem, it will help in finding root cause.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();

DataSet dsCustomer = new DataSet();

// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");

// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);

GridView1.DataSource = dsCustomer;

GridView1.DataBind();
}
}

Ankush said...

who wrote this article?
could anyone please tell me the name of that guy coz I want to mention this article as a reference in my report.

Victoria said...

Good post. It's very detailed

Navin C said...

Hii,
Cool article, thanks for sharing.

haro said...

Hey..it really helped me a lot..i suggest u to post some related contents related to webservice..thanks man...

Not emo said...

it didnt worked for me :(, the web service does not return any XML when i invoke, HTTP error 500

i thought it was the lack of a connection string so i put one but still the same result

im really new to .net, maybe im not running the server correctly?

Antony said...

Nice Article,Thanks for Sharing.

veda said...

Very Nice article..Thanks

rakhi said...

thanks... nice article with complete information..

Vidhya said...

That was very helpful.

Thanks
Learning asp.net

snehalata said...

Really its a nice article.it is very helpful to me about webservice.it is appreciable.Tons of thanks to u.I will follow it. My request add new post more.

pavan said...

Good job ,keep posting such good articles

@j said...

Very nice article and compilation... Really appreciable :)

Good job done..

Handi said...

very good article

Amirthalingam said...

it is really super, easy to understand the concept , hatsoff for you, keep it up

Vishnu Kumar said...

nice article... good one cheer up..

Prabhu Palaniappan said...

Very nice article about Web Services basics and its usage.

Abhinav said...

Very good and clear wordings to explain the basics of Web Services. Thank You very much. :-)

Raj said...

this very useful article....

Harshanand said...

Very nice artical..Great way of explaning one of the biggest technology.

KiranKumar Roy said...

Very nice explanation.
short and detailed!!

Manoj Gupta said...

I think Soap is just Formatter
and soap have three part one is soap
envelop second is soap header and soap dody
soap body contains data and its type
it use http protocal as a chennel and xml contains data .

eg.



"<"soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">"

"
"

Bhavani said...

it is very good article about webservice

Thiwanka said...

Thank you very much for your article, but Im getting following error,

Value cannot be null.
Parameter name: node

please tell me why this is coming?

deepak said...

very nice article.

Ramrao Patil said...

this is very good article for beginers

navn said...

Thanks for providing basic n brief discussion with eample about web services

Chinmayasri Behera said...

Really a nice article. Basic funda about webservices will get clear with this.

Keep Writing such fantastic things.

Thanks,
Chinmayasri

hari said...

good article, even a new step one can also will get an idea on WEBSERVICES.......


i can comment with ....

WHAT A WEBSITE SURJEEEEE..!!!!

kru said...

Hi dotnetgutz,

i m gettin error when i m executin foll code.

error:
'System.Xml.XmlElement.Protected Friend Sub New(prefix As String, localName As String, namespaceURI As String, doc As System.Xml.XmlDocument)' is not accessible in this context because it is 'Protected Friend'.

code is as follows:


Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dsCustomer As DataSet
Dim objGetCustomerCountryWise As localhost.WSGetCustomerCountryWise
Dim elem As New System.Xml.XmlElement

Dim nodeReader As System.Xml.XmlNodeReader
If Page.IsPostBack = False Then
'//Create object of WSGetCustomerCountryWise Object
objGetCustomerCountryWise = New localhost.WSGetCustomerCountryWise()

dsCustomer = New DataSet()

'// Get the data from Webservice.

elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA").ToString()

'// Load the XML to the Typed DataSet that you want.
nodeReader = New System.Xml.XmlNodeReader(elem)
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto)

GridView1.DataSource = dsCustomer

GridView1.DataBind()
End If



End Sub
End Class

Roopika sai said...

Its really very nice to understand the concept of webservice in .net

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape