You are on page 1of 11

Web Services Page 1

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

What is a Web Service?


The Internet is quickly evolving from today's Web sites that just deliver user interface
pages to browsers to a next generation of programmable Web sites that directly link
organizations, applications, services, and devices with one another. These programmable
Web sites become more than passively accessed sites - they become reusable, intelligent
Web Services. They allow different applications to share business logic over the network.
The technical definition of a Web Service is programmable application logic
accessible via Standard web protocols.
Programmable Application Logic: A Web Service is Application non-specific. The
application logic can be implemented by components, by PERL scripts, or by any other
mechanism that supports XML.
Standard Web Protocols: Web Services use Internet transport protocols such as SOAP,
HTTP and SMTP.

Why we need a Web Service?


Server and client need to understand following:
• Implementation details of a particular service,
• Service deployment,
• Security types and trusts, etc.

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

SEED Infotech Pvt. Ltd.


Web Services Page 2

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.

Web Services Infrastructure


The Web services infrastructure provides several components that enable client
applications to locate and consume Web services. These components include the
following:

XML Web services directories (UDDI)


These directories provide a central place to store published information about
Web services. The Universal Description, Discovery, and Integration (UDDI)
specifications define the guidelines for publishing information about Web
services. The XML schemas associated with UDDI define four types of
information that you must publish to make your Web service accessible. This
information includes business information, service information, binding
information, and service specifications. Microsoft provides one such directory
service, which is located at http://uddi.microsoft.com.

Web services discovery. (WSDL)


Using this process, clients locate the documents that describe a Web service using
WSDL. The discovery process enables clients to know about the presence of a
Web service and about the location of a particular XML Web service.

Web services description.


This component provides information that enables you to know which operations
to perform on a Web service. The Web service description is an XML document
that specifies the format of messages that a Web service can understand.

Web service wire formats.


To enable communication between disparate systems, Web services use open wire
formats. Open wire formats are the protocols that can be understood by any
system that is capable of supporting common Web standards, such as HTTP and
SOAP. The HTTP-GET and HTTP-POST protocols are the standard Web
protocols that allow you to send parameters as name-value pairs. The HTTP-GET
protocol allows you to send URL-encoded parameters as name-value pairs to an
XML Web service. The HTTP-GET protocol requires you to append the
parameter name-value pairs to the URL of the Web service. You can also use the
HTTP-POST protocol to URL-encode and pass parameters to the Web service as

SEED Infotech Pvt. Ltd.


Web Services Page 3

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

SEED Infotech Pvt. Ltd.


Web Services Page 4

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.

Client and Web service communication


As shown in Figure, the interaction between a client and a Web service consists of several
phases. The following tasks are performed during these phases:

SEED Infotech Pvt. Ltd.


Web Services Page 5

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.

ASP.NET Web Services


ASP.NET provides support for Web Services with the .asmx file. An .asmx file is a text file
that is similar to an .aspx file. These files can be part of an ASP.NET application that
includes .aspx files. These files are then URI-addressable, just as .aspx files are.

The following example shows a very simple .asmx file.

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

SEED Infotech Pvt. Ltd.


Web Services Page 6

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.

Entering the address:

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.

Accessing Web Services


In addition to the ASP.NET server side technology that allows developers to create
Web Services, the .NET Framework provides a sophisticated set of tools and code to
consume Web Services. Because Web Services are based on open protocols such as
the Simple Object Access Protocol (SOAP), this client technology can also be used to
consume non-ASP.NET Web Services.

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.

Dim myHelloWorld As New HelloWorld()


Dim sReturn As String = myHelloWorld.SayHelloWorld()

The return would be "Hello World".

Write a Simple Web Service


A Web Service can be written by using any text editor. The service mentioned in this
section, MathService, exposes methods for adding, subtracting, dividing, and
multiplying two numbers.

SEED Infotech Pvt. Ltd.


Web Services Page 7

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

Public Class MathService : Inherits WebService


<WebMethod( )> Public Function Add(A As Integer, B As Integer) As Integer
Return (A + B)
End Function

<WebMethod( )> Public Function Subtract(A As Integer, B As Integer) As Integer


Return (A – B)
End Function

<WebMethod( )> Public Function Multiply(A As Integer, B As Integer) As Integer


Return (A * B)
End Function

<WebMethod( )> Public Function Divide(A As Integer, B As Integer) As Integer


If B = 0
Return -1
End If
Return CInt (A / B)
End Function

End Class

Consuming a Web Service from a Client Application


