AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=979&pId=-1
Working with Web Services Using ASP.NET
page
by SANJIT SIL
Feedback
Average Rating: 
Views (Total / Last 10 Days): 59327/ 76

Introduction

XML Web Services provide a simple technique for accessing a method on an object that is running on a local or remote computer.  Web Services can be accessed by an application written in any language and running on any operating system.  They utilize HTTP as the underlying transport, which allows function requests to pass through corporate firewalls (as they move through port 80).  In ASP.NET we can write a Web Service as simple as a normal business object and the only difference is that the functions are preceded with a special <WebMethod ()>attribute that makes them as Web Services.  Typical implementation of Web Services might include shipment tracking, credit card verification, searching for airfare rates, Weather forecasting, etc.

Synchronous & Asynchronous communication

Web Services support both synchronous and asynchronous communication between the client and the server that hosts the Web Service.  Under synchronous communication, the client sends a request to the server and waits for the response.  This prevents the client from performing other operations while waiting for the results.  On the other hand, in asynchronous communication, the client continues processing other tasks as it waits for a response.  The client responds to the result of the service request when it becomes available.

Common Terminology used in Web Services

SOAP

Simple Object Access Protocol (SOAP) is a way to structure data so that any computer program in any language can read SOAP and send messages in SOAP.  This is because it is XML based and language and platform independent.  SOAP supports any transport protocol and use Hyper Text Transfer Protocol (HTTP), File Transfer Protocol (FTP), Simple Mail Transfer Protocol (SMTP) and Post Office Protocol 3 (POP3) to carry documents.


SOAP Message Structure

The SOAP message consists of three parts: an envelope, one or more headers and a body.  The following example message below shows how the Envelope, Header and Body are used to build a complete message.  The explanation of each of these follows after the following figure.

Figure 1



Envelope

It is the root element in SOAP message and is required for every SOAP message.  It identifies the following:

Message content

Desired recipients

Special processing information (if any)

The Schemas

Header

This is an optional part of the SOAP message.  It lets the application exchange information.  It even enables identification of the features in the message and explains whether a feature is optional or mandatory.  This also provides processing information and furnishing additional products for some specific tasks such as security or transaction management. (We can use SOAP header to pass along username and password information so that only the users we choose can access the service.)

Body

The Body is the most important part of a SOAP message; rather we may say that it is the mandatory part of the SOAP message.  If the SOAP message contains no header, it is the first element after the envelope.  It contains the XML information being exchanged.  In a Web Service interaction there is SOAP request message and SOAP response message.  In case of SOAP request message, the client sends a SOAP message to the server, invoking some method.  In SOAP response message the server returns a response which includes the return value of the method.  In SOAP request message, the SOAP Body contains the name of the method, along with the method's input parameters.  In SOAP response message, the server sends back in the body the return value of the method.  (Even if there is no return value, a message is still sent back to verify that the method executed.)  The SOAP Body is signified by the <soap:Body> element. There may be SOAP fault element in SOAP message -<soap:Fault> for reporting errors.

Web Services Description Language (WSDL)

Web Services Description Language (WSDL) is an open standard language used in conjunction with XML-based languages.  A WSDL file is an XML document that describes a set of SOAP messages and how the messages are exchanged.

Universal Description, Discovery, and Integration (UDDI)

Universal Description, Discovery, and Integration (UDDI) is an open, Internet-based specification that is the building block on which businesses may quickly and easily locate desired services and perform business with one another.

Transport Protocol for Web Service

Unless we specify otherwise, .NET will attempt to bind Web Services to three separate protocols: HTTP/POST, HTTP/GET, and SOAP.  Bindings for these three protocols will be included in the WSDL file automatically generated by .NET and consumer clients will have the option of choosing any one of them for communication with service.  However, GET and POST are limited to sending and receiving name/value pairs of data whereas we can use SOAP to serialize complex structure, such as ASP.NET DataSets, complex arrays, custom types and XML nodes.

We can easily remove these bindings by adding the followings as specified in Listing 1 to our web.config file as:

Listing 1

<webservices>
  <protocols>
    <remove name="HttpPost" />
    <remove name="HttpGet" />
  </protocols>
