In-Depth Series - Web Services: Basics and Beyond

Introduction

VINI, VIDI, VICI

Thus proclaimed Julius Caesar meaning, "he came, he saw, he conquered". Such is the glory of web services. It sweeps everything under its feet in its attempt to take the Internet industry by storm. By now article readers might have read the basic concepts of web services [SOAP(XML+HTTP), WSDL and UDDI]. This article series shall attempt an explanation that will go beyond the basics of web services.

The key things to know before you start creating web services are:

  1. What is a Web service?
  2. UDDI (Universal Description, Discovery, and Integration)
  3. DISCO (Discovery)
  4. The Role of SOAP and WSDL
  5. The .asmx and .asmx.cs files: A Quick Peek.
  6. Web Services Type Marshalling. 
  7. Web Service Capabilities

What is a Web Service?

Web services are software components that expose a service over the web. Technically it is an application that exposes a web-accessible API i.e., you can invoke this application programmatically over the Web Using SOAP protocol. It allows applications to share data and functionality. It can be called across platforms and operating systems regardless of the programming language used by applications. Web services enable 100% interoperability.

In .Net a web service is a ASP.NET application with <.asmx> extension. The basic elements of web services are SOAP(XML + HTTP) + WSDL + UDDI + DISCO. It can be implemented in a variety of languages. VC++.NET, VisualC#.NET, VB.NET are some of the languages supported by the Microsoft .NET Framework. A total of 25 languages currently target the .Net Framework.

UDDI (Universal Description Discovery and Integration)

UDDI is an industry effort started in the September of 2000 by Ariba, IBM, Microsoft, and 33 other companies. Today, UDDI has over 200 community members.

UDDI defines a way to publish and discover information about web services. A UDDI registry cloud or business registry provides "register once, publish everywhere" access to information about web services.

UDDI is like a registry rather than like a repository. A registry contains only reference information. For example, the Windows registry contains the name of COM objects not the entire code (Components). When we invoke a COM object, the system finds the registry entries and then it redirects execution to the actual binary part for that COM object. UDDI works the same way. On the other hand repository contains the actual information itself. For example, a library is a repository of books/information.

Using Microsoft UDDI SDK, web services can be registered for public use at http://www.uddi.org. UDDI has white pages, green pages and yellow pages. White pages describe information such as the company name, address and contact info. Yellow pages provide information based on industrial categories. Green Pages describe the interface for web services. Web services are defined through UDDI using a document called Type Model or tModel. The WS-Inspection specification from the Global Web Services Architecture can be used to browse UDDI to determine a web service suitable for a specific set of requirements. Visual Studio.Net provides a web service with the option to register and publish itself from the IDE. (Microsoft stands high in this regard compared to other products in the IDE market... Bill's Great).

DISCO (Discovery)

Once a web service is selected through the UDDI and its location identified, the next step in accessing it is discovery. Discovery is the process of locating and interrogating XML Web service descriptions. Through this process a client understands web service capabilities. Programmatic discovery is enabled through a ".disco" file, which is an XML document that contains links to other discovery documents, XSD schemas, and service descriptions (WSDL).

XML Web services created using ASP.NET automatically have a generated discovery document. A discovery document is automatically generated for an XML Web service when the web service is accessed using a URL with "?DISCO" in the query string. For instance, if the URL to an XML Web service is http://www.ragavan.com/Mathfunctions.asmx, then a discovery document is automatically generated with a URL of http://www.ragavan.com/Mathfunctions.asmx?DISCO.

Role of SOAP and WSDL

SOAP stands for Simple Object Access Protocol. SOAP is an XML based lightweight protocol, which allows software components and applications communicate, mostly using HTTP. SOAP sits on top of the HTTP protocol. It is message-based and nothing but an XML document with a pre-defined format. The following features make it the most preferred way of communication over the web:

  • Platform independency 
  • Language independency
  • XML Based
  • Based on W3C standard

Every SOAP message has an Envelope, a Header (optional) and Body (SOAP message in XML Format).

SOAP Message format

WebSer3.jpg

