Apply Your Knowledge





Apply Your Knowledge

Exercises

Calling a Web Service Asynchronously

Depending on the speed of your Internet connection, you may have noticed that the Web service client applications you constructed earlier in this chapter "freeze" when you invoke the Web service. By default these applications use synchronous methods to communicate with the Web service, waiting for the SOAP response before allowing any other code to execute. But the proxy classes constructed by .NET include asynchronous methods as well. In this exercise, you'll learn how to call a Web service asynchronously.

Estimated Time: 30 minutes.

  1. Create a Visual C# .NET Windows Application in the Visual Studio .NET IDE.

  2. Right-click the References folder in Solution Explorer and select Add Web Reference. The Add Web Reference dialog box appears.

  3. Type http://live.capescience.com/wsdl/AirportWeather.wsdl in the Address bar of the Add Web Reference dialog box and press Enter. This connects you to the StringProc Web service and creates the appropriate proxy classes.

  4. Click the Add Reference button.

  5. Add a new Windows form to your Visual C# .NET project.

  6. Place a Label control, a TextBox control (txtCode), a Button control (btnGetWeather), and a Listbox control (lbResults) on the form. Refer to Figure for the design of this form.

  7. Double-click the Button control and enter the following code to invoke the Web service when the user clicks the Get Weather button:

    
    private void btnGetWeather_Click(
    
        object sender, System.EventArgs e)
    
    {
    
        // Declare the Web service main object
    
        com.capescience.live.AirportWeather aw=
    
     new com.capescience.live.AirportWeather();
    
    
    
        // Invoke the Web service.
    
        // This may take some time, so
    
        // call it asynchronously.
    
        // First, create a callback method
    
        AsyncCallback wcb = new AsyncCallback(
    
           WebServiceCallback);
    
        // Initiate the asynchronous call
    
        aw.BegingetSummary(
    
            txtCode.Text, wcb, aw);
    
    }
    
    // This method will get called
    
    // when the Web service call is done
    
    public void WebServiceCallback(
    
        IAsyncResult ar)
    
    {
    
        // Retrieve the state of
    
        // the proxy object
    
        com.capescience.live.AirportWeather aw=
    
          (com.capescience.live.AirportWeather)
    
          ar.AsyncState;
    
    
    
        // Call the End method
    
        // to finish processing
    
        com.capescience.live.WeatherSummary ws=
    
            aw.EndgetSummary(ar);
    
    
    
        // And display the results
    
        lbResults.Items.Clear();
    
        lbResults.Items.Add(ws.location);
    
        lbResults.Items.Add(
    
            "Wind " + ws.wind);
    
        lbResults.Items.Add(
    
            "Sky " + ws.sky);
    
        lbResults.Items.Add(
    
            "Temperature " + ws.temp);
    
        lbResults.Items.Add(
    
            "Humidity " + ws.humidity);
    
        lbResults.Items.Add(
    
            "Barometer " + ws.pressure);
    
        lbResults.Items.Add(
    
            "Visibility " + ws.visibility);
    
    }
    
    
  8. Insert the Main() method to launch the form. Set the form as the startup object for the project.

  9. Run the project and enter a four-digit ICAO airport code. Click the Get Weather button. Wait a few moments; you will see the current weather at that airport in the list box. Note that while you're waiting, you can still drag the form around the screen, which shows that it is not blocked by the Web service call.

If you compare the code for this exercise with the code that you saw in Step-by-Step 4.1, you'll find some significant changes. In the .NET Framework, asynchronous Web service calls are managed by callback methods. When you add a Web reference, the proxy class includes Begin and End methods for each Web method. In this case, those are the BegingetSummary() and EndgetSummary() methods.

The Begin method takes all the same parameters as the underlying Web method, plus two others. The first is the address of a callback method, and the second is an object whose properties should be available in the callback method. When you call the Begin method, the .NET Framework launches the call to the Web service in the background. When the Web method call completes, the callback method is invoked. The code in this exercise shows how you can then retrieve the original object and use its End method to finish the work of using the Web service.

Using a Web Service from ASP.NET

Although the examples in this chapter were written as Windows applications, Web services work equally well when called from ASP.NET Web applications. In this exercise, you use ASP.NET to retrieve information from the Airport Weather Web service.

