Lesson 5: Consuming XML Web Services

Lesson 5: Consuming XML Web Services

XML Web services are business logic components that can be accessed over the Internet. Consuming a Web service simply means using that service from within your application. In this lesson, you ll learn how to locate, reference, and use XML Web services from a Web application.

After this lesson, you will be able to

  • Search for XML Web services by company name

  • Add a reference to an XML Web service from a Visual Studio .NET project

  • Use an XML Web service from within a Web application

  • Use an XML Web service from client-side scripts

  • Use a licensed XML Web service

Estimated lesson time: 15 minutes

Finding XML Web Services

XML Web services are made public over the Web using a Universal Description, Discovery, and Integration (UDDI) registry. Currently, Microsoft and IBM manage two UDDI registry nodes available for locating XML Web services. Businesses register their Web services on these nodes so that customers (you and I) can locate the Web services they want to use.

There are many different ways to search for XML Web services on the Internet. The easiest way is just to select XML Web Services from the Start Page in Visual Studio .NET, as shown in Figure 7-12.

figure 7-12 finding xml web services

Figure 7-12. Finding XML Web services

The XML Web Services item on the Start Page lets you locate XML Web services by general category of task that the service performs, such as calendar, financial, math, or weather. The Search In option buttons above the Category box let you search for XML Web services that have been put into production (presumably these have been debugged and tested) or are still under development.

In some cases, a Web service might be available to the public but not listed in the UDDI registry. In these cases, you must know the address of the Web service. This information is often listed on the Web site of the company that offers the service, usually under a heading such as Developer Tools.

Using an XML Web Service

Using an XML Web service is much the same as using a .NET or COM component: you establish a reference to the class, create an instance of an object from the class, and then use the object s properties and methods within your code. There are several ways to establish a reference to an XML Web service from within Visual Studio .NET; perhaps the easiest is to do so from the Start Page.

To reference XML Web services from the Visual Studio .NET Start Page, follow these steps:

  1. Find the XML Web service you want to use by clicking the XML Web Services link on the Online Resources tab on the Start Page in Visual Studio .NET.

  2. Click the Add As Web Reference To Your Current Project hyperlink underneath the XML Web service description. Visual Studio adds a Web reference to the Web References section of Solution Explorer, as shown in Figure 7-13.

    figure 7-13 web references

    Figure 7-13. Web references

To use the reference in code, follow these steps:

  1. Create a new object from the XML Web service class. The XML Web service class name is displayed in the Web References folder of Solution Explorer.

  2. Use the XML Web service s properties and methods from the new object. XML Web service classes work with Visual Studio s autocomplete and Object Browser features, so using XML Web service properties and methods is the same as for any other object.

NOTE
The following example depends on the availability of a third-party Web site. At the time this book was written, this Web site was available. However, its future availability can t be guaranteed.

For example, the following code uses the CDYNE Credit Card Checker Web service to validate a credit card number entered in a text box:

Visual Basic .NET

Private Sub butCheck_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butCheck.Click Dim wsCheck As New com.cdyne.secure.LUHNChecker() Dim wsValid As com.cdyne.secure.ReturnIndicator wsValid = wsCheck.CheckCC(txtNumber.Text) lblMsg.Text = wsValid.CardType & " " & wsValid.CardValid.ToString() End Sub

Visual C#

private void butCheck_Click(object sender, System.EventArgs e) { com.cdyne.secure.LUHNChecker wsCheck = new com.cdyne.secure.LUHNChecker(); com.cdyne.secure.ReturnIndicator wsValid; wsValid = wsCheck.CheckCC(txtNumber.Text); lblMsg.Text = wsValid.CardType + " " + wsValid.CardValid.ToString(); }

Using XML Web Services from Client-Side Scripts

In some cases, it makes more sense to call an XML Web service from client-side scripts than from server code. An XML Web service might take a long time to respond there s no point in making the server wait for the response when the server is just going to pass that response on to the client anyway.

To use an XML Web service from client-side scripts, follow these steps:

  1. Create a style class for the WebService behavior (Webservice.htc).

  2. Add an HTML element to the page that uses the class you created in step 1.

  3. Write script procedures to initialize and call methods on the XML Web service using the XML Web service behavior.

The following HTML creates a webservice style class and then initializes and calls a Web service to display a daily quote when the user clicks Show Quote:

VBScript

<HTML> <HEAD> <title>WebForm2</title> <style> .webservice { BEHAVIOR:url(webservice.htc) } </style> <script language="VBScript"> Dim iCallID Sub init(control, wsAddress, name) control.useService wsAddress, name End Sub Function getResult() if window.event.result.error And (iCallID = window.event.result.id) Then Dim xfaultcode, xfaultstring, xfaultsoap xfaultcode = window.event.result.errorDetail.code xfaultstring = window.event.result.errorDetail.string xfaultsoap = window.event.result.errorDetail.raw ' Display error information. alert("Error " & xfautlcode & "   " & xfaultstring & "   " & xfaultSoap) Else getResult = window.event.result.value End If End Function Sub getQuote() ' Initialize Web service on the selected control. init ws, "http://webservice.effective-web.net/globalself/ globalselfDailyThought.WSDL", "DailyQuote" ' Call a method within the Web service. iCallID = ws.DailyQuote.callService("getTodaysQuote") ' Result is displayed in the ws div element by onresult. End Sub </script> </HEAD> <body> <form  method="post" runat="server"> <h2>Using Web Services from Client-Side Code</h2> <div    onresult="ws.innerText = getResult()"></div> <br> <input type="button" onclick="getQuote()" value="Get Quote"> </form> </body> </HTML>