SOAP Envelop defines the content of the message.
SOAP header (optional) contains header information.
SOAP body contains call and response information.

Advantages of SOAP over DCOM/CORBA/RMI

Before the advent of web services and .Net, technologies like DCOM, CORBA and RMI were used for network communication. But these technologies are vendor specific and interoperability between them was quite complex. Remote procedure calls (RPC) was used for communication between technologies like DCOM and CORBA, but HTTP was not designed for this. RPC calls are (mostly non-compatible and) less secure and firewalls/proxy servers will normally block this kind of traffic. Most of the corporate networks use proxy/firewalls that allow only HTTP requests. Web sites too allow mostly HTTP traffic through port 80. All Internet browsers and servers support HTTP. So HTTP is generally a better way to communicate between applications. SOAP accomplishes this.

WSDL: (Web Service Description Language)

All right, let's say we have created a web service. Who is going to use that? How does the consumer know which method to invoke and what parameters to pass?
There are many possible ways we can think of to accomplish this task. May be we can write a document that provides this information or we can verbally explain the information to the user. These informal approaches have at least one serious problem. When a developer sits down to build a client for your Web service, their development tool (e.g. Visual Studio) cannot offer them any help because that tool has no idea about the Web service's functions and parameters. Providing a formal description in a machine-readable format would solve this problem. The Web Service Description Language is an XML-based grammar for describing the web service; it's functions, parameters, and return values. Being XML-based, WSDL is both machine and human readable. (Hey! This is cool stuff!). There are tools that can generate a WSDL document from a web service and tools that can read a WSDL document and create the necessary code to invoke the web service.

The .asmx and .asmx.cs files: A Quick Peek

As told earlier, in .Net a web service is a ASP.NET application with a file that has <.asmx> extension. The <.asmx> file is like the main function in a C++ program. In other words it the starting point of the web service application. It can either contain code within itself or code in a code-behind file <.asmx.cs or .asmx.vb>. The second option is the default style followed in Visual Studio.Net.

Let us use the code-behind option in our discussion too. The <.asmx> file has the "WebService" processing directive, which provides information as to which code-behind file and class implement the functionality of the web service. This is implemented by the following attributes: Language, Codebehind and Class.

Usage Syntax:

<%@ WebService Language="C#" Codebehind="Service1.asmx.cs"
Class="WebService1.Service1" %>

The code-behind file <eg: .asmx.cs> defines the web service class, which inherits from "System.Web.Services.WebService". All the methods of the class are not accessible over the web. Optionally the WebService attribute can be used to specify certain properties for the web service. The WebService attribute has four properties, which provide information about the web service. We now have a web service class but then what good will it do when it doesn't expose it's functionality over the web?

The WebMethod attribute is used to expose a public method of a web service class over the web. The WebMethod attribute has six properties, which control the way the web method operates over the web.

WebService Attribute

The four properties of the WebService attribute are as follows:

Namespace
Description
Name
TypeID

Each of the above properties is explained in detail below.

Namespace
In order for an XML Web Service to be distinguishable over the web from other web services, the Web Service should use a unique namespace. In Visual Studio.NET the default namespace is http://tempuri.org. This is fine during the development phase. But a namespace should be provided when the web service is published in the UDDI (Universal Description Discovery Integration). The namespace does not have to be an existing URL. A name such as the name of the company can be used as a web service name space. The main purpose of the namespace is only to uniquely identify the web service. The 'Namespace' property of the WebService attribute is used to specify a namespace for the web service.

Usage Syntax:
<WebService(Namespace:="http://www.Ragavan.com/",
Name:="SreeniWebServiceForCCardCheck")>
Public Class Service1
Inherits System.Web.Services.WebService

Description
This property is used for providing a brief description to a web service.

Usage Syntax:
<WebService(Description:="This is Math Functions Webservice")> _
Public Class Service1
Inherits System.Web.Services.WebService

Name
The default name that VisualStudio.Net provides for a web service is Service1. A web service shall be given a name using the 'Name' property.

Usage Syntax:
<WebService(Description:="This is Math Functions Webservice", Name:="Ragavan Math Functions Service")> _ Public Class Service1
Inherits System.Web.Services.WebService

WebSerBBImg1.jpg

The above screen shows a web service that displays it's name and description.

TypeId
This property is rarely used. It is used to uniquely identify the type of the attribute in scenarios where the WebService attribute is derived from WebMethod Attribute.

The six properties of the WebMethod attribute are as follows: 

Description
MessageName
EnableSession 
CacheDuration
TransactionOption
BufferResponse

Each of the above properties is explained in detail below.

Description
This property provides a brief description to the web method.

Usage Syntax:
<WebMethod(Description:="This Method add two integer")>
Public Function Add2Integer(ByVal Num1 As Integer, ByVal Num2 As Integer) As
Integer
Return Num1 + Num2
End
Function

The web method described above takes two integers as parameters and returns their sum also as an integer.

MessageName
This property is useful particularly when web methods need to be overloaded. Function overloading is accomplished when functions have the same name but different implementation.

Usage Syntax:
<WebMethod (MessageName:="SayHello")>
Public Function SayHello() As
String
Return "Hi Ragavan"
End
Function
<WebMethod()> Public Function SayHello(ByVal sName As String) As
String
Return "Hello" & " " & sName
End
Function

In the above example, the SayHello method is overloaded. One method takes parameters and other does not.

EnableSession
XML+HTTP=SOAP 

SOAP sits on top of the HTTP protocols as mentioned before. HTTP (Hyper Text Transfer Protocol) is a stateless protocol. EnableSession property helps to maintain session state between server and the client. 

By default the EnableSession property is false. By setting this property to true the session between the first and subsequent requests can be maintained. If EnableSession is false, session state cannot be maintained at any point.

Usage Syntax: 
<WebMethod (EnableSession:=true)>

CacheDuration
What is Cache? Cache is the memory buffer, which contains the result of a previously accessed method by a web services consumer. Cache mechanism provides good performance and high scalability. Cache Duration web method property allows to cache a web service result for a specified period of time (in milliseconds).

Let's say we have a web service, which provides the list of books available in a particular library. When a user accesses this Web service for the first time the result of this request is cached in memory. If during the next time some other user request the same service the result will be served from cache. This speeds up web service requests. But caching output blindly for all web services doesn't make sense. Let us consider a web service, which provides stock quotes. In this case, caching is not worth because stock quotes change every second.

Usage Syntax:
<WebMethod(CacheDuration:=60)>
Public Function PrintTime() As
String
Return Now().ToString
End
Function

In the above example, the cache duration is 60 milliseconds. If the same method is invoked within 60 milliseconds, both requests will print the same time.

TransactionOption
A transaction is a set of events that are committed or rolled back as a unit. Either all of the events happen or none of them do. For example, transferring $100 from your savings account to your checking account requires both subtracting the money from your savings account and adding it to your checking account. To achieve a consistent result, either both operations should succeed or fail. Transaction-oriented applications like this are very common. Therefore, many vendors provide software that makes writing transactional applications easier. And because transactional applications often need to handle hundreds and thousands of clients (i.e., users at workstations), services that make it easier to build scalable applications are commonly built into products that support transactions.

The following matrix explains the transaction options supported by the TransactionOption property. 

Transaction Options Description
Disabled Ignores any transaction in the current context.
NotSupported Creates the component in a context with no governing transaction.
Required Shares a transaction if one exists and creates a new transaction if necessary.
RequiresNew Creates the component with a new transaction, regardless of the state of the current context.
Supported Shares a transaction, if one exists.

The Disabled and NotSupported option behave the same way, because these options are inherited from EnterpriseServices (COM+).

Usage Syntax:
<WebMethod(TransactionOption:=TransactionOption.RequiresNew)> _
Public Function DoSomethingTransactional() As
String
'The transaction was successful...
ContextUtil.SetComplete()
DoSomethingTransactional = ContextUtil.TransactionId.ToString()
End
Function

