Wednesday, June 11, 2008

.NET Web Services

Creating a .NET Web Service

Introduction

Microsoft .NET marketing has created a huge hype about its Web Services. This is the first of two articles on Web Services. Here we will create a .NET Web Service using C#. We will look closely at the Discovery protocol, UDDI, and the future of the Web Services. In the next article, we will concentrate on consuming existing Web Services on multiple platforms (i.e., Web, WAP-enabled mobile phones, and windows applications).

Why do we need Web Services?
After buying something over the Internet, you may have wondered about the delivery status. Calling the delivery company consumes your time, and it's also not a value-added activity for the delivery company. To eliminate this scenario the delivery company needs to expose the delivery information without compromising its security. Enterprise security architecture can be very sophisticated. What if we can just use port 80 (the Web server port) and expose the information through the Web server? Still, we have to build a whole new Web application to extract data from the core business applications. This will cost the delivery company money. All the company wants is to expose the delivery status and concentrate on its core business. This is where Web Services come in.

What is a Web Service?
Web Services are a very general model for building applications and can be implemented for any operation system that supports communication over the Internet. Web Services use the best of component-based development and the Web. Component-base object models like Distributed Component Object Model (DCOM), Remote Method Invocation (RMI), and Internet Inter-Orb Protocol (IIOP) have been around for some time. Unfortunately all these models depend on an object-model-specific protocol. Web Services extend these models a bit further to communicate with the Simple Object Access Protocol (SOAP) and Extensible Markup Language (XML) to eradicate the object-model-specific protocol barrier (see Figure 1).

Web Services basically uses Hypertext Transfer Protocol (HTTP) and SOAP to make business data available on the Web. It exposes the business objects (COM objects, Java Beans, etc.) to SOAP calls over HTTP and executes remote function calls. The Web Service consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web.


Figure 1. SOAP calls are remote function calls that invoke method executions on Web Service components at Location B. The output is rendered as XML and passed back to the user at Location A.


How is the user at Location A aware of the semantics of the Web Service at Location B? This question is answered by conforming to a common standard. Service Description Language (SDL), SOAP Contract Language (SCL) and Network Accessible Specification Language (NASSL) are some XML-like languages built for this purpose. However, IBM and Microsoft recently agreed on the Web Service Description Language (WSDL) as the Web Service standard.

The structure of the Web Service components is exposed using this Web Service Description Language. WSDL 1.1 is a XML document describing the attributes and interfaces of the Web Service. The new specification is available at msdn.microsoft.com/xml/general/wsdl.asp.

The task ahead
The best way to learn about Web Services is to create one. We all are familiar with stock quote services. The NASDAQ, Dow Jones, and Australian Stock Exchange are famous examples. All of them provide an interface to enter a company code and receive the latest stock price. We will try to replicate the same functionality.

The input parameters for our securities Web service will be a company code. The Web service will extract the price feed by executing middle-tier business logic functions. The business logic functions are kept to a bare minimum to concentrate on the Web service features.

Tools to create a Web Service
The core software component to implement this application will be MS .NET Framework SDK, which is currently in beta. You can download a version from Microsoft. I used Windows 2000 Advance Server on a Pentium III with 300 MB of RAM.

The preferred Integration Development Environment (IDE) to create Web Services is Visual Studio .NET. However, you can easily use any text editor (WordPad, Notepad, Visual Studio 6.0) to create a Web Service file.

I assume you are familiar with the following concepts:

Basic knowledge of .NET platform
Basic knowledge of C#
Basic knowledge of object-oriented concepts

Creating a Web Service
We are going to use C# to create a Web Service called "SecurityWebService." A Web Service file will have an .ASMX file extension. (as opposed to an .ASPX file extension of a ASP.NET file). The first line of the file will look like



This line will instruct the compiler to run on Web Service mode and the name of the C# class. We also need to access the Web Service namespace. It is also a good practice to add a reference to the System namespace.

using System;
using System.Web.Services;


The SecurityWebService class should inherit the functionality of the Web Services class. Therefore, we put the following line of code:

public class SecurityWebService : WebService

Now we can use our object-oriented programming skills to build a class. C# classes are very similar to C++ or Java classes. It will be a walk in the park to create a C# class for anyone with either language-coding skills.

Dot-net Web Services are intelligent enough to cast basic data types. Therefore, if we return "int," "float," or "string" data types, it can convert them to standard XML output. Unfortunately, in most cases we need get a collection of data regarding a single entity. Let's take an example.