</webservices>

This section will tell the WSDL generator not to include bindings for HTTP/POST and HTTP/GET. The two remove sections specify that HttpPost and HttpGet should not be supported.  With regard to interoperability where SOAP is a widely-used standard for Web Service communication, HTTP/GET and HTTP/POST are not.  As a result, many automatic proxy generation tools were not designed to understand the HTTP/GET and HTTP/POST bindings included by default in a .NET-generated WSDL document.  If our service does not make use of these bindings, removing them can increase our service's interoperability.

The Web Service Attribute

The Web Service Attribute is a member of the System.Web.Services namespace.  This we can use to let the clients know where to find information about a Web Service.  There are three properties of the Web Service attribute.  They are as follows:

1.      Description

2.      Namespace

3.      Name

Description

The Description property is used to provide a brief description of the functionality of the class.  We can write the same as specified in Listing 2.

Listing 2

[WebService(Description="This class contains methods for working with Addition of numbers and Population of DataSet")]

Namespace

The Namespace property sets the XML namespace for the service.  Generally we use an URL.  It does not have to be an actual URL; it can be any string value.  The idea is that it should be unique.  It is common practice to use URL because a URL is always unique.

Name

When the WSDL is generated for an ASP.NET Web Service, the name of the class is used for the service name within the WSDL.  When a proxy uses the WSDL and builds a proxy class, the name of the class generated corresponds to the name value of service.  This property allows overriding the default value.

The Web Method Attribute

A Web Service class can contain any number of WebMethods that are accessible across the HTTP wire.  Like the Web Service attribute, WebMethod can also contain some properties which are described in this section.

CacheDuration

CacheDuration specifies the number of seconds that the response should be held in the system’s cache.  By default, the caching is disabled.  Putting an XML Web Service’s response in the cache increases the Web service’s performance.  We can write the same as specified in Listing 3

Listing 3

[WebMethod(CacheDuration=30)]

BufferResponse

Buffering allows the server to buffer the output from the response of XML Web Service and transmit it only once the response is completely buffered.  By default, this property is set to true. If we make the property to false, the response is sent to the client as it is constructed on the server.

Description

The description property is used to provide a brief description to the WebMethod and the description becomes part of the service description (WSDL) document.

EnableSession

EnableSession property enables session state for a particular WebMethod if we set the property to true. The default setting is false.

MessageName

MessageName property is required to uniquely identify polymorphic methods within a class.  In case of working with overloaded WebMethods this property is a required one.

TransactionOption

By default, transactions are disabled.  If we decide to use .NET transactions, our WebMethod will be able to participate only as the root object in a transaction.  This means that our WebMethod may call other transaction-enabled objects, but may not itself be called as part of a transaction started by another object.  This limitation is due to the stateless nature of the HTTP protocol.  As a result, the Required and RequiresNew values for TransactionOption are equivalent (and both declare a RequiresNew method that will start a new transaction).  Disabled, NotSupported, and Supported are all disable transactions for the web method despite what their names imply.

Building a Web Service

Building a Web Service with Visual Studio.Net involves creating a new Web Services project and adding methods and properties to a Web Services class form (i.e. an .asmx file).  This section builds a Web Service with Visual Studio.Net.  Followings are the steps in short to create an .asmx file.

1.      Start Visual Studio .NET

2.      Select New Project

3.      Select Visual C# Project as Project Type and Asp.Net Web Service as Template

A solution will be generated.  In solution explorer there will be an asmx file.

The following code we should write in .asmx file as specified in Listing 4.

Listing 4

[WebMethod]
  public string Add(int a, int b)
  {
    return Convert.ToString(a + b);
  }
 
[WebMethod]
  public DataSet Populate(string con, string sql)
  {
    DataSet DS=new DataSet();
    SqlConnection conn=new SqlConnection(con);
    SqlDataAdapter DA=new SqlDataAdapter(sql, conn);
    DA.Fill(DS);
    return DS;
  }

In the above code there are two methods in Web Service.  These methods are known as the WebMethods.  The Add WebMethod returns the sum of two integer value as string.  Populate web method takes two string type arguments, one for connection string and the other for sql query, and returns a DataSet object.