BufferResponse
This property is used to determine if the Web Service Response will be buffered. When set to true (which is the default), ASP.NET buffers the entire response before sending it to the client. This type of buffering is very efficient and helps improve performance by minimizing communication between the worker process and the Internet Information Services (IIS) process. When set to false, ASP.NET buffers the response in chunks of 16 kilobytes. Typically, you set this property to false only if you do not want the entire contents of the response to be stored in memory at one time. For example, if you are writing back a collection that is streaming its items out of a database. Unless specified, the default value is true.

Usage Syntax:
<WebMethod (BufferResponse:=true)>

Web Service Type Marshalling

Web Service Type Marshalling is the process of moving different data types over the web. Various data types can be passed to and back from Web Service methods. As the XML Web services implementation is built on top of the XML Serialization architecture it supports lots of data types. The code samples below provide examples for marshalling the following types: String, Array, Class, Integer and Dataset.

Integer

//This WebMethod will take two integer arguments and
// return the result as an int.
[WebMethod]
public int Add (int A, int B)
{
return A+B;
}
String
//This WebMethod will take no arguments and return
// the result as a string.
[WebMethod]
public string HelloWorld()
{
return "Hello Seenivasaragavan";
}

Class

//This WebMethod will take no arguments and return
// the result as a class.
[WebMethod]
public Person GetMyRecord ()
{
Person s= new Person ();
s.Name ="S.Siddarth Sundarram";
s.age ="1.5";
s.Address ="1036 san Jacinto drive";
return s;
}

Integer Array

//This WebMethod will take no arguments and return
// the result as an array of int.
[WebMethod]
public int[] MyMarks()
{
int i;
int [] Marks = new int [5];
for (i=0;i<5;i++)
{
Marks[i]=3*20;
}
return Marks;
}

Dataset

//This WebMethod will take no arguments and return
// the result as a Dataset.
// This WebMethod reads the windows eventlog and //constructs an XML message in a file and then
// writes the message from the file to a Dataset.
[WebMethod()]
public DataSet ReadEventLog()
{
DataSet ds = new DataSet();
// Creating DataSet objects
EventLog aLog = new EventLog();
AppLog.Log = "Application";
//Reading only Application logs
AppLog.MachineName = ".";
// Local machine
string str="<?xml version='1.0' ?>";
str=str+"<MSG>";
foreach (EventLogEntry entry in AppLog.Entries)
{
str = str +"<Msg>";
str=str + "<Type>"+entry.EntryType+"</Type>";
str =str+"<Date>"+entry.TimeWritten.ToString()+"</Date>";
str =str +"<Source>"+entry.Source+"</Source>";
str =str+"<Description>"+entry.Message.ToString()+"</Description>";
str=str+"</Msg>";
}
str=str+"</MSG>";
FileStream fs = new FileStream("c:\\Raga.xml" , FileMode.Create, FileAccess.ReadWrite);
//Now let's put some text into the file using the StreamWriter
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(str);
sw.Flush();
sw.Close();
ds.ReadXml("c:\\raga.xml");
return ds;
}

The Windows EventLog returned from ReadEventLog WebMethod as a dataset looks like this:

WebSerBBImg2.jpg

Web Services Capabilities

This part of the article ends with some fast facts on web services capability. The following table depicts a web services capability matrix:

Capability Web services
Invoke single method on a stateless object Yes
Invoke multiple methods on a stateful object No
Have all clients invoke methods on the same serverside object No
Pass through firewalls Yes
Uses HTTP for communication Yes
Uses raw TCP socket for communication No
Use IIS as host Yes
Allow custom host No
Uses SOAP-compliant formatting of data Yes
Uses smaller binary formatting of data No
Retrieve partial copy of data from complex object Yes
Retrieve complete copy of complex object No

Conclusion

The first part has provided a sneak-peek into the elements of web services. The next part of this article shall deal with some topics like "Productively creating web services using Visual Studio.Net with a demonstration", Developing smart clients to consume a web service (Windows Client, Web Client and a Java Client [Jeez! can't believe myself!]). Let's push it to the limits and see where it takes us!
Hurrah!