Consuming a Web Service Synchronously


ASP.NET Developer's JumpStart
By Paul D. Sheriff, Ken Getz
Table of Contents
Chapter 30.  Investigating Web Service Consumers

In this section, you'll create a standard synchronous Web Service consumer. You'll also investigate how the proxy class makes it look like you're working with a local object and its methods when you make method calls in the Web Service.

The Sample Web Service

For this example, you'll modify the InventoryService Web Service you created in the previous chapter. This service provides a simple UnitsInStock method, which returns the available inventory for a product matching the ProductID value your method call supplies. In the following steps, you'll add code that causes the method to delay 10 seconds before returning its value to simulate the behavior of a Web Service that takes measurable time to do its work.

Follow these steps to slow down your Web Service method:

  1. In Visual Studio .NET, load the InventoryService project you created in the previous chapter. You should be able to locate the project in the Jumpstart\InventoryService folder.

  2. View the code for the Inventory.asmx file.

  3. Modify the code in the UnitsInStock procedure so that it looks like this (we only show a few lines of code here to indicate the context for the new line of code):

     cmd = New OleDbCommand(strSQL, cnn) UnitsInStock = cmd.ExecuteScalar() ' Wait for a few seconds... System.Threading.Thread.Sleep(10000) 

To call this Web Service method, you pass in a product ID, and the method returns the number of items currently in inventory.

The code that you've added pauses the thread for 10 seconds. This code uses the shared Sleep method of the Thread object provided by the .NET Framework, emulating a long-running Web Service method.


A thread is a single path of execution within an application. Each application must contain at least one thread, and many applications use more than one thread to do their work. Your Web Service only uses one thread, unless you write code that creates more, and the call to Thread.Sleep causes the single thread in use to block for the specified number of milliseconds. The outcome of this is that the caller, waiting for a response from this method, waits for 10 seconds for the function's return value. You won't normally add code to your applications to slow them down, but in this case, it helps test the concept of asynchronous Web Service consumer applications.

To verify that the sample Web Service works, follow these steps:

  1. Press F5 to run the project.

  2. Click the UnitsInStock link on the page that's displayed.

  3. On the test page, enter a number between 1 and 15 or so in the text box, click the Invoke button, and verify that 10 seconds or so later, you get the available inventory for the item you requested.

  4. Save your project.

Calling the Web Service

To create the sample page, for both this section and the next, follow these steps:

  1. Create a new ASP.NET Web Application project. Set the location to Jumpstart\AsyncConsumer.

  2. Add the controls shown in Figure 30.1 to the Webform1.aspx page. Set properties for these controls as shown in Table 30.1.

    Figure 30.1. Your sample page should look like this.


    Table 30.1. Set These Control Properties on the Sample Page
    Control Property Value
    Label Text Product ID:
    TextBox ID txtProductID
      Text 1
    Button ID btnSync
      Text Get Inventory (Sync)
    Button ID btnAsync
      Text Get Inventory (Async)
    Label ID lblResults

  3. Add a Web reference to your project, referring to the InventoryService Web Service you modified in the previous section.

  4. Select the Project, Add Web Reference menu item and enter the address for the InventoryService Web Service, using this address:

  5. Select the Add Reference button once you've found the Web Service.

  6. Right-click the name of the newly added Web Service, select Rename from the context menu, and rename the service to InventoryService.

  7. Select the Project, Show All Files menu item so that you can view all the files added to your project.

  8. Next, you'll add code to your page, calling the newly added Web Service. To begin, double-click btnSync and modify the btnSync_Click procedure, adding the following procedure call:

  9. Add the TestSync procedure, shown in Listing 30.1, to your class.

    Listing 30.1 Add Code to Handle the Synchronous Call to the Web Service
     Private Sub TestSync()   Dim ws As New InventoryService.Inventory()   Dim intResults as Integer   Dim intProductID as Integer   intProductID = CInt(txtProductID.Text)   intResults = ws.UnitsInStock(intProductID)   lblResults.Text = FormatResults( _    intProductID, intResults) End Sub 
  10. Add the FormatResults procedure shown in Listing 30.2, which formats the item number and inventory for display on the page (and for the Event Log item, later).

    Listing 30.2 Format the Results Using This Procedure
     Private Function FormatResults(ByVal Item As Integer, _  ByVal ItemCount As Integer) As String   Dim blnSingular As Boolean   ' Format the results.   blnSingular = (ItemCount = 1)   Dim strResults As String = _    String.Format( _    "There {0} currently {1} {2} of item {3} in stock.", _    IIf(blnSingular, "is", "are"), _    ItemCount, _    IIf(blnSingular, "unit", "units"), Item)   Return strResults End Function 


    The FormatResults function you just added doesn't do much besides "prettify" the output. It accepts the item number and the item count as parameters and then creates a string such as "There are currently 4 units of item 12 in stock." The code takes into account the embarrassing singular versus plural issue.

  11. Finally, you can test the page. Press F5 to run the project.

  12. Enter a value into the Product ID text box, click Get Inventory (Sync), and wait for the response. After 10 seconds or so, you should see the results displayed in the Label control on the page.

  13. Close the Browser window and save your project.

What's Going On?

If you look carefully at the code in the btnSync_Click procedure, you'll see that you're creating an instance of the InventoryService.Inventory class:

 Dim ws As New InventoryService.Inventory() 

Where did that namespace and class come from? They're both provided by the proxy class created for you when you added the Web reference. To check it out, open the Reference.vb file, hidden as a code-behind file for in the Solution Explorer.


You won't see Reference.vb in the Solution Explorer if you didn't select the Project, Show All Files menu item. If you can't find Reference.vb, make sure you show all the files first.

If you investigate the Reference.vb file, you'll find code like this:

 Namespace InventoryService   Public Class Inventory     Inherits System.Web.Services.Protocols. _      SoapHttpClientProtocol 

(Note that we've removed the distracting procedure attributes, which don't add much to our explanation here.) As you can see, the file provides a namespace (InventoryService) and a class (Inventory). The class inherits from SoapHttpClientProtocol, so it can call any of the methods provided by that base class. This will be important, in just a few paragraphs.

Because your project includes a file that creates the namespace and class, your code can refer to InventoryService.Inventory as if that were a local object, because it is. Even though it looks like you're referring to the Web Service class, you're actually working with the local class (often called a proxy class, because it stands in place of, as a proxy, for the real Web Service).

Now let's get back to the procedure you added. Next, the procedure calls the UnitsInStock method of the proxy class, like this:

 lblResults.Text = ws.UnitsInStock( _  CInt(txtProductID.Text)).ToString 

Looking in the proxy class, you'll find a UnitsInStock procedure, like this (again, we've removed procedure attributes that affect how SOAP handles the procedure, but that doesn't affect anything at the moment):

 Public Function UnitsInStock( _ ByVal ProductID As Integer) As Integer   Dim results() As Object = _    Me.Invoke("UnitsInStock", New Object() {ProductID})   Return CType(results(0), Integer) End Function 

This method, which is actually what your code is calling, calls the Invoke method provided by the base class (SoapHttpClientProtocol), which uses the URL provided in the class's constructor to call the actual Web Service method:

 Public Sub New()   MyBase.New()   Me.Url = _    http://localhost/jumpstart/inventoryservice/" & _    "inventory.asmx" End Sub 

The Invoke method expects that you'll pass it two parameters:

  • The name of the method to call (UnitsInStock, in this case).

  • An array of Objects, containing the parameters to be passed to the method. In this case, it's just an array with a single element the ProductID value passed as a parameter to the procedure.

The Invoke method returns an array of Objects, and the UnitsInStock method retrieves the first item in the array (index 0), converts it to a Short, and returns the value as its return value.

As you can see, when you instantiate and make a call to a Web Service method, you're actually instantiating a local object and calling a method of that object that knows how to call the Web Service for you. This proxy class makes your interaction with the Web Service much simpler.


    ASP. NET Developer's JumpStart
    ASP.NET Developers JumpStart
    ISBN: 0672323575
    EAN: 2147483647
    Year: 2002
    Pages: 234 © 2008-2017.
    If you may any questions please contact us: