Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Visual CSharp .NET Developer's Handbook (2002) [eng]

.pdf
Скачиваний:
35
Добавлен:
16.08.2013
Размер:
4.94 Mб
Скачать

of performing data transfer—using the same techniques as a browser uses to request web pages for display.

Testing Your SOAP Knowledge

Microsoft maintains two websites to check your SOAP messages. The first accepts SOAP messages, parses them, and provides a check of their validity. You'll find it at http://www.soaptoolkit.com/soapvalidator/. Figure 16.5 shows what this website looks like. (You'll find this message as the Test.XML file in the \Chapter 16 folder on the CD.)

Figure 16.5: The SOAP Message Validation site tests your SOAP knowledge.

As you can see, there are three panes in this display. The SOAP Message Text window contains the message you want to verify. You can also choose one of the valid or invalid samples from the drop-down boxes. These samples can teach you quite a bit about SOAP by showing what you can and can't do within a message and the results that you'll get when performing certain actions. You don't need to include the HTTP or XML headers in the SOAP Message Text window, just the SOAP message.

The Parsed Version window shows what the message looks like after the SOAP listener parses it. This window doesn't tell you about the validity of the message, but it does help you understand the XML formatting better. You can use this window to determine if the message is well formed. The use of text coloring also helps you to distinguish between specific text elements.

The Message Check Results window will show the results of diagnostics the site performs on your SOAP message. You'll see error messages in places where the SOAP message doesn't contain required entries or the entry format is incorrect. When all of the error messages are gone, the SOAP message is ready for use. Of course, the website doesn't check the validity of the data within the SOAP message. You can create a perfect SOAP message that still doesn't work because the server-side component is expecting the data in a different format or it even requires other arguments.

The second website is a generic SOAP listener. You can send a SOAP message to it using an application. The site will test the message much like the Message Check Results window of the SOAP Message Validation site. You'll find this website at

http://www.soaptoolkit.com/soapvalidator/listener.asp. Figure 16.6 shows an error output from this site. This is also an example of the SOAP fault message that we'll discuss in the next section of the chapter.

Figure 16.6: The SOAP Message Listener site will validate requests from your applications.

SOAP Fault Messages

Sometimes a SOAP request will generate a fault message instead of the anticipated reply. The server may not have the means to answer your request, the request you generated may be incomplete, or bad communication may prevent your message from arriving in the same state in which you sent it. There are many reasons that you may receive a SOAP fault message. However, you can generally categorize them into four general areas, as described in the following list.

Client The client generated a request that the server couldn't process for some reason. The most common problem is that the XML format of the SOAP message is incorrect (malformed). Another common problem is the server can't find the requested component or the client doesn't provide all of the information the server needs to process the message. If the client receives an error message of this type, it must recreate the message and fix the problems of the original. The server usually provides amplifying information if it can determine how the request is malformed or otherwise in error.

mustUnderstand This error only occurs when you set the SOAP message mustUnderstand attribute to 1. The error occurs when the client sends a request that the server can't understand or obey for some reason. The server may not understand a request when the client relies on capabilities of a version of SOAP that the server's listener doesn't provide. A server may not obey a client request due to security or other concerns.

Server The server couldn't process the message even though the request is valid. A server error can occur for a number of reasons. For example, the server could run out of resources for initializing the requested component. In a complex application environment, the server may rely on the processing of another server that's offline or otherwise inaccessible. The server usually provides amplifying information if it can determine the precise server-side error that occurred.

VersionMismatch SOAP doesn't have a versioning system. It does rely on the namespaces that you define to perform useful work. This error message occurs when the SOAP envelope namespace is either incorrect or missing.

When a server returns a fault message, it doesn't return any data. Look at Figure 16.6 and you'll see a typical client fault message. Notice the message contains only fault information. With this in mind, the client-side components you create must be prepared to parse SOAP

fault messages and return the information to the calling application in such a way that the user will understand the meaning of the fault.

Figure 16.6 shows the standard presentation of a SOAP fault message. Notice that the fault envelope resides within the body of the SOAP message. A fault envelope will generally contain a faultcode and faultstring element that tells you which error occurred. All of the other SOAP fault message elements are optional. The following list tells you how they're used.

