microsoft press home   All Products  |   Support  |   Search  |   microsoft.com Home  
 
  Microsoft Press Home  |   Register Books  |   Site Index  |   All Books  |

 

Advanced Search
Books about:
Books for:
Products for:

Developer Feature Article
Microsoft ASP.NET: A Better Way to Build Dynamic, Secure Web Applications
Designing Microsoft ASP .NET Applications

By Scott Mauvais

In my previous articles on the Microsoft� .NET Framework, I focused mainly on the architectural aspects of Microsoft's .NET strategy. I've helped you develop a .NET mind set, drill-down on C#, and use the SOAP toolkit to build XML Web Services for Microsoft Visual Basic� 6.0. Although talking about a platform's architecture is an important part of learning best practices (and often leads to stimulating discussions that are quite fun), what really matters to me is how quickly I can produce high-quality, high-performance code and how easy it is to maintain it.  

 

To that end, I focus this month on what I consider to be the most important part of Microsoft's .NET strategy: providing by far the most productive development environment available today. In this article, I show you how to use the Microsoft ASP.NET development platform to quickly build Web Services. I start off by talking about some of the problems the Microsoft .NET development and runtime environments seek to solve. Next I show you how to convert a simple C# console application to a Web Server, which (in this example) requires fewer lines of code than the original application! I then highlight some of the Microsoft ASP.NET features that help you build and unit-test your code faster.

Because this article is all about productivity, I am going to make it shorter than usual. Rather than go into all the details, my goal is to show you how Microsoft ASP.NET works. This gives you enough information to start playing around with the programming model. If you want to learn more about Microsoft ASP.NET, pick up a copy of Douglas J. Reilly's new Microsoft Press� book, Designing Microsoft ASP.NET Applications. Reilly covers everything you need to know about building ASP.NET applications�from the basics of managed code and the common language runtime (CLR) to building and configuring your application to advanced topics such as security and error handling. Whether you are interested in building user-centric Web pages, machine-accessible Web Services, or ASP.NET components, Reilly's book provides you the information you need.
 
 

The Problem

I, like most developers I know, am fundamentally lazy. I love identifying problems and figuring out creative ways to solve them. Once I have figured out the solution, however, I find I don't have a lot of patience writing that tedious data-munging code that comes with most projects. That's when the laziness starts to kick in.

I can't tell you how many times I have written (and cursed) the code to move data from null-aware fields in a database to string-based XML elements to strongly typed properties in the middle tier and finally to variant-based controls on a Web page�and then back again. At times I find myself spending more time muddling through (and debugging!) these yucky helper routines than I do developing the main logic of the applications.

 

The Solution

Microsoft .NET fixes all this by removing much of the drudgery from programming. First off, all Microsoft .NET languages are interoperable thanks to the .NET CLR and common type system (CTS) which virtually eliminate all those little annoyances that challenge you when you switch from one language to another. Better yet, Microsoft .NET eliminates entire classes of bugs such as buffer overruns, memory leaks, and privilege violations because all code is managed by a single runtime engine.

Furthermore, Microsoft .NET automatically handles much of the plumbing such as serializing and deserializing SOAP requests, synchronizing relational dataset and XML resultsets, and state management. This provides three huge benefits:

  • First, it makes lazy programmers (like myself) happy because they no longer have to write that aforementioned yucky code. It also makes their clients happy because they no longer have to pay for it.
  • Second, like the CLR, this common plumbing eliminates many bugs from your code as you no longer have to worry about some junior developer introducing a bug in one of his or her helper routines. Also, because this plumbing is part of the runtime engine rather than high-level application code that most developers write, it performs much better. And because Microsoft is building utility code that every .NET developer is going to use, .NET developers will spend more time tweaking these routines than most other developers would spend tuning their own utility procedures.
  • Third, because everyone (except the curmudgeonly, die-hard "not-invented-here" types) will be using the same helper routines, debugging and maintenance will be much easier. Whenever a problem is escalated up to you, it will be much easier to dive right in and identify the problem because you won't have to waste any time trying to reverse-engineer the data flow.

Speaking of diving right it, let's move on to the code.

 

Converting a Console App to a Web Service

Over the past few months, I have spoken to many, many developers about the XML Web Services model. While many have immediately seen its value and started building a new breed of applications, I find others are somewhat reluctant to make the switch to this new model because of a perceived learning curve. Usually they assume they need to ramp up on Internet protocols in general and XML and SOAP in particular before they can begin writing XML Web Services. Fortunately, Microsoft ASP.NET shields you from all these details.

