Consuming Web Services from a NET Windows Forms Application

In this section, you'll create a C# Windows application that uses the Mortgage Calculator Web Service to display calculated payments. The code for this project is separate from the CSharpASP ASP.NET project you've been working with in most of this book.

First, create a new Windows Application project and name it MortgageCalculator. Although the interface uses Windows Form controls, it's essentially identical to the Web Form interface you just saw in the preceding section (see Figure 21.11).

Mortage Fayment ami Total Coit Figure 21.11: The Mortgage Payment Windows Form application interface

The major differences are that Validation controls aren't (yet) available in the System.Windows.Forms namespace, so you have to code your own validation. Most of the code for the project does exactly that—checks the user-entered values to make sure they meet the Web Service requirements. For example, you must ensure that you can cast the APR and Amount Financed to doubles and the Mortgage Duration to an integer as well as ensure that the values are within some reasonable range.

Just as with the IE-based UI, the button on the form makes two calls to the Mortgage Calculator Web Service: one to the getPayment method to obtain the monthly payment, and one to retrieve the total cost of the mortgage. It places the results into the two labels (that look like text boxes) in the lower panel of the form. The form acts just like the IE interface, but it communicates with the Web Service via SOAP messages rather than with an HTTP get request.

Add a Web Reference

The .NET framework makes the process extremely simple. All you need to do is add a Web Service reference to the form. To do that, right-click the References item in the Solution Explorer and select the Add Web Reference menu item from the pop-up menu. You'll see the Add Web Reference dialog shown in Figure 21.12.

Figure 21.12: The Add Web Reference Wizard

In my setup, the CSharpASP project is on the local Web server; therefore, I was able to use the Web References on Local Web Server link at the bottom of the left panel to find the reference. If the Web server containing the CSharpASP project is not on the same machine as your VS.NET development environment, you'll need to enter the server address in the Address field at the top of the dialog in the form http://yourServerName. The left panel is a WebBrowser, so you can navigate to the correct location if links are available to do so.

If you can't find the reference, enter the following name, substituting your server name for localhost if you aren't using your local machine server:


When the Add Web Reference Wizard finds the server, it requests a discovery file called default.vsdisco, which is an XML file containing locations to look in (and to avoid looking in) for Web Services available on that server. The left panel of the dialog displays the results of the search, while the wizard reads the file and fills the right panel with links to the various Web Services available on that server. Each .NET project on the server also has a .vsdisco file containing a similar list of locations in which the server can find Web Services exposed by that project. Find the CSharpASP project and select it. You'll see the ch21-payment.asmx Web Service shown in the right panel and the .vsdisco file that describes the location of the Web Service in the left panel (see Figure 21.13).

Figure 21.13: The CSharpASP ch21-payment.asmx Web Service in the Add Web Reference Wizard dialog

Click the Add Reference button at the bottom of the dialog window to add the reference to your project. When you do this, VS.NET creates a proxy that your project can use to call the Web Service just as you call any other class methods.

Warning If your Web server is not on the same machine as your VS.NET development environment, you'll need to delete the Web Reference to the ch21-payment.asmx Web Service and then add it back using the correct server.

VS.NET adds a Web References item to your Solution Explorer window containing one item that has the same name as the selected server. That item, in turn, contains a WSDL file describing the Web Service interface (see Listing 21.4 for details), a .disco file containing location information for files related to the Web Service, and a file that maps URLs to the local cached file location and contains references to the discovery (.disco) file and the WSDL files.

After adding the Web Reference, using the referenced Web Service is straightforward. For example, after validating the user input, the button click event for the Get Payment button on the form calls a runWebMethods method that calls the Web Service methods and updates the two Label controls in the bottom half of the form (see Listing 21.6).

Listing 21.6: The MortgageCalculator Form's runWebMethods Method (MortgageCalculator.frmMortgageCalculator.cs)