faultcode The faultcode contains the name of the error that occurred. It can use a dot syntax to define a more precise error code. The faultcode will always begin with a classification. For example, the faultcode in Figure 16.6 consists of a client error code followed by an XMLERR subcode. This error tells you that the request message is malformed because the XML formatting is incorrect. Since it's possible to create a list of standard SOAP faultcodes, you can use them directly for processing purposes.

faultstring This is a human-readable form of the error specified by the faultcode entry. This string should follow the same format as HTTP error strings. You can learn more about HTTP error strings by reading the HTTP specification at http://www.normos.org/ietf/rfc/rfc2616.txt. A good general rule to follow is to make the faultstring entry short and easy to understand.

faultactor This element points to the source of a fault in a SOAP transaction. It contains a Uniform Resource Identifier (URI) similar to the one used for determining the destination of the header entry. According to the specification, you must include this element if the application that generates the fault message isn't the ultimate destination for the SOAP message.

detail You'll use this element to hold detailed information about a fault when available. For example, this is the element that you'd use to hold server-side component return values. This element is SOAP message body–specific, which means you can't use it to detail errors that occur in other areas like the SOAP message header. A detail entry acts as an envelope for storing detail sub-elements. Each sub-element includes a tag containing namespace information and a string containing error message information.

Desktop Application Example

If you worked with the Microsoft SOAP Toolkit under Visual Studio 6.0 and found yourself disappointed from an ease-of-use perspective, Visual Studio .NET makes life a lot easier. Creating a SOAP application no longer requires you to create a myriad of objects that are unlikely to work the first time. In addition, creating a connection to the server is so easy that you'll wonder if there's some hidden problem waiting to jump out from the dark recesses of the SOAP support mechanism.

We won't discuss the component end of this example, except to say that it's a simple component that adds two numbers together. You'll find the component in the \Chapter 16\AddIt folder on the CD. This same component works fine on the local machine, or you could access it using DCOM. In short, it's a typical component representative of hundreds of components already on the market.

The example also relies on a Web Services Description Language (WSDL) and associated Web Services Meta Language (WSML) files. You can generate the files in a number of ways.