Our SecurityWebService stock quotes service requires the user to enter a company code, and it will deliver the full company name and the current stock price. Therefore, we have three pieces of information for a single company:

Company code (data type - string)
Company name (data type - string)
Price (data type - Double)

We need to extract all this data when we are referring to a single stock quote. There are several ways of doing this. The best way could be to bundle them in an enumerated data type. We can use "structs" in C# to do this, which is very similar to C++ structs.

public struct SecurityInfo
{
public string Code;
public string CompanyName;
public double Price;
}

Now we have all the building blocks to create our Web Service. Therefore, our code will look like.



using System;
using System.Web.Services;

public struct SecurityInfo
{
public string Code;
public string CompanyName;
public double Price;
}

public class SecurityWebService : WebService
{
private SecurityInfo Security;

public SecurityWebService()
{
Security.Code = "";
Security.CompanyName = "";
Security.Price = 0;
}

private void AssignValues(string Code)
{
// This is where you use your business components.
// Method calls on Business components are used to populate the data.
// For demonstration purposes, I will add a string to the Code and
// use a random number generator to create the price feed.

Security.Code = Code;
Security.CompanyName = Code + " Pty Ltd";
Random RandomNumber = new System.Random();
Security.Price = double.Parse(new System.Random(RandomNumber.Next(1,10)).NextDouble().ToString("##.##"));
}


[WebMethod(Description="This method call will get the company name and the price for a given security code.",EnableSession=false)]
public SecurityInfo GetSecurityInfo(string Code)
{
AssignValues(Code);
SecurityInfo SecurityDetails = new SecurityInfo();
SecurityDetails.Code = Security.Code;
SecurityDetails.CompanyName = Security.CompanyName;
SecurityDetails.Price = Security.Price;
return SecurityDetails;
}

}

Remember, this Web Service can be accessed through HTTP for any use. We may be referring to sensitive business data in the code and wouldn't want it to fall into the wrong hands. The solution is to protect the business logic function and only have access to the presentation functions. This is achieved by using the keyword "[Web Method]" in C#. Let's look at the function headers of our code.

[WebMethod(Description="This......",EnableSession=false)]
public SecurityInfo GetSecurityInfo(string Code)


This function is exposed to the public. The "description" tag can be used to describe the Web Service functionality. Since we will not be storing any session data, we will disable the session state.

private void AssignValues(string Code)

This is a business logic function that should not be publicly available. We do not want our sensitive business information publicly available on the Web. (Note:- Even if you change the "private" keyword to "public," it will still not be publicly available. You guessed it, the keyword "[Web Method]" is not used.)

We can use the business logic in this function to get the newest stock price quote. For the purpose of this article I have added some text to the company code to create the company name. The price value is generated using a random number generator.

We may save this file as "SampleService.asmx" under an Internet Information Service (IIS)-controlled directory. I have saved it under a virtual directory called "/work/aspx." I'll bring it up on a Web browser.



This is a Web page rendered by the .NET Framework. We did not create this page. (The page is generated automatically by the system. I did not write any code to render it on the browser. This graphic is a by-product of the previous code.) This ready-to-use functionality is quite adequate for a simple Web Service. The presentation of this page can be changed very easily by using ASP.NET pagelets and config.web files. A very good example can be found at http://www.ibuyspy.com/store/InstantOrder.asmx.

Notice a link to "SDL Contract." (Even if we are using WSDL, .NET Beta still refers to SDL. Hopefully this will be rectified in the next version). This is the description of the Web Service to create a proxy object. (I will explain this in the next article.) This basically gives an overview of the Web Service and it's public interface. If you look closely, you will only see the "Web-only" methods being illustrated. All the private functions and attributes are not described in the SDL contract. The SDL contract for the SecurityWebService can be found in Appendix A.


How do we use a Web Service?
Now we can use this Web Service. Let's enter some values to get a bogus price feed.



By clicking the Invoke button a new window will appear with the following XML document



This is how the Web Service releases information. We need to write clients to extract the information from the XML document. Theses clients could be

A Web page
A console / Windows application
A Wireless Markup Language (WML) / WMLScript to interact with mobile phones
A Palm / Win CE application to use on Personal Digital Assistants (PDAs).

You can also call the Web Service directly using the HTTP GET method. In this case we will not be going through the above Web page and clicking the Invoke button. The syntax for directly calling the Web Service using HTTP GET is