JScript

<HTML> <HEAD> <title>WebForm2</title> <style> .webservice { BEHAVIOR:url(webservice.htc) } </style> <script language="JScript"> var iCallID; function init(control, wsAddress, name) { control.useService(wsAddress, name); } function getResult() { if((event.result.error)&&(iCallID==event.result.id)) { var xfaultcode = event.result.errorDetail.code; var xfaultstring = event.result.errorDetail.string; var xfaultsoap = event.result.errorDetail.raw; // Display error information. alert("Error " + xfautlcode + "   " + xfaultstring + "   " + xfaultSoap); } else { return event.result.value; } } function getQuote() { // Initialize Web service on the selected control. init(ws, "http://webservice.effective-web.net/globalself/ globalselfGlobalSelf.WSDL", "DailyQuote"); // Call a method within the Web service. iCallID = ws.DailyQuote.callService("getTodaysQuote"); // Result is displayed in the ws div element by onresult. } </script> </HEAD> <body> <form  method="post" runat="server"> <h2>Using Web Services from Client-Side Code</h2> <div    onresult="ws.innerText = getResult();"></div> <br> <input type="button" onclick="getQuote()" value="Get Quote"> </form> </DIV> </body> </HTML>

For more information about using XML Web services from client-side scripts, search for Web Service Behavior in the Visual Studio online Help.

Using Licensed XML Web Services

The preceding XML Web service examples are available on the Internet for free as demonstrations. Other services might require a license in order to charge a fee for their use or to control and track who is using their services.

The XML Web services provided by Amazon.com and Google are good examples of XML Web services that require a license. Neither XML Web service charges for use at this time in fact, Amazon.com actually credits users through their associates program. Instead, these companies use licensing to establish rules of use and to keep in touch with the developers using their services.

To use a licensed Web service, follow these steps:

  1. Visit the Web service developer s Web site, and complete the requested license information.

  2. Reference the XML Web service using the address of the Web Services Description Language (WSDL) file. Licensed XML Web services are often not listed in the UDDI.

  3. Use the XML Web service methods.

For example, you can get the Amazon XML Web service information from the following address: http://www.amazon.com/webservices. You can download the XML Web service documentation from that address and apply for a developer s token that allows you to use the service. Once you have a developer s token, you use it in code to call the XML Web service methods. The Amazon.com XML Web service is available from this address: http://soap.amazon.com/schemas2/AmazonWebServices.wsdl.

Once you establish a Web reference to the preceding address, you can use the Web service, as shown in the following code:

Visual Basic .NET

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Declare an object to represent the Web Service. Dim wsAmazon As New com.amazon.soap.AmazonSearchService ' Declare a structure to pass search criteria in. Dim Search As New com.amazon.soap.KeywordRequest ' Set the search criteria. Search.keyword = "ASP.NET" ' This is the special license number issued to developers. ' Get your own from Amazon. Search.devtag = "DT7Y0UZAPK4PI" ' This is the associates ID for Amazon partners. Get your ' own number from Amazon if you wish to get credit for sales. Search.tag = "webservices-20" ' This property determines how much detail is returned. Search.type = "heavy" ' Which version of the Web Service to use. Search.mode = "books" ' Get the ProductInfo from the Web Service. Dim Info As com.amazon.soap.ProductInfo = _ wsAmazon.KeywordSearchRequest(Search) ' Declare a variable to use with For Each iteration. Dim Book ' Go through the returned ProductInfo array. For Each Book In Info.Details 'Insert an image of the cover. litResult.Text += "<h4>Amazon Sales Rank: " & Book.SalesRank &_ litResult.Text += "</h4><img src='/books/3/467/1/html/2/" & Book.ImageUrlMedium & "'>" Next End Sub

Visual C#

private void Page_Load(object sender, System.EventArgs e) { // Declare an object to represent the Web Service. com.amazon.soap.AmazonSearchService wsAmazon = new com.amazon.soap.AmazonSearchService(); // Declare a structure to pass search criteria in. com.amazon.soap.KeywordRequest Search = new com.amazon.soap.KeywordRequest(); // Set the search criteria. Search.keyword = "ASP.NET"; // This is the special license number issued to developers. // Get your own from Amazon. Search.devtag = "DT7Y0UZAPK4PI"; // This is the associates ID for Amazon partners. Get your // own number from Amazon if you wish to get credit for sales. Search.tag = "webservices-20"; // This property determines how much detail is returned. Search.type = "heavy"; // Which version of the Web Service to use. Search.mode = "books"; // Get the ProductInfo from the Web Service. com.amazon.soap.ProductInfo Info = wsAmazon.KeywordSearchRequest(Search); // Go through the returned ProductInfo array. foreach(com.amazon.soap.Details Book in Info.Details) { //Insert an image of the cover. litResult.Text += "<h4>Amazon Sales Rank: " + Book.SalesRank + "</h4>"; litResult.Text += "<img src='/books/3/467/1/html/2/" + Book.ImageUrlMedium + "'>"; } }

The Amazon.com Web service documentation provides a practical guide to using their Web service in different ways and in a variety of languages.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

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