To see for yourself, imagine you have an existing application you want to turn into a Web Service. To keep things simple, let's assume that it is a console application that takes two command line arguments and prints out the sum.

Listing 1 shows the source code in Microsoft C#.  Even if you haven't seen a single line of Microsoft C# code before, you should be able to follow this example, so I won't walk through it. (To learn about Microsoft C#, turn to Tom Archer's Microsoft Press� book Inside C#.) As always, I have placed the source code for this on my Web site.


Listing 1
Console version of MyMath

using MyMath; 

class Host{
    public static void Main() {

    // Declare our variables
      string[] args;
     int      i;
     double   d;
       
    // Get command line args
    args = System.Environment.GetCommandLineArgs() ;
       
    // Instantiate My Class
    MyMath.Calc oCalc = new MyMath.Calc();
       
    // Call the add method after converting
     // the string args to int
    i = oCalc.Add(System.Convert.ToInt32(args[1]),
                   System.Convert.ToInt32(args[2])) ;

       
    // Call the add method after converting
     // the string args to double
    d = oCalc.Divide(System.Convert.ToDouble(args[1]),
                      System.Convert.ToDouble(args[2])) ;

    // Print results to console
    System.Console.WriteLine(System.String.Concat("Add says: ", i)) ;
    System.Console.WriteLine(System.String.Concat("Divide says: ", d));

    }
}

namespace MyMath {
   public class Calc{

       //Add Method
       public int Add (int x, int y ) {
           return x + y;
       }  
   
      // Divide Method
       public double Divide (double x, double y) {
           // Not ready for prime time!
           // No handling for divide by zero
           return x / y ;  
       }     
   }
}

To turn this C# application into a Microsoft ASP.NET Web Service all you need to do is copy the Calc class as shown in Figure 1 and paste it into a new file with an .asmx extension; I called mine NewMath.asmx.

Figure 1
 
Figure 1:  To create an XML Web Service, you start off by simply defining a class, and ASP.NET will do nearly everything else for you.
 
Next you have to add a directive line at the top of the file so that Microsoft ASP.NET knows how to process the file. You also need to import the System.Web.Services library.

<%@ WebService  Language="C#"  class="Calc" %>
using System.Web.Services;

Finally you have to tag the methods as Web Methods so that Microsoft ASP.NET knows to expose them to clients. This is done by adding [WebMethod] directive right above the method itself. On the other hand, if you do not want to expose a particular method�for example the Divide method, which has an intentional bug in it�you would simply remove the [Web Method] tag. For now, leave the bug in. If you have the .NET Framework installed, download the code, enter zero as the divisor, and see what happens. If you don't have the .NET Framework, you can download it from the Microsoft .NET Framework site.
The final source code looks like this: 
 

<%@ WebService  Language="C#"  
            
            class="Calc" %>

using System.Web.Services;

public class Calc {

    //Add Method
    [ WebMethod ]
    public int Add (int x, int y ) {
       return x + y;
    }  

    // Divide Method
    [ WebMethod ]
    public double Divide (double x, double y) {
       // Not ready for prime time!
       // No handling for divide by zero.
       return x / y ;  
    }    
}

Counting the comments and the pretty formatting, you have written an XML Web Service in 20 lines of code. If you are keeping score, the console app required 49 lines. (Yes, I realize this sample needs some error checking and input validation, but in the interest of space I have decided to leave it out. Remember, this is sample code and not template code.) Now that you are feature complete on your first ASP.NET Web Service, fire up Microsoft Internet Explorer and see what it looks like. Your Internet Explorer window should look similar to Figure 2.

Figure 2
 
Figure 2: Your first ASP.NET Web Service, complete with built-in test harness.

You will notice three things about the output. First, it has created a customized test harness for you so that you can exercise your Web Service. Microsoft ASP.NET has automatically provided links to each of the methods you tagged as Web Methods. Second, Microsoft ASP.NET has noticed a problem with your Web Service and provided a recommended solution. Third, it has given you a link where you can inspect the Web Service Description Language (WSDL). Let's look at each of these items in more detail.

 

Exploring the Built-In Test Harness

Say you are building a typical ASP/COM Web site. What's the first thing you do after you have stubbed out the first method of your Visual Basic (or C++ or whatever) DLL? If you are like me, you spend a minute or two creating a brain-dead host application with a single form and one big button on it to unit-test your method. As you develop this DLL, you spend an additional minute or two adding new command buttons to your test app every time you compile, and by the time you are done it has become a mess of command buttons and text boxes. (Now was it Command16 or Command17 that I hooked up to MyApp.CreateFakeData()?)

Here, with no effort on my own, I now have a test harness for all of my new Microsoft ASP.NET application. When I click the Add link in Figure 2, I get the page shown in Figure 3, which not only gives me a means of entering all the necessary arguments but also provides the actual request/response streams expected by the XML Web Service in HTTP GET, HTTP POST, and SOAP formats. Yes, Microsoft ASP.NET automatically processes input in each of these formats; you don't have to code any of it yourself. I have found this absolutely invaluable when developing for clients on, shall we say, less developer-friendly platforms for XML Web Services I have implemented with Microsoft .NET.

Figure 3
 
Figure 3: Microsoft ASP.NET comes with a built-in test harness.

 

Correcting Common Mistakes

One thing I neglected to do when I created my XML Web Service was to set the default namespace. The Microsoft ASP.NET engine caught this oversight and placed my Web Service in the http://tempuri.org/ namespace. What's more, it not only explained what the problem was but also provided a sample on how to fix it for both Microsoft Visual C#� and Microsoft Visual Basic .NET. A quick cut-and-paste later, and my Web Service is correct. Okay, so now I have 21 lines of code.

 

Reviewing Automatically Generated WSLD

The final thing to note about this test page is the Service Descriptor link that enables you to review the Web Service Description Language (WSLD). Writing this code by hand was one of the worst parts of developing early XML Web Services (and still is on some other platforms). Microsoft ASP.NET, however, not only generates all this code for you; it also returns it to the client based on the query string as shown in Figure 4.  First, this means that it is parsed at runtime so that the contract always matches the code itself (when is the last time your docs exactly matched your code?) Second, because it is readily available at a well-known location, other applications can query it and determine what methods the Web Services supports. 

Figure 4
 
Figure 4: Microsoft ASP.NET automatically generates SLD, which you can view by adding the ?WSDL query string.

For developers, this is a crucial feature. Just like earlier versions of Microsoft Visual Studio� processed type libraries to provide IntelliSense� and statement completion for COM objects, Visual Studio .NET additionally now parses the WSLD exposed by Web Services to provide that same level of productivity with Web Services that many developers have grown to depend upon for COM.

This concludes my demonstration of the productivity boost available on the Microsoft .NET platform. I stepped you through the conversion of a simple console application to an XML Web Service (with less than half the lines of code as the original application) and introduced you to a built-in test harness where you can start unit tests.

Next month I will take a look at Visual Studio .NET and show you how to build an application that consumes this and other Web Services and give you a tour of the other productivity boosts that are built into the development tool itself.

 

Microsoft Press Solutions

Now that you have an overview of Microsoft ASP.NET and have seen how easy it is, you should be ready to start building your own Web Services.
As you start to take on some relatively complex projects, the best way to ramp up quickly on all the features and best practices is to get a copy of Designing Microsoft ASP.NET Applications by Douglas J. Reilly.

Microsoft Press provides in-depth documentation for these and all the other issues related to developing for .NET. For a complete list of .NET titles from Microsoft Press, see the Inside Information about Microsoft .NET section.

For a more broad overview of all the Microsoft .NET technologies, you should look at David S. Platt's Introducing Microsoft .NET. It has some great information on COM Interop, Windows Forms, and .NET memory management.

Another good book is XML Step by Step by Michael Young. It is a practical, hands-on learning title that clearly explains the basics of XML and shows both nonprogrammers and Web developers alike how to create effective XML documents and display them on the Web.

One of my favorites is Jake Sturm's book, Developing XML Solutions, which  examines XML-related technologies for data exchange and shows how XML fits in the Microsoft Windows architecture.

For a complete list of all the developer titles, see the Developer Tools section.

For some great links and the latest information on Web Services, see the MSDN� Web Services home page. A good troubleshooting resource is Keith Ballinger's article on Web Services Interoperability and SOAP.

For more information on Microsoft Visual Studio .NET, see the Visual Studio Next Generation Home Page.

 

Top of Page
 
Last Updated: Tuesday, December 4, 2001