Using a Web Service

JavaScript EditorJavascript debugger     Javascript examples


Team LiB
Previous Section Next Section

Using a Web Service

So now that you’ve got a couple of nifty Web services, you’ll probably want to know how to use them, beyond testing them by invoking them from a browser. While the formatting of SOAP requests and responses necessary to call a Web service can be somewhat complicated, the .NET Framework adds an abstraction layer that hides much of this complexity.

Nonetheless, you still need to know how to locate and use a Web service, including the following techniques:

Locating a Web Service

The first step in using an XML-based Web service is to locate it. If you’re dealing with a Web service that you or someone in your organization created, you might already know the location of the Web service. If so, you can skip this step.

Locating a Web service is essentially the mirror image of advertising a Web service, so the same techniques apply here. There are two techniques for locating a Web service in ASP.NET: discovery documents and UDDI.

Locating a Web Service with a Discovery Document

To use a discovery document to locate Web services, you need the URL for the discovery document that describes the services in which you’re interested. You might get the URL for the document from a listing on an organization’s public Web site, from an e-mail promotion, or from a catalog.

Once you have the URL for a discovery document, you can use the disco.exe command line utility to generate WSDL contracts for using the Web services described in the discovery document. The syntax for the disco.exe utility is

disco [options] URL

Here, options represents one or more command-line options for the utility, and URL represents the URL to the discovery document. Table 11-2 shows options for the disco.exe utility.

Table 11-2: disco.exe Options

Option

Description

/d:domain or
/domain:domain

Sets the domain to use when connecting to a site that requires authentication.

/nosave

Prevents disco.exe from saving files for the discovered WSDL and discovery documents.

/nologo

Prevents the start-up banner from being displayed.

/o:directory or
/out:directory

Provides the directory name where output should be saved.

/p:password or
/password:password

Sets the password to use when connecting to a site that requires authentication.

/proxy:url

Sets the proxy to use for HTTP requests.

/pd:domain or
/proxydomain:domain

Sets the domain to use when connecting to a proxy server that requires authentication.

/pp:password or
/proxypassword:password

Sets the password to use when connecting to a proxy server that requires authentication.

/pu:username or
/proxyusername:username

Sets the username to use when connecting to a proxy server that requires authentication.

/u:username or
/username:username

Sets the username to use when connecting to a site that requires authentication.

/?

Provides help for command-line options.

Locating a Web Service with UDDI

Unlike using a discovery document to locate a Web service, UDDI does not require you to know in advance the URL of a document describing the desired Web service. Any provider of a UDDI business registry usually will provide a tool for searching their instance of the registry for businesses or Web services that meet your needs. The criteria you can search on will depend on the organization hosting that instance. For example, Microsoft’s UDDI registry at http://uddi.microsoft.com supports searching by business name, business location, discovery URL, keyword, and a variety of other criteria. The following illustration shows the list of available criteria for searching the Microsoft UDDI registry.

Click To expand

One effective technique for searching for Web services on the http://uddi.microsoft.com registry is to search by discovery URL and search for URLs that contain “wsdl.” These URLs are the most likely to point to live WSDL contracts that you can use to access available Web services.

Understanding WSDL Files

WSDL is an XML-based standard for documents that describe the services exposed by a Web service. You can view the WSDL contract for any of the Web services you create with ASP.NET by calling up the URL for a Web service in a browser and appending ?WSDL to it.

WSDL contracts are similar to COM type libraries or .NET assembly metadata in that they are used to describe the public members of the Web service, including all publicly available methods, the parameters (and data types) those methods expect when called, and the data type of any return value. Because this information is encoded in a standard XML-based format, any client that can read XML and can understand WDSL and SOAP should be able to effectively consume the Web application that the WSDL contract describes.

Important 

The SOAP and WSDL specifications are still in the process of being standardized. In the short term, this means that there might be inconsistencies between different implementations of WSDL on different platforms, since these implementations can be based on different drafts of the proposed standard. Until SOAP and WSDL become settled standards (W3C Recommendations), you might need to tweak your WSDL contracts to achieve interoperability between different Web services implementations. This shouldn’t be an issue once these specifications have received approval as W3C Recommendations. In the meantime, you can read an interesting article on interoperability between various Web services implementations on the MSDN Library Web site at http://msdn.microsoft.com/library/en-us/dn_voices_webservice/html/ service08152001.asp.

Creating a Proxy Class

