Creating an XML Web Service

In this section, you are going to see how easy it is to create an XML Web service in Visual Studio .NET. The ASP.NET Web service project template handles most of the steps described in the preceding paragraph. In Exercise 4.1, you will put together a simple service that performs two calculations. You can test the web service directly from your web browser. After the exercise, we will discuss the items that are created automatically for you by Visual Studio .NET in more detail.

Note 

Because XML Web services that you create with Visual Studio .NET run on Microsoft Internet Information Server (IIS) with ASP.NET, make sure that you know the location of the development web server that you will be using to complete the exercises in this chapter. The exercises specify localhost as the web server name. This assumes that you are running a local copy of IIS on your development computer (the same computer that you are running Visual Studio .NET on). If you are connecting to a different web server, over the network, please substitute the appropriate computer name for localhost.

Exercise 4.1: Creating and Testing a Simple XML Web Service

start example

Creating the Web Service:

  1. Start Visual Studio .NET and create a new project by using the ASP.NET Web Service template. In the Location text box, specify http://localhost/SquareRootService.

    This creates a virtual root directory on your web server. This example uses localhost as the server name. This indicates that the web server is running on the same computer as Visual Studio .NET. You can substitute a different server name for localhost if it is appropriate to your environment.

  2. In the Solution Explorer, change the name of the file Service1.asmx to Square.asmx.

  3. Right-click the file Square.asmx and choose View Code.

  4. Change the name of the class from Service1 to Square. Notice the text and sample code that is commented out. Visual Studio .NET is providing an example of a simple Web method. You will follow this example and create two simple methods for your web service.

    click to expand

  5. Add the Name and Description parameters to the WebService attribute for the class definition. Your code should look like this:

    <WebService(Namespace:="http://tempuri.org/", _     Name:="SquareRootService", _     Description:="Performs square and square root calculations.")> _

  6. Add the following code within the class to create the first Web method, called GetSquare:

    <WebMethod(Description:="Get the square of a number")> _  Public Function GetSquare(ByVal inputVal As Double) As Double     Return inputVal * inputVal End Function

    Notice that an Imports statement for the System.Web.Services namespace has been automatically added to the code.

  7. The next method that you are going to create uses the sqrt() function from the System.Math namespace. You need to add another Imports statement. Your code should look like this:

    Imports System.Web.Services Imports System.Math 
  8. Add the following code within the class to create the second Web method, called GetSquareRoot:

    <WebMethod(Description:="Get the square root of a number")> _  Public Function GetSquareRoot(ByVal inputVal As Double) As Double     Return sqrt(inputVal) End Function

  9. Make sure that the Square.asmx page is set as the start page for the project. To do this, right-click Square.asmx in the Solution Explorer and then choose Set As Start Page.

  10. Save your work and build SquareRootService.

    Testing the Web Service:

  11. Start your web browser and type the following URL:

     http://localhost/SquareRootService/Square.asmx 

    A standard test page is generated by Visual Studio based on the methods it finds in your Web service code. It should look like the following screen.

    click to expand

  12. Click the hyperlink for the GetSquareRoot method. You will see a second test page, which shows the parameter required when calling the GetSquareRoot method and an Invoke button to run the test. Type a value (in this case, 144) into the text box provided on the page and click the Invoke button.

    click to expand

    The results of the test are displayed in a new browser window. The results are returned as an XML document, as shown here.

    click to expand

  13. Click the Back button on your web browser to return to the first test page. Click the hyperlink for the GetSquare method. Test this method in the same way.

end example

As you can see from Exercise 4.1, creating an XML Web service in Visual Studio .NET is simple. That’s because Visual Studio .NET takes care of several steps that you would otherwise have to perform manually. First of all, references to System.Web and System.Web.Services have been added to the project. An Imports statement for System.Web.Services is also added. Each class in a Web service project is marked to inherit from the System.Web.Services.WebService class and the class declaration is marked with an attribute called WebService.

The WebService attribute is shown with a parameter used to declare a unique namespace for your web service. The value assigned to the Namespace parameter is in the form of a Uniform Resource Identifier (URI). A URI is defined as any unique string that is used to identify the publisher of a particular web service. By default, this is set to http://tempuri.org/. It is OK to use this string during development, but you should replace it with your own identifier when the web service is made available on the Internet, in order to make sure that the namespace and web service name combination uniquely identifies your web service. Although the namespace URI is conventionally taken from an organization’s Internet domain name, it is not meant to be a Uniform Resource Locator (URL), that is, it does not need to be set to the URL that will be used to access the web service or to any other specific web page location.

Note 

If you point your web browser to http://tempuri.org, Visual Studio .NET will display a Help page that has more information about namespaces and URIs.

Each method that you want to expose as a part of the public interface of your service is marked with a WebMethod attribute. You can have private methods included in the class that can be called only from your public methods, not by the end users of your web service. Any procedure without the WebMethod attribute will not be visible to your users. A complete list of Web service attributes is shown in Table 4.2 in the next section. Table 4.1 shows the parameters that are available for the WebMethod attribute.

Table 4.1: Parameters of the WebMethod Attribute

Parameter

Description

BufferResponse

Gets or sets whether the response for this request is buffered before being sent down to the client. Defaults to True.

CacheDuration

Gets or sets the number of seconds the response should be held in the cache. A value of 0 disables caching for the method.

Description

Describes the purpose of the XML Web service method. This text is printed on the service Help page.

EnableSession

Shows whether session state is enabled for an XML Web service method. Defaults to False.

MessageName

Specifies the message name, which is used to call the method. This parameter will be specified most commonly when you overload a method with different implementations for different data types, because it provides a way for the user to call the method implementation appropriate for the type of data they are providing. Defaults to the method name.

TransactionOption

Provides the transaction support of an XML Web service method. Defaults to TransactionOption.Disabled.

Listing 4.1 shows the complete code for the SquareRootService project that you created in Exercise 4.1.

Listing 4.1: The Complete Code for the SquareRootService

start example
Imports System.Web.Services Imports System.Math <WebService(Namespace:="http://tempuri.org/", _     Name:="SquareRootService", _     Description:="Performs square and square root calculations.")> _   Public Class Square     Inherits System.Web.Services.WebService 'Region " Web Services Designer Generated Code "     ' 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, ensure that the .asmx file is the start page     ' and press F5.     '     '<WebMethod()> Public Function HelloWorld() As String     'HelloWorld = "Hello World"     ' End Function     <WebMethod(Description:="Get the square of a number")> _      Public Function GetSquare(ByVal inputVal As Double) As Double         Return inputVal * inputVal     End Function     <WebMethod(Description:="Get the square root of a number")> _      Public Function GetSquareRoot(ByVal inputVal As Double) As Double         Return sqrt(inputVal)     End Function End Class
end example

start sidebar
Real World Scenario—Google Web Services Interface

In the folklore of the computer industry, for a new technology to capture attention and quickly gain widespread acceptance, there must be a “killer app” that makes use of it. This “killer” application provides new and powerful capabilities that are so compelling that the technology quickly becomes a new standard. The killer app for XML Web services has not yet been identified, but one of the most significant advancements for XML Web services is the Google web service API. In early 2002, Google announced that they would make their search services available through a web service interface.

As of this writing, this is not yet a commercial application; it is offered for testing and demonstration purposes. There is no fee; however, users must register and use a special license key provided by Google when accessing the service. Each license key is limited to a certain number of connections per day. You can download sample code for Visual Studio .NET, and other languages too, at: http://www.google.com/apis/.

Here is the Object Browser view of the Google web class.

click to expand

The following code snippet shows a call to the doGoogleSearch method:

end sidebar

Dim r As Google.GoogleSearchResult = s.doGoogleSearch(txtLicenseKey.Text, _     txtSearchTerm.Text, 0, 1, False, "", False, "", "", "") 'Extract the estimated number of results for the search and display it Dim estResults As Integer = r.estimatedTotalResultsCount lblSearchResults.Text = CStr(estResults)

The method call passes the user’s license key, the term to be searched for, and several other parameters to the service. This method does not return actual URLs; it displays only the total number of matches found for the current search term. Other methods available in the demo programs offer other features.

By having services such as this available, developers can greatly extend the possibilities for what they can deliver in their applications. Other web services are available that provide weather information, address and zip code searches, and many more. Rather than having to develop functionality from scratch and maintain databases on this information, you can use the Internet to connect to a service that is already offering the information you need and integrate that data seamlessly into your applications. Another use for the web service interface is to automate a process that otherwise might require a user to manually look up information over and over again. A web service application could monitor a stock quote server—for example, checking the price every few minutes, but only notifying the user if a change occurred.

