Understanding Web Services



Understanding Web Services

Create and consume an XML Web service.

  • Instantiate and invoke an XML Web service.

Before I get into the nuts and bolts of actually working with Web services, I'll give you an overview of the way they work. The key to understanding Web services is to know something about the protocols that make them possible:

  • Simple Object Access Protocol (SOAP)

  • Disco and Universal Description, Discovery, and Integration (UDDI)

  • Web Services Description Language (WSDL)

NOTE

Naming Web Services As with many rapidly-developing technologies, different companies use different names for Web services. Some prefer the capitalized form "Web Services," and others use the explicit "XML Web Services." In this book, I've gone along with the MCAD exam objectives guide, which calls them "Web services."


One important thing to realize is that, by default, all communication between Web services servers and their clients is through Extensible Markup Language (XML) messages transmitted over the Hypertext Transfer Protocol (HTTP) protocol. This has two benefits. First, because Web services messages are formatted as XML, they're reasonably easy for human beings to read and understand. Second, because those messages are transmitted over the pervasive HTTP, they can normally reach any machine on the Internet without being blocked by firewalls.

SOAP

For Web services to manipulate objects through XML messages, there has to be a way to translate objects (as well as their methods and properties) into XML. SOAP is a way to encapsulate object calls as XML sent via HTTP.

EXAM TIP

SOAP over Other Protocols You often read that SOAP messages travel over HTTP. Although this is the default for SOAP as implemented by Visual Studio .NET, it's not a part of the SOAP specification. SOAP messages could be sent by email or File Transfer Protocol (FTP) without losing their content. As a practical matter, SOAP today uses HTTP in almost all cases.


There are two major advantages to using SOAP to communicate with Web services. First, because HTTP is so pervasive, it can travel to any point on the Internet, regardless of intervening hardware or firewalls. Second, because SOAP is XML based, it can be interpreted by a wide variety of software on many operating systems. Although you'll only work with the Microsoft implementation of Web services in this chapter, numerous Web services tools from other vendors can interoperate with Microsoft-based Web services.

Here's a typical SOAP message sent from a Web services client to a Web services server:


<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope

  xmlns:soap=

    "http://schemas.xmlsoap.org/soap/envelope/"

  xmlns:soapenc=

    "http://schemas.xmlsoap.org/soap/encoding/"

  xmlns:tns=

    "http://www.capeclear.com/AirportWeather.wsdl"

  xmlns:types="http://www.capeclear.com/

    AirportWeather.wsdl/encodedTypes"

  xmlns:xsi=

    "http://www.w3.org/2001/XMLSchema-instance"

  xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <soap:Body soap:encodingStyle=

    "http://schemas.xmlsoap.org/soap/encoding/">

    <q1:getLocation

      xmlns:q1="capeconnect:AirportWeather:Station">

      <arg0 xsi:type="xsd:string">KSEA</arg0>

    </q1:getLocation>

  </soap:Body>

</soap:Envelope>

Even without digging into this file in detail, you can see some obvious points:

  • The SOAP message consists of an envelope and a body, each marked with a specific XML tag.

  • This particular message invokes a method named getLocation() from a specified uniform resource locator (URL).

  • The method takes a single parameter, arg0, which is transmitted as an XML element.

Here's the SOAP message that comes back from the server:


<?xml version="1.0" encoding="utf-8"?>

<SOAP-ENV:Envelope

  xmlns:SOAP-ENV=

     "http://schemas.xmlsoap.org/soap/envelope/"

  xmlns:xsd="http://www.w3.org/2001/XMLSchema"

  xmlns:cc1=

    "http://www.capeclear.com/AirportWeather.xsd"

  xmlns:xsi=

    "http://www.w3.org/2001/XMLSchema-instance"

  xmlns:SOAP-ENC=

     "http://schemas.xmlsoap.org/soap/encoding/">

  <SOAP-ENV:Body SOAP-ENV:encodingStyle=

    "http://schemas.xmlsoap.org/soap/encoding/">

    <cc2:getLocationResponse

      xmlns:cc2="capeconnect:AirportWeather:Station"

      SOAP-ENC:root="1">

      <return xsi:type="xsd:string">

        Seattle, Seattle-Tacoma International Airport,

        WA, United States</return>

    </cc2:getLocationResponse>

  </SOAP-ENV:Body>