Consuming a Web service via SOAP is a fairly complex affair. It involves creating and formatting a SOAP envelope, a set of SOAP headers, and a SOAP body, all with the correct elements and attributes for the Web service you’re targeting. Fortunately, thanks to the built-in support for Web services in the .NET Framework, all of the plumbing necessary for accessing a Web service is provided for you. The .NET Framework provides another command-line utility, wsdl.exe, to help you by creating a .NET proxy class for a Web service described by a WSDL contract.

Using the wsdl.exe Utility

The wsdl.exe utility generates a proxy class in C#, Visual Basic .NET, or JScript .NET for a WSDL contract specified by URL or path. This proxy class can be instantiated and its methods called by any client, just like any other .NET class. Visual Studio .NET provides an easier way to generate a proxy class, which the next example will cover. However, at times (especially when you have special requirements not met by the standard proxy classes) you might find it handy to manually create the proxy class.

The syntax for the wsdl.exe utility is as follows:

wsdl [options] {URL | path}

Here, options represents one or more command-line options for the utility, and URL represents the URL to the WSDL contract. Alternatively, a file path to the WSDL contract can be passed as the path argument. Table 11-3 shows options for the wsdl.exe utility.

Table 11-3: wsdl.exe Options

Option

Description

/appsettingurlkey:key or
/urlkey:key

Sets the key of the configuration setting from which to read the default URL for generating code.

/appsettingbaseurl:baseurl
or /baseurl:baseurl

Sets the base URL to use for calculating relative URLs when a URL fragment is specified for the URL argument.

/d:domain or
/domain:domain

Sets the domain to use when connecting to a site that requires authentication.

/l:language or
/language:language

Sets the language to use when generating the proxy class. Valid values include CS, VB, JS, or the fully qualified name of any class that implements the System.CodeDom.Compiler.CodeDomProvider class. Default is CS (C#).

/n:namespace or
/namespace:namespace

Sets the namespace to be used when generating the proxy class.

/nologo

Prevents the start-up banner from being displayed.

/o:filename or
/out:filename

Provides the file name (and path) to use for saved output.

/p:password or
/password:password

Sets the password to use when connecting to a site that requires authentication.

/protocol:protocol

Sets the protocol (SOAP, HttpGet, or HttpPost) to use for requests. Default is SOAP.

/proxy:url

Sets the proxy to use for HTTP requests.

/pd:domain or
/proxydomain:domain

Sets the domain to use when connecting to a proxy server that requires authentication.

/pp:password or
/proxypassword:password

Sets the password to use when connecting to a proxy server that requires authentication.

/pu:username or
/proxyusername:username

Sets the username to use when connecting to a proxy server that requires authentication.

/server

Creates an abstract base class with the same interfaces as specified in the WSDL contract.

/u:username or
/username:username

Sets the username to use when connecting to a site that requires authentication.

/?

Provides help for command-line options.

Take the following steps to create proxy classes in Visual C# .NET for the HelloService and AuthorsService example Web services created earlier in this chapter.

Create proxy classes

  1. Open a command line and navigate to the directory where you would like the proxy classes to be generated. (Or use the /o option to specify a path and filename for saving the proxy class.)

  2. Execute the wsdl.exe utility, using the /l option to specify Visual C# .NET as the language and passing the URL to the HelloService.asmx file, including the ?WSDL parameter, which tells ASP.NET to return the WSDL contract for the .asmx file. (Both of the following lines should form a single command.) The URL you specify should match the location of the .asmx file on your Web server, and it might differ from the following URL.

    wsdl /l:cs /n:ASPNETSBS_CS http://localhost/Chapter11/Service1.asmx?WSDL
  3. Execute the wsdl.exe utility again for AuthorsService.asmx, using the same syntax as shown in step 2 but modifying the URL to point to AuthorsService.asmx.

  4. Optionally, you can create a batch file (with the .bat extension) containing both of the preceding commands. If you want to see the results of the batch execution before the command window closes, add a pause command at the end of the batch file. A batch file similar to this is included in the practice files for this chapter.

Once you’ve created your proxy class, you’ll need to compile the class using the command-line compiler for the language you chose to generate (in this example, Visual C# .NET). The following listing, MakeServices.bat, shows the command-line compiler syntax to compile these classes and output the resulting assembly to the bin subdirectory of the directory from which the command is run. For this example, this should be the bin subdirectory of the Chapter_11 project. Note that this listing represents a single command and has been wrapped to multiple lines for readability. A batch file similar to this is included in the practice files for this chapter.

MakeServices.bat

csc /t:library /r:System.Web.dll /r:System.dll /r:System.Web.Services.dll /r:System.Xml.dll /r:System.Data.dll /out:bin\Services.dll AuthorsService.cs Service1.cs 
Important 

By default, the .NET Framework and Visual Studio .NET setup programs do not add the paths to either wsdl.exe or csc.exe to the PATH environment variable. This means that to call these programs from the command line, you must either change directories to the location of the program before calling it (the technique used in the batch files contained in the practice files for the chapter), or you must add the program’s path to the PATH environment variable. Instructions for adding these paths to the PATH environment variable are found in Appendix C.

Consume a Web service from Visual Studio .NET

  1. Open the project for this chapter, Chapter_11, in Visual Studio .NET if it is not already open.

  2. Right-click on the root of the project in the Solution Explorer, and select Add Web Reference from the drop-down menu. The Add Web Reference dialog box will appear, as shown in the following illustration.

    Click To expand
  3. Type the URL to the AuthorsService.asmx file (if you followed the directions in this chapter, this should be http://localhost/Chapter_11/ AuthorsService.asmx) in the address text box, and click Go (you can also click Web Services On The Local Machine to browse for all local Web services, then select the AuthorsService service). The result should look similar to the illustration on the next page.

    Click To expand
  4. Click the Add Reference button at the bottom right-hand corner of the Add Web Reference dialog box. When the Add Web Reference dialog box closes, look in the Solution Explorer to find a new node named Web References. Under Web References, you’ll see a node added called localhost (assuming the URL entered in Step 2 was on the localhost domain). Expand that node (you might need to click the Show All Files button in the Solution Explorer toolbar first). The result should look similar to the following illustration.

  5. Right-click on localhost, and select Rename from the drop-down menu. Rename localhost to Authors.

    When you add a Web reference, Visual Studio .NET creates a folder with the same name as the Web reference under the Web References folder that is under the main project folder. There are several files created by Visual Studio .NET in this folder. Most interesting is Reference.cs (which is hidden by default), which contains the proxy code generated by Visual Studio for accessing the Web service.

  6. Add a new Web Form. Type the name of the new Web Form as ShowAuthors.aspx.

  7. Click and drag a DataGrid control from the toolbox to the surface of the page of ShowAuthors.aspx.

  8. Press F7 to change to code view. Scroll down to the Page_Load method, and then modify it so that it looks like the following code:

    private void Page_Load(object sender, System.EventArgs e  DataSet ds Authors.AuthorsService svc = new Authors.AuthorsService() ds = svc.GetAuthors() DataGrid1.DataSource = ds.Tables["Authors"] DataBind() }
  9. Save and build the project.

  10. Browse ShowAuthors.aspx using Internet Explorer. The output should look similar to the following illustration.

    Click To expand

One important thing to notice about this example is that while the table we are displaying is a Microsoft SQL Server table, we do not reference System.Data.SqlClient. We don’t have to because this application is not directly connecting to a SQL Server database. Rather, the application connects to the Web service created earlier (which returns a generic DataSet), and from there the Web service itself connects to SQL Server. Because the project already contains a reference to the System.Data namespace (which is added by default to all new projects), we don’t need to add any additional namespace references to use the dataset returned from the Web service.

How the Proxy Code Works

The magic behind consuming a Web service in Visual Studio .NET is not magic at all. Web services use a proxy class (just like the ones generated by the wsdl.exe utility) on the client end (in this case, the Web server) to provide access to the methods of the Web service. The proxy class is a class containing all of the methods exposed by the Web service. Rather than actual functionality (in our case, the code that connects to the SQL Server database), the proxy code descends from SoapHttpClientProtocol and calls out to the required Web method indirectly using its own Invoke method. The proxy class for the AuthorsService in the Chapter_11 project is called Reference.cs, and you can find it in the practice files for this chapter.

Tip 

It’s important to note that Web services clients are not limited to ASP.NET Web Forms. You can just as easily consume Web services from Windows Forms applications, Console applications, Windows Services, or even other Web services.

Additional Resources

Web Services are a useful tool, particularly for providing interoperability between functionality provided by different applications, and even on different platforms. But the technology and specifications behind Web Services are still in development. For this reason, it’s best to check for the latest information at sites such as the following:


Team LiB
Previous Section Next Section


JavaScript EditorJavascript debugger     Javascript examples