Consuming Existing Web Services

Keep in mind that code in an XML Web Service is object-oriented code. You don't actually write the code behind the Web Service on the machine consuming the Web Service, but you do need code that represents the Web Service code. Generating this code is the role of WSDL.

WSDL figures out the methods and types exposed by the Web Service and creates a proxy class for the Web Service. This proxy class permits Web Service consumersyou and meto refer to the methods and types exposed by the Web Service as if that code actually resided on our workstations.

When you add a reference to a Web Service, the WSDL technology adds a Web References folder to your project and a Reference.vb file to that folder. The Reference.vb file contains a class that inherits from System.Web. Services.Protocols.SoapHttpClientProtocol . This class contains proxy methods for invoking the Web methods defined by the Web Service. In addition, any types that are returned by the Web Service's methods are represented by wrapper classes. These wrapper classes are the client's view of the types returned by the Web Service.

Additionally, when you add a Web reference, a folder named Web References shows up in the Solution Explorer in Visual Studio .NET (Figure 13.2). This folder includes a namespace name that is the same as the Web Service host name. For example, when you implement a Web Service on your workstation and refer to that service, the namespace name is localhost . Files that show up in the Web References folder include .wsdl , .map , and .disco files. The .wsdl file describes the Web Service methods, types defined in the Web Service, and invocation information. The .map file contains the URL statements that return the .wsdl and .disco information, and the .disco file contains information used by UDDI to discover the Web Service.

Figure 13.2. The Web References folder in the Solution Explorer, with the localhost namespace name and Web Services mapping files.

graphics/13fig02.gif

Adding a Web Reference to Your Project

For our first example, I created a Web Service that returns a type named Commission . The Commission type is a very simple type that stores a trade amount and a commission rate and then calculates the commission as the product of the trade amount and the commission rate. The Web Service is defined in Commissions.sln , and the ConsumeWebService Windows application consumes the Web Service.

To add a Web reference to a project, perform the following steps.

  1. Open the Solution Explorer and select the project to which you want to add the Web Service.

  2. From the right-click context menu, select the Add Web Reference menu item. This will open the Add Web Reference dialog.

  3. Enter the host URL of the computer containing the Web Service. (In our example, the Web Service is on the same workstation; as a result, the URL to the Commissions Web Service is http://localhost/Commissions/Service1.asmx .)

  4. When you select the Web Service, the Add Reference button will become enabled (see Figure 13.1). Click Add Reference.

Now you are ready to create an instance of the Web Service, invoke operations on the methods defined in the Web Service, and use the types exported by the Web Service.

Declaring an Instance of the Web Service Class

When you have added a reference to a Web Service, the WSDL technology and the generated proxy class allow you to add an Imports statement to the Web Service and declare instances of the Web Service class, invoke operations on the Web methods, and use the types exported by the Web Service. You already know how to perform these basic operations, but I will repeat them here because the new context may be disorienting.

Listing 13.1 demonstrates a simple Windows application that shows you how to add an Imports statement and consume the Commissions Web Service.

Listing 13.1 A Windows Application That Consumes the Commissions Web Service
 1:  Imports ConsumeWebService.localhost 2: 3:  Public Class Form1 4:      Inherits System.Windows.Forms.Form 5: 6:  [ Windows Form Designer generated code ] 7: 8:    Private Service As Service1 = New Service1() 9: 10:   Private Sub Button1_Click(ByVal sender As System.Object, _ 11:     ByVal e As System.EventArgs) Handles Button1.Click 12: 13:     TextBox1.Text = Service.GetCommission(555).Rate.ToString 14: 15:   End Sub 16: End Class 

Line 1 shows how to add an Imports statement that refers to the host namespace added by the WSDL utility. Line 8 shows how to create an instance of the Web Service class. Note that this is precisely the same syntax you would use to create any instance of a class. Line 13 demonstrates an inline call to the Web method GetCommission . We could have declared a temporary variable of type Commission , assigned the result of GetCommission to that variable, and then assigned the rate value to the TextBox.Text property, but the behavior is the same.

Invoking Web Methods

Adding a reference to a Web Service permits you to declare types defined and exported by the Web Service and invoke methods in that service. Visual Studio .NET is an excellent tool, providing you with the same Intellisense information about Web Services, Web methods, and Web Service types that you get with classes defined in the .NET Framework.

The key to invoking a Web method is to determine the name of the method, prepare the method arguments, and respond to the return arguments. Of course, you can search the list of information provided by Intellisense to figure out the method signatures, or you can look at the XML in the WSDL file or the Reference.vb file. The XML in the WSDL file may be difficult to decipher, but the Reference.vb file is straightforward. Listing 13.2 shows the GetCommission Web method as it was generated by the WSDL utility.

Listing 13.2 The GetCommission Web Method Generated by the WSDL Utility
 Public Function GetCommission(ByVal ID As Long) As Commission   Dim results() As Object = _     Me.Invoke("GetCommission", New Object() {ID})   Return CType(results(0),Commission) End Function 

From the Reference.vb file it is clear that GetCommission accepts a Long integer and returns a Commission object. (Refer to the Creating a Web Service Application section later in this chapter for the code that implements the Commissions Web Service.)

Exploring the Web Service Proxy Class

We can consume Web Services without ever creating one, although as developers we will definitely want to create Web Services. The next section begins the discussion of creating Web Services. But first, indulge me for a moment longer while we complete our discussion of consuming Web Services.

There is more to explore about the Web Service proxy class. In Chapter 14 you will discover that the multithreading model in Visual Basic .NET supports calling Web methods asynchronously. Consequently the proxy class contains information for asynchronous calls to Web Services. Additionally, the proxy file contains classes that represent types exported by Web Services. Listing 13.3 (available in Commissions.sln ) shows these pieces of the Reference.vb proxy file.

Listing 13.3 The Proxy Code for the Commissions Web Service
 1:  '------------------------------------------------------------------ 2:  ' <autogenerated> 3:  '   This code was generated by a tool. 4:  '   Runtime Version: 1.0.3705.0 5:  ' 6:  '   Changes to this file may cause incorrect behavior and will be 7:  '   lost if the code is regenerated. 8:  ' </autogenerated> 9:  '------------------------------------------------------------------ 10: 11: Option Strict Off 12: Option Explicit On 13: 14: Imports System 15: Imports System.ComponentModel 16: Imports System.Diagnostics 17: Imports System.Web.Services 18: Imports System.Web.Services.Protocols 19: Imports System.Xml.Serialization 20: 21: ' 22: 'This source code was auto-generated by Microsoft.VSDesigner, 23: 'Version 1.0.3705.0. 24: ' 25: Namespace localhost 26: 27:   '<remarks/> 28:   <System.Diagnostics.DebuggerStepThroughAttribute(), _ 29:   System.ComponentModel.DesignerCategoryAttribute("code"), _ 30:   System.Web.Services.WebServiceBindingAttribute( _ 31:   Name:="Service1Soap", [Namespace]:="http://tempuri.org/")> _ 32:   Public Class Service1 33:     Inherits System.Web.Services.Protocols.SoapHttpClientProtocol 34: 35:     '<remarks/> 36:     Public Sub New() 37:       MyBase.New() 38:       Me.Url = "http://localhost/Commissions/Service1.asmx" 39:     End Sub 40: 41:     '<remarks/> 42:     <System.Web.Services.Protocols.SoapDocumentMethodAttribute( _ 43:     "http://tempuri.org/GetCommission", _ 44:     RequestNamespace:="http://tempuri.org/", _ 45:     ResponseNamespace:="http://tempuri.org/", _ 46:     Use:=System.Web.Services.Description.SoapBindingUse.Literal, _ 47:     ParameterStyle:= _ 48:     System.Web.Services.Protocols.SoapParameterStyle.Wrapped)> _ 49:     Public Function GetCommission(ByVal ID As Long) As Commission 50:       Dim results() As Object = Me.Invoke("GetCommission", _ 51:         New Object() {ID}) 52:       Return CType(results(0), Commission) 53:     End Function 54: 55:     '<remarks/> 56:     Public Function BeginGetCommission(ByVal ID As Long, _ 57:       ByVal callback As System.AsyncCallback, _ 58:       ByVal asyncState As Object) As System.IAsyncResult 59:         Return Me.BeginInvoke("GetCommission", New Object() {ID}, _ 60:           callback, asyncState) 61:     End Function 62: 63:     '<remarks/> 64:     Public Function EndGetCommission( _ 65:       ByVal asyncResult As System.IAsyncResult) As Commission 66:       Dim results() As Object = Me.EndInvoke(asyncResult) 67:         Return CType(results(0), Commission) 68:     End Function 69:   End Class 70: 71:   '<remarks/> 72:   <System.Xml.Serialization.XmlTypeAttribute( _ 73:   [Namespace]:="http://tempuri.org/")> _ 74:   Public Class Commission 75: 76:     '<remarks/> 77:     Public TradeAmount As Double 78: 79:     '<remarks/> 80:     Public Rate As Double 81:   End Class 82: End Namespace 

The Web Service proxy class for Service1 is defined in lines 28 to 69. The proxy class for the Commission type is defined in lines 72 through 81. The Service1 proxy class looks complicated but really contains only proxies for invoking methods in the Web Service marked with the WebMethodAttribute . We defined only one Web method. Then why so much code? Well, you have to remember that we are invoking operations across the Web, so we need extra information to marshal calls across a network.

In addition, there are actually three methods for each Web method. One method is used to make synchronous calls to our Web method, and the remaining pair of methods is used for the asynchronous invocation of our Web method. Thus, given a Web method named GetCommission , we can expect three methods in the proxy class: GetCommission , BeginGetCommission , and EndGetCommission . GetCommission is the synchronous proxy call and BeginGetCommission and EndGetCommission are used to make an asynchronous call. Hence, if you sift through the noise in Listing 13.3, you will quickly realize that the proxy class contains code to hide the additional information needed to marshal calls across a network, making Web Services easier to use.

The second part of the Reference.vb file contains proxy classes for types that we are exporting. These proxy classes are generated by the WSDL utility using the CodeDOM. In our example (Listing 13.3) we export a GetCommission method, which returns a custom type Commission . The Commission proxy class represents a fields-only version of our custom type. In Chapter 14 I will show you how to return a fat version of objects returned by Web methods. The skinny, fields-only proxy class will suffice for now.



Visual Basic. NET Power Coding
Visual Basic(R) .NET Power Coding
ISBN: 0672324075
EAN: 2147483647
Year: 2005
Pages: 215
Authors: Paul Kimmel

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net