In this chapter, you will learn how to
- Describe InfoPath s XML Web service requirements and limitations
- Use the Data Connection Wizard and a UDDI registry to add a public XML Web service as a main data source
- Design a simple receive-only form based on an XML Web service
- Create a Web service main data source for receiving and submitting data
- Design a form that retrieves, updates, and inserts records in a Web service “enabled database
- Create secondary data sources from Web services to populate drop-down lists
For more information
- Go to the Web Services Development Center at msdn.microsoft.com/ webservices / , and choose Understanding Web Services, Web Service Basics to read background material on Microsoft s approach to XML Web service technology.
- Go to www.oakleaf.ws/ for live online demonstrations of a wide range of XML Web services created with Visual Studio .NET. Most of these demonstration Web services have links to complete documentation for the ASP.NET Web services and online Web Forms clients.
To work through this chapter
- You must be familiar with basic form layout practices and with adding sections and controls to forms.
- You need an Internet connection to consume the publicly available XML Web services for this chapters procedures. A high-speed connection isnt required because the basic exercises dont send or receive large XML documents.
- You should have experience using the Microsoft InfoPath Data Connection Wizard to create forms from Microsoft Access (Jet) or SQL Server tables, as described in Chapter 13, Connecting Forms to Databases.
Service-oriented architecture (SOA) is a hot topic in the IT industry, and XML-based Web services are one of SOAs primary enablers. Most current applications for XML Web services involve server-to-server communication, but some especially publicly available utility servicesare well suited for server-to-desktop applications. As Web services gain industry-wide acceptance, interaction of desktop productivity applications with Web services will become a common method of communicating with networked servers. One of InfoPath 2003s initial design criteria was to provide an easy-to-use, flexible graphical user interface (GUI) for Web services. Microsofts InfoPath 2003 Product Guide describes InfoPath as the premier smart client for XML Web services.
This chapter assumes that youre familiar with basic Web services terminology, such as SOAP (formerly an acronym for Simple Object Access Protocol), Web Services Description Language (WSDL), and Universal Description, Discovery, and Integration (UDDI) services. If these terms are unfamiliar, check out the For More Information topics at the beginning of this chapter. You dont need experience with creating or consuming XML Web services applicationsor writing script, or Visual Basic .NET codeto complete this chapters examples.
Understanding InfoPaths Web Service Requirements
InfoPath imposes several restrictions on XML Web services that you can use to create main or secondary data sources without adding Visual Basic .NET code or script to your form. Following are the most important of the Data Connection Wizards requirements for and restrictions of Web service data connections:
- The Web service must use the SOAP 1.1 document/literal (doc/lit) format. Web services have style and use attributes; the style value is either document or rpc , and the use value can be literal or encoded . (The abbreviation rpc is short for remote procedure call .) The doc/lit format defines exchanging XML messages with their structures defined by a schema in the WSDL document; doc/lit is the default style for ASP.NET Web services.
- The Web service cant include mandatory SOAP headers . SOAP headers are extensions to SOAP messages that, as an example, implement message routing and security features, such as digital signatures and message encryption. InfoPath disregards optional headers.
Using the Data Connection Wizard with XML Web Services
The Data Connection Wizard inspects the Web services WSDL document to create the XML schema for a main or secondary data source. You can search Microsofts UDDI 2.0 registry at http://uddi.microsoft.com to find Web services that meet your needs or type the URL for the WSDL document in a text box. If the Web service cant derive a schema from the WSDL file and the service requires parameters, youre prompted to provide parameter values. Unlike forms you create from Jet or SQL Server databases, the Data Connection Wizard doesnt add a New Record button.
The Data Connection Wizard supports the following three types of InfoPath forms that consume Web services:
- Receive-only form Sends a SOAP 1.1 request message to a Web service, receives SOAP 1.1 response messages, extracts the data from the SOAP 1.1 envelope, and displays the data in sections or layout tables with controls you add to the default form. The request message usually contains one or more parameters to specify the data to be returned. You can save the original or edited data as an InfoPath data document, but you cant submit the data to the Web service.
- Submit-only form Sends a SOAP 1.1 message that contains the data from controls bound to the data source to a Web service, but has no provision to display return values. A submit-only form usually performs create (insert) operations on tables in a Web serviceenabled database. You add controls to enter new data and configure a submit button to send the data to the Web service.
- Receive-and-submit form Combines the features of receive-only and submit- only forms, but requires a common data structure. You specify the group that contains data common to both receive and submit operations in an additional step, and the wizard creates default Query and Data Entry views. As with submit-only forms, you must add and configure a submit button.
Designing a Simple Form to Receive Data
Receive-only forms you create from XML Web services are the simplest of the Data Connection Wizard s three supported form types. Most publicly accessible utility Web services, such as Cdyne Systems AddressLookup service that s used in this section s procedure, don t permit submitting data. The AddressLookup ASP.NET Web service connects to a database of U.S. Postal Service (USPS) ZIP Code information and has several methods for performing individual operations, such as checking one-line or two addresses. If the address is found, the service returns USPS-standardized address data and related information. AddressLookup is a commercial Web service with monthly service and transaction fees, but Cdyne provides a test license key for evaluation purposes.
You can learn more about the Cdyne AddressLookup Web service at www.cdyne.com . The InfoPath Web service client example for the Cdyne service is for test purposes only, and is not intended for commercial or production use.
Previewing the CheckAddress Web Method s SOAP Messages
The SOAP request message to AddressLookup s CheckAddress Web method has five parameters ” AddressLine , ZipCode , City , StateAbbrev , and LicenseKey . AddressLine and LicenseKey are required; if you provide a ZipCode value, you can omit City and StateAbbrev. The test LicenseKey value is 0. A typical SOAP test request message to the method looks like this:
The method elicits a SOAP response message that contains the USPS s standard address format with ZIP+4 codes and related address information, as shown here:
Creating a Form Template from an UDDI Registered Web Service
Follow these steps to create a single-view USPSAddress form based on the CheckAddress method of the AddressLookup Web service.
Create the main data source from a UDDI lookup
- Start InfoPath, and click the Fill Out A Form dialog box s Design A Form link. Click the New From Data Connection link to open the Data Connection Wizard, select the Web Service option, and click Next.
- Select the Receive Data option, and click Next.
- Click the Search UDDI button to open the Search Web Service dialog box. Leave the defaults in the two drop-down lists, and type cdyne in the Search For box. Click Search to display a list of Cdyne Web services registered with Microsoft s UDDI 2.0 site, and select the CDYNE::Address Correction for USA Addresses service entry, as shown here:
- Click OK to close the dialog box and add the URL for the WSDL document, http://ws.cdyne.com/psaddress/addresslookup.asmx?wsdl , to the location box. (Microsoft ASP.NET Web services generate dynamic WSDL documents, which you access by adding a ?wsdl suffix to the ServiceName .asmx file for the Web service. Most Java-based Web services have a static ServiceName.wsdl file.)
- Click Next to display a list of Web methods supported by the Web service. Select the CheckAddress method to display its documentation in the Description Of Operation pane, as shown here:
- Click Next to display a summary screen. Type CheckAddressWS or the like in the name box, and click Finish to close the dialog and create the main data source and a default view for the service.
Working around a missing or an inoperable CheckAddress Web method
There is no guarantee that the AddressLocator service or CheckAddress method will continue to offer public access with the test LicenseKey value. If you can t connect to the CheckAddress service or AddressLocator returns an error, you can open typical XML data documents in the final version of the USPSAddress.xsn template in the C:Microsoft PressIntroducing InfoPath 2003Chapter14USPSAddress folder.
Add bound controls to the default view
- Type USPS Address Correction as the form s title, delete the title table s second row, and delete both layout tables.
- Expand the queryFields node in the Data Source task pane. Drag the s0:CorrectedAddress group , which contains fields for the Web method s five parameters, above the Run Query button, and choose Controls In Layout Table from the menu that appears. Your form should appear as shown here:
- Add a column to the table to contain the text boxes for the corresponding SOAP response message values.
- In the Data Sources task pane, scroll to and expand the dataFields node and its subnodes. Drag the DeliveryAddress field to column C, row 1, and delete its label.
- Repeat step 4 for the ZipCode, City, and StateAbbrev fields, placing them in rows 2 through 4, and then close the task pane.
- Delete Line from the Address Line label, change Zip to ZIP, and remove Abbrev and Key from the labels.
- Increase the width of columns B and C to make room for longer addresses, and adjust the width of the text boxes to suit their content. Your form should now look like this:
- Click Preview Form, type a known-good address, with or without a ZIP Code, and 0 as the License in the column A text boxes, and click Run Query to consume the AddressLookup service s CheckAddress Web method. Your preview window should look similar to this:
Detecting addresses with multiple entries
The CheckAddress Web method returns only the Address values you typed and doesn t provide the USPS-standardized address values, if the postal address has multiple entries. If you encounter this situation, try an address for a private residence. The AddressLookup service has another Web method, AdvancedCheckAddress, that returns an array of entries for a single address.
- Save your template with an appropriate name in a new My DocumentsInfopath subfolder named USPSAddress as USPSAddress.xsn or the like, and name the template USPSAddress - Test1.
In your C:Microsoft PressIntroducing InfoPath 2003Chapter14USPSAddress folder, you ll find a completed version of the USPSAddress.xsn template and a copy of the WSDL document for the service, AddressLookup.wsdl, which you can open with Internet Explorer. There s also a 1200Broadway.xml file that you can open in Internet Explorer, in case you can t connect to the Cdyne service.
Creating a Form That Receives and Submits Data
Creating a Web service “based InfoPath form that receives and submits persistent data usually requires access to a database service that enables updates. InfoPath data documents generated from Web service “enabled databases have a more conventional structure than those created by the direct database connections that use InfoPath s ADOAdapter. The OakLeaf XML Web services demonstration site provides a NWOrdersWS Web service that permits editing and updating a very large version of the NorthwindCS sample database. The database contains about 200,000 Orders records and 500,000 Order Details records. The Web service uses SQL Server stored procedures to retrieve, update, and create new Orders and Order Details records.
For more information about the database back-end design and data object structures for the NWOrdersWS Web service, see the article Optimizing SQL Server Data Access, at www.ftponline.com/vsm/2003_11/magazine/features/jennings/ .
Understanding SOAP Messages from Serialized Objects
Following is the SOAP request message to the GetOrderSP Web method that returns data from a single Orders record and its Order Details records:
The SOAP response message contains a serialized Order object within the element. The term serialize means to create a hierarchical XML document from an instance of a class or type; deserializing creates a class or type instance from an XML document. Here s an example of the SOAP response message returned from the preceding request message:
Split Rail Beer & Ale
P.O. Box 555
The UpdateOrInsertOrderSP Web method accepts a SOAP request message that s almost identical to the preceding response message. The difference is that a single < UpdateOrInsertOrderSP ... > element replaces the < GetOrderSPResponse ... > and < GetOrderSPResult > elements within the < /soap:Body > element. Specifying 0 as the < OrderID > element s value adds a new order to the database when you click the submit button.
Creating a Data Source and Form Template from a WSDL Document
To create a main data source and a receive-and-submit form from the NWOrdersWS services GetOrderSP and UpdateOrInsertOrderSP Web methods and then test the form, follow these steps.:
Create the main data source from a URL
- Start InfoPath, and click the Fill Out A Form dialog box s Design A Form link. Click the New From Data Connection link to open the Data Connection Wizard, select the From A Web Service option, and click Next. Leave the default Receive And Submit Data Option, and click Next again.
- Type the URL for the WSDL document ”http://www.oakleaf.ws/nwordersws/nwordersws.asmx?wsdl for this example ”in the location box, and click Next.
- Select the Web method for the receive data operation ”GetOrderSP for this example ”as shown here. (You ll use the other Get methods to populate drop-down lists in the next section, Using Web Services as Secondary Data Sources. )
- Click Next, type GetOrderSP as the data connection name , and click Next again to specify the submit data Web method.
- Leave the URL you typed in step 2, and click Next again.
- Select the UpdateOrInsertOrderSP Web method, as shown here:
- Click Next to open the wizard s Parameters screen, and click the Modify button next to the Fields Or Group box to open the Select A Field Or Group dialog box. You specify the group that returns an Order object when submitting data to the service.
- Expand the dataFields node to display the source data for submission ”GetOrderSPResult for this example ”and select the group, as shown here:
- Click OK to add the XPath expression for the group to the Field Or Group box, as shown here:
- Click Next to display the Summary screen, type UpdateOrInsertOrderSP in the Name box, and click Finish to create the main data source for the form and display the default view.
Add the query and data entry text boxes
- Change the title of the form to Northwind Traders Order Entry and Editing or the like, remove the second row of the title table, split the upper layout table into three columns and two rows, and delete the second layout table. Merge the three cells of row 2, and insert a horizontal line.
- Expand the queryFields node in the Data Source task pane, and drag the intOrderID field to column A, row 1. Remove Int from the label, reduce the width of the Order ID text box, and drag the Run Query button to column B, row 1.
- Expand the dataFields node, drag GetOrderSPResult to below the layout table, and select Section to add a section bound to the Order object s data fields.
- Drag GetOrderSPResult to the added section, and choose Controls in Layout Table from the menu.
- Expand the OrderDetails node, drag the OrderDetail repeating group to below the layout table, and choose Repeating Table from the menu.
- Widen the data entry table, split column B into three columns, and rearrange the columns as you did in the section Adding Controls to a Default Form, in Chapter 13.
- Reduce the width of the repeating table s columns to suit their contents. Your template should appear as shown here:
- Add a button control to column C of the query layout table. Right-click the button, and choose Button Properties from the shortcut menu to open the Button Properties dialog box. Change the Label to Submit to Web Service, and select Submit from the Actions list to open the Submitting Forms dialog box.
- Select Submit To A Web Service, leave UpdateOrInsertOrderSP as the data connection, and clear the Enable The Submit Menu Item On The File Menu check box, as shown on the next page.
(Don t add the custom success and failure messages you specified for the database example in Chapter 13. You need the ability to display message details for the custom SOAP exceptions the service returns when an error occurs.)
- Click OK twice to apply the changes, and reduce the width of the Submit To Web Service button.
- Save your template as NWOrdersWS.xsn in a new My DocumentsInfoPath NWOrdersWS subfolder, name the template NWOrdersWS - Test1, and it.
Test data retrieval, updates, and inserts
- Reopen NWOrdersWS.xsn, and type an Order ID value between 1445151 and 1617870 ” 1445152 for this example ”in the query table. If no one has edited the record, your form looks like this:
- Make a change to a value, such as Freight, and click Submit To Web Service. Click OK to dismiss the success message.
- Click Run Query again to confirm that your change updated the Orders record.
- Type 0 in the Order ID box below the horizontal line, and click Submit to Web Service to test inserting a new order. (You can t verify the addition, because InfoPath doesn t accept the new order number that the method returns. You ll almost solve this problem in the next section.)
- Test the GetOrderSP method s custom SOAP exception by typing an invalid Order ID query value, such as 100, in the text box and clicking Submit To Web Service. You receive an error message similar to this when you click the Details button:
- Repeat step 4, but type 100 in the Order ID box to receive an error message similar to that shown in step 5.
- Repeat step 6, but type 0 in the Order ID box, and delete all OrderDetail items. You ll receive this error message The Order object must have at least one OrderDetail element .
- Add an OrderDetail element with 0 as the Order ID; add an invalid Product ID value, such as 100; and add values for Unit Price, Quantity, and Discount. You ll receive a SQLClient exception, transaction rolled back error message. The Web service throws the same exception for invalid Customer ID, Employee ID, and Ship Via codes.
Unlike forms that connect to database tables, child records require foreign key values, so you can t remove the Order ID column of the repeating table.
Using Web Services as Secondary Data Sources
You can use Web service methods to create a secondary data source that populate drop- down lists. Creating a secondary data source from a Web method with the Data Connection Wizard is similar to the process you used for database tables and queries in the section Creating Secondary Data Sources for List Boxes, in Chapter 13.
The NWOrdersWS service has five Web methods designed for secondary data source use: GetCustomers, GetProducts, GetProductsDetailed, GetShippers, GetEmployees, and GetLast10Orders. All but the GetLast10Orders method return a serialized object; GetLast10Orders returns an array of integers. A drop-down list of the last 10 orders added to the database is useful to populate a list box that aids in guessing the OrderID value of records you insert in the database. Guesswork is required because the secondary data sources load when you open the form, so newly added orders don t appear in the list unless you close and reopen the form. Updating the form with an added Orders record that displays the correct Order ID text box values requires adding code.
To add secondary data sources to populate drop-down list boxes from the GetLast10Orders, GetEmployees, and GetShippers Web methods, follow these steps.
Add secondary data sources from the Get Web methods
- With the NWOrdersWS.xsn template open in design mode, choose Tools, Data Connections to open the Data Connections dialog box.
- Click Add to start the Data Connection Wizard, select the Receive Data option, click Next, select the Web Service option, and click Next again.
- Type http://www.oakleaf.ws/nwordersws/nwordersws.asmx?wsdl in the Location box, copy the URL to the Clipboard for reuse, and click Next.
- Select the GetLast10Orders method, which has no parameters, and click Next.
- Remove Get from the Enter A Name For This Data Connection box, and click Finish to add the secondary data source to the Secondary Data Sources dialog box s list.
- Repeat steps 2 through 5 for the GetEmployees and GetShippers methods. If you have a high-speed Internet connection, add the GetCustomers and GetProducts methods, which have much larger SOAP response messages.
- Click Close to close the Data Connections dialog box.
Add drop-down list boxes for three secondary data sources
- Drag a drop-down list box from the Controls task pane to the right of the upper Order ID text box. The Drop-Down List Box Binding dialog box opens.
- Expand the queryFields node, select intOrderID as the bound field, and click OK.
- Remove the list s label, reduce the list s width, and adjust the size of the table cells to accommodate the added control.
- Right-click the list box, and choose Drop-Down List Box Properties from the short-cut menu to open the dialog box of the same name. Select the Look Up In A Data Connection To A Database, Web Service, File, Or SharePoint Library Or List option.
- Open the Data Connection list, select Last10Orders, and click the Select XPath button to the right of the Entries box to open the Select A Field Or Group dialog box. Select the int result node, which is a repeating field of integer array values, and click OK. Default self-references (periods or dots) appear in the Value and Display Name text boxes, as shown on the next page.
- Click OK to close the dialog box, right-click the Order ID text box, and choose Properties from the shortcut menu to open its Properties dialog box. Click Format, clear the Use A Digit Grouping Symbol check box, and click OK twice to close the dialog boxes. Also remove the digit grouping symbol from the second Order ID boxes in the data entry section and the repeating table. Optionally, format the Freight and Unit Price text boxes as Currency, and format the Discount text box as Percentage.
- Click Preview Form, open the added list box, select one of the last orders, and click Run Query to check the Order ID value. Your preview window, with all numeric formatting applied, should look like the figure on the next page.
- Repeat steps 1 through 5 for the Employee ID and Ship Via text boxes, but in step 5, select the Employee and Shipper repeating groups, respectively, and specify the emplName and shipNamefield as the Display Name values, respectively.
- Save your template changes, and open a new form. Test the added list boxes, save the XML data document as NW OrderID .xml, and open it in Notepad to view the data structure.
Your C:Microsoft PressIntroducing InfoPath 2003Chapter14NWOrdersWS folder contains a copy of the WSDL document for the service, NWOrdersWS.wsdl, and a modified data document, 1445152.xml, which you can open in Internet Explorer for easier reading.
Chapter 17, Writing Advanced Event Handlers, describes an enhanced version of the NWOrdersWS Web service client that uses managed code behind the form to improve its ease of use. The C:Microsoft PressIntroducing InfoPath 2003Chapter24NWOrdersWS folder includes the Visual Basic .NET source code for the NWOrdersWS ASP.NET XML Web service, which connects to a local instance of SQL Server 2000 s Northwind or MSDE s NorthwindCS database. SQL scripts to create the required stored procedures are in the same folder.
InfoPath is the first general-purpose GUI for XML Web services thats designed for Windows users rather than developers. The Data Connection Wizard automates the process of designing receive-only, submit-only, and receive-and-submit forms that consume document/literal XML Web services. Creating a single-view, receive-only form from a public XML Web service takes only a few minutes. Receive-and-submit forms take a bit more design effort and dont support New Record or Delete & Submit buttons without adding code to the template. Despite a few other limitations, such as the inability to handle mandatory SOAP headers without writing code, InfoPath can consume most publicly available document/literal Web services. InfoPath also enables creating secondary data sources from document/literal Web services so you can add Web service populated drop- down lists that are bound to data entry controls.
Where can I find more public Web services that work with InfoPath?
Can I preview a Web service s WSDL document to determine whether it s compatible with InfoPath?
Can InfoPath handle serialized ADO.NET Dataset objects as the SOAP message payload for data retrieval and updates?
How do I handle unknown (Null) date values, such as Shipped Date, with InfoPath?
Can I add a digital signature to a Web service “based form?
Try the XMethods Web service registry, at www.xmethods.com . Most listed services that specify DOC as the Style value will create receive-only InfoPath forms. The AddressLocator Web service is listed in XMethods s registry. Click the FULL LIST link on the home page, and search for cchenoweth. Click Find Next until you encounter the Postal Address Correction link.
Yes. ASP.NET provides a WSDL help document that you can read in Internet Explorer. Type the URL for the .asmx file, but don t include the ?wsdl suffix. As an example, type http:// www.oakleaf.ws/nwordersws/nwordersws.asmx in Internet Explorer to display the help document for the NWOrdersWS service. If the service has a static WSDL file, open it in Internet Explorer, search for style= and use= , and verify that the attribute values are document and literal , respectively.
Yes, but Dataset objects are related to disconnected ADO recordsets and include a proprietary XML schema for the Dataset object that s embedded in the SOAP message. Web services that send or receive Dataset objects aren t interoperable with conventional XML Web services running on non-Windows platforms or created with programming frameworks other than .NET. The object structures serialized and deserialized by the NWOrdersWS Web service can be created with Java and any compatible relational database running under UNIX, Linux, or Windows.
Date picker controls require a date value, unless the data source s WSDL document specifies date values as nillable , and the XML Schema specification doesn t define or permit a Null date value. The WSDL document generated by ASP.NET for the NWOrdersWS Web service doesn t add the nillable=true attribute to RequiredDate or ShippedDate, so the InfoPath schema that s inferred from the WSDL document doesn t include these attributes.
ASP.NET Web services return 0001-01-01T00:00:00.0000000-08:00 as the dateTime value for NULL SQL Server datetime or Jet DateTime column values. ( -08:00 is the offset from GMT or UCT for Pacific Standard time and varies with your time zone; open the NullDate.xml data document in your ...Chapter14NWOrdersWS folder to see an example.) InfoPath s date picker control doesn t recognize this date, and converts a typed 1/1/0001 short date value to 1/1/2001.
The only safe workaround for this problem is to detect January 1 of any year (or 0001 and 2001) in the Web service code and update the table column with a NULL value. (The UpdateOrInsertOrderSP Web method implements this workaround. Run a query, type 1/1/0001 in the Required Date or Shipped Date date picker text box, submit an update, and requery the NWOrdersWS Web service.)
Yes, if you submit the data document as text ( string ) to a Web service that s capable of processing a text message and verifying the signature. A string is required because the white space (spaces, tabs, and newline characters ) in the message must be preserved. If the Web service requires a complex type, such as a serialized Orders object, with digital signatures, data encryption, or both, you must download the Microsoft Web Services Enhancements (WSE) 2.0 add-in from msdn.microsoft.com/ webservices / and write Visual Basic .NET or C# code to create InfoPath consumer applications that implement the WS-Security specifications. Using WSE 2.0 with InfoPath forms is beyond the scope of this book.
On Your Own
Here are suggestions for additional exercises with forms based on XML Web services:
- Use conditional formatting to disable the USPSAddress.xsn templates Run Query button unless the Address and ZIP Code text boxes have entries or Address, City and State values are present. Assign tab order 1 through 3 to the query text boxes, and make all returned data text boxes read-only.
- Modify the design of the USPSAddress.xsn template by adding controls bound to additional data fields, such as County, CarrierRoute, CheckDigit, ServiceError, and AddressError.
- Add to the NWOrdersWS.xsn template Customer ID and Product ID drop-down lists that you populate from the NWOrdersWS services GetCustomers and GetProducts methods .
- Apply the conditional formatting rules from the section Disabling Buttons with Conditional Formatting, in Chapter 13, to the NWOrdersWS.xsn template.