Testing the Web Service

Web Services are not designed to be viewed in a browser.  Instead, Web Services are consumed by a client application using protocols.  Some of these protocols, such as SOAP, are more appropriate for server-to-server communication while others, such as HTTP GET, are more frequently associated with the model of traditional web page access.

A Web Service that uses HTTP GET as a transport protocol can be accessed in much the same way as a regular web page.  All that is necessary to access such a page is to point a web browser to the service endpoint.  In our example, the endpoint comes is an .asmx page.  Web Services are applications that expose functionality to Web Service clients and as a result have no required graphical user interface.  .NET provides a Web Service test page that is displayed when we point our browser to an .asmx page.  If we open a browser and type in the URL of the .asmx web service we just created, we will see the IE test page shown as follows.

The below page is generated by the .NET HTTP runtime each time it receives a request for an .asmx page.

Figure 2

The test page displays the Service1 service name along with the Populate method, the Add method and even a link to the service description.  The service name and any additional information about this service are retrieved through a process called reflection which uses the System.Reflection namespace to reveal information about existing types via metadata.

Consuming Web Service

To consume a Web Service we need to create an Asp.Net web application.  After creating an application we should add a web reference (Add web Reference option will come if we right click on Reference In the solution explorer window).  In the web reference dialog box the following should be pasted in the URL selection box:

http://localhost/ArticleWS/Service1.asmx

Figure 3

Now by clicking on Add Reference button the web reference will be added.

In the web.config file we should add the following as specified in Listing 5.

Listing 5

<appSettings>    
<add key  = "CString" value = "Server=Sanjit; Database=Test; User ID=sa; Password = sa;"></add>
 </appSettings>

In WebForm1 we should add the following as specified in Listing 6 in the Page Load event code.

Listing 6

string con=ConfigurationSettings.AppSettings["CString"].ToString();
string sql="Select * from customer";
localhost.Service1 ws=new localhost.Service1();
DataSet DS;
DS=ws.Populate(con,sql);
DataGrid1.DataSource=DS;
DataGrid1.DataBind();

Note that before adding the above code to our Web Service implementation, we need to add a DataGrid control in the WebForm.  Then add the following namespace as specified in Listing 7.

Listing 7

 
using System.Configuration;

After adding all the above mentioned code we can run the application.  Then the grid would be populated with the data from the customer table.  To test the Add WebMethod, add the following as specified in Listing 8.

Listing 8

localhost.Service1 ws=new localhost.Service1();
int a=Convert.ToInt32(TextBox1.Text);
int b=Convert.ToInt32(TextBox2.Text);
TextBox3.Text=ws.Add(a,b);

We should take three textbox controls and a Button Control.  On Button Click event we have written the above code.  If we run the application and input two integer values in two textboxes, the sum of two integers will be displayed in third text box after clicking on button.

Differences between Web Service and Remoting

ASP.NET Web Services and .NET Remoting are two separate paradigms for building distributed applications using Internet-friendly protocols and the .NET framework.  Each has its advantages and drawbacks which are important factors in deciding which one to use in an application.  Web Services typically use SOAP for the message format.  This makes Web Services good for communication over the Internet and for communication between non-Windows systems.  Web services are a good choice for message-oriented services that must support a wide range of client platforms and a potentially heavy load.  Remoting can be configured to use either SOAP or Microsoft's proprietary binary protocol for communication.  The binary protocol yields higher performance and is great for .NET to .NET communication, but cannot be used to communicate with non-Windows platforms.  In .NET’s Remoting technology we require the Server and the Client both to be of the same technology; in other words, they should both be .NET applications and require the .NET framework to be running in both of these environments.  This is in contrast to Web Services where a typical Web Service implemented in .NET can even be invoked for Java.

Suggested Readings
Conclusion

In this article an XML Web Service is defined as a software service exposed on the Web through SOAP, described with a WSDL file and registered in UDDI.  Typically, Web Services are utilized to solve data transfer problems and to create platform-neutral interfaces for distributed systems.  I hope that this article has provided the necessary information to the readers for understanding and implementing a Web Service.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-23 5:28:28 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search