Take a look at some of the sample services that are offered; it’s fun to connect to other people’s applications over the Internet and see what kind of uses you can find for the data they are making available. Other websites where you can find XML Web services for learning and testing are http://www.gotdotnet.com and http://www.xmethods.com.

As you can see from completing Exercise 4.1, Visual Studio .NET makes working with XML Web services easy by doing a lot of the underlying work for you. If you are creating XML Web services that will be used by other platforms, you might need to make some adjustments to the format of the SOAP messages that your application is sending, to meet the other platform’s particular needs. Next, you’ll learn how to use attributes to change the way that the XML markup of the SOAP message is formatted.

Using Attributes to Control XML Wire Format

In addition to the WebService and WebMethod attributes shown earlier, there are additional attributes that you can add to your XML Web service code to control how the XML/SOAP messages are formatted when they are serialized and sent over the Internet (or the “wire”). For example, you can determine what XML tag names are created for your methods and their parameters, and how those tags are nested in relation to one another. Table 4.2 shows attributes that can be applied to the classes and methods that make up an XML Web service.

Table 4.2: Attributes That Can Be Used with XML Web Services

Attribute

Description

WebMethod

Indicates a method to be exposed to users of the XML Web service.

WebService

Indicates a class that implements an XML Web service; parameters for this attribute include the default XML namespace.

WebServiceBinding

Indicates a class that implements an XML Web service or a proxy class that specifies the bindings, similar to interfaces, implemented by the XML Web service that are outside of the default namespace.

SoapDocumentMethod

Indicates that an XML Web service method or a method of a proxy class expects document-based SOAP messages.

SoapDocumentService

Indicates that by default XML Web service methods within the class expect document-based SOAP messages.

SoapRpcMethod

Indicates that an XML Web service method or a method of a proxy class expects RPC-based SOAP messages.

SoapRpcService

Indicates that by default XML Web service methods within the class expect RPC-based SOAP messages.

SoapHeader

Indicates that an XML Web service method or a method of a proxy class can process a specific SOAP header.

SoapExtension

Indicates that a SOAP extension should execute when the XML Web service method executes.

MatchAttribute

Indicates a regular expression for using text pattern matching. Valid only for XML Web service clients.

According to the SOAP specification, there are two styles of mapping the Web service method’s parameters to XML elements in the SOAP message that is generated. ASP.NET is capable of processing both formats. However, when accessing XML Web services that are hosted on other platforms, you might find that you are required to specify one or the other.

The two types of mapping are called RPC encoding and Document encoding. Use the SoapDocumentMethod attribute and the SoapRpcMethod attribute to specify which you prefer. These attributes can be applied to the individual methods of an XML Web service class and also to the methods of a proxy class. Alternatively, you can mark an entire XML Web services class with the SoapDocumentService or SoapRpcService attribute.

Remote Procedure Call encoding (RPC encoding) uses general rules from the SOAP specification and generates a format of XML with an element whose tag name that matches the method name. Nested inside that element are additional elements matching the parameter names for the method. The SOAP specification does not require that these parameters appear in any particular order. An application that is receiving the SOAP request must be able to handle these variations in formatting.

By using Document encoding, you can use the Web Services Description Language (WSDL) information for your web service which strictly describes the exact format of XML that will be created in the SOAP message (see the section later in this chapter titled Using Web Services Description Language).

The following code snippet shows the use of the SoapDocumentMethod attribute:

<SoapDocumentMethod(Use:=SoapBindingUse.Literal, _     ParameterStyle:=Wrapped), WebMethod()> _     Public Function GetSquare(ByVal inputVal As Double) As Double         Return inputVal * inputVal End Function

The Use parameter of the attribute is set to either Encoded or Literal. ParameterStyle determines whether the parameters are encapsulated within a single message part following the body element (Wrapped) or whether each parameter is an individual message part (Bare). The following is an example of the format of the SOAP message that is created:

<soap:Envelope namespaces>     <soap:Body>         <GetSquare xmlns="http://tempuri.org/">             <inputVal>12</inputVal>         </GetSquare>     </soap:Body> </soap:Envelope>

You will also look at the SoapHeader and SoapExtension attributes later in this chapter, in the section titled “Creating and Using SOAP Headers and SOAP Extensions.”



MCAD/MCSD(c) Visual Basic. NET XML Web Services and Server Components Study Guide
MCAD/MCSD: Visual Basic .NET XML Web Services and Server Components Study Guide
ISBN: 0782141935
EAN: 2147483647
Year: 2005
Pages: 153

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