</SOAP-ENV:Envelope>

In the response message, the getLocationResponse element is the result of the call to the object on the server. It includes a string wrapped up as an XML element.

Disco and UDDI

Before you can use a Web service, you need to know where to find the service. Handling such requests is the job of several protocols, including Disco and UDDI. These protocols enable you to communicate with a Web server to discover the details of the Web services that are available at that server. You'll learn more about these protocols later in the chapter.

WSDL

Another prerequisite for using a Web service is knowledge of the SOAP message types that it can receive and send. You can obtain this knowledge by parsing WSDL files. WSDL is a standard by which a Web service can tell clients what messages it accepts and which results it will return.

Here's a portion of a WSDL file:


<?xml version="1.0" encoding="utf-16"?>

<definitions

  xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"

  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

  xmlns:s="http://www.w3.org/2001/XMLSchema"

  xmlns:s0=

    "http://www.capeclear.com/AirportWeather.xsd"

  xmlns:soapenc=

    "http://schemas.xmlsoap.org/soap/encoding/"

  xmlns:tns=

     "http://www.capeclear.com/AirportWeather.wsdl"

  xmlns:tm=

     "http://microsoft.com/wsdl/mime/textMatching/"

  xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"

  targetNamespace=

    "http://www.capeclear.com/AirportWeather.wsdl"

  name="AirportWeather"

  xmlns="http://schemas.xmlsoap.org/wsdl/">

  <types>

    <s:schema targetNamespace=

      "http://www.capeclear.com/AirportWeather.xsd">

      <s:complexType name="WeatherSummary">

        <s:sequence>

          <s:element minOccurs="1" maxOccurs="1"

            name="location" nillable="true"

            type="s:string" />

          <s:element minOccurs="1" maxOccurs="1"

            name="wind" nillable="true"

            type="s:string" />

          <s:element minOccurs="1" maxOccurs="1"

            name="sky" nillable="true"

            type="s:string" />

          <s:element minOccurs="1" maxOccurs="1"

            name="temp" nillable="true"

            type="s:string" />

          <s:element minOccurs="1" maxOccurs="1"

            name="humidity" nillable="true"

            type="s:string" />

          <s:element minOccurs="1" maxOccurs="1"

            name="pressure" nillable="true"

            type="s:string" />

          <s:element minOccurs="1" maxOccurs="1"

            name="visibility" nillable="true"

            type="s:string" />

        </s:sequence>

      </s:complexType>

    </s:schema>

  </types>

  <message name="getHumidity">

    <part name="arg0" type="s:string" />

  </message>

  <message name="getHumidityResponse">

    <part name="return" type="s:string" />

  </message>

  <message name="getLocation">

    <part name="arg0" type="s:string" />

  </message>

  <message name="getLocationResponse">

    <part name="return" type="s:string" />

  </message>

  <message name="getOb">

    <part name="arg0" type="s:string" />

  </message>

...

</definitions>

EXAM TIP

Exposure Is Optional Although UDDI and WSDL files make it possible to interact with Web services without any prior knowledge, these files are not required for a Web service to function. You can make a Web service available on the Internet without any UDDI or WSDL file. In that case, only clients who know the expected message formats and the Web service's location are able to use it.


WSDL files define everything about the public interface of a Web service, including the following:

  • The data types that it can process

  • The methods that it exposes

  • The URLs through which those methods can be accessed

Invoking Your First Web Service

At this point, I'd like to show you a Web service in action. Step-by-Step 4.1 shows how you can use a Web service, in this case one that supplies the weather at any airport worldwide.

