Active Server Pages+: ASP+ Improves Web App Dep...

We were unable to locate this content in de-de.

Here is the same content in en-us.

This article may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. To maintain the flow of the article, we've left these URLs in the text, but disabled the links.
MIND

Active Server Pages+: ASP+ Improves Web App Deployment, Scalability, Security, and Reliability

Dave Sussman

This article assumes you�re familiar with Visual Basic and ASP
Level of Difficulty    1   2   3 
SUMMARY ASP has been rebuilt from the ground up. The result? Active Server Pages+.
      ASP+, with a host of new features, provides for easier to write, cleaner code that's simple to reuse and share. ASP+ boosts performance and scalability by offering access to complied languages; development is more intuitive thanks to Web Forms; and an object-oriented foundation facilitates reuse. Other important features include page events, Web Controls, and caching.
      Server Controls and improvements in data binding are also new with ASP+. Libraries for use with ASP+, and the Microsoft .NET Framework which allows custom business functions to be exposed over the Web, provide more new development opportunities.

W
hat do you get when you take Active Server Pages and rewrite it from the ground up? Active Server Pages+. Active Server Pages+ (ASP+) is not just ASP 4.0. If it were, it would have just a few new features, and that would be that. ASP+ is more than just a few new goodies shoved into the same old schemaâ€"it's a whole new framework for Web development. Before delving into the details, let's take a look at a few of the goals of ASP+.

