Chapter 32. Exposing Functionality with Web Services

IN THIS CHAPTER

XML Web Services is a technology that has rapidly grown from a powerful concept to a tried-and true standard, to the point where web services are now an almost ubiquitous standard for developing distributed applications. This chapter provides you with an introduction to web services development and gives you the basics you need to get started integrating web services into your web applications, thin clients, or distributed applications.

Introduction to Web Services

Ever since the early days of client/server applications, applications have benefited from separation of tiers, whether that separation was physical or logical. Applications could communicate with databases that were in remote locations, or using technologies like DCOM, they could communicate with remotely located business logic.

Ever since its creation, the web has been an incredibly powerful tool for disseminating information and content. However, due to the nature of HTML, it has been difficult to use the web to disseminate data in formats that can be easily consumed by client applications.

When powerful new server-side programming technologies became available, such as Active Server Pages, Java, Perl, CGI, and more, developers began creating their own custom solutions to use the web to expose data in a consumable format.

This eventually led to the development of web pages that rendered raw XML that could then be consumed by clients. That led to the development of a standard dialect of XML that defined the contract by which a web service and its client would agree: WSDL (Web Services Description Language).

Using WSDL, modern programming languages could obtain information about functionality exposed over HTTP using web services and then consume that functionality. This provided developers with a whole new model of development that allowed them to expose discrete units of functionality on the Internet and consume it in any language on any platform so long as both the client and server could read and generate XML.

ASP.NET has provided built-in support for web services since its original release. That support has only gotten better in recent versions and will undoubtedly see even more advancements in upcoming releases.

How Web Services Work

Web services describe the methods they expose, including their parameters and return types, in an XML dialect called the Web Services Description Language (WSDL). This language provides a platform-independent description of functionality that can be consumed by any language on any platform that can interpret XML.

Using the information contained in the WSDL document, the functionality can be consumed. In the .NET world, this means that a wrapper class is created around the WSDL exposed by a web service to provide object-oriented access to the underlying web service.

When a method is invoked, it can either be invoked using an HTTP POST statement with simple parameters or it can be invoked by submitting a SOAP (Simple Object Access Protocol) envelope to the ASP.NET web service (represented by a .asmx file on the server). SOAP provides a wire format that can be used to encode method execution requests as well as return values from executed methods. The contents of the POST request or the SOAP envelope are then processed and the requested method is then executed on the server. The return value and any output parameters of that method are then encoded into output that is then sent to the client. A high-level diagram of this process is shown in Figure 32.1.

Figure 32.1 Two-step process to consume a web service.

Image

Creating a Simple “Hello World” Service

To see how web services work in action, this section walks you through creating the simplest web service you can create: the “Hello World” service.

Start Visual Studio and select File, then New, and then Website. Choose the ASP.NET Web Service template from the menu and call it HelloWorldService.

The newly created project contains a C# class file called Service.cs in the App_Code directory and a Service.asmx file in the web application’s root directory.

The Service.asmx file is the main point of interface for a web service. It can be used to obtain the WSDL contract for the web service as well as to test the service. Highlight the Service.asmx file and run the application.

When you run the application in debug mode for the first time, you might be prompted to add a Web.config file to the project and enable debugging mode. You will see a new web browser containing a list of the services available within the application. Click the HelloWorld link to bring up a web page that looks similar to the one shown in Figure 32.2.

Figure 32.2 The HelloWorld web service page.

Image

Click the Invoke button to test-run the web service. This web service simply returns the phrase “Hello World” to any application invoking the HelloWorld() method. The results of testing this web service are shown in the following lines:

<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://tempuri.org/">Hello World</string>

The output from the web service is in an XML format that can be interpreted by any client aware of the Web Services XML format. To see how .NET, and specifically Visual Studio 2005, handles web services, you need to create a web service client.

To do this, add a new console application project to the existing solution called WSClient. Right-click the new console application project and select Add Web Reference. You will be prompted with a dialog asking for the location of the web service. In this case, the web service is part of the current solution, so you can click the “Web Services in This Solution” link. Then click the displayed link to add a web reference to the “Hello World” web service. Accept localhost as the web service name and click Add Reference.

With the web reference in place, you can modify the code in Program.cs to create an instance of the web service and invoke it, as shown in the following example:

Image

When you run this application, you will see the phrase “Hello World.” This phrase comes from the web service in the solution. When the client represented by the localhost.Service wrapper class invokes the HelloWorld() method, the code contained in the Service.cs file on the server (shown in Listing 32.1) is executed.

Listing 32.1 Service.cs

Image

The WebMethodAttribute code attribute class is what marks a method as being exposed to clients via the web service. The WebServiceAttribute class allows you to define additional properties of the web service directly within the code.

Despite how often the “Hello World” sample is used to illustrate the use of new technology, it isn’t very practical. The next sample shows you how to create a web service that takes input parameters and returns values both as a method return value and through output parameters.

First, add a new web method to the Service.cs file as shown in Listing 32.2.

Listing 32.2 Service.cs Containing an Additional Web Method

Image

The new method takes two input parameters and supplies the concatenation of those two parameters as the third parameter and then returns the length of the new string as the return value.

If you have worked with web services in previous versions of Visual Studio, you will be pleasantly surprised to see that just a few seconds after you add the new method to the web service, the web reference in the console application you created is automatically updated. If it doesn’t automatically update, you can just right-click the localhost item in the Solution Explorer and choose Update Web Reference.

Run the web application again and get to the test page for the StringConcat method. Note that you can’t test-fire this method from the web any more because of the output parameter.

To see this new method in action, modify the source code to the Program.cs file in the console application to look like the code in Listing 32.3.

Listing 32.3 Consuming a Web Service Method with Output Parameters

Image

The complexity of converting the request for method execution into a portable XML format, transmitting that XML to the remote host, waiting for a response, retrieving the response XML, and finally decoding the response XML into .NET native types is all handled automatically by the Web Service wrapper class. The output of the preceding code is as follows:

Hello World
Concat Result: The quick brown fox ran over the slow 486 DX2/66 length 48

This book will not spend much time on the details of WSDL, but it does help to see how everything works, including the WSDL describing the service you just created. To see the WSDL for any .NET service, simply append ?WSDL to the end of the URL. The WSDL for the service created in this section is shown in Listing 32.4.

Listing 32.4 WSDL for a Two-Method Web Service

Image

Image

Image

Image

There is a lot going on in the preceding WSDL document. The basic idea is that operations (remote method invocations) are defined and associated with specific ports (URLs). For each operation, there are elements defined as input and elements defined as output. By consuming this WSDL document, a web service client is able to format messages sent to the service and interpret response messages from the service.

Creating Transactional Services

Imagine that you are creating a web service for a bank and you have several methods on that web service: Transfer, Inquiry, and Deposit. In order to produce the most reliable web service possible, you need to make it so that if an error occurs during a Transfer or a Deposit method call, the changes will be rolled back in order to avoid placing a customer’s bank account in an inconsistent state. The Inquiry method doesn’t need to have any transactional support because it is a read-only method, and an exception within that method call won’t create inconsistent data.

The way transactional support is added to a web service method is through the TransactionOption parameter to the WebMethod attribute. Listing 32.5 shows the three sample web methods discussed in the preceding paragraph, two of which have been set to use transactions.

Listing 32.5 Transactional Web Services

Image

The TransactionOption enumeration tells the underlying transaction system how to handle transactions. In the preceding code, Required indicates that if a transaction already exists, it will be reused; otherwise, a new transaction will be created. The transaction system used to support transactional web services is found in the System.EnterpriseServices namespace, which is part of the COM+ system. COM+ and Enterprise Services are discussed in Chapter 40, “Using Enterprise Services.”

If any of the transactional methods throw an exception, the current transaction will be rolled back and any changes will be lost. Keep in mind that only transaction-aware resources will roll back. This means that if your code makes changes to a disk file during the transactional method and an exception occurs and the transaction is rolled back, the disk file will still contain any changes made during the method call. Resources like SQL Server connections, Oracle connections, Microsoft Message Queues, and others are all aware of transactions and capable of rolling back changes.

Managing State in Web Services

A web service is really nothing more than a specialized type of ASP.NET page. As such, a web service is actually part of an ASP.NET web application and can take advantage of application state management techniques such as using the Application object. In addition, session state can be enabled or disabled using properties of the WebMethod attribute.

State should be used sparingly within web services. Maintaining state between multiple calls to the same web service can potentially lead to scalability problems and even inconsistent data. If you absolutely have to make use of some means of state maintenance, then consider using session state over application state, because application state can grow rapidly and has the potential of creating memory problems. Refer to Chapter 23, “State Management in ASP.NET 2.0,” for more details on the reasons for and against the various types of state management.

To enable session state and use application state within a web service, you can use code similar to the code in Listing 32.6.

Listing 32.6 State-Aware Web Service

Image

Deciding which state management method you want to use will be a decision very similar to the decision made for a standard ASP.NET application’s state management solution. The difference is that web services tend to be invoked more frequently than web pages and typically have different usage patterns. You will generally want to keep state maintenance for web services even lower (if used at all) than what is used for ASP.NET Web Forms applications. This is because each method should be considered a discrete unit of functionality, and subsequent method calls should not normally depend on state created by previous method calls.

Summary

This chapter provided you with a brief introduction to the world of web services programming without bogging you down in too much detail. The chapter covered how to create web service applications and add web methods to services within those applications. You saw how to create regular web services as well as web services that take advantage of state management as well as transactions. Chapter 33, “Advanced Web Services Programming,” will provide you with an even more detailed coverage of web services as well as explain some advanced concepts not covered in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.77.161