WARNING

Working with the Internet Most of the examples in this chapter assume that you're working on a computer that is connected to the Internet. It's okay if there's a proxy server between you and the Internet, as long as you can connect to Web sites.


STEP BY STEP

4.1 Invoking a Web Service

  1. Create a new Visual C# .NET Windows application in the Visual Studio .NET Integrated Development Environment (IDE). Name the project 320C04.

    NOTE

    Airport Codes You can find a list of four-letter ICAO airport codes to use with this Web service at www.house747.freeserve.co.uk/aptcodes.htm. Codes for airports in the United States all start with K; codes for Canadian airports all start with C.

  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 in the Address bar of the Add Web Reference dialog box and press Enter. This connects you to the Airport Weather Web service and downloads the information shown in Figure.

    1. The Add Web Reference dialog box enables you to connect to a Web service over the Internet.

    graphics/04fig01.jpg

    WARNING

    Web Service Stability Web services come and go, and there's no guarantee that the one I'm using in this chapter will still be available when you go to test it. If the Airport Weather Web service doesn't seem to be available, one good way to find others is to use your favorite search engine to look for the term "Web service examples." You can also search for Web services through public UDDI directories such as, uddi.microsoft.com and uddi.ibm.com.

  4. Click the Add Reference button.

  5. In the Solution Explorer, rename the default Form1.cs to StepByStep4_1.cs. Open the form in code view and change all occurrences of Form1 to refer to StepByStep4_1 instead.

  6. Place a Label control, a TextBox control (txtCode), a Button control (btnGetSummary), and a ListBox control (lbResults) on the form. Figure shows the design of the form.

    2. Design of a form that invokes an Airport Weather Web service.

    graphics/04fig02.jpg

  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);
    
    }
    
    

    NOTE

    IntelliSense with Web Services You'll see as you type this code that IntelliSense operates even though the objects you're working with are on the remote server.

  8. 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. After a brief pause while the Web service is invoked, you see the current weather at that airport in the list box, as shown in Figure. This information is delivered from the server where the Web service resides, as properties of the WeatherSummary object.

    3. You can invoke a remote Web service and access the objects returned by the Web service.

    graphics/04fig03.jpg

You'll learn more about the techniques in Step by Step 4.1 in the rest of the chapter, but you should be able to see the broad outlines of Web services already. In one sense, there's not much new here, compared to invoking any other object. After you've set a reference to the server, you can create objects from that server, invoke their methods, and examine the results. You could do the same with objects from a .NET library on your own computer.

But in another sense, there's a lot of revolutionary work going on here, even though you don't see most of it happening. When you create the Web reference, for example, Visual Studio .NET reads the appropriate WSDL file to determine which classes and methods are available from the remote server. When you call a method on an object from that server, the .NET infrastructure translates your call and the results into SOAP messages and transmits them without any intervention on your part.

Depending on the speed of your Internet connection, you may notice that the Web service client that you created in Step-by-Step 4.1 "freezes" when you invoke the Web service. This program uses a synchronous method to communicate with the Web service, waiting for the SOAP response before allowing any other code to execute. You will learn later in this chapter, in Exercise 4.1 and in Chapter 5, "Advanced Web Services," how to call a Web service asynchronously to increase the responsiveness of the client program.

REVIEW BREAK

  • Web services provide you with the means to create objects and invoke their methods even though your only connection to the server is via the Internet.

  • Communication with Web services is via XML messages transported by the HTTP.

  • Because they communicate over HTTP, Web services are typically not blocked by firewalls.

  • The Simple Object Access Protocol (SOAP) encapsulates object-oriented messages between Web service clients and servers.

  • The Universal Description, Discovery, and Integration (UDDI) protocol enables you to find Web services by connecting to a directory.

  • The Web Services Description Language (WSDL) lets you retrieve information on the classes and methods that are supported by a particular Web service.