To consume this web service from the client you have Add Web Reference to the
project. When you right click on the project it will open a UDDI window which has got
an Address bar. Give the url of your .asmx file and check for the availability of the
service. If it is present then the service will be shown to you or else the Error page will
be displayed to you. There is Textbox where you can enter the name for your web
reference. Say Add reference and the reference will be added into your references
section of your project.

SEED Infotech Pvt. Ltd.


Web Services Page 8

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

Description: It is used to provide a brief description of the functionality of the web-callable


method or property.
e.g. …. <WebMethod (Description:=”[String]”)>…..

EnableSession: It is used to maintain the session state between calls.


e.g. …. <WebMethod (EnableSession:= [“True/False”])>…..

MessageName: This property is used to alias method or property names. It uniquely


identifies polymorphic methods within a class that we wish to mark as web callable.
e.g. ….<WebMethod(MessageName:=”[string]”)>….

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]”)>….

CacheDuration: Outputcaching allows for the result of a particular resource to be saved to a


cache rather than executed on each request. The use for caching for Web Services is
configured on a method-by-method basis through the use of the WebMethod attributes
CacheDuration property.
e.g. ….<WebMethod(CacheDuration:= [int])>….

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:

wsdl.exe /l:VB /n:MathService /out:MathService.vb MathService.wsdl

SEED Infotech Pvt. Ltd.


Web Services Page 9

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

Dim Service As MathService = New MathService()


Label1.Text = CType(Sender, Control).ID
Select Case (CType(Sender, Control).ID)
Case "Addition"
Label1.Text = "<b>Result</b> = " & Service.Add(Op1, Op2).ToString()
Case "Subtract"
Label1.Text = "<b>Result</b> = " & Service.Subtract(Op1, Op2).ToString()
Case "Multiply"
Label1.Text = "<b>Result</b> = " & Service.Multiply(Op1, Op2).ToString()
Case "Divide"
Label1.Text = "<b>Result</b> = " & Service.Divide(Op1, Op2).ToString()
End Select
End SubEnd Class

<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>

Use Data in Web Services


The example given below shows how DataSets, a powerful new XML-based way to
represent disconnected data, can be returned from a Web Service method. This is an
extremely powerful use of Web Services, as DataSets can store complex information and

SEED Infotech Pvt. Ltd.


Web Services Page 10

relationships in an intelligent structure. By exposing DataSets through a service, you can


limit the database connections your data server is experiencing.

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

Public Class DataService

<WebMethod()> Public Function GetTitleAuthors() As DataSet

Dim MyConnection As SQLConnection = New


SQLConnection("server=localhost;uid=sa;pwd=;database=pubs")
Dim MyCommand1 As New SQLCommand("select * from Authors", MyConnection)
Dim MyCommand2 As New SQLCommand ("select * from Titles", MyConnection)

Dim DS As New DataSet


MyCommand1.Fill (DS, "Authors")
MyCommand2.Fill (DS, "Titles")

Return DS
End Function

<WebMethod()> Public Function PutTitleAuthors(DS As DataSet) As Integer


' TODO: Do something interesting here...
Return DS.Tables(0).Rows.Count
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

Public Class MyForm1


Protected Sub Page_Load(Src As Object, E As EventArgs)

Dim D As DataService = New DataService()


Dim MyData As DataSet = D.GetTitleAuthors()

SEED Infotech Pvt. Ltd.


Web Services Page 11

Authors_DataGrid.DataSource=MyData.Tables("Authors").DefaultView
Authors_DataGrid.DataBind()

Label1.Text = "The number of rows is: " & MyData.Tables("Authors").Rows.Count.ToString()

End Sub

Protected Sub Submit_DataSet(Src As Object, E As EventArgs)

Dim D As DataService = New DataService()


Dim MyData As DataSet = D.GetTitleAuthors()

'Remove three rows from the Authors table


MyData.Tables("Authors").Rows.Remove(0)
MyData.Tables("Authors").Rows.Remove(1)
MyData.Tables("Authors").Rows.Remove(2)

Dim RowCount As Integer = D.PutTitleAuthors(MyData)

Authors_DataGrid.DataSource=MyData.Tables("Authors").DefaultView
Authors_DataGrid.DataBind()

Label2.Text = "The modified number of rows is: " & RowCount.ToString()


End Sub

End Class

<Html>
<body style="font: 10pt verdana">

<h4>Using Data Access with Web Services</h4>

<form runat="server">

<input type="submit" OnServerclick="Submit_DataSet" value="Remove three rows from the


DataSet" runat="server"/>
<asp:Label id="Label1" runat="server"/>
<asp:Label id="Label2" runat="server"/>

<ASP:DataGrid id="Authors_DataGrid" runat="server" />

</form>

</body>
</html>



SEED Infotech Pvt. Ltd.

You might also like