http://server/webServiceName.asmx/functionName?parameter=parameterValue

Therefore, the call for our Web Service will be

http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo?Code=IBM

This will produce the same result as clicking the Invoke button.

Now we know how to create a Web Service and use it. But the work is half done. How will our clients find our Web Service? Is there any way to search for our Web Service on the Internet? Is there a Web crawler or a Yahoo search engine for Web Services? In order to answer these questions we need to create a "discovery" file for our Web Service.

Creating a Discovery file
Web Service discovery is the process of locating and interrogating Web Service descriptions, which is a preliminary step for accessing a Web Service. It is through the discovery process that Web Service clients learn that a Web Service exists, what its capabilities are, and how to properly interact with it. Discovery file is a XML document with a .DISCO extension. It is not compulsory to create a discovery file for each Web Service. Here is a sample discovery file for our securities Web Service.



We can name this file "SampleService.disco" and save it to the same directory as the Web Service. If we are creating any other Web Services under the "/work/aspx" directory, it is wise to enable "dynamic discovery." Dynamic discovery will scan for all the *.DISCO files in all the subdirectories of "/work/aspx" automatically.



An example of an active discovery file can be found at http://services3.xmethods.net/dotnet/default.disco. By analyzing the discovery file we can find where the Web Services reside in the system. Unfortunately both these methods require you to know the exact URL of the discovery file. If we cannot find the discovery file, we will not be able to locate the Web Services. Universal Description, Discovery, and Integration (UDDI) describes mechanisms to advertise existing Web Services. This technology is still at the infant stage. UDDI is an open, Internet-based specification designed to be the building block that will enable businesses to quickly, easily, and dynamically find and transact business with one another using their preferred applications. A reference site for UDDI is http://uddi.microsoft.com/.

There have been a lot of Web Services written by developers. www.xmethods.com is one of the sites that has an index of Web Services. Some developers are building WSDL search engines to find Web Services on the Web.

Deploying a Web Service
Deploying the Web Services from development to staging or production is very simple. Similar to ASP.NET applications, just copy the .ASMX file and the .DISCO files to the appropriate directories, and you are in business.

The future of the Web Services
The future looks bright for the Web Service technology. Microsoft is not alone in the race for Web Service technology. Sun and IBM are very interested. There are SOAP toolkits available for Apache and Java Web servers. I believe Web Services needs a bit of work, especially the Web Service discovery process. It is still very primitive.

On a positive note, Web Services have the potential to introduce new concepts to the Web. One I refer to as "pay per view" architecture. Similar to pay-TV, we can build Web sites that can generate revenue for each request a user sends (as opposed to a flat, monthly subscription). In order to get some data, we can sometimes pay a small fee. Commercially this could be handy for a lot of people.

Examples
Online newspaper sites can publish a 10-year-old article with a $2 "pay per view" structure.

Stock market portals can itemize every user portfolio for every single stock quote and build pricing and discount structures.

And the list goes on ...

On a very optimistic note, Web Services can be described as the "plug and play" building blocks of enterprise Business to Business (B2B) Web solutions.


-------------------------------- Part II ------------------------------

Asynchronous Web Services for Visual Basic .NET

Asynchronous Web Services rely on the basic asynchronous behavior built into .NET; it is part of the multithreading model of .NET. The basic idea is that you can invoke a Web Method asynchronously, which means it returns before it has finished the computation, and the Web Service will tell you at a later time when it has finished. Collectively, all of this technology relies on the CodeDOM, multithreading, SOAP, HTTP, and delegates, which illustrates why a well-architected platform is essential. Fortunately, .NET is designed so that you don't really have to master any of these technologies to use asynchronous Web Services. The hardest thing you have to learn to do is to use delegates.

When you are finished reading this article you will have the basic information necessary to invoke Web Methods asynchronously. We'll use a basic Web Service that returns simple data, pretending the process is long enough to warrant an asynchronous call. In July 19th's article, I wrote about calculating prime numbers. I will use a Web Service based on the ability to calculate prime numbers, returning a Boolean to indicate prime-ness.

Integrating a Web Service into Your Application
The basic steps for integrating a Web Service are reviewed in the numbered-list that follows for convenience.