Benefits of ASP+

      ASP+ makes code cleaner. No matter how well you write them, existing ASP applications tend to be full of spaghetti code. ASP+ code is not only easier to write, it's cleaner and easier to read than ASP code. The manner in which ASP+ code is structured also promotes its reuse and sharing.
      ASP+ improves deployment, scalability, security, and reliability. With simple ASP applications, deployment isn't really an issue, but you run into problems when you start moving to proper n-tier designs that utilize components. The whole process of DLL Hell (component registration, versioning, locked DLLs, and so on) comes into play when you have to deploy and maintain these types of applications. ASP+ addresses this by eliminating component registration, DLL locking, and the use of XML configuration files. This allows you to deploy a Web application simply by copying directories.
      ASP+ provides better support for different browsers. The browser compatibility issue has felt like an eternal problem for ASP developers. You either have to code for downlevel browsers (using HTML 3.2, for example), or restrict your reach. The introduction of Wireless Application Protocol (WAP) devices (see http://msdn.microsoft.com/msdnmag/issues/0600/wireless/wireless.asp) will only further this problem. The section on Web Forms in this article describes how ASP+ addresses browser compatibility issues.
      ASP+ enables a new breed of Web applications. The current crop of Web applications all tend to follow the same patternâ€"a set of linear apps with logic built into one of them. ASP+ will allow developers to break out of this mold and produce more dynamic, scalable applications that better meet the business needs of corporations, as well as providing a richer development environment.
      At first glance you might think that although these are noble goals, they will probably make writing applications harder. That's where you'd be wrong. I've found all aspects of development in ASP+ to be much simpler.
      Let's look at the features in ASP+, including its support for compiled languages, Web Forms, page events with the Page Object, Web Controls, Web Services, caching, debugging, separation of code and content, common libraries available in namespaces, and easy configuration and deployment.

Using Compiled Languages

      Existing versions of ASP are based on scripting languages like VBScript and JScript®. There's nothing wrong with scripting languages per se, but they suffer from two major flaws: they are interpreted, and they are not strongly typed. Both of these lead to performance hits that you can certainly do without. ASP+ hasn't thrown out the idea of scripting languages, but it has introduced support for fully compiled languages, giving you the ability to write your server-side code in Visual Basic®, for example.

<script language="vb" runat="server">
One great advantage of Visual Basic is the support for strongly typed variables. So, the following is possible in ASP+:

Dim FirstName As String
      In addition to Visual Basic and C++, you can also use the updated Microsoft language, C#, to write server-side code. C# is C++ with all the unwieldy bits removed and made easier to understand. Even I can understand C#, so it can't be too difficult. (Check out "Sharp New Language: C# Offers Power of C++ and Simplicity of Visual Basic" by Joshua Trupin in this issue for more information on C#.)
      With ASP+, compilation occurs when the page is first loaded. Even scripting languages are compiled before execution, so JScript pages will also see a performance improvement. In fact, this is one of the fundamental new features of the .NET Framework. Previous versions of language compilers treated data types and objects differently, meaning that the only kind of cross-language development that could be done was COM objects creation. The new common language runtime in the Microsoft .NET Framework allows the close interaction of any code that has been compiled with common runtime support, and that's what the new Visual Basic and C# compilers doâ€"produce code that can be managed by the runtime.
      The greatest benefit of this is that true cross-language development is possible. With the common runtime you can create objects in C# and extend them in Visual Basic through inheritance. How is that possible? Well, in case you missed it, Visual Basic .NET now supports inheritance. So you can author components in C# and then subclass them in Visual Basic.
      Although Visual Basic, C#, and scripting are the only languages being supported in the Beta 1 timeframe, other languages (such as Smalltalk, Eiffel, Pascal, and so on) should be supported later. One advantage of the Microsoft .NET Framework is that extensibility is easy, so dropping in a new language is simply a matter of providing compiler support for generating runtime-compatible output.

Web Forms

      ASP+ Web Forms are Web pages that you let write code just as you do for ASP today. More than that, though, ASP+ Web Forms are designed on top of an object-oriented programming model, enabling code reuse and separation of the application code from page content. In Visual Basic you draw the controls on a form, then implement the event procedures underneath. In traditional ASP this isn't possible because there's no link between the UI controls and their server-side code. In ASP+, however, there is a link; instead of having to manually pull out values from the form variables, you can write code like that shown in Figure 1.
      There are two important points to note in Figure 1. The first is the use of the runat="server" attribute on the form and asp:textbox controls. This tells ASP+ that these controls can be accessed both on the server and the client. Controls used like this are called Server Controls. The use of asp: as a prefix to the control name itself identifies where the control comes from. I'll discuss this later.
      The second snippet to note is the OnClick event. When developing DHTML code you often use the OnClick event to fire an event in the browser. Well, this is the same principle, only the event is fired on the server because the runat="server" attribute is set for the control. This example could be extended simply by removing the Response.Write and replacing it with a server-based control as shown in Figure 2.
      The code behaves pretty much like a traditional client or Visual Basic form and is much more intuitive to code. You can use the server controls to link event procedures to server-based code. These server-based controls send pure HTML to the browserâ€"there's no client-side script involved. In fact, one of the key design objectives was to stick with the intrinsic HTML 3.2 elements to provide the best possible browser compatibility. For example, the code in Figure 2 generates the following HTML:

<html>
<body>

<FORM name="HtmlForm2" method="post" action="Test.aspx"
 id="HtmlForm2">
    <INPUT type="hidden" name="__VIEWSTATE" 
     value="a0z664351470__x">
    Name: <input name="txtName" type="text" id="txtName"><br>
    <input type="submit" name="Button5" value="Enter">
    <br>
    <span id="lblYouEntered"></span>
</FORM>

</body>
</html>
      The code that is generated is HTML 3.2. It performs a standard form post that sends the user input back to the same file. There is no server state maintained and no client-side script that maintains state either. The hidden field maintains the controls' state. This means that the controls automatically retain their state between page postbacks without any programming intervention.
      Although the default output of ASP+ Web Controls is HTML 3.2, they can also output DHTML for uplevel browsers such as Microsoft® Internet Explorer 5.0. This enables you to author pages using a single set of server controls, allowing the controls themselves to decide which type of output will be sent depending on the browser. This allows you to have controls that send DHTML and client-side scripting to recent versions of Internet Explorer, and plain HTML 3.2 to other browsers.

Page Events

      Earlier I mentioned that ASP+ has been rewritten from the ground up, but I didn't point out that it was rebuilt with object-orientation in mind. At the top of the object tree is the Page object; each ASP+ control, application, and page inherits from Page. This means that each page is an instance of the Page object. This becomes important when you realize that the Load event of the Page is an event you can respond to, as shown in Figure 3.
      Here you'll see the same Load/Unload order you are used to seeing in Visual Basic. The Load event is fired as the page is loading, when all of the server-based controls are available for use. During the interaction with the user, other events are generated, and then the Unload event is fired when the page is unloaded.

Web Controls

      You might be worried that controls like <asp:TextBox> represent a completely new set of controls you have to master. The controls are new, but they're not difficult to learn because they pretty much map onto their HTML equivalents. For example, consider something as simple as a text box. In HTML you'd do this:

<input type="text" value="Your Name"></input>
The corresponding Web Control looks like this:

<asp:TextBox Text="Your Name" runat="server" />
      Two things you might immediately notice are that the Web Control is identified by the asp: code namespace, and the use of the trailing slash to close the element as in XML. You don't have to use this XML styleâ€"you could use HTML style with a separate closing tag (</asp:TextBox>)â€"but you'll see it used in plenty of code samples, and it's quicker to type. The namespace does have to be used because it identifies where the TextBox control comes from; all of the standard WebControls are part of the ASP namespace. This becomes important when you author your own controls, which I'll discuss a little later.
      The TextBox control might not seem much of an advantage over the standard input box, but you should consider the following three input controls:

<input type="text" ...>
<input type="password" ...>
<textarea rows="5" ...>
They are all used for input in HTML, but there's no consistency. Wouldn't it be simpler if you could do this:

<asp:TextBox runat="server" ...>
<asp:TextBox TextBoxMode="Password" ...>
<asp:TextBox Rows="5" ...>
One simple control can provide the functionality of three, depending on how it's used. In fact, these two TextBox controls generate the same HTML output. What's different is that it's far easier to remember and code.
      ASP+ will ship with five families of Web Controls:
  • Intrinsic controls that map to their HTML equivalents
  • List controls to provide data flow across a page
  • Rich controls to provide richer UI content and functionality
  • Validation controls to perform a variety of form validation
  • Mobile controls to encapsulate WML for WAP devices, which is a post-Beta 1 feature
      The intrinsic server controls are similar to HTML controls, but have been rationalized to provide a more consistent usage. These controls include LinkButton, ImageButton, HyperLink, TextBox, CheckBox, RadioButton, DropDownList, ListBox, Image, Label, Panel, Table, TableRow, and TableCell.
      List controls include Repeater, DataList, and DataGrid (which will be covered in more detail in the next section). List controls also include a RadioButtonList and CheckBoxList to ease creation of lists of radio buttons and checkboxes.
      The rich controls consist of Calendar and AdRotator. The Calendar control will output pure HTML for downlevel browsers, or DHTML for uplevel browsers (such as Internet Explorer 5.0). The AdRotator outputs images, and has built-in rotation code. There are likely to be more rich controls after Beta 1.
      The validation controls include RequiredFieldValidator, CompareValidator, RangeValidator, RegularExpressionValidator, CustomValidator, and ValidationSummary. These provide easy ways for developers to build validation into form handling.
      Details of the mobile controls have yet to be released, but they will aid in the construction of WAP-enabled Web sites.

Authoring New Controls

      You are not limited to using only the supplied controls, and it's fairly easy to author your own. For example, if you wanted a single control to encapsulate two text boxes (perhaps for first and last name input fields), you could write code that looks like this:

<asp:Panel runat="server">
  <asp:Textbox id="txtFirstName" text="First Name"
   runat="server" />
  <asp:Textbox id="txtLastName"  text="Last Name"
   runat="server" />
</asp:Panel>
You can save this code in a file named Name.aspc (note the new extension), and treat this as though it were a Web Form control. For example, you can add the following to your Web Form:

<%@ Register TagName="NameControl" TagPrefix="Foo"
 Src="Name.aspc" %>
<form>
    <foo:NameControl runat="Server"/>
</form>
      The beauty of this is that you can create easily reusable code. You can also create controls directly in Visual Basic or C#, allow them to subclass from other controls, and render any output they require. Because controls are identified by a namespace, there should be no clashes of controlsâ€"in fact, you can even have controls of the same name, as long as they are in different namespaces. You can see how extensible this makes ASP+, and how the programming environment should get richer and richer. In fact, there's likely to be quite a large third-party market for rich controls.

Controls for Data Binding

      One of the new Web Controls is the DataGrid, which has built-in support for rendering sets of data. To generate an HTML table from SQL-generated data, you simply create ADO+ objects and execute the command to get the data, which you use as the source for the grid, as shown in Figure 4. All you have to do is bind the data to the data grid, and a neat HTML table is produced (see Figure 5). Data binding isn't just restricted to data from databasesâ€"you can bind to hash tables, arrays, other server controls, properties of the pageâ€"just about anything.
      If using the default set of columns doesn't suit you, you can customize it to only show those you're interested in.

<asp:DataGrid id="DataGrid1"
     AutoGenerateColumns="false" runat="server">
  <property name="Columns">
    <asp:BoundColumn HeaderText=" Name" 
     DataField="ProductName"/>
    <asp:BoundColumn HeaderText="Description" 
        DataField="ProductDescription"/>
  </property>
</asp:DataGrid>
      To pick a simple column you just use the BoundColumn control, specifying the column title and the column to bind to. Adding the AutoGenerate="false" attribute ensures that the grid doesn't create all of the columns for you. If you want more complexity, you can use a template for the column, too.
      The Repeater and DataList controls I mentioned earlier also support templating, which is a way of allowing the look of the control to be customized. The Repeater actually has no look at allâ€"you have to supply the UI, which means you'll have to use a template. The DataList control, on the other hand, is a data-bound list with a default look and rich behavior. Adding templates is done the same way for both:

<asp:DataList is="DataList1" runat="server">

  <template name="HeaderTemplate">
    Here's your list of titles<br>
  </template>

  <template name="ItemTemplate">

     <%# DataBinder.Eval(Container.DataItem, "Title") %> <br>

  </template>

</asp:DataList>
      With this form of templating you can specify which HTML controls will make up each part of your data-bound control. There are five template names you can use with the Data-List control: HeaderTemplate for the top part of your control, ItemTemplate for each item, Alternating-ItemTemplate for every other item, SeparatorTemplate for the area between each item, and FooterTemplate for the bottom part of your control.
Figure 6 DaveSGrid2.aspx Output
Figure 6 DaveSGrid2.aspx Output

      The beauty of this system is that you have a great deal of control over exactly how you want your interface to be displayed. Taking the list of products one step further, you could generate the output seen in Figure 6 with the code shown in Figure 7. This code is pretty simple and doesn't require much more than the DataList code shown earlier. One thing to note about the code in Figure 7 is that you can specify the number of columns that will appear, and the list will automatically handle column wrapping.
      So with just a little bit of formatting code, the Web page has been improved dramatically. You no longer have the traditional grid that is used on many Web pages, and with very little effort you have a great looking page.

Development of Web Services

      Software delivered as a service over the Internet is the key theme of Web Services. ASP+ provides a Web Services infrastructure that enables developers to create services for this service model.
      Let's take order tracking as a simple example. Imagine you buy books from an online book retailer and they have a tracking system that lets you see the status of your order. The book retailer uses a ground shipping company to ship your order. The shipping company also has a tracking system, so to see the exact status of your order you need to check two sites. Wouldn't it be more convenient for the book retailer to show its own order status as well as the status information from the shipping company?
      Web Services allow you to expose your custom business functions (such as package tracking details) to the public over the Web. You do this by writing an object that exposes its methods as URIs and which returns data as XML. Now the bookseller could call the shipping company tracking service and incorporate the tracking results into its own order-tracking application. Here's how the shipping company could create a service using C#:

<%@ WebService language="c#" %>

using System.Web.Services;

public class Shipping {
    [WebMethod]
    public String OrderStatus(String OrderNumber) {
        // code here to retrieve order details from data store
       return Status;
    }
}
      This could be placed in a file called Tracking.asmx in the application directory at the shipping company's Web site. The bookseller could then call this Web Service in a number of ways. It could use HTTP-GET, where the method parameters would be passed along with the query string. For example:

http://orders.ups.com/orders/Tracking.asmx/OrderStatus?
 OrderNumber=BRU123
The bookseller could use HTTP-POST, where the method parameters are passed within the body of the post as form values. Or it could use HTTP-SOAP, where the method parameters are packaged in an industry-standard XML format.
      Now the user can simply query the bookseller for their order details, and the bookseller's Web application will gather tracking information from the shipping company and return that along with the book status. The bookseller could also expose its order status details as a Web Service to allow other people to use it.
      The great thing about Web Services is that it allows you to expose a service without exposing data or proprietary business rules. Your code and data are kept safe while you supply business services automatically. The market for Web Services will grow rapidly in the next several years as a range of business-to-business solutions become available.

Improved Caching

      To build a high-performance, scalable Web site, you're bound to use some form of caching. Certain page-building operations are expensive to construct, and caching them once they have been constructed saves server resources and allows them to be served more quickly. There are plenty of tricks you can use with existing ASP applications to improve speed, but none go as far as the features that ASP+ has to offer including:
  • Page level caching, which allows entire pages to be cached
  • Fragment caching, which will allow portions of pages to be cached (post-Beta 1)
  • Cache API, which gives programmers access to the cache engine
      Page caching is the simplest, and allows dynamic pages to be output-cached so they are served directly from the cache rather than executed on every single request. You can specify either an absolute time (such as midnight) or a relative time (such as 20 minutes after the page was last accessed) for fine control over how long the pages stay in the cache. Fragment caching will offer the same degree of control over individual portions of an ASP+ page. Both of these techniques use the Cache API, which is exposed to the programmer to allow you to cache your own objects, rather than recreating them each time they are required. Smart use of caching can greatly improve speed.
      Caching is especially valuable for sites such as product catalogs where the content needs to be dynamic, but doesn't change very often. In ASP, if you need a dynamic catalog, you either have to rebuild it from the database on each page request or convert it to HTML. With page caching in ASP+ you can specify that the dynamic page be cached for a day, so that the first hit of the day caches the output from the page. Subsequent hits to that page are served from the cache.

Debugging and Tracing

      Are you fed up with using Response.Write as your primary debugging tool? I thought so. One of the goals of ASP+ is to make writing applications easier, and much as you would like to avoid the issue altogether, debugging is a key part of development. The way that ASP+ pages are compiled allows COM+ to hook into them as they are being executed and provide a rich debugging environment. And remember, this is the Microsoft .NET Framework, so debugging will be cross-language. You'll be able to step from your Visual Basic-based Web page into a control that has been written in C#.
      What sort of debugging facilities you get depends on the tool you're using. The Microsoft .NET Framework services come with a debugger built in, providing a comprehensive set of features, but only on the local machine. When the next version of Visual Studio® is released, it is expected to feature an enhanced version of the debugger, allowing remote application debugging.
      Profiling and tracing are also important techniques used during development. Apart from Response.Write, it's never been easy to monitor the progress of an ASP application. This isn't important just for watching the flow of the application. It's also important from a testing point of view to see which areas of your code are performing poorly.
      Tracing is built into ASP+ via the Trace method of the page. For example, to trace entry and exit into an event procedure you could use this code:

Sub Page_Load(Source As Object, E As EventArgs)
    Trace.Write "Page_Load", "Start"

    ' rest of code goes here

    Trace.Write "Page_Load", "End"
End Sub
To enable output of this trace information, you would use a Page directive like this:

<%@ Page Trace="True" %>
When this page is run, you'll get a table at the end of the page that looks like the one in Figure 8.
Figure 8 Trace Information Output
Figure 8 Trace Information Output

      By default, the tracing shows times for the default methods, but adding Trace.Write allows you to add your own details to this. If you want trace information but don't want users to be able to see it, you can always set up the application to send the trace information to another location where it can be examined at a later time. An added benefit is that you can get a complete trace tree of all controls on the page, the server control variables, and so on. This is a real productivity boon for the developer.
      ASP+ has also been integrated with the Performance Monitor in Windows NT® and Windows® 2000, and has a full set of PerfMon counters to allow the state of ASP+ as well as individual ASP+ applications to be monitored.

Separation of Code and Content

      One of the great advantages of ASP+ is the ability to separate code from content. All inline code can be split from the page and placed in a class module. This allows your art department to make the site look nice, while the programmers can take care of the work on their end.
      There are other advantages to splitting content from style. One is that standard design tools can be used to construct the UI without worrying about code being munged. Another is that localization becomes much simpler since the UI page consists purely of UI, rather than a mix of UI and code.

Libraries

      Because the functionality of ASP+ has been modularized, common features have been neatly packaged together into libraries. In traditional ASP these would probably be used by way of include files or DLLs. In ASP+, everything that is used during the processing of ASP+ code is contained within hierarchical namespaces, providing a structured way of organizing not only the system code, but also your own code. That means that these are accessible from within pages by importing the namespace that contains the code.

<%@ Import Namespace="System.ASP.Util" %>
      This code will import the Util namespace, allowing access to ASP+ utilities. One great use of the utility package is sending mail. If you hang around the ASP newsgroups you might be surprised by how often the question "How do I send mail from an ASP page?" crops up. There are plenty of ways to do this, depending on what you've got installed, and it's never as easy as it should be. ASP+ makes it simple because an SMTP SendMail component has been built in, allowing code like:

<% Import Namespace="System.ASP.Util" %>

<html>
    <script language="vb" runat="server">
    
    Sub SendMail_Click(Source As Object, E As EventArgs)
        Dim myMessage   As New MailMessage
        Dim myMail      As New SmtpMail

        myMessage.From = "me@here.com"    
        myMessage.To = "you@there.com"    
        myMessage.Subject = "Great News"    
        myMessage.Body = "ASP+ rocks"    
    
        myMail.Send (myMessage)
        End Sub
        </script>
        <form runat="server">
            <asp:button id="SendMail" text="Send Mail"
                    OnClick="SendMail_Click" runat="server" />
        </form>
  </html>
      The Util assembly is just one of a number of prebuilt code libraries containing code for network communication, cryptography, event log writer, and so on. What's great about these libraries is that, like everything else in ASP+, they are cross-language, so there are no restrictions regarding which language they can be written in or used from.

Configuration and Deployment

      ASP+ configuration informationâ€"information such as the name of the application handling the HTTP requests and permissions dataâ€"is stored in XML files. If you change one of these files, thereby updating the configuration, the common runtime will automatically pick up and propagate any change that you have made.
      For simple site deployment isn't much of a problem. However, start building a three-tier application with components and your problems have only just begun. During development it's not much of a problem to stop the Web server so you can install a new version of a DLL; it's inconvenient, but it's not the end of the world. On a live site, however, it's not so easy to shut down the Web server. (Hotmail®, for example, has around 5,000 servers.) It's also a pain to manage the DLL registration process when you deploy a site.
      Deploying an ASP+ application is simply a matter of copying the directory. Yes, that's all there is to it. Any components placed in the application's bin directory are automatically availableâ€"there are no problems with locked files, and no registration is required. Just copy the whole lot and you're set. Need to update that component? Just recompile and copy it over. When I first saw ASP+ demonstrated, this got the biggest applause!
      ASP+ will also support the deployment of a fully compiled application. The benefit is that none of the source code is visible to the administrator of the Web serverâ€"an important feature if another company hosts your application.

Summary

      ASP+ will be offered at no charge on Microsoft Internet Information Services (IIS) 5.0 (in Windows 2000), IIS 4.0 (in Windows NT 4.0), as well as personal versions for Windows 95 and Windows 98. Only the Windows 2000 version is available during the Beta 1 timeframe (from July 2000). The other platforms will support it at a later date.
      ASP+ takes a giant leap from the existing ASP architecture. The whole infrastructure allows for development of structured applications. Web Forms brings a development model that is more intuitive and certainly easier to use. Server Controls add the ability to provide common features and makes extending and enhancing existing functionality easier. Data binding allows simple creation of data-bound applications.
      ASP+ is really exciting. Not only are there lots of great new features, but at long last there is a real framework for developing Web applications. In the past, ASP applications have seemed a bit like sticky tape and string. Having been a professional developer of client-server systems, I was used to a good development environment and a rich set of tools and features. ASP+ has delivered those features and more.
      Thanks go to Scott Guthrie, Rob Howard, and the rest of the ASP team for help during the writing of this article.

For background information see:
COM Objects in ASP
ASP Conventions

Dave Sussman is a full-time author, specializing in data access and Internet technologies. Most of his working life is spent authoring books for Wrox Press. In what little spare time he has, he listens to music or juggles. Or both.

From the September 2000 issue of MSDN Magazine.

Page view tracker