Creating and Consuming XML Web Services



Similar documents
Ambientes de Desenvolvimento Avançados

CRM Setup Factory Installer V 3.0 Developers Guide

Creating XML Report Web Services

Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer

VB.NET - WEB PROGRAMMING

How To: Create a Crystal Report from ADO.NET Dataset using Visual Basic.NET

Web services can convert your existing applications into web applications.

Internationalization and Web Services

Creating Reports Using Crystal Reports

Accessing Data with ADOBE FLEX 4.6

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio Lab version: Last updated: 12/10/2010.

Visual Studio.NET Database Projects

XML Processing and Web Services. Chapter 17

14.1. bs^ir^qfkd=obcib`qflk= Ñçê=emI=rkfuI=~åÇ=léÉåsjp=eçëíë

Integrating with BarTender Integration Builder

Creating Form Rendering ASP.NET Applications

Building and Using Web Services With JDeveloper 11g

LabVIEW Internet Toolkit User Guide

How To Use Query Console

Creating Web Services Applications with IntelliJ IDEA

Crystal Reports. For Visual Studio.NET. Reporting Off ADO.NET Datasets

Dynamic Web Programming BUILDING WEB APPLICATIONS USING ASP.NET, AJAX AND JAVASCRIPT

Building a Scale-Out SQL Server 2008 Reporting Services Farm

1. Tutorial Overview

Author: Gennaro Frazzingaro Universidad Rey Juan Carlos campus de Mostòles (Madrid) GIA Grupo de Inteligencia Artificial

Web services with WebSphere Studio: Deploy and publish

Installing the ASP.NET VETtrak APIs onto IIS 5 or 6

Web Services with ASP.NET. Asst. Prof. Dr. Kanda Saikaew Department of Computer Engineering Khon Kaen University

Visual COBOL ASP.NET Shopping Cart Demonstration

Business Insight Report Authoring Getting Started Guide

How to test and debug an ASP.NET application

Chapter 3 ADDRESS BOOK, CONTACTS, AND DISTRIBUTION LISTS

Staying Organized with the Outlook Journal

Learn how to create web enabled (browser) forms in InfoPath 2013 and publish them in SharePoint InfoPath 2013 Web Enabled (Browser) forms


WA2087 Programming Java SOAP and REST Web Services - WebSphere 8.0 / RAD 8.0. Student Labs. Web Age Solutions Inc.

Introduction to Testing Webservices

INFOPATH FORMS FOR OUTLOOK, SHAREPOINT, OR THE WEB

Developing and Implementing Web Applications with Microsoft Visual C#.NET and Microsoft Visual Studio.NET

Dynamic Decision-Making Web Services Using SAS Stored Processes and SAS Business Rules Manager

CHAPTER 10: WEB SERVICES

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

DEPLOYMENT GUIDE Version 2.1. Deploying F5 with Microsoft SharePoint 2010

Password Reset Server Installation Guide Windows 8 / 8.1 Windows Server 2012 / R2

INFOPATH FORMS FOR OUTLOOK, SHAREPOINT, OR THE WEB

Designing and Implementing Forms 34

Expanded contents. Section 1. Chapter 2. The essence off ASP.NET web programming. An introduction to ASP.NET web programming

Agents and Web Services

WhitePaper. Web services: Benefits, challenges, and a unique, visual development solution

Integrating Siebel CRM with Microsoft SharePoint Server

DEVELOPING CONTRACT - DRIVEN WEB SERVICES USING JDEVELOPER. The purpose of this tutorial is to develop a java web service using a top-down approach.

Visual Basic. murach's TRAINING & REFERENCE

Web Services in.net (1)

Crystal Reports for Visual Studio.NET

Deploying Microsoft Operations Manager with the BIG-IP system and icontrol

User Guide. Version 3.2. Copyright Snow Software AB. All rights reserved.

Managing Software Updates with System Center 2012 R2 Configuration Manager

Chapter 4 Accessing Data

HOUR 3 Creating Our First ASP.NET Web Page

NS DISCOVER 4.0 ADMINISTRATOR S GUIDE. July, Version 4.0

Creating your first Web service and Web application

Terms and Definitions for CMS Administrators, Architects, and Developers

WEB SERVICES. Revised 9/29/2015

Remote Console Installation & Setup Guide. November 2009

Tracing and Debugging in ASP.NET

Hypercosm. Studio.

Grid Computing. Web Services. Explanation (2) Explanation. Grid Computing Fall 2006 Paul A. Farrell 9/12/2006

Team Foundation Server 2013 Installation Guide

Firewall Builder Architecture Overview

Web Services API Developer Guide

Team Foundation Server 2012 Installation Guide

So you want to create an a Friend action

JBoss SOAP Web Services User Guide. Version: M5

Customer Tips. Xerox Network Scanning HTTP/HTTPS Configuration using Microsoft IIS. for the user. Purpose. Background

Release 2.1 of SAS Add-In for Microsoft Office Bringing Microsoft PowerPoint into the Mix ABSTRACT INTRODUCTION Data Access

Microsoft Dynamics GP SQL Server Reporting Services Guide

Developing a Web Server Platform with SAPI Support for AJAX RPC using JSON

TIBCO ActiveMatrix Service Bus Getting Started. Software Release 2.3 February 2010

Application. 1.1 About This Tutorial Tutorial Requirements Provided Files

multiple placeholders bound to one definition, 158 page approval not match author/editor rights, 157 problems with, 156 troubleshooting,

T320 E-business technologies: foundations and practice

Oracle SOA Suite 11g Oracle SOA Suite 11g HL7 Inbound Example

Analytics Configuration Reference

Search help. More on Office.com: images templates

Intranet Website Solution Based on Microsoft SharePoint Server Foundation 2010

Oracle Service Bus Examples and Tutorials

How To Build A Connector On A Website (For A Nonprogrammer)

Authoring for System Center 2012 Operations Manager

Bitrix Site Manager ASP.NET. Installation Guide

T Network Application Frameworks and XML Web Services and WSDL Tancred Lindholm

Content Author's Reference and Cookbook

How To Test Your Web Site On Wapt On A Pc Or Mac Or Mac (Or Mac) On A Mac Or Ipad Or Ipa (Or Ipa) On Pc Or Ipam (Or Pc Or Pc) On An Ip

Ingenious Testcraft Technical Documentation Installation Guide

User Manual. Onsight Management Suite Version 5.1. Another Innovation by Librestream

Secret Server Installation Windows 8 / 8.1 and Windows Server 2012 / R2

Web Services Technologies

WCF WINDOWS COMMUNICATION FOUNDATION OVERVIEW OF WCF, MICROSOFTS UNIFIED COMMUNICATION FRAMEWORK FOR.NET APPLICATIONS

Transcription:

Creating and Consuming XML Web Services Creating and Consuming XML Web Services Objectives Understand the motivation and standards for XML Web Services. Create and test an XML Web Service in Visual Studio.NET. Learn how to call a Web Service from an HTTP client. Learn how to call a Web Service from a.net client. Learn how to call a Web Service from a Visual Basic 6 client. Learn how to use UDDI to locate a Web Service. Visual Basic.NET Professional Skills Development 19-1

Creating and Consuming XML Web Services The Motivation for XML Web Services Originally, the Internet was used to allow people to communicate with servers that dispensed documents in response to requests using the Hypertext Transfer Protocol (HTTP). As the Internet evolved, the servers became more sophisticated by employing technologies like ASP to perform processing in response to requests and to deliver dynamic content rather than static documents. In the meantime, the markup language HTML, which was standardized as the page-description language for Internet documents, evolved into XML, which uses the same basic structure to represent any type of data, not just page descriptions. Using the Internet to transmit XML means that any kind of data can be communicated, taking advantage of the fact that virtually every type of computing device can now connect to the Internet. XML Web Services are provided over the Internet to support communication between software applications. Using the HTTP and XML Internet standards, XML Web Services allow disparate types of software running on disparate platforms to send questions and answers to each other. These communications use a standard protocol named SOAP (Simple Object Access Protocol). A more recently developed protocol that is equally important is WSDL (XML Web Services Description Language). WSDL provides the type libraries for XML Web Services, allowing programs to dynamically discover exactly what types of requests they can send to a particular Web Service, and what data they should expect to get back. A third standard, UDDI (Universal Description and Discovery and Integration), allows companies to publish standardized summaries of the XML Web Services that they offer and to search among published service descriptions for the service they need. Support for XML Web Services in ASP.NET ASP.NET makes it very easy for developers to take any class and turn it into a published Web Service. The developer only has to add a single attribute to the class and to each method, and ASP.NET does all the work to create the various XML files plus a Web page that describes the service and allows it to be tested. 19-2 Visual Basic.NET Professional Skills Development

The Motivation for XML Web Services Web Service Requirements and Technologies To enable communication between software components, the following infrastructure requirements and supporting technologies need to be in place. Universal Programmatic Access By providing universal access, the Internet itself meets the most basic requirement for Web Services. The TCP/IP network of the Internet is universally available. Furthermore, the HTTP protocol provides a standard messaging format that allows a Web Service consumer to submit a request to a Web Service provider and receive a response, using a URL to access the Web Service. Other Internet communications protocols, including the e-mail protocol SMTP, have also been used to support Web Services; however HTTP is the most commonly used protocol. A Standard Way to Represent Data The HTTP protocol was originally used to transmit HTML page descriptions to browsers in response to Web requests. The evolution of Extensible Markup Language (XML) allowed this same mechanism to be used to transmit any type of data, not just page descriptions. The development of XML standards ensured that this data could be universally understood. XML has been augmented by supplemental standards that add to its utility. The XML Schema Description language (XSD) provides a standard way to define classes of XML documents. XML Stylesheet language provides a standard for transforming XML documents into other formats. The XPath expression language allows any subset of the data in an XML document to be specified and extracted. And new XML-based technologies for representing and manipulating data continue to evolve. A Standard Message Format It is not enough to have a way of communicating and a way of encoding data as XML. A specific implementation of XML was needed to provide a standard way of packaging procedure calls and return values into XML requests and responses. The Simple Object Access Protocol (SOAP) meets this need by standardizing the XML envelope used for calling Web methods, appending parameter values to these procedure calls, and then packaging a response. SOAP provides a predictable format, or XML structure, that Web Service clients and providers can rely on for exchanging messages. Visual Basic.NET Professional Skills Development 19-3

Creating and Consuming XML Web Services A Service Description Format In addition to the SOAP messaging format, you need a standard way to describe a Web Service, so that consumers of the service know what to call it, what types of parameters it requires, and what type of data it returns. Web Services Description Language (WSDL) builds upon XML schema description language to meet this need. Standards for Publishing and Discovering Web Services Visual Studio.NET uses a proprietary XML file format with the extension.vsdisco in each project. This file allows you to set a Web Reference that operates similarly to the references that you set to other.net and COM components. In addition to this proprietary discovery file format, there is a more universal standard for describing and discovering Web Services: Universal Description, Discovery, and Integration (UDDI). Microsoft supports this standard, but there is currently no specific support for it in Visual Studio.NET. UDDI enables Web Services to be published to an XML-based directory that can be consulted by potential consumers. The Bad News You can write your own Web Service from scratch, but the code required to pack and unpack SOAP packets can be a daunting task. In addition, WSDL documents are complex and difficult to create. The Good News The good news is that ASP.NET and Visual Studio.NET make it simple to create a Web service that automatically implements the SOAP and WSDL protocols. When you create a Web Service project, all the plumbing happens for free. 19-4 Visual Basic.NET Professional Skills Development

Creating an XML Web Service with Visual Studio.NET Creating an XML Web Service with Visual Studio.NET When you create a Web Service using Visual Studio.NET, all of the necessary files are automatically created for you. However, you ll still need to write the code to make your Web Service actually do something. Try It Out! Follow these steps to create a new, empty Web Service project: 1. Choose File New Project menu item and choose the Visual Basic Projects folder in the Project Types list. In the Templates list, click ASP.NET Web Service, as shown in Figure 1. Click OK, accepting the default Name and Location values. Figure 1. Creating a new Web Service. 2. Figure 2 shows the Solution Explorer window, where Visual Studio.NET has set up the standard files needed for the Web Service. (We ve used the Project Show All Files menu item to display all the files in the project, even the ones Visual Studio.NET normally hides.) Visual Basic.NET Professional Skills Development 19-5

Creating and Consuming XML Web Services Figure 2. Files automatically created for a new Web Service. In addition to the usual files and references needed in a Visual Studio.NET project, the application created a virtual directory on your Web server. Here s a rundown of what the files contain: The AssemblyInfo.vb file contains information about the assembly that the project creates, including the assembly name and version. The Global.asax and Global.vb files reference and create event handlers for the site. The Service1.asmx file contains just a Web Service directive, similar to the Page directive that appears at the top of an aspx file. Web Services created by Visual Studio all end with the.asmx extension. The Service1.asmx.vb file contains code that implements the service. The Web.config file has general site configuration information. The WebService1.vsdisco file provides discovery of available services to clients outside the project. 3. Right-click on the Service1.asmx file in the Solution Explorer and choose Set as Start Page from the context menu. 4. Right-click again on the Service1.asmx file in the Solution Explorer and choose View Code from the context menu. The Web Service 19-6 Visual Basic.NET Professional Skills Development

Creating an XML Web Service with Visual Studio.NET project comes with a pre-defined Hello World example that you can test. Uncomment the code, which looks like this: <WebMethod()> Public Function HelloWorld() As String HelloWorld = "Hello World" End Function 5. Press the F5 key to run the project. You ll see the list of operations supported by the Web Service (the bulleted item HelloWorld shown in Figure 3). This is an HTML page that Visual Studio generates for your Web Service to make testing the service easy. Figure 3. You can test the HelloWorld Web Service by pressing F5. 6. Click HelloWorld to load the test page for the HelloWorld Web Service shown in Figure 4. You can inspect the SOAP examples that appear in the lower portion of the page, although you won t need to Visual Basic.NET Professional Skills Development 19-7

Creating and Consuming XML Web Services worry about creating the SOAP requests and responses Visual Studio does that for you. Figure 4. The test page to run the HelloWorld Web Service. 7. Click the Invoke button. Figure 5 displays the XML returned by the HelloWorld Web Service. 19-8 Visual Basic.NET Professional Skills Development

Creating an XML Web Service with Visual Studio.NET Figure 5. The XML returned by the Web Service. Obviously, HelloWorld isn t going to be of much use as part of a real application. You ll need to remove the canned code that implements HelloWorld and write a Web Service that actually does something. The HelloWorld template does make it easy to get started, however, but it s time to move on. An Example XML Web Service See Inventory.asmx in Inventory WebService.sln The InventoryWebService solution is a more useful example of a Web Service. As you saw in the preceding example, when you create a new Web Service project, the default class is always named Service1. You don t have to stick with that name you can name it anything you like, as long as you retain the.asmx extension in this case the default class is named Inventory.asmx. Adding Web Methods Inventory.asmx includes two methods: GetAllInventory, which returns a list of products and the number of units in stock; and GetInventory, which takes a single ProductID input parameter and returns only the number of units in stock for that product. The Web Service needs to connect to the SQL Server Northwind database to obtain the necessary information, so Inventory.asmx.vb imports the System.Data.SqlClient namespace, along with the namespace for the.net Framework s Web Services classes: Imports System.Web.Services Imports System.Data.SqlClient Visual Basic.NET Professional Skills Development 19-9

Creating and Consuming XML Web Services The first Web method, GetAllInventory, returns a DataSet. DataSets work well as Web method return values, because the.net Framework can automatically serialize DataSets as XML. The Web Service methods use the <WebMethod()> attribute to have Visual Studio automatically create the necessary plumbing code automatically: <WebMethod()> _ Public Function GetAllInventory() As DataSet The sample method initializes some string variables for the connection information to the SQL Server database and for the SELECT query used to return the product information: Dim strcnn As String Dim strsql As String strcnn = "user id=sa;pwd=;" & _ "database=northwind;server=(local)" strsql = _ "SELECT ProductID, ProductName, UnitsInStock " & _ "FROM Products ORDER BY ProductID" The method then creates a new DataSet object, fills it using a SqlDataAdapter, and returns the DataSet: Dim sda As New SqlDataAdapter(strSQL, strcnn) Dim ds As New DataSet() sda.fill(ds) Return ds The GetInventory method takes a single input parameter, a Long integer named ProductID, and returns a Short integer: <WebMethod()> _ Public Function GetInventory( _ ByVal ProductID As Long) As Short 19-10 Visual Basic.NET Professional Skills Development

Creating an XML Web Service with Visual Studio.NET Just as in the previous procedure, the GetInventory method sets up strings for the connection and SQL information: Dim strcnn As String Dim strsql As String strcnn = "user id=sa;pwd=;" & _ "database=northwind;server=(local)" strsql = _ "SELECT UnitsInStock FROM Products " & _ "WHERE ProductID = " & ProductID In this case, the code uses the ExecuteScalar method of a new SqlCommand object to do its work. The ExecuteScalar method returns an Object, and the code uses the CType function to convert this into the required Short return value: Dim cnn As New SqlConnection(strCnn) cnn.open() Dim sc As New SqlClient.SqlCommand(strSQL, cnn) GetInventory = CType(sc.ExecuteScalar(), Short) cnn.close() Testing the Web Service You can test the new Web Service using the same technique employed earlier in this chapter for the Hello World example: 1. Right-click on Inventory.asmx. 2. Choose Set as Start Page from the context menu. 3. Press F5 to run the sample project. WSDL Document Details One of the most valuable services that Visual Studio provides when you create a Web Service is to create the WSDL schema document for you. This XML Visual Basic.NET Professional Skills Development 19-11

Creating and Consuming XML Web Services document is essentially the type library for your Web Service, using a standardized format to describe the messages that your service will support. To view the WSDL for the Web Service, click the Service Description link in the test page, or enter this URL in the browser: http://localhost/vbnet/inventorywebservice/ Inventory.asmx?wsdl This loads the contents of the WSDL file, as shown in Figure 6. Even for this simple Web Service, the document is quite long and detailed. Figure 6. Viewing the WSDL. The WSDL document can be divided into two groups of sections. The first group contains abstract definitions of the types and messages used by the Web Service. The second part of the document includes concrete definitions, referred to as bindings, that specify which services and methods employ the abstract types and messages defined in the first part of the WSDL. If you scan the full document, you ll be very grateful that Visual Studio.NET relieves you of building it yourself! 19-12 Visual Basic.NET Professional Skills Development

Creating an XML Web Service with Visual Studio.NET Defining the Target Namespace Most of the namespaces declared at the top of the WSDL document are fixed and mandatory. However, one namespace is up to you to define the target namespace that will be used by any client working with your Web Service. When you create a Web Service, Microsoft adds a default placeholder namespace, http://tempuri.org. This strange name stands for temporary URI, which refers to the Unique Resource Identifiers used to define namespaces. It is common to use Web addresses (URLs) for these unique identifiers, but any unique string will work. If you do use a URL, it doesn t need to be one that a browser could actually navigate to it is only a unique identification for your namespace. To define a target namespace, you need to modify an attribute of the class declaration that names your Web Service. Try It Out! 1. Open the file Inventory.asmx.vb in the code editor. 2. Modify the WebService attribute, defining a custom namespace: <WebService _ (Namespace:="http://www.northwind.com/services/")> _ 3. Save your change, build and browse the revised service, and notice that the test page no longer includes the lengthy explanation of how to replace the default target namespace. 4. Bring up the WSDL by clicking on Service Description, and notice that your namespace shows up in the WSDL namespace declarations. TIP: The actual name you use for your NameSpace attribute isn t the issue the only important point is that the namespace should be unique to your organization. Someone should be able to identify your Web Service, given this information. Because URLs are generally unique (no other company could have the same URL as your company), they make good identifiers. Visual Basic.NET Professional Skills Development 19-13

Creating and Consuming XML Web Services Designing XML Web Services Web Services represent a new programming paradigm. Here are some guidelines to consider as you plan your own Web Services. Providing Services Many companies, including Microsoft, are planning to provide software in the form of Web Services. You may want to do this for your company. Think about whether any of the information provided by your Web site would also work as a Web Service. The primary difference from a Web site is that a Web Service is consumed by another software application rather than by a person. You would create a Web Service to expose any functionality that you or other software developers would want to employ. If the service will only be used by your own site, then a conventional DLL usually runs more efficiently than a Web Service. Web Services provide an opportunity to derive revenue from the consumers of your services. However, as with page-based Web sites, it may be worthwhile to provide Web Services simply as a way to build corporate identity. Be careful when you create the interface for your Web Service the methods, their parameters, and their return values. Once you publish a service, you will need to maintain these interfaces to avoid breaking applications that depend on them. Marshalling Data Web Services always return data in the form of XML, using data types supported by XML. For complex result sets, ADO.NET DataSets provide an easy way to marshal data, because they are automatically translated into wellformed XML that includes both schema and data. One useful guideline to consider when designing a Web Service is to make it chunky not chatty. This relates to the overhead and performance implications of making repeated calls to a set of Web Services. It is much more efficient to package as much data as possible in one chunky call rather than requiring multiple chatty calls to get the same data. 19-14 Visual Basic.NET Professional Skills Development

Creating.NET Consumers Creating.NET Consumers Now that you ve seen how to create and test XML Web Services, it s time to learn about creating clients for the services. In the remainder of the chapter, you ll learn how to create client applications, both using Windows Forms and using legacy Visual Basic 6 applications. In addition, you ll see how to use UDDI (Universal Description, Discovery, and Integration) to locate available Web Services. The easiest way to create a client is by using Visual Studio.NET, where so much of the work is done for you. In this section, you ll create a simple Windows application that consumes the Web Service created in the previous section. Introducing Web References Just as you must set a reference to an external assembly before you can use it as part of your project, you must somehow indicate to your project what members are available for the Web Service that you d like to interact with. You can do that by adding a Web reference to your project. Unlike standard references, however, Web references refer to XML Web Services that are published either on the Internet, on an intranet, or locally. In order to take advantage of a Web Service, you need some way to locate the service, which may be out there somewhere on the Internet. (You ll generally use UDDI to locate a public service.) Once you ve found the service, you need some way of knowing what it can do, and that s the reason for WSDL description files. Adding a Web reference to your project for the Web Service makes it easy for you to interact with the Web Service s methods when you add the reference, Visual Studio.NET generates a proxy class that interfaces with the Web Service. In other words, this proxy class makes it seem like you re interacting with a local object, when in fact, you re programming against some remote XML service! Your goal, then, is to add a Web reference to your project, so you can program against the Web Service just as you might program against a local object. TIP: Although this sample works with a local Web Service, there s no reason that you couldn t accomplish the same goals with a Web Service that exists on a remote server. It s simpler to demonstrate on a single machine, however. Visual Basic.NET Professional Skills Development 19-15

Creating and Consuming XML Web Services Try It Out! Follow these steps to create a new project, set a Web reference to the InventoryWebService, and test out the service: 1. Create a new Windows Application project. 2. Right-click on the project name in the Solution Explorer, and choose Add Web Reference from the context menu. This displays the Add Web Reference dialog box, as shown in Figure 7. Figure 7. The Add Web Reference dialog box allows you to search for, or enter the address of, an existing Web Service. 3. Type in the address of the Web Service in the Address box, press ENTER, and the Inventory pane on the left will list the available methods, as shown in Figure 8: http://localhost/vbnet/inventorywebservice/inventory.asmx TIP: If you click the View Contract option in the right pane, the Add Web Reference dialog box displays the Web Services contract, the WSDL information, in the left pane. 19-16 Visual Basic.NET Professional Skills Development

Creating.NET Consumers Figure 8. The Web Service documentation for InventoryWebService. 4. When you re done, click the Add Reference button. 5. Find the new additions to your project under the Web References node in the Solution Explorer window. 6. Right-click on the localhost item, select Rename, and rename the reference as InventoryService. TIP: You don t really have to rename the Web reference you ve created, but the examples that follow do require this in order for the code to work. If you don t rename the Web reference, you re stuck referring to it by the name of its server throughout your code. It seems to us that the code s easier to read if the name of the Web reference reflects its functionality. Understanding the Additions to the Project Once you add a reference to a Web Service, several new items show up in your Solution Explorer under the Web References node, as shown in Figure 9. Visual Basic.NET Professional Skills Development 19-17

Creating and Consuming XML Web Services Figure 9. Adding a Web reference. The *.disco File The Inventory.disco file doesn t have anything to do with 70s pop music it contains information on the location of the WSDL file. 19-18 Visual Basic.NET Professional Skills Development

Creating.NET Consumers <?xml version="1.0" encoding="utf-8"?> <discovery xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://schemas.xmlsoap.org/disco/"> <contractref ref="http://localhost/vbnet/inventorywebservice/ inventory.asmx?wsdl" docref="http://localhost/vbnet/inventorywebservice/ inventory.asmx" xmlns="http://schemas.xmlsoap.org/disco/scl/" /> <soap address="http://localhost/vbnet/inventorywebservice/ inventory.asmx" xmlns:q1="http://tempuri.org/" binding="q1:inventorysoap" xmlns="http://schemas.xmlsoap.org/disco/soap/" /> </discovery> The *.wsdl File The Inventory.wsdl file contains information on the various protocols and schema it is, in fact, the contract that describes the service. Here s a partial listing of the Inventory.wsdl. This is the same information you can view in several other places, including the Add Web Reference dialog box. The Reference.map File The Reference.map file contains information about the location of the.disco and.wsdl files. Visual Basic.NET Professional Skills Development 19-19

Creating and Consuming XML Web Services <?xml version="1.0" encoding="utf-8"?> <DiscoveryClientResultsFile xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <Results> <DiscoveryClientResult referencetype="system.web.services.discovery. DiscoveryDocumentReference" url="http://localhost/vbnet/inventorywebservice/ inventory.asmx?disco" filename="inventory.disco" /> <DiscoveryClientResult referencetype="system.web.services.discovery. ContractReference" url="http://localhost/vbnet/inventorywebservice/ inventory.asmx?wsdl" filename="inventory.wsdl" /> </Results> </DiscoveryClientResultsFile> The Code-Behind (*.vb) File In order to see the code-behind (*.vb) files, you ll need to indicate to Visual Studio that you want to view all files. To do that, locate and click the Show All Files button on the Solution Explorer s toolbar (it s the third button from the left). You should see some extra files appear in the Solution Explorer window. The References.vb file is the code-behind file that contains the proxy class, which is a wrapper around the SOAP plumbing. A proxy class is code that does work on behalf of other code, which in this case includes mirroring InventoryWebService. It inherits from the SoapHttpClientProtocol class: Public Class Inventory Inherits System.Web.Services. _ Protocols.SoapHttpClientProtocol 19-20 Visual Basic.NET Professional Skills Development

Creating.NET Consumers NOTE It s important that the proxy class name is Inventory, just like the class in the Web Service itself. Because of this, from within the client project it appears that you re simply programming against the Web Service directly when, in fact, you re calling methods of this proxy class. The proxy class, in turn, calls methods in the remote Web Service for you. The InventoryWebService Web Service contains two methods stored in a class. When it s implemented as a Web Service, the service exposes its two methods over the network. The proxy class exposes those two methods as members of a local class with the same name as the service itself, thereby acting as a proxy for the real Web Service. Code within the proxy class handles the calls out to the real service, hiding the details from you. In the proxy class, you ll find three methods for each method exposed by the Web Service itself. Consider the following three methods that wrap a Web Service method named GetInventory: GetInventory: A synchronous call to the corresponding Web Service method. BeginGetInventory: An asynchronous call to the GetInventory Web Service method. Under the covers, this method sets up a callback mechanism, allowing your application to take other action while awaiting the response from the Web Service method. Once the Web Service method completes its work, it calls the EndGetInventory method. EndGetInventory: The final call, in response to the Web Service method completing its asynchronous work. Although it s simpler to call the synchronous method, doing so ties up the application s thread while it s waiting for the response. If you try calling a Web Service directly (as in the examples for this chapter), you ll see a distinct lag. Working with Web Services asynchronously is beyond the scope of this chapter, and working that way does require more programming effort. Regardless of whether you use synchronous or asynchronous calls, the method calls are wrapped in SOAP messages and all communication with the InventoryWebServices uses SOAP. If you take a look into the sample code-behind file, you ll see these procedures corresponding to the GetInventory method: Visual Basic.NET Professional Skills Development 19-21

Creating and Consuming XML Web Services Public Function GetInventory( _ ByVal ProductID As Long) As Short Dim results() As Object = _ Me.Invoke("GetInventory", New Object() {ProductID}) Return CType(results(0), Short) End Function Public Function BeginGetInventory( _ ByVal ProductID As Long, _ ByVal callback As System.AsyncCallback, _ ByVal asyncstate As Object) As System.IAsyncResult Return Me.BeginInvoke("GetInventory", _ New Object() {ProductID}, callback, asyncstate) End Function Public Function EndGetInventory( _ ByVal asyncresult As System.IAsyncResult) As Short Dim results() As Object = Me.EndInvoke(asyncResult) Return CType(results(0), Short) End Function NOTE In order to make the procedures more readable, we ve reformatted the text, and removed procedure attributes that you ll find within the proxy class. These attributes control the behavior of the SOAP serializer as it creates the SOAP messages going back and forth between your project and the remote class. At this point, you won t want to change them, and they only add clutter to the code shown here. The important thing to notice, in the three procedures, is that each calls a method of the base SoapHttpClientProtocol class: Invoke, BeginInvoke, or EndInvoke. The Invoke and BeginInvoke methods take, as parameters, the name of the procedure to call (GetInventory) and at least one other parameter: An array of objects that contain the parameters needed by the GetInventory 19-22 Visual Basic.NET Professional Skills Development

Creating.NET Consumers method. The Invoke/BeginInvoke methods wrap this information in XML, as SOAP packets, and send the XML off to the receiving XML Web Service. TIP: So that you needn t create the sample form yourself, we ve created a completed project, WebServiceClient, which you can load and investigate. This project includes the steps you ve walked through in the previous section. You ll use this project s sample form in the next demonstrations. Calling a Web Service Load WebService- Client.sln You can call Web Services from many different types of applications. It s simple to create either a Windows or Web application that acts as a Web Service client. The following steps walk you through investigating the functionality required to call the Web Service from the Windows form that s part of the current project. Figure 10 shows the frminventoryclient.vb form. Figure 10. The InventoryClient form calls both Web Service methods. Visual Basic.NET Professional Skills Development 19-23

Creating and Consuming XML Web Services Double-click Get Inventory To investigate calling the GetInventory Web Service method, load the sample form, and double-click on Get Inventory, loading the Click event procedure for the button. Private Sub btngetinventory_click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btngetinventory.click BreakIfChecked(Me.chkDebug) Dim ws As New InventoryService.Inventory() lblunitsinstock.text = _ String.Format("There are {0} units in stock.", _ ws.getinventory(clng(txtproductid.text))) End Sub You should note some interesting details about this procedure: Double-click Get All Inventory The call to ws.getinventory calls the GetInventory method of the proxy class, which is named Inventory. Although it looks like you re calling a method in the Web Service, you re not. You re calling a method in the local proxy class, which uses the Invoke method of its parent to call the Web Service indirectly. Because the sample application has Option Strict turned on, you have to make sure all the conversions happen correctly. This example uses the CLng method to convert the Text property value in the text box into a Long value. The String.Format method converts the Short value returned from the call to GetInventory into a String for you. The String.Format method allows you to embed numbered placeholders within a formatting string, and replace them at runtime with items from the list of parameters that follows the formatting string. This example uses String.Format to insert a number within the output string. If you double-click on Get All Inventory, you can investigate the code that calls the GetAllInventory method: 19-24 Visual Basic.NET Professional Skills Development

Creating.NET Consumers Private Sub btngetallinventory_click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btngetallinventory.click BreakIfChecked(Me.chkDebug) Dim ws As New InventoryService.Inventory() grddata.datasource = ws.getallinventory.tables(0) End Sub TIP: What s going on here? How can you bind a grid to the return value of a Web Service? Remember that the Web Service s GetAllInventory method is returning a DataSet object, and you can bind a DataGrid to a DataSet or DataTable, among other types. That s all it takes get the DataSet back from the Web Service, and then set its first DataTable as the DataSource property of the grid. Seems awfully easy! For fun, try binding the DataSource property directly to the results of the Web Service method (that is, to the DataSet itself.) The results aren t quite as attractive, for this simple case. Visual Basic.NET Professional Skills Development 19-25

Creating and Consuming XML Web Services Web Services and Legacy Clients You don t need Visual Studio.NET or even a browser to take advantage of Web Services. You can build Web Service clients in Microsoft Office or Visual Basic 6.0, as long as you take a few minutes to download the Microsoft SOAP Toolkit. NOTE Although creating legacy clients isn t directly related to building Visual Basic.NET applications, the existence of this opportunity (that is, creating clients for Web Services outside of the.net world) is important. Although most of this course is focused on creating Visual Basic.NET applications, Web Services are a part of.net, as well, and so require coverage from the consumer point of view. The Microsoft SOAP Toolkit Older programs, such as Visual Basic 6.0, can t communicate natively with Web Services using SOAP. You could handle the SOAP transport details yourself by writing lots of code, or you could download the Microsoft SOAP Toolkit 2.0 from Microsoft s Web site: http://msdn.microsoft.com/soap TIP: How hard is it to write your own SOAP parser? You can certainly do it yourself. It requires expert knowledge of XML and parsing XML streams. It requires knowledge of the SOAP specification, down to the lowest level. In other words, although you can do this yourself, you generally won t want to. WARNING! Although Microsoft released an earlier version of the SOAP Toolkit, that version isn t supported, and doesn t play with WSDL (the contract binding clients to XML Web Services), and isn t supported by Microsoft. Make sure you ve downloaded the latest version of this Toolkit before embarking on any SOAP/XML/Web Service adventures. 19-26 Visual Basic.NET Professional Skills Development

Web Services and Legacy Clients The SOAP Toolkit is a simple install and includes a COM component that serves as a Web Service proxy. Remember, your Web form client for a Web Service used a proxy class that called methods in the remote Web Service for you. In Visual Basic 6, there s no mechanism for adding that proxy class, and no way to add a Web reference. The SOAP Toolkit provides that same type of proxy as a COM component. You need to create an instance of the component, send it some information, and you can work with your Web Service just as you might in Visual Studio.NET. TIP: If you re building Office applications, consider using the Microsoft Office XP Web Services Toolkit. This toolkit makes it easy for Office developers to consume XML Web Services, much like Visual Studio.NET makes it easy for developers working in that environment. To download the toolkit, go to http://msdn.microsoft.com/downloads and search. Creating a Visual Basic 6 Client See WebClientVB6.vbp It s possible to create a Visual Basic 6 client application to run the InventoryWebService that isn t any more complex than the Visual Studio.NET client the SOAP Toolkit takes care of the work for you. The first thing you have to do is to set a reference to the Microsoft Soap Type Library by choosing Project References from the menu, as shown in Figure 11. Figure 11. Setting a reference to the Microsoft Soap Type Library. Visual Basic.NET Professional Skills Development 19-27

Creating and Consuming XML Web Services You can then take advantage of the Object Browser, as shown in Figure 12, which is currently displaying information about the SoapClient object. You create an instance of a SoapClient to run the Web Service. Figure 12. The MSSOAPLib SoapClient object. If you need online Help when getting started with the SOAP Toolkit, choose Programs Microsoft SOAP Toolkit User Guide on the Windows Start menu. In this example, you only need the SoapClient object in order to run the InventoryWebService example. See frmgetinventory All of the code to run the Web Service is contained in the cmdgetinventory_click() event. The code takes these actions in order to call the Web Service: Declares and initializes a SoapClient object variable. Private Sub cmdgetinventory_click() Dim strinventory As String Dim sclient As MSSOAPLib.SoapClient Set sclient = New MSSOAPLib.SoapClient 19-28 Visual Basic.NET Professional Skills Development

Web Services and Legacy Clients Calls the mssoapinit method, passing in the WSDL file reference required to initialize the client. This provides the mapping information so that the Web Service can process the request. Call sclient.mssoapinit( _ "http://localhost/vbnet/inventorywebservice/" & _ "Inventory.asmx?wsdl") Where did the name InventorySoap come from? If you go back to the WSDL file that the Web Service provides, you ll find a section in the file, shown here, which defines a port named InventorySoap. This fragment defines the exact details of how the SOAP messages should be created in order to communicate with the Web Service. Luckily, the SOAP Toolkit handles all these details: <porttype name="inventorysoap"> <operation name="getallinventory"> <input message="s0:getallinventorysoapin" /> <output message="s0:getallinventorysoapout" /> </operation> <operation name="getinventory"> <input message="s0:getinventorysoapin" /> <output message="s0:getinventorysoapout" /> </operation> </porttype> Calls the GetInventory method, passing in the value for the ProductID. Assigns the output text containing the returned value to the label control. strinventory = sclient.getinventory(txtproductid.text) lblinventory = "There are " & strinventory & _ " units in stock." Runs the necessary cleanup code. Visual Basic.NET Professional Skills Development 19-29

Creating and Consuming XML Web Services Set sclient = Nothing End Sub TIP: The SOAP Toolkit provides several different layers for programming Web Services. The highest-level layer, the one you ll use here, is the simplest, but doesn t provide much flexibility. The other layers provide more flexibility, but are more difficult to program. For more information, consult the documentation that comes with the SOAP Toolkit. 19-30 Visual Basic.NET Professional Skills Development

Discovering Web Services Using UDDI Discovering Web Services Using UDDI If you re interested in building an application that could conceivably have a use for a Web Service, where do you turn? For example, maybe you re building an e-commerce application and need to perform credit card validations. Where do you go to look for those services? Or what if you wanted to let possible clients know the inventory on hand for various Northwind products? How do you let the world know that you even exist? The answer is UDDI, or Universal Description, Discovery, and Integration. What Is UDDI? UDDI is a joint project undertaken by Microsoft, IBM, and Ariba that attempts to define how businesses describe and publish Web Services over the Internet. UDDI is a platform-independent, open framework for describing services, discovering businesses, and integrating business services using the Internet, as well as an operational registry. The UDDI project takes advantage of W3C and IETF standards such as the XML, HTTP, and DNS protocols, as well as SOAP XML Protocol messaging specifications. UDDI consists of two parts: Web-Based Registry: The business description data is available through a standard browser interface or through published, SOAPbased Web Services. You can use Web Services for programmatic interaction with the UDDI schema repository. UDDI XML Schema for Business Description: This schema is used to define the XML documents and describes the various elements of a business to be used for the search features in UDDI. To summarize, you can think of UDDI as the Yellow Pages for Web Services on the Internet. The UDDI home page, where you can obtain additional information about UDDI, is located at: http://www.uddi.org/ To get to the Microsoft implementation of UDDI, go to: http://uddi.microsoft.com/default.aspx Visual Basic.NET Professional Skills Development 19-31

Creating and Consuming XML Web Services The home page is shown in Figure 13, where you can register for free, or research available Web Services. Figure 13. The Microsoft homepage for UDDI. If you choose one of the Browse items at the top of the page, you can jump to Web Services that are already registered. For example, clicking on Standard Industrial Classification takes you to the listings for general industries, and clicking on a specific industry, say Services, allows you to drill down the following levels and request a list of companies at the bottom level: Standard Industrial Classification Services Business services Computer and data processing services Information retrieval services When you request a list of companies, you see the current listings for information retrieval services, as shown in Figure 14. 19-32 Visual Basic.NET Professional Skills Development

Discovering Web Services Using UDDI Figure 14. Listings for information retrieval services. Note that the page provides an Advanced Search capability that allows you to hone in more precisely on a particular service. Options include business name, location, service type, SIC codes, and others. If you click on a company, you will get information on the services the company provides, as well as contact information, identification type, business classifications, and a discovery URL, which displays the actual XML used in the listing. At the time of this writing, UDDI is still new. As time goes on, the available listings will most likely increase. NOTE Although all the images and instructions in this section were current at the time we captured them, it s quite possible (and probable) that the interface and layout of these pages might change by the time you do your investigation. So Now What? Once you ve found a Web Service, you still have to obtain more information about what a particular Web Service can do, what the SOAP request and response interface looks like, the data types supported, and whether the Web Service requires an XML schema. In the chapter on building Web Services, Visual Basic.NET Professional Skills Development 19-33

Creating and Consuming XML Web Services you learned about WSDL, and how it is automatically included in your Web Service when you create it in Visual Studio.NET. WSDL provides all of this information to clients when they connect to the Web Service. It s WSDL that makes it possible for UDDI to be useful without WSDL, there s no programmatic interface possible with the Web Service. The UDDI Test Server In addition to the real UDDI server, there s also a test server that you can use to experiment with. The test server is located at the following address: http://test.uddi.microsoft.com/default.aspx Yasser Shohoud, of DevXpert, Inc. (http://www.vbws.com) has created a demonstration Web Service that provides current temperature information, and has registered this service with the test UDDI Directory. You can test it out easily in Visual Studio.NET by creating a new Web form or Windows form. Try It Out! Follow these steps to use UDDI to locate and use the Temperature Web Service in your application: 1. Create a new Windows Application project. 2. Right-click on the project name in the Solution Explorer and choose Add Web Reference from the menu. 3. Click on Test Microsoft UDDI Directory. 4. In the Business name text box type VBWS and click Search. 5. Expand the Weather Service registered through the Visual Studio.NET node, and click the link displayed in the dialog box, as shown in Figure 15. Once you click, the pane on the left shows you the WSDL, and the pane on the right shows you the location of the service (see Figure 16). 19-34 Visual Basic.NET Professional Skills Development

Discovering Web Services Using UDDI Figure 15. Select the reference listed in the test UDDI directory. Figure 16. The WSDL for the WeatherRetriever Web Service. Visual Basic.NET Professional Skills Development 19-35

Creating and Consuming XML Web Services 6. Click the Add Reference button. You will now see the Web Service listed in the Solution Explorer, as shown in Figure 17. Figure 17. Adding a Web reference. 7. Rename the new Web reference WeatherService. 8. Add two text boxes to the form within your project. Textbox1 is where you ll enter a Zip Code, and Textbox2 is where the current temperature for the Zip Code will be displayed. 9. Add a Button to the form and place these two lines of code behind the button: Dim ws As New WeatherService.WeatherRetriever() TextBox2.Text = ws.gettemperature(textbox1.text).tostring 10. Run your project, displaying the form. Enter your zip code into the text box and click the button. You will see the temperature listed for your zip code. You can see how easy it is to locate a Web Service using UDDI, and how WSDL allows Visual Studio.NET to create the proxy class that you use to communicate with the Web Service, and to call its methods. 19-36 Visual Basic.NET Professional Skills Development

Discovering Web Services Using UDDI Summary An XML Web Service is an application that exposes procedures using Internet standards that can be accessed by software running on any platform. SOAP provides message formatting for Web Services. WSDL defines an XML schema that describes Web Services. You can publish your Web Service to UDDI or use UDDI to discover other public Web Services. Web methods are declared using the <WebMethod()> attribute. The WSDL file serves the same purpose as a type library by informing a client application of the methods and parameters available in a Web Service. Make your Web Services chunky not chatty. To create a.net client for a Web Service, simply add a Web Reference to the project, which adds the Web Service proxy class. Executing a Web Service method requires instantiating an object variable that points to the Web Service. The SOAP Toolkit simplifies calling a Web Service from a legacy client, by providing a COM component that serves as a Web Service proxy. You need to set a reference to the Microsoft Soap Type Library to use it in your application. UDDI is a framework for describing and discovering services over the Internet. You can use the UDDI Test Server to experiment with UDDI. Visual Basic.NET Professional Skills Development 19-37

Creating and Consuming XML Web Services (Review questions and answers on the following pages.) 19-38 Visual Basic.NET Professional Skills Development

Discovering Web Services Using UDDI Questions 1. What does a Web Service use to represent data? 2. What does the WSDL define? 3. What is the purpose of UDDI? 4. Which file contains the code that actually implements a Web Service? 5. What is the first step in using a Web Service from a.net client? 6. What purpose does the proxy class in a.net client serve? 7. What tool simplifies calling a Web Service from a legacy application? Visual Basic.NET Professional Skills Development 19-39

Creating and Consuming XML Web Services Answers 1. What does a Web Service use to represent data? XML and SOAP 2. What does the WSDL define? The types and services that make up the interface to a Web Service 3. What is the purpose of UDDI? You can publish your Web Service to UDDI or use it to discover other public Web Services. 4. Which file contains the code that implements a Web Service? The asmx.vb files 5. What is the first step in using a Web Service from a.net client? Add a Web Reference to the project. 6. What purpose does the proxy class in a.net client serve? It serves as a wrapper around the SOAP plumbing. 7. What tool simplifies calling a Web Service from a legacy application? The SOAP Toolkit 19-40 Visual Basic.NET Professional Skills Development

Discovering Web Services Using UDDI Lab 19: Creating and Consuming XML Web Services TIP: Because this lab includes code that you must type in, we ve tried to make it simpler for you. You ll find all the code in WebServices.txt, in the same directory as the sample project. To avoid typing the code, you can copy/paste it from the text file instead. Visual Basic.NET Professional Skills Development 19-41

Lab 19: Creating and Consuming XML Web Services Lab 19 Overview In this lab you ll learn how to create an XML Web Service that retrieves and returns data from a SQL Server database in response to a parameterized request. Then, you ll create a simple Windows application that consumes the Web Service. To complete this lab, you ll need to work through two exercises: Create and Test an XML Web Service Create a Windows Application Consumer Each exercise includes an Objective section that describes the purpose of the exercise. You are encouraged to try to complete the exercise from the information given in the Objective section. If you require more information to complete the exercise, the Objective section is followed by detailed step-bystep instructions. 19-42 Visual Basic.NET Professional Skills Development

Create and Test an XML Web Service Create and Test an XML Web Service Objective In this exercise, you ll create an XML Web Service named CustomerOrders. Callers of the service will call a method named GetOrderCount. They will submit a CustomerID and year, and the service will respond with the number of orders placed in that year by the specified customer, retrieving data from the SQL Server Northwind sample database. In addition, you should add a second Web method to the Web Service, named GetCustomerIDs, which will return a DataSet containing a single column: an alphabetized list of customers from the Northwind sample database. Define the following target namespace for your Web Service: www.northwind.com/services. Test your Web Service by attempting to retrieve the count of 1997 orders for customer ALFKI. Things to Consider You ll need to create an ASP.NET Web Service project. You ll need a connection string, like this, to connect to the data: "user id=sa;password=;" & _ "initial catalog=northwind;data source=(local)" In order to retrieve a count of orders, you ll need to use the ExecuteScalar method of a SqlCommand object. In order to use a SqlCommand object, you ll need to create a SqlConnection object, as well. Your Web methods require the WebMethod attribute, in order to be callable over the Web. Modify the WebService attribute of the class to add your own namespace. The GetCustomerIDs method should return a DataSet, filled in with customer information. Visual Basic.NET Professional Skills Development 19-43

Lab 19: Creating and Consuming XML Web Services Step-by-Step Instructions 1. Open Visual Studio.NET, and create a new ASP.NET Web Service project. Locate the project in the VBNetLabs folder, and name the project WebServiceLab, as shown in Figure 18. Figure 18. Creating a Web Service project in Visual Studio. 2. Select Service1.asmx in the Solution Explorer window, and change its name to CustomerOrders.asmx. 3. Right-click on CustomerOrders.asmx and select View Code. 4. Import the SqlClient namespace at the top of the code to make it easier to work with classes from the SqlClient namespace: Imports System.Data.SqlClient Imports System.Web.Services 5. Modify the WebService attribute of the class definition, defining a target namespace, and rename the class CustomerOrders. Note that this attribute appears on the same logical line as the class declaration. We ve used line continuation characters here: 19-44 Visual Basic.NET Professional Skills Development

Create and Test an XML Web Service <WebService _ (Namespace:="http://www.northwind.com/services/")> _ Public Class CustomerOrders 6. Beneath the code generated by the Web Services Designer, delete the commented sample code, and add the following Web method attribute and function signature line: ' Code fragment 1. <WebMethod()> _ Public Function GetOrderCount( _ ByVal CustomerID As String, _ ByVal Year As Short) As Integer End Function 7. Modify the procedure you ve created, adding the following ADO.NET code to implement the retrieval of the requested order count: Visual Basic.NET Professional Skills Development 19-45

Lab 19: Creating and Consuming XML Web Services ' Code fragment 2. <WebMethod()> _ Public Function GetOrderCount( _ ByVal CustomerID As String, _ ByVal Year As Short) As Integer Dim cnn As New SqlConnection( _ "user id=sa;password=;" & _ "initial catalog=northwind;data source=(local)") Dim strsql As String Dim cmd As SqlCommand strsql = _ "SELECT Count(*) FROM Orders" & _ " WHERE CustomerID='" & CustomerID & _ "' AND Year(OrderDate) = " & Year cmd = New SqlCommand(strSQL, cnn) cnn.open() GetOrderCount = CInt(cmd.ExecuteScalar) cnn.close() End Function 8. Create a new method, named GetCustomerIDs, adding the following code: 19-46 Visual Basic.NET Professional Skills Development

Create and Test an XML Web Service ' Code fragment 3. <WebMethod()> _ Public Function GetCustomerIDs() As DataSet Dim strcnn As String = _ "user id=sa;password=;" & _ "initial catalog=northwind;data source=(local)" Dim strsql As String = _ "SELECT CustomerID " & _ "FROM Customers " & _ "ORDER BY CustomerID" Dim sda As New SqlDataAdapter(strSQL, strcnn) Dim ds As New DataSet() sda.fill(ds) Return ds End Function 9. To test the service, save your changes, right-click on CustomerOrders.asmx, and select Build and Browse. Click on the GetOrderCount method link in the test page, enter ALFKI for CustomerID, enter 1997 for Year, and click Invoke. The return value should be 3. Test the GetCustomerIDs method, as well, verifying that the return value is a DataSet saved as XML. Visual Basic.NET Professional Skills Development 19-47

Lab 19: Creating and Consuming XML Web Services Create a Windows Application Consumer Objective In this exercise, you ll complete a simple Windows application consumer for the Web Service you created in the previous exercise. Your form will fill a ComboBox control with the DataSet returned from the GetCustomerIDs method. In addition, clicking Retrieve Orders will call the GetOrderCount method, filling the Label control on the form with the number of orders for the selected customer, in the selected year. The finished form should look like Figure 19. Figure 19. The finished form calls two Web methods. Things to Consider To fill the ComboBox control with the results of calling the GetCustomerIDs Web method, set the control s DataSource property to the first table (numbered 0) in the Tables collection of the DataSet. Don t forget to set the DisplayMember property of the ComboBox, as well, to be the string CustomerID. Because you re reading and writing text values when you call the GetOrderCount method, call the correct type conversion methods (CType, ToString) to convert types. 19-48 Visual Basic.NET Professional Skills Development

Create a Windows Application Consumer Step-by-Step Instructions 1. In Visual Studio.NET, open the WebServicesClientLab.sln project. 2. In the Solution Explorer window, right-click the References node, and select Add Web Reference from the context menu. 3. In the Add Web Reference dialog box, enter the path to the Web Service you created in the previous exercise, then press ENTER. http://localhost/vbnetlabs/webservicelab/ customerorders.asmx 4. In the Add Web Reference dialog box, select Add Reference to add the reference to your project. 5. In the Solution Explorer window, right-click on the new Web Reference (named localhost), select Rename from the context menu, and change the name to OrderService. 6. In the Solution Explorer window, double-click frmcustomerorder.vb to load the form. 7. Double-click on the form itself (not on any control) to load the code editor, displaying the form s Load event handler. 8. Modify the frmcustomerorders_load procedure so that it looks like this: ' Code fragment 4. Private Sub frmcustomerorders_load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load Dim co As New OrderService.CustomerOrders() With cbocustomerid.datasource = co.getcustomerids.tables(0).displaymember = "CustomerID" End With End Sub Visual Basic.NET Professional Skills Development 19-49

Lab 19: Creating and Consuming XML Web Services 9. In the Solution Explorer window, double-click on frmcustomerorders.vb to load the form in the designer. 10. Double-click Retrieve Orders, loading the code editor with the btnlookup_click procedure selected. 11. Modify the btnlookup_click procedure so that it looks like this: ' Code fragment 5. Private Sub btnlookup_click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnlookup.click Dim co As New OrderService.CustomerOrders() lblresults.text = _ co.getordercount( _ cbocustomerid.text, _ CType(txtYear.Text, Short)).ToString() End Sub 12. Press F5 to run the project (it will load slowly, since it must call the Web Service to fill the combo box before it can display its data). Select a customer, enter a year, and then click Retrieve Orders. Verify that you see the correct number of orders in the Label control on the form. 19-50 Visual Basic.NET Professional Skills Development