For example, you can use the WSDL Generator utility that comes with the Microsoft SOAP Toolkit (http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdnfiles/027/001/580/msdncompositedoc.xml). Third-party vendors such as PhalanxSys, the makers of psSOAP (http://www.phalanxsys.com/soap/wsdlwiz.htm) have created WSDL generator utilities. Finally, you can create the two required files as part of your project. The \Chapter 16\AddIt folder on the CD also contains the WSDL and WSML files for this example. You'll need to edit the WSDL URLs to match your web server setup as needed.

After you complete the component requirements, you can begin creating the desktop application to access the web service provided by the component. Previous versions of Visual Studio made this task relatively difficult. When working with Visual Studio .NET, the task is easy because you create a special type of web reference to the web service. The web reference forces the IDE to generate some additional local code automatically, making the task of accessing the service automatic. The following steps tell how to create the web reference. (You'll find the source code for this example in the \Chapter 16\SOAPAdder folder on the CD.)

1.Right-click References in Solution Explorer and choose Add Web Reference from the context menu. You'll see an Add Web Reference dialog box. This is actually a special type of browser you'll use to locate the WSDL file on the web server (local or remote—it doesn't matter).

2.Type the URL for the web service in the Address field of the Add Web Reference dialog box.

3.Locate the WSDL file. The Add Web Reference dialog box will display the content of the WSDL file in the left pane and the reference information in the right pane, as shown in Figure 16.7.

Figure 16.7: The Add Web Reference dialog box contains information about the WSDL file associated with a component.

Note Notice that the WSDL file is just another form of XML file. It includes an XML declaration at the beginning. Each of the <types> tags contains a description of any custom data types used by the component. The <message> tags each contain one path that a message can take between client and server. Consequently, if a method provides a return value, it will produce two <message> tags within the

WSDL file—one to transmit the data and another to transmit the result. The two messages are transparent to the client and server. As far as the client and server are concerned, the message traffic occurs as normal. The WSDL file also contains port, binding, and service information that the Visual Studio .NET IDE will use to create a connection.

4.Click Add Reference. You'll see a new Web Reference added to Solution Explorer. The Web Reference folder will include a reference to the web server and the WSDL file on the server. Double-click the WSDL entry, and you'll see a copy of the WSDL information for the service. You'll also see a Reference Map entry that describes the contract between the client and the server.

5.Add a using statement to the source code that describes the new Web Reference. The example program uses SOAPAdder.winserver;, which is a combination of the application name and the web server name. The reference isn't optional in this case— the application will likely fail to work without it because of the additional files the IDE generates for you.

Now that we have a reference to the web service, it's time to write some code to use it. Forget everything you know if you've used other SOAP toolkits in the past; Visual Studio .NET uses an entirely different technique to access the web service. Listing 16.4 shows you how.

Listing 16.4: Using SOAP in Visual Studio .NET Is Extremely Easy

private void btnTest_Click(object sender, System.EventArgs e)

{

//Create a reference to the object. AddIt AddObj = new AddIt();

//Create some intermediate variables. short Input1 = Int16.Parse(txtValue1.Text); short Input2 = Int16.Parse(txtValue2.Text); short Results = 0;

//Call the Web service using SOAP.

Results = AddObj.DoAdd(ref Input1, ref Input2);

// Display the results on screen. txtResults.Text = Results.ToString();

}

If you're thinking this is a mistake, it's really this easy to use a web service. All you need to do is create a reference to the web service, define any intermediate variables, and then call the method you want to use within the associated component. Figure 16.8 shows the output from this example.

Figure 16.8: The SOAP example adds two numbers together using a web service.

Where Do You Go From Here?

This chapter has taught you about new data movement methods offered by Visual Studio

.NET. While you don't have a complete solution to every problem that the distributed environment will present (such as the infamous data schema problem) you do have enough information to begin experimenting with distributed application development. We've looked at the two technologies most likely to make your next project doable: XML and SOAP.

In Chapter 13, we looked at a method for importing and exporting data from a desktop application using XML. Actually, this is a good place to start working with this new technology. SQL Server 2000 includes features that enable you to work with XML data. All you need to do is set the connection up slightly differently and you're ready to go.

After you get a desktop application working, try using XML with a web application. Combine XML and SOAP functionality to transfer data to a browser or a browser-like desktop application. If you have a Pocket PC available, try one of the third-party SOAP solutions, such as PocketSOAP (http://www.pocketsoap.com/) to move your application from the desktop to a portable device.

Speaking of portable devices, Chapter 17 is your introduction to coding on a Pocket PC and other portable devices. We'll discuss various methods you can use to create applications for your mobile devices. Unfortunately, the mobile form of the .NET Framework wasn't released at the time of this writing, so we won't discuss that option, but you'll find many other useful programming techniques in the chapter.

Chapter 17: PDA Application Development

Overview

The Personal Digital Assistant (PDA) started out as a handheld contact manager and appointment scheduler. It included a black and white display and very little in the way of

application functionality. Memory, processing speed, and data entry options were all so limited that few people were excited about the device for use as anything but a toy.

Today the PDA is the number one tool for many users on the road. It's lighter and easier to carry than a laptop. The handwriting interface enables a user to input data without the clack of keys during a meeting. (You use a PDA as you'd use pen and paper—the only difference is a digital result.) The Pocket PC even makes it possible to use miniature versions of Word, Excel, Access, and Internet Explorer. More than a few developers have used these capabilities to implement full-blown distributed applications that rely on technologies such as Simple Object Access Protocol (SOAP). (Admittedly, most of these applications are still in the experimental stage—I know of only one fully functional production system that relies on both the power of the Pocket PC and SOAP.)

Working with PDAs in the past meant working with arcane toolkits or jumping through hoops to accomplish even basic tasks. The .NET Framework has taken some of the sting out of working with PDAs by hiding some implementation details from the developer and providing web-based tools for automation. This chapter discusses several alternatives for PDA development. It's important to note that some solutions will work better than others for a given task, so you need to know more than one way to accomplish your desired task.

Tip Just in case you feel that the new web technologies such as SOAP are a dead end, consider that Google recently opened its search engine to the public using a SOAP interface. That's right, you can now add Internet search engine capability to your PDA (or desktop) application using SOAP. You'll find a general article about this topic at http://www.infoworld.com/articles/hn/xml/02/04/11/ 020411hngoogleapi.xml?0412fram. The technical article at http://www.ruby-talk.org/cgi-bin/scat.rb/ruby/ruby-talk/37623 provides development details you'll need to create your first PDA application with built-in search engine.

Special Needs for PDAs

There's no free lunch—I often wish I had been the first one to say that because it's so true. Companies that want to gain the advantages of using PDAs also have to decide how to handle the special needs of these devices. A PDA isn't a single-purpose device like a radio, but it isn't a full-fledged computer either; it's somewhere in between. A PDA has more to offer than the cell phones that some developers will eventually target as data sources. However, a PDA can't process data as quickly as your desktop or laptop machine, it has severe memory constraints, and it has only a small space for semi-permanent storage—which means you have to scale your applications down to fit within the hardware confines of the PDA.

Tip The easiest way to create a single application that will run on both laptops and PDAs is to use a browser front end and a component or ASP.NET back end. Using SOAP combined with components offers greater flexibility and better performance. Using ASP.NET enables you to perform changes on-the-fly and develop the application faster.

When I first began looking at PDA development, a developer had a limited number of not-so- pleasant choices. Microsoft provided a Windows CE development kit, but not much for remote application development. It wasn't long before someone had developed a toolkit or two for creating distributed applications on a PDA using SOAP as a conduit for exchanging

information. None of these choices were from Microsoft. You can see my favorite choice in the "Getting SOAP for Your PDA" sidebar.

Even now, your choices for development of PDA software are somewhat limited. You can still use Microsoft Embedded Visual Tools 3.0 (see the "Obtaining the Required Tools" section for details). There are also third-party tools for adding SOAP capability to your PDA. (Microsoft doesn't currently provide a SOAP toolkit for the Pocket PC or any of the other PDA offerings on the market.) Finally, the .NET Framework can enable you to create applications for your PDA, but you'll need to download the Microsoft Mobile Internet Toolkit (MMIT), which is also discussed in the "Obtaining the Required Tools" section.

It might seem like I'm hitting SOAP very hard, and that's because it provides one of the truly transparent development alternatives for PDA development. However, don't get the idea that SOAP is a perfect solution—it still has plenty of warts, partly because the SOAP specification is still in a state of flux. The issues regarding PDA application development using SOAP also make sense, because software of this sort normally appears on the desktop first. However, it also means that you need to consider your PDA development plans carefully, because there are many pitfalls. In all cases, you'll want to build a desktop version of your application before you attempt to create one for your favorite PDA.

Tip It's impossible to know, at this point, just how many SOAP-related specifications will eventually appear on the horizon. One of the best places to learn about new specifications is the XML Web Service Specifications page at GotDotNet (http://www.gotdotnet.com/team/xml_wsspecs/default.aspx). Vendors are now trying to make all of these variations on a theme fit within a framework (http://www.w3.org/2001/03/WSWS-popa/paper51). The idea of a framework is to show how the pieces fit together into a cohesive whole. You can monitor progress on the framework as well as other XML projects at http://www.w3.org/2001/04/wsws- proceedings/ibm-ms-framework/.

You can create a SOAP application for your favorite PDA; it just takes a little more planning. However, it's also important to note that the Microsoft Mobile Internet Toolkit (MMIT) provides an easy-to-use framework for creating mobile applications using the standard features of .NET. The following sections examine the special needs of PDAs. It's important to note that most of these special considerations are in addition to what you need to consider for a desktop application.

Getting SOAP for Your PDA

If you're the lucky owner of a Pocket PC, getting a SOAP toolkit is relatively painless. Unfortunately, none of the other PDA choices on the market has a SOAP toolkit available as of this writing. (There are rumors of a SOAP toolkit for the Palm, but none of the potential toolkits have appeared on the market yet.) However, given the newness of this technology, you can expect other vendors to provide SOAP toolkit offerings for other platforms eventually. The SOAP::Lite site (http://www.soaplite.com/) contains a section of SOAP toolkit links you can check periodically for new additions. This list tells which toolkits will work with PDAs.

Despite the long list of SOAP toolkits you find on the SOAP::Lite site, most aren't ready for prime time. The vast majority are in beta or not in any released state at all. The choices of usable toolkits for SOAP are extremely limited now, but you should see more choices as SOAP becomes entrenched within the corporate environment. The bottom line is that you not only need to find a SOAP toolkit for your PDA, but you need to find one that's fully functional.

Three new specifications recently appeared on the standards groups agenda including Web Services Routing Protocol (WS-Routing), Direct Internet Message Encapsulation (DIME), and XLANG. Each of these three specifications is so new that there's little in print about them yet. Here's the short overview of the three new specifications.

XLANG (http://www.gotdotnet.com/team/xml_wsspecs/xlang-c/default.htm) will allow developers to model business processes using a standardized syntax. Microsoft uses XLANG with their BizTalk Server product. You'll find the XLANG discussion group at http://discuss.develop.com/xlang.html.

WS-Routing (http://msdn.microsoft.com/ws/2001/10/Routing/) makes it easier to move data using SOAP over transports such as TCP, UDP, and HTTP in one-way, request/response, and peer-to-peer scenarios. You'll also want to check the discussion group for WS-Routing (formerly known as SOAP-RP) at http://discuss.develop.com/soap-rp.html.

DIME (http://gotdotnet.com/team/xml_wsspecs/dime/default.aspx) is used to package data using a binary format in a form called payloads. You'll find the DIME discussion group at http://discuss.develop.com/dime.html.

Of course, you'll still need a toolkit for developing a SOAP application for your PDA if you decide to use something more generic than .NET. One called pocketSOAP is the best choice if you own a Pocket PC. The same developer, Simon Fell, produces Simon's Soap Server Services for COM (4S4C) and pocketSOAP (http://www.pocketsoap.com/). You'll find desktop and PDA versions of pocketSOAP, making it easy to develop applications on your desktop machine and move them to your PDA later. This is especially true if you use scripts within a web page, as we will for one of the examples in this chapter. The Pocket PC version is easy to install and works just as well within the confines of the Pocket PC's feature set.

Although this product is still in beta, you'll find that most applications work with few problems. The only major problem that I experienced during testing was an occasional HTTP timeout error. The developer has promised to keep working on the kinks, so you'll likely find this product an optimum choice for PDA development.

The only caveat when using pocketSOAP is that you need to create the message by hand. It doesn't support a high-level API like the Microsoft SOAP Toolkit or the tools provided with the Visual Studio .NET IDE. However, this actually turned out to be beneficial when working with more than one platform (as we'll see in the examples). The bottom line is that you need to be prepared to spend a little more time coding when working with pocketSOAP, but the outcome is well worth the effort.

The Case for PDAs

Developing applications for PDAs will require considerable work. SOAP applications provide the greatest flexibility, native embedded applications provide the best performance and smallest resource usage, and MMIT uses developer time most productively. None of the current solutions are perfect, but some work better than others do in a given situation. Many developers are unused to working with devices that have small screens; the memory limitations are problematic at best, and there's a limit to the number of available development tools. However, the need for PDA development is strong.

Consider the case of Sears. They recently purchased 15,000 PDAs for their business. The deal is worth between $20 million and $25 million. That's a lot of PDA power for their staff. Each PDA is equipped with a built-in bar-code scanner and a wireless modem. The company plans to use these new devices for inventory management, price changes, and merchandise pickups. Some developer has a large programming task in the works as I write this. You can bet that such a serious investment comes with an equally serious need to affect the bottom line. In short, PDAs are becoming mainline systems for many different tasks.

Companies often cite two main reasons for switching to PDAs after using other devices. The first reason is that PDAs cost less to buy, operate, and maintain than many other devices. A PDA equipped with the right add-on devices can perform a myriad of tasks in an intelligent manner.

The second main reason is ease of use. PDAs have a limited number of buttons on them and the functions of each button are easy to understand. The user writes on the screen the same as they would using pen and paper—the PDA uses handwriting recognition to convert the handwritten information into text.

Sears may be looking toward the future as well. A customer could come into the store with their PDA, beam the information to a sale clerk's PDA, and get their merchandise faster than ever before. Of course, this scenario is in the future; most shoppers today don't place their orders via PDA. The point is that Sears and other companies like K-Mart are already planning for this eventuality.

Unlike older, single-function devices, PDAs are completely programmable. This means an investment in hardware today won't become an albatross tomorrow. Companies can extend the life of an investment by using the same PDA in more than one way. As the PDAs age, they'll handle applications with lower programming requirements.

Special Add-ons

Most vendors design PDAs as electronic versions of the calendar, address book, and personal note taker. Early versions of these products didn't include the mini-word processors and spreadsheets you'll find in modern versions. In fact, with special add-ons, you can now extend many PDAs to double as cameras, scanners, and other devices.

The PDA isn't exactly a standard device to begin with. There are many hardware implementations, more than a few operating systems, and even different capabilities to consider. When users start adding features to their PDA, you may find that it's nearly