Create the solution for you client application
Use UDDI to find a Web Service (or you can use a known Web Service)
Select Project|Add Web Reference, entering the URL for the Web Service in the Address bar. (This process is just like browsing in internet explorer)
When you have navigated to the URL of the Web Service, the Add Web Reference button should be enabled in the Add Reference dialog. Click Add Reference
After you have selected the .asmx file representing the Web Service and added the reference, a new entry will be added to your project in the Web References folder. The folder name will be Web References (see figure 1) and a namespace, representing the Web Service host will be added to that namespace. There will be three files with the extensions .map, .disco, and .wsdl. Collectively, this information points at our Web Service.

There is one other file that was added to the Web References folder that doesn't show up in the Server Explorer, Reference.vb. Reference.vb contains a proxy class that inherits from System.Web.Services.Protocols.SoapHttpClientProtocol; this class is a proxy-or wrapper-for the Web Service. The proxy class is generated using the .NET CodeDOM technology and is responsible for marshalling calls between your application and the Web Service, making Web Services easier to use.

Tip: To obtain a Web Service description you can type the URL followed by the query WSDL. For example, on my machine I can obtain a Web Service description of the Primes service by typing http://localhost/primes/service1.asmx?wsdl in the Address bar of Internet Explorer.
Importantly, the proxy class contains three methods for every Web Method. One is a proxy for the synchronous version of the Web Method, and the other two are proxy methods for the SoapHttpClientProtocol.BeginInvoke and SoapHttpClientProtocol.EndInvoke. That is, the second pair of methods represents proxies for asynchronous invocation of the Web Service.

Invoking a Web Method Asynchronously
We can figure out how to invoke the Web Service asynchronously by examining the proxy methods. Listing 1 shows the proxy methods for the Web Method IsPrime.

Listing 1: Asynchronous proxy methods for the Web Method IsPrime.

Public Function BeginIsPrime(ByVal number As Long, _
ByVal callback As System.AsyncCallback, _
ByVal asyncState As Object) As System.IAsyncResult

Return Me.BeginInvoke("IsPrime", New Object() {number}, _
callback, asyncState)

End Function

Public Function EndIsPrime( _
ByVal asyncResult As System.IAsyncResult) As Boolean

Dim results() As Object = Me.EndInvoke(asyncResult)
Return CType(results(0),Boolean)

End Function

As the name suggests we call BeginIsPrime to initiate the asynchronous call. The proxy for BeginInvoke is a function that returns an interface IAsyncResult. The return value is used to synchronize interaction between the client and the Web Service. The first parameter is the value we pass to the Web Service; in this instance it is the number that we want to check for prime-ness. The second parameter is the callback. The second parameter will be the address of the method we want the Web Service to invoke when the Web Method has finished processing. The type of the callback method is the delegate AsyncCallback. The third argument is any additional object we want to pass through to the Web Service and the callback method. The third parameter can be used for any additional information, including simple data or objects.

The second method is called when the Web Service is ready or to block in the client until the Web Service is ready. For example, you can call the EndInvoke proxy in the callback method when the Web Service calls it. The callback is defined such that it accepts, and will receive, an IAsyncResult argument that you pass back to the EndInvoke proxy. The IAsyncResult object is used to synchronize the data exchange between the client and Web Service.

Listing 2 provides a slim example that combines all of the elements together. After the listing is an overview of the code as I wrote it.

Listing 2: Invoking a Web Method asynchronously.

1: Imports System.Console
2: Imports System.Threading
3:
4: Public Class Form1
5: Inherits System.Windows.Forms.Form
6:
7: [ Windows Form Designer generated code ]
8:
9: Private Sub Button1_Click(ByVal sender As System.Object, _
10: ByVal e As System.EventArgs) Handles Button1.Click
11:
12: ListBox1.Items.Clear()
13: Start()
14: End Sub
15:
16: Private Service As localhost.Service1 = _
17: New localhost.Service1()
18: Private Sub Start()
19:
20: Dim Numbers() As Long = _
21: New Long() {103323, 2, 3, 56771, 7}
22: Dim Number As Long
23:
24: For Each Number In Numbers
25: Dim Result As IAsyncResult = _
26: Service.BeginIsPrime(Number, _
27: AddressOf Responder, Number)
28: Next
29:
30: End Sub
31:
32: Private Sub Responder(ByVal Result As IAsyncResult)
33:
34: Dim IsPrime As Boolean = Service.EndIsPrime(Result)
35:
36: If (InvokeRequired) Then
37: Invoke(New MyDelegate(AddressOf AddToList), _
38: New Object() {IsPrime, _
39: CType(Result.AsyncState, Long)})
40: End If
41:
42: End Sub
43:
44: Private Delegate Sub MyDelegate( _
45: ByVal IsPrime As Boolean, ByVal Number As Long)
46:
47: Private Sub AddToList(_
48: ByVal IsPrime As Boolean, ByVal Number As Long)
49:
50: Const Mask As String = _
51: "{0} {1} a prime number"
52:
53: Dim Filler() As String = New String() {"is not", "is"}
54: ListBox1.Items.Add( _
55: String.Format(Mask, Number, _
56: Filler(Convert.ToInt16(IsPrime))))
57:
58: End Sub
59:
60: End Class

