Professional Documents
Culture Documents
Chapter 11
Web Services
Introduction
In this chapter we are going to see following,
1. What is a Web Service?
2. Why we need a Web Service?
3. ASP.Net Web Services
4. Use Data in Web Services
The common language runtime provides built-in support for creating and exposing Web
Services, using a programming abstraction that is consistent and familiar to both ASP.NET
Web Forms developers and existing Visual Basic users. The resulting model is scalable
and extensible, and supports open Internet standards (HTTP, XML, SOAP, WSDL).
Therefore it can be accessed and consumed from any client or Internet-enabled device.
One important feature of the Web services based computing model is that a client need
not know the language in which XML Web services are implemented. The client just
needs to know the location of an XML Web service and the methods that the client can
call on the service.
Web services use XML-based messaging to send and receive data, which enables
heterogeneous applications to interoperate with each other. You can use Web services to
integrate applications that are written in different programming languages and deployed
on different platforms. You can deploy Web services within an intranet as well as on the
Internet. While the Internet brings users closer to organizations, Web services allow
organizations to integrate their applications.
name-value pairs. However, the parameters are passed inside the actual request
message and not appended to the URL of the Web service.
The SOAP protocol allows you to exchange structured and typed information between
the applications on the Internet. The SOAP protocol consists of four parts. The first part
is mandatory and defines the envelope that contains the message. The SOAP envelope is
the basic unit of exchange between the processors of SOAP messages. The second part
defines the optional data encoding rules that you use to encode application-specific data
types. The third part defines the request/response pattern of message exchanges between
Web services. The fourth part, which is optional, defines the bindings between the SOAP
and HTTP protocols.
How components of the XML Web services infrastructure enable clients to locate and call
methods on XML Web services.
When a client accesses a UDDI service to locate a Web service, the UDDI service returns
a URL to the discovery document of the Web service. A discovery document is a .disco
file, which contains the link to the resources that describe a Web service. A discovery file
is an XML document that enables programmatic discovery of a Web service. After the
client receives the URL to the discovery document, the client requests a server, which
returns the discovery document to the client. The contents of a sample discovery
document are shown in the following code.
XML
<?xml version="1.0" ?>
<disco:discovery xmlns:disco="http://schemas.xmlsoap.org/disco"
xmlns:wsdl="http://schemas.xmlsoap.org/disco/wsdl">
<wsdl:contractRef ref="http://www.seed.com/MyWebService.asmx?WSDL"/>
</disco:discovery>
The client uses the information in the discovery document and requests a server to return
the service description of a Web service. The service description is a .wsdl file and
enables a client to interact with a Web service.
Next the client invokes methods on an XML Web service.
The process of communication between a client and an XML Web service is similar to a
remote procedure call (RPC). The client uses a proxy object of the XML Web service on
the local computer to call methods on the Web service.
Figure shows the process of communication between a client and a Web service.
1. The client creates an object of the Web service proxy class on the same computer
on which the client resides.
2. The client calls a method on the proxy object.
3. The Web services infrastructure on the client system serializes the method call and
arguments into a SOAP message and sends it to the Web service over the network.
4. The infrastructure on the server on which the Web service resides deserializes the
SOAP message and creates an instance of the Web service. The infrastructure then
calls the method with the arguments on the Web service.
5. The Web service executes the method and returns the value with any out
parameters to the infrastructure.
6. The infrastructure serializes the return value and any out parameters into a SOAP
message and sends them to the client over the network.
7. The infrastructure on the client computer deserializes the SOAP message
containing the return value and any out parameters and sends them to the proxy
object.
8. The proxy object sends the return value and any out parameters to the client.
To build Web services that the clients can consume, you use the ASP.NET infrastructure,
which is an integral part of the .NET Framework. Visual Studio .NET provides tools to
build, deploy, and publish your Web services using ASP.NET.
Imports System
Imports System.Web.Services
Public Class HelloWorld
Inherits System.Web.Services.WebService
<WebMethod()> Public Function SayHelloWorld() As String
Return("Hello World")
End Function
End Class
Note: If you are writing services in the HTML pages then you have to include the
<%@WebService ... %> Directive along with Language and Class attributes. If you writing it in
code-behind then you have to use the namespace Imports System.Web.Services
The first line has the imports statement which imports namespace System.Web.Services.
Next, the class HelloWorld is declared. This class is derived from the base class
WebService; note that deriving from the WebService base class is optional. We then write
the functions which we want to expose as services. These functions are exposed by the
keyword <WebMethod()>, which is given in front of their signatures. To make this service
available, we save the file as “FileName.asmx” and place it in a virtual directory on a Web
Server. Using a Web browser, you could then enter the URL
http://SomeDomain.com/virtualDirectory/HelloWorld.asmx
Or
http://localhost/MyService/HelloWorld.asmx
And the resulting page would show the public methods for this Web Service (those marked
with the WebMethod attribute), as well as which protocols (such as SOAP, or HTTP GET)
you can use to invoke these methods.
http://SomeDomain.com/virtualDirectory/HelloWorld.asmx?WSDL
into the browser returns a Web Service Description Language (WSDL) document. This
WSDL document is very important, and is used by clients that will access the service.
Within the SDK, there is a tool called the Web Services Description Language tool
(WSDL.exe). This command-line tool is used to create proxy classes from WSDL. For
example, you could enter:
http://SomeDomain.com/virtualDirectory/HelloWorld.asmx?WSDL
From the client perspective, the code would be simple, as shown in the following example.
The client has to Add Web Reference to the particular webservice by right clicking on the
project in the solution explorer or through the projects option in the toolbar; and gives it a name.
We then declare an object of this service, create an instance of it and use that service in our
application.
Open one .asmx file; and define a class that will encapsulate the functionality of your
service. This class should be public, and can optionally inherit from the WebService
base class. Each method that will be exposed from the service is flagged with a
<WebMethod()> attribute in front of it. Without this attribute, the method will not be
exposed from the service. This is sometimes useful for hiding implementation details
called by public Web Service methods, or in the case where the WebService class is
also used in local applications (a local application can use any public class, but only
WebMethod classes are remotely accessible as Web Services). Like ASP.NET Pages,
ASP.NET Web Services support directives that instruct ASP.NET how to process the
request.
Web Service files or .asmx files are automatically compiled by the ASP.NET runtime when a
request to the service is made (subsequent requests are serviced by a cached precompiled
type object).
Note that if an .asmx file is requested by a browser, the ASP.NET runtime returns a Web
Service Help page that describes the Web Service.
Example: MathService.asmx
Imports System
Imports System.Web.Services
End Class
Properties of WebMethod:
WebMethod attribute is used to mark either a method or property as web callable –
that’s web callable in the sense that the method is able to communicate using one of
the supported ASP.NET Web Services protocols for sending and receiving data. These
protocols include HTTP-GET, HTTP-POST, and SOAP.
The <WebMethod( )> attribute is represented by the WebMethod Attribute Class, which
is found in the System.Web.Services namespace in the System.Web.Services.dll
assembly.
There are six properties on the WebMethod attribute that we can manipulate:
Description EnableSession MessageName
TransactionOption CacheDuration BufferResponse
Note: All these properties are optional
TransactionOption:ASP.NET Web Services support transactions, but only those that the
Web Service originates.i.e. a transaction cannot be started by another application and then
flow into a Web Service. Default option is Required.
e.g. ….<WebMethod(TransactionOption:=”[TransactionOption]”)>….
BufferResponse: By default ASP.NET Web Services buffer the response before sending it
as this is usually most optimal for the server, but the BufferResponse property allows us to
configure ASP.NET WebServices to not buffer the response. By default this property is set to
true.
e.g. ….<WebMethod(BufferResponse:=”[True | False ]”)>….
WSDL.exe accepts a variety of command-line options, however to create a proxy only one
option is required: the URI to the WSDL. In this example, we are passing a few extra options
that specify the preferred language, namespace, and output location for the proxy. We are
also compiling against a previously saved WSDL file instead of the URI to the service itself:
Once the proxy class exists, you can create objects based on it. Each method call made with
the object then goes out to the URI of the Web Service (usually as a SOAP request).
Imports ApplicationName.MathService
Public Class myClient
Public Sub Submit_Click(ByVal Sender As System.Object, ByVal E As System.EventArgs) _
Handles Divide.ServerClick, Multiply.ServerClick, Subtract.ServerClick, Addition.ServerClick
Try
Op1 = Int32.Parse(Operand1.Text)
Op2 = Int32.Parse(Operand2.Text)
Catch Exp As Exception
Response.Write(Exp.Message)
End Try
<html>
<head>
<title>Math Service</title>
</head>
<body style="font: 10pt verdana">
<h4>Using a Simple Math Service </h4>
<form runat="server" ID=Form1>
<div>
Operand 1: <br><asp:TextBox id="Operand1" runat="server"/>
Operand 2: <br><asp:TextBox id="Operand2" runat="server"/>
<asp:Label id="Result" runat="server" />
<INPUT id="Divide" type="submit" value="Divide" name="Divide" runat="server">
<INPUT id="Multiply" type="submit" value="Multiply" name="Multiply" runat="server">
<INPUT id="Subtract" type="submit" value="Subtract" name="Subtract" runat="server">
<INPUT id="Addition" type="Submit" value="Addition" name="Addition" runat="server">
</div>
</form>
</body>
</html>
The method GetTitleAuthors connects to a database and issues two SQL statements: one
that returns a list of authors and another that returns a list of book titles. It places both result
sets into a single DataSet called ds, and returns this DataSet.
The method PutTitleAuthors illustrates a Web Service method that takes a DataSet as a
parameter, returning an integer that represents the number of rows received in the "Authors"
table of the DataSet. Although the implementation of this method is somewhat simplistic, this
method could also intelligently merge the passed data with the database server.
Imports System
Imports System.Data
Imports System.Data.SQL
Imports System.Web.Services
Return DS
End Function
End Class
The client application for this Web Service calls GetTitleAuthors and binds the Authors table
to a DataGrid control, as we've seen in previous examples. To illustrate the PutTitleAuthors
method, the client removes three rows of data from the DataSet before calling this method,
printing out the number of rows received by the service.
Imports ApplicationName.DataService
Imports System.Data
Imports System.Data.SQLClient
Authors_DataGrid.DataSource=MyData.Tables("Authors").DefaultView
Authors_DataGrid.DataBind()
End Sub
Authors_DataGrid.DataSource=MyData.Tables("Authors").DefaultView
Authors_DataGrid.DataBind()
End Class
<Html>
<body style="font: 10pt verdana">
<form runat="server">
</form>
</body>
</html>