private void runWebMethods(Double apr, Double totalCost, int durationInYears) { String payment; String cost ; try {

this.Cursor = Cursors.WaitCursor; localhost.ch21_payment ws = new localhost.ch21_payment();

payment = ws.getPayment(apr, totalCost, (Int16) durationInYears);

this.lblPaymentResult.Text = payment; payment = payment.Substring(1);

cost = ws.totalPaymentAmount(Double.Parse(payment), (Int16) durationInYears);

lblCostResult.Text = cost;

catch (Exception ex) {

this.Cursor = Cursors.Default;

MessageBox.Show("An error occurred: " + ex.Message, "An Error Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);

finally {

this.Cursor = Cursors.Default;

The highlighted lines create an instance of the Web Service proxy and call its methods. Use the syntax servername.WebServiceName to create the proxy object. Note that after obtaining the proxy object, calling its methods is identical to calling methods for any other class. VS.NET uses the WSDL file to provide IntelliSense for method names and parameters.

Visual Studio's transparent use of the WSDL and .disco files makes consuming Web Services from a Windows client much easier than consuming the same Web Services from IE and has two ramifications that will have a huge effect on future application development—and probably on your Web application development tasks as well.

The first is that, until now, it's been relatively difficult to provide a rich-client UI because HTML, while it has many strengths as a data display markup language, has many weaknesses as an interactive GUI interface. In contrast, Windows, Mac, and other windowing client interfaces support superior GUI interfaces but lack a means for generically displaying information, lack intrinsic support for network communications, are bound to specific platforms and hardware configurations, and are often difficult to distribute and install.

Many attempts have been made to solve this problem. Initially, Java was touted as the answer to cross-platform problems. Browsers were able to host Java applets, small binary programs that used all or a portion of the browser window to provide capabilities that HTML was incapable of providing, such as dynamic graphics, background server communications, and complex GUI controls. As long as the host machine had a platform-specific Java runtime package installed, the browser could download and launch applet code on command. The runtime constrained the actions that applets could take by running them in a "sandbox" that prevented the applet, for example, from writing files or launching local applications. Despite an initial flurry of interest when applets first appeared, poor runtime implementations, restricted bandwidth, and the slower machines available at the time caused users to categorize applets as "slow." Although all these problems have been solved or (in the case of bandwidth) ameliorated, the technology never recovered its initial allure. A similar, more powerful, but much more dangerous Microsoft-specific technology used COM components called ActiveX controls or ActiveX documents hosted in Internet Explorer. To avoid IE displaying default security warnings about such components, they had to be "signed," thus letting you trace the author of malevolent code (after the damage was done) before IE would let them run (although users can defeat the warnings via the security settings). Unfortunately, they also had to be installed and registered like any other COM component, with all the attendant versioning and portability problems. ActiveX controls delivered with Internet Explorer or distributed inside intranets have enjoyed widespread use, but the Internet at large eschewed and vilified the technology because of its potential for abuse.

The Java applet and ActiveX control efforts focused on improving browser interfaces and capabilities through hosted code add-ons. At the same time, a third effort, Dynamic HTML (DHTML), focused on improving the browser's intrinsic capabilities. DHTML is a good idea that has never quite managed to come to fruition because browser manufacturers' support for DHTML varies widely. In addition, because DHTML was (and is) a work in progress, developers face many problems supporting even different versions of browsers from the same manufacturer.

Web Services help solve this problem by letting you create platform-specific rich-client interfaces that communicate relatively transparently with servers through a simple XML-based format. In other words, Web Services give platform-specific applications many of the networking capabilities that browsers provide—without being version specific (although it remains to be seen how robust and stable SOAP and other protocols will be); bound to individual manufacturers like IE, Netscape, and Java are; or dependent on complex, specific binary implementations, like DCOM and CORBA. In my opinion, the advent of Web Services is one step toward the end of the browser era. Browsers will remain important as generalized display applications but will rapidly diminish in importance as application delivery platforms, because using a robust native environment to build interactive data-driven applications provides a better user experience than general-purpose browsers can provide.

The second way Web Services will affect your Web application development is that, because they give you a clean way to abstract program logic and data from the interface, the demand for that separation will inevitably grow. Despite this book's emphasis on Web development and browsers, the future reality is much broader. Browsers are not the only clients, and Internet/intranet development is highly likely to become even more important than it already is. HTTP-based communications are part of the new application infrastructure not because they're more efficient or easier to develop, but because they're standardized and widely available. As the number of devices increases, the pressure to develop centralized ways of delivering the same data to multiple types of devices also increases. It's just not efficient—from either the user or the business point of view—to create multiple applications that store or consume the same types of data in different ways.

For example, many applications use contact lists, but I'm sure you're well aware of the difficulties involved in transferring data from one application to another, because most applications use proprietary formats to store the lists. Typically, the most popular programs buy or reverse-engineer the file formats of other popular programs so that they can "import" or "export" data. However, now XML and schema remove the necessity for programs to create proprietary binary formats for common data. That means you'll see increasing interoperability and simplified data sharing between different applications. However, the concept reaches further than that. If you can share data between the various applications, then there's no need to maintain multiple copies of that data other than for speed and for use when the applications can't connect to a central server.

Again, Web Services hold the promise of a solution. By making it easy for applications of all types to communicate with and retrieve data from a central server via common and ubiquitous network protocols, they also increase the probability that common data will be stored as "master files" in a centrally located store.

Web Services also help solve the real and increasing problems within and between organizations that have incompatible hardware and software. An entire branch of programming, called Enterprise Application Integration (EAI), has grown up around writing software that enables these incompatible systems to exchange data. Because it's much easier and faster to write Web Services wrappers for the applications than to write custom code to translate from one format to another, EAI's future probably lies almost entirely within Web Services.

Finally, because any type of application can read and process XML without much effort, you can write programs that can find or "discover" and consume Web Services without knowing in advance where those services are or knowing the details of communicating with those services. Until such capabilities become so commonplace that they're part of the background infrastructure, it's useful to know a little bit about the technologies involved. From the .NET viewpoint, you should be aware of two public standards: the Universal Description, Discovery, and Integration (UDDI) specification, which lets programs find Web Services, and the Simple Object Access Protocol (SOAP), which lets them communicate. You've already seen the third piece of this puzzle, WSDL, which describes the requirements that you need to create properly formatted SOAP messages.

Was this article helpful?

0 0

Post a comment