(The code generated by the designer is condensed-simulating Code Outlining in Visual Studio .NET-on line 7.) The basic idea is that the consumer sends several inquiries about possible prime numbers. Large prime numbers take longer to calculate than prime numbers; so the client application is designed to send every number asynchronously rather than get bogged down on big prime candidates.

The process is initiated in the Button1_Click event on line 13 when Start is invoked. (The actual application sends the same numbers ever time, but you could easily make this dynamic, too.)

Start is defined on lines 18 through 30 in listing 1. An array of candidate numbers is created on lines 20 and 21, demonstrating inline initialization in Visual Basic .NET. As you can see the largest number is first. In a synchronous application the remaining numbers would wait in line until 103323 was evaluated. In our model all requests will be sent and the results displayed as they are available. The For Each loop manages sending every number to be processed, representing ongoing work while preceding requests are being serviced by the Web Service.

The code we are interested in is on lines 25 through 27. Line 25 shows you how to obtain an IAsyncResult object in case we elect to block in the Start method. (We won't.) The first argument is the Number to be evaluated by the Web Method IsPrime; the second argument is the delegate, created implicitly with the AddressOf operator, and the third argument is the Number. I passed the Number a second time for display purposes (refer to line 55). The Web Service was created on lines 16 and 17, before the Form's constructor was called. The name localhost represents a namespace in this context and happens to be derived from the Web Service host computer.

Retrieving the Results from the Web Method
There are several ways to block while you are waiting for a Web Service to return. You can use the IAsyncResult.IsCompleted property in a loop, call Service.EndIsPrime-the EndInvoke proxy-or request theIAsyncResult.AsyncWaitHandle. In our example, we process merrily until the callback is invoked by the Web Service. The callback method is defined on lines 32 through 42. When the callback is called we can obtain the result by calling the EndInvoke proxy method as demonstrated on line 34.

Lines 36 through 40 and 44 through 58 exist in this instance due to the kind of application—a Windows Form application. When you invoke a Web Service asynchronously the callback method will be called back on a different thread than the one the Windows Forms controls reside on. As Windows Forms is not thread-safe-which means you should interact with Windows Forms controls on the same thread as the one they live on-we can use the Control.Invoke method and push the "work" onto the same thread that the control lives on. Again we use delegates to represent the work to be done.

The method InvokeRequired can be used to determine if you need to call invoke, as demonstrated on line 36. Lines 37, 38, and 39 demonstrate the Invoke method. Define a new delegate based on the signature of the procedure you want to Invoke. Create an instance of that delegate type, initializing the delegate with the address of your work procedure. Pass an array of objects matching the parameters your work-method needs. The delegate is defined on lines 44 and 45. An instance of the delegate is created on line 37, and the array of arguments is demonstrated on lines 38 and 39. Lines 38 and 39 create an array of Object inline passing a Boolean and a Long as is expected by the AddToList method. Pay attention to the fact that the delegate signature, the procedure used to initialize the delegate, and the arguments passed to the delegate all of have identical footprints.

Summary
Asynchronous Web Services depend on a lot of advanced aspects of the .NET framework, including SOAP, XML, HTTP, CodeDOM, TCP/IP, WDSL, UDDI, multithreading, and delegates, to name a view. Fortunately, these technologies exist already and work on our behalf behind the scenes for the most part. If you want to use asynchronous Web Services, the hardest thing you need to master are delegates.

Don't let anyone trivialize Web Services. They are powerful and complicated, but the complicated part was codified by Microsoft. The end result is that Web Services are easy to consume, with only modest additional complexity to invoke them asynchronously.

Asynchronous Web Services will add some zip to your applications. Be mindful of the existence of more than one thread and you are all set.

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home