Flylib.com

Books Software

 
 
 

15.7 SOAP, WSDL, and Discovery

15.7 SOAP, WSDL, and Discovery

What is needed to make web services possible is a simple, universally accepted protocol for exposing, finding, and invoking web service functions. In 1999, Simple Object Access Protocol (SOAP) was proposed to the World Wide Web Consortium. SOAP has the advantages of being based on XML and of using standard Internet communications protocols.

SOAP is a lightweight, message-based protocol built on XML, HTTP, and SMTP. Two other protocols are desirable, but not required, for a client to use a SOAP-enabled web service: a description of the methods provided by a particular service that can be understood and acted upon by clients , and a description of all such services available at a particular site or URL. The first of these is provided in .NET by the Web Service Description Language (WSDL) protocol, jointly developed by Microsoft, IBM, and others. Two other protocols have been proposed for discovery: UDDI, a joint effort by a number of companies including IBM and Microsoft, and Discovery, a proprietary offering from Microsoft.

WSDL is an XML schema used to describe the available methods—the interface—of a web service. Discovery enables applications to locate and interrogate web service descriptions, a preliminary step for accessing a web service. It is through the discovery process that web service clients learn that a service exists, what its capabilities are, and how to properly interact with it. A Discovery ( .disco ) file provides information to help browsers determine the URLs at any web site at which web services are available. When a server receives a request for a .disco file, it generates a list of some or all of the URLs at that site that provide web services.

15.7.1 Server-Side Support

The plumbing necessary to discover and invoke web services is integrated into the .NET Framework and provided by classes within the System.Web.Services namespace. Creating a web service requires no special programming on your part; you need only write the implementing code, add the [WebMethod] attribute, and let the server do the rest. You can read about attributes in detail in Chapter 18.

15.7.2 Client-Side Support

You make use of a web service by writing client code that acts as though it were communicating directly with the host server by means of a URL. However, in reality, the client interacts with a proxy . The job of the proxy is to represent the server on the client machine, to bundle client requests into SOAP messages that are sent on to the server, and to retrieve the responses that contain the result. Proxies and the details of dealing with objects on other machines are covered in detail in Chapter 19.

15.8 Building a Web Service

To illustrate the techniques used to implement a web service in C# using the services classes of the .NET Framework, build a simple calculator and then make use of its functions over the Web.

Begin by specifying the web service. To do so, define a class that inherits from System.Web.Services.WebService . The easiest way to create this class is to open Visual Studio and create a new C# Web Service project. The default name that Visual Studio provides is WebService1 , but you might want to choose something more appropriate.

Visual Studio .NET creates a skeleton web service and even provides a Web Service example method for you to replace with your own code, as shown in Example 15-4.

Example 15-4. Skeleton web class generated by Visual Studio .NET
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;

namespace WSCalc

{
    /// <summary>
    /// Summary description for Service1.
    /// </summary>
    public class Service1 : System.Web.Services.WebService
    {
        public Service1( )
        {
            //CODEGEN: This call is required by
            // the ASP.NET Web Services Designer
            InitializeComponent( );
        }

        #region Component Designer generated code
        
        //Required by the Web Services Designer 
        private IContainer components = null;
                
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent( )
        {
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if(disposing && components != null)
            {
                components.Dispose( );
            }
            base.Dispose(disposing);        
        }
        
        #endregion

        // WEB SERVICE EXAMPLE
        // The HelloWorld( ) example service
        // returns the string Hello World
        // To build, uncomment the following lines
        // then save and build the project
        // To test this web service, press F5

//        [WebMethod]
//        public string HelloWorld( )
//        {
//            return "Hello World";
//        }
    }
}

Create five methods : Add( ) Sub( ) , Mult( ) , Div( ) , and Pow( ) . Each takes two parameters of type double , performs the requested operation, and then returns a value of the same type. For example, here is the code for raising a number to some specified power:

public double Pow(double x, double y)
{
   double retVal = x;
   for (int i = 0;i < y-1;i++)
   {
      retVal *= x;
   }
   return retVal;
}

To expose each method as a web service, you simply add the [WebMethod] attribute before each method declaration:

[WebMethod]

You are not required to expose all the methods of your class as web services. You can pick and choose, adding the [WebMethod] attribute only to those methods you want to expose.

That's all you need to do; .NET takes care of the rest.

WSDL and Namespaces

Your web service will use a Web Service Description Language XML document to describe the web-callable end points. Within any WSDL document, an XML namespace must be used to ensure that the end points have unique names . The default XML namespace is http://tempuri.org, but you will want to modify this before making your web service publicly available.

You can change the XML namespace by using the WebService attribute:

[WebService(Namespace=
    "http://www.LibertyAssociates.com/webServices/")]

Example 15-5 shows the complete source code for the calculator web service.

Example 15-5. Calculator web service program
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;

namespace WSCalc
{
    [WebService(Namespace="http://www.libertyAssociates.com/webServices/")]
    public class Service1 : System.Web.Services.WebService
    {
        public Service1( )
        {
            //CODEGEN: This call is required by the
            //ASP.NET Web Services Designer
            InitializeComponent( );
        }

        #region Component Designer generated code
        
        //Required by the Web Services Designer 
        private IContainer components = null;
                
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent( )
        {
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if(disposing && components != null)
            {
                components.Dispose( );
            }
            base.Dispose(disposing);        
        }
        
        #endregion

        [WebMethod]
        public double Add(double x, double y)
        {
            return x+y;
        }

        [WebMethod]
        public double Sub(double x, double y)
        {
            return x-y;
        }
        [WebMethod]
        public double Mult(double x, double y)
        {
            return x*y;
        }
        [WebMethod]
        public double Div(double x, double y)
        {
            return x/y;
        }
        [WebMethod]
        public double Pow(double x, double y)
        {
            double retVal = x;
            for (int i = 0;i < y-1;i++)
            {
                retVal *= x;
            }
            return retVal;
        }
    }
}

When you build this project with Visual Studio .NET, a DLL is created in the appropriate subdirectory of your Internet server (e.g., C:\InetPub\ wwwroot \WSCalc ). A quick check of that directory reveals that a . vsdisco file has also been added.

There is nothing magical about using Visual Studio .NET; you can create your server in Notepad if you like. Visual Studio .NET simply saves you the work of creating the directories, creating the .vsdisco file, and so forth. Visual Studio .NET is particularly helpful when creating the client files, as you'll see shortly.

15.8.1 Testing Your Web Service

If you open a browser to your web service's URL (or invoke the browser by running the program in Visual Studio .NET), you get an automatically generated, server-side web page that describes the web service, as shown in Figure 15-7. Pages such as this offer a good way to test your web service. (The next section illuminates the seeming hocus-pocus that produces these pages.)

Figure 15-7. The web service web page
figs/pcsharp3_1507.gif

Clicking a method brings you to a page that describes the method and allows you to invoke it by typing in parameters and pressing the Invoke button. Figure 15-8 illustrates.

Figure 15-8. Test page for a web service method
figs/pcsharp3_1508.gif

If you type 3 into the first value field and 4 into the second field, you will have asked the web service to raise 3 to the fourth power. The result is an XML page describing the output, as shown in Figure 15-9.

Figure 15-9. XML output for a web service method
figs/pcsharp3_1509.gif

Notice that the URL encodes the parameters of 3 and 4 , and the output XML shows the result of 81 ( 3*3*3*3 = 81 ).

15.8.2 Viewing the WSDL Contract

A lot of work is being done for you automatically. HTML pages describing your web service and its methods are generated, and these pages include links to pages in which the methods can be tested . How is this done?

As noted earlier, the web service is described in WSDL. You can see the WSDL document by appending ?WSDL to the web service URL, like this:

http://localhost/WSCalc/Service1.asmx?wsdl

The browser displays the WSDL document, as shown in Figure 15-10.

Figure 15-10. Sample WSDL output for calculator web service
figs/pcsharp3_1510.gif

The details of the WSDL document are beyond the scope of this book, but you can see that each method is fully described in a structured XML format. This is the information used by SOAP to allow the client browser to invoke your web service methods on the server.