Estimated Time: 25 minutes.

  1. Create a new Visual C# .NET Web Application project.

  2. Right-click the References folder in Solution Explorer and select Add Web Reference. This opens the Add Web Reference dialog box.

  3. Type http://live.capescience.com/wsdl/AirportWeather.wsdl into the Address bar of the Add Web Reference dialog box and press Enter. This connects you to the Airport Weather Web service and creates the appropriate proxy classes.

  4. Click the Add Reference button.

  5. Add a new Web form to the project.

  6. Place a Label control, a TextBox control (txtCode), a Button control (btnGetSummary), and a ListBox control (lbResults) on the Web form in the project.

  7. Double-click the Button control and enter the following code to invoke the Web service when the user clicks the Get Weather button:

    
    private void btnGetWeather_Click(
    
       object sender, System.EventArgs e)
    
    {
    
        // Declare the Web service main object
    
        com.capescience.live.AirportWeather aw=
    
     new com.capescience.live.AirportWeather();
    
    
    
        // Invoke the service
    
        // to get a summary object
    
        com.capescience.live.WeatherSummary ws=
    
            aw.getSummary(txtCode.Text);
    
    
    
        // And display the results
    
        lbResults.Items.Clear();
    
        lbResults.Items.Add(ws.location);
    
        lbResults.Items.Add("Wind " + ws.wind);
    
        lbResults.Items.Add("Sky " + ws.sky);
    
        lbResults.Items.Add(
    
            "Temperature " + ws.temp);
    
        lbResults.Items.Add(
    
            "Humidity " + ws.humidity);
    
        lbResults.Items.Add(
    
            "Barometer " + ws.pressure);
    
        lbResults.Items.Add(
    
            "Visibility " + ws.visibility);
    
    }
    
    
  8. Set the Web form as the start page for the project.

  9. Run the project and fill in an airport code. Click the button. Wait a few moments, and the list box will show the details of the weather for that airport, as shown in Figure.

    15. You can also invoke a Web service from an ASP.NET application.

    graphics/04fig15.jpg

Review Questions

1:

What is the purpose of a Web service proxy class?

A1:

A Web service proxy class is an object that you can create on the client to communicate with a Web service. The proxy accepts messages, forwards them to the Web service, and returns the results of those messages.

2:

Describe the general purpose of SOAP.

A2:

SOAP is an XML-based protocol designed to exchange structured information on the Web. The purpose of SOAP is to enable Web services based on the Web infrastructure such as HTTP, SMTP, and so on.

3:

Describe the general purpose of Disco and UDDI.

A3:

Disco and UDDI are designed to help discover the interface details of a Web service.

4:

Describe the general purpose of WSDL.

A4:

WSDL exists to supply information on the interface of a Web service.

5:

Can a Web service exist without a WSDL file?

A5:

A Web service can exist without a WSDL file, but you must then know the exact incoming SOAP message that the Web service expects before you can use it.

6:

Explain two ways in which you can create proxy classes for a Web service.

A6:

You can create proxy classes for a Web service by using the disco.exe and wsdl.exe tools or by creating a Web reference within Visual Studio .NET.

7:

List three steps involved in using Visual Studio .NET to build a Web service.

A7:

To build a Web service you must create a new Web service application, mark the classes to be exposed with the [WebService] attribute, and mark the methods to be exposed with the [WebMethod] attribute.

8:

What tools can you use to make local copies of the configuration files for a Web service?

A8:

The disco.exe tool makes local copies of the configuration files for a Web service. Creating a new Web reference also creates these files.

9:

How can you test a Web service without building a client application?

A9:

You can use a tool such as .NET WebService Studio to test a Web service without building a client application. You can also use Microsoft Internet Explorer to test Web services using the HTTP GET protocol.

10:

What is the advantage of sending SOAP messages over the HTTP?

A10:

Using HTTP as the transport protocol for SOAP messages means that the messages can take advantage of pervasive Internet connectivity to reach their destination; they are not blocked by firewalls.

Exam Questions

1:

You want to use a Web service that supplies inventory level information in your application. You know the URL of the .asmx file published by the Web service. What step should you take first?

  1. Open the .asmx file in a Web browser.

  2. Run the XML Schema Definition tool.

  3. Run the Web Services Discovery tool.

  4. Copy the .asmx file to your client project.

A1:

C. The Web Services Discovery tool retrieves copies of the files that you need to proceed with this project. For more information, see the section "Discovering Web Services" in this chapter.

2:

Your application includes a Web reference to a Web service that delivers customer information as an object with multiple properties. The developer of the Web service has added a new property named CreditRating to the object. What should you do to be able to use the CreditRating property in your code?

  1. Create an entirely new client application, and add a Web reference for the Web service to the new application.

  2. Delete and re-create the Web reference in the existing application.

  3. Update the Web reference in the existing application.

  4. Use a generic Object variable to hold customer information, so you can call any property you like.

A2:

C. The Update Web Reference menu item for a Web reference refreshes local configuration information from the server that hosts the Web service. For more information, see the section "Using Web References" in this chapter.

3:

You have used ASP.NET to create a Web service that returns financial information. One of the methods in your Web service is defined with this code:


public Double Cash()

{

    // Calculations omitted

}

Potential consumers of your Web service report that although they can set a reference to the Web service, the Cash() method is not available. What could be the problem?

  1. The .asmx file for the Web service is not available on your Web server.

  2. The Web service class is not marked with the [WebService] attribute.

  3. The Cash() method is not marked with the [WebMethod] attribute.

  4. Web services can return only string values.

A3:

C. All exposed methods of a Web service must be marked with the [WebMethod] attribute. For more information, see the section "Creating Web Services" in this chapter.

4:

You have created a new Web service to perform financial calculations. You're working in an ASP.NET project within Visual Studio .NET. What's the easiest way to test your new Web service to make sure that it's returning the proper results?

  1. Cut and paste the code into a Windows application project and test it in the new project.

  2. Run the Web service project and use the test page that it opens in the browser.

  3. Use a tool such as .NET WebService Studio to send SOAP requests directly to the server.

  4. Have a large number of beta testers use the application, and monitor the server for odd behavior.

A4:

B. When you're creating a Web service in ASP.NET, running the project opens a testing form in a browser window. For more information, see the section "Testing a Web Service" in this chapter.

5:

Your application uses a Web service named Northwind. The Northwind Web service includes a Web method named Suppliers() that returns a DataSet containing all the company's suppliers. What data type should you use to declare an object to hold the result of the Suppliers() method?

  1. Suppliers.DataSet

  2. DataSet

  3. Northwind.DataSet

  4. DataRow[]

A5:

B. The client needs to declare the same data type that the server is returning, in this case the DataSet object. For more information, see the section "Testing the Web Service Project" and Guided Practice Exercise 4.1 in this chapter.

6:

You're using the Web Services Discovery tool to determine information about a Web service on a particular server. You receive the error message The HTML document does not contain Web service discovery information. What could be the problem?

  1. The server address that you typed does not exist.

  2. The server requires authentication and you have entered improper credentials.

  3. The Web Services Discovery tool works only on your local computer.

  4. There is no WSDL or Disco file available at the address that you typed.

A6:

D. The Web Services Discovery tool requires the URL to a Disco or WSDL file in order to function. For more information, see the section "Using the Web Services Discovery Tool (disco.exe)" in this chapter.

7:

You are using the Web Services Description Language tool to create a proxy class for a Web service. The Web service exposes a class named Customer. You already have a Customer class in your application. What should you do to allow both classes to coexist in the same application?

  1. Use the /namespace option of the Web Services Description Language tool to specify a unique namespace for the new class.

  2. Rename the existing class.

  3. Use the /out option of the Web Services Description Language tool to specify a unique output file name for the new class.

  4. Manually edit the generated proxy class to change the classname that it contains.

A7:

A. Specifying a unique namespace for the new object removes the chance that it can clash with a pre-existing object name. For more information, see the section "Creating Proxy Classes with the Web Services Description Language Tool (wsdl.exe)" in this chapter.

8:

You have used a UDDI registry to locate a Web service that might be able to supply information for your business. You want to test the interface of the Web service to make sure that it meets your requirements before you invest the effort to build a client application. How should you proceed?

  1. Use the Web Services Discovery tool to download the WSDL file for the Web service and inspect it in an XML editor.

  2. Use the Web Services Description Language tool to create a proxy class for the Web service and to use a text editor to inspect the class.

  3. Craft SOAP messages in an XML editor and use them to test the Web service.

  4. Use a tool such as the .NET WebService Studio to test the Web service's interface.

A8:

D. By using an automated tool you can avoid tedious and error-prone inspection of XML files. For more information, see the section "Testing a Web Service" in this chapter.

9:

Your application calls a Web service that performs complex, time-consuming calculations. Users complain that the user interface of the application freezes while it's recalculating. Which of the following approaches is guaranteed to solve this problem?

  1. Move the application to a faster computer.

  2. Install a faster link to the Internet.

  3. Install more memory in the computer.

  4. Use asynchronous calls to invoke the Web service.

A9:

D. Speeding up the client computer will do nothing to speed up the Web service, which runs on the server computer. For more information, see the section "Invoking Your First Web Service" and Exercise 4.1 in this chapter.

10:

One of your partner businesses has informed you that it is making its inventory information available via a Web service. You do not know the Web service's URL. How can you discover the URL?

  1. Use the Web Services Discovery tool to download the information.

  2. Use the Web Services Description Language tool to create a proxy class.

  3. Use a UDDI registry to locate the Web service.

  4. Use a search engine to explore your partner's Web site.

A10:

C. UDDI registries exist so that you can find business services by browsing or searching. For more information, see the section "Disco and UDDI" in this chapter.

11:

What must a developer do to make a Web service built with Visual Studio .NET available asynchronously?

  1. Nothing. The client can always call a Web service asynchronously.

  2. Use a separate Thread object for each invocation of the Web service.

  3. Provide callback methods to invoke the Web service.

  4. Host the Web service on an Internet Information Server 6.0 server.

A11:

A. Building the proxy class, either with wsdl.exe or by setting a Web reference, automatically creates methods to invoke the Web service asynchronously. For more information, see the section "Instantiating and Invoking Web Services" and Exercise 4.1 in this chapter.

12:

You are invoking a Web service that returns a DataSet object. Your client application is written in Visual C# .NET, whereas the Web service itself is written in Visual Basic .NET. The Web service is outside of your corporate firewall. You receive an object not found error when you call the method that returns the DataSet. What could be the problem?

  1. The client project and the Web service project must use the same language.

  2. Objects supplied by a Web service cannot cross a firewall.

  3. The client project does not contain a reference to the System.Data namespace.

  4. Web services cannot properly serialize a complex object such as the DataSet object.

A12:

C. Web services client and server applications must agree on the definition of the data to be exchanged. For more information, see the section "Instantiating and Invoking Web Services" in this chapter.

13:

Your application invokes a Web service named Northwind that includes a Web method named GetOrders(). GetOrders() returns a DataSet object containing order information. What must you do to use this DataSet object in your client application?

  1. Create a new DataSet object and use the ReadXml() method of the DataSet object to initialize it from the returning SOAP message.

  2. Obtain an XSD file that specifies the schema of the DataSet object. Use this XSD file to instantiate a DataSet object from the returned data from the GetOrders() method.

  3. Assign the return value from the GetOrders() method to an array of DataRow variables. Loop through the array to build the DataSet.

  4. Assign the return value from the GetOrders() method to a DataSet variable.

A13:

D. The only thing you need to do to use a complex variable returned by the Web service is to declare an instance of the same data type in the client application. For more information, see the section "Instantiating and Invoking Web Services" in this chapter.

14:

You have used the Web Services Discovery tool to retrieve information about a Web service named ZipcodeService. Which file will contain the URL for any documentation of the ZipcodeService Web service?

  1. disco.exe

  2. results.discomap

  3. ZipcodeService.wsdl

  4. ZipcodeService.disco

A14:

D. The Disco (.disco) file is the only one that contains pointers to non-XML resources. For more information, see the section "Discovering Web Services" in this chapter.

15:

You have used the Web Services Description Language tool to create a proxy class for a Web service. When you add the proxy class to your project, you discover that it is coded in the Visual Basic .NET language. What must you do to get the proxy class in Visual C# .NET instead of Visual Basic .NET?

  1. Manually convert the Visual Basic .NET code to C# code.

  2. Rerun the tool, using the /language:CS option.

  3. Rerun the tool, using the /namespace:CS option.

  4. Select File, Save As and save the file with the .cs extension.

A15:

B. The /language option controls the output language of the wsdl.exe tool. For more information, see the section "Creating Proxy Classes with the Web Services Description Language Tool (wsdl.exe)" in this chapter.

Suggested Readings and Resources

1. Visual Studio .NET Combined Help Collection.

2. .NET Framework SDK Documentation, including "XML Web Services Created Using ASP.NET and XML Web Service Clients."

3. Kenn Scribner & Mark C. Stiver. Applied SOAP: Implementing .NET XML Web Services. Sams, 2001.

4. Scott Short. Building XML Web Services for the Microsoft .NET Platform. Microsoft Press, 2002.

5. Eric Newcomer. Understanding Web Services: XML, WSDL, SOAP, and UDDI. Addison-Wesley, 2002.


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows