5,317,180 members and growing! (22,149 online)
Email Password   helpLost your password?
General Reading » Book Chapters » Apress     Intermediate

A Preview of Active Server Pages+ - Chapter 1: Introducing ASP+

By Wrox

An introduction to ASP.NET
Windows, .NET 1.0, .NET, ASP.NET, Visual Studio, Dev

Posted: 27 Nov 2000
Updated: 27 Nov 2000
Views: 62,064
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
12 votes for this Article.
Popularity: 4.86 Rating: 4.50 out of 5
Sample Image
Title A Preview of Active Server Pages+
Authors Richard Anderson, Alex Homer, Robert Howard, David Sussman
Publisher Wrox
Published July 2000
ISBN 1861004753
Price US 34.99
Pages 300

Even though the ink is barely dry on the documentation for Active Server Pages 3.0, Microsoft is already hard at work on the next generation of their core server-side programming technology. In this chapter, we introduce this new product, and look at what it is all about. Currently called ASP+ Next Generation Web Services (though this name might yet change) we'll see why we need a new version of ASP, and explore the concepts behind its design and implementation. While this book is aimed predominantly at experienced developers who have used ASP before, we start out in this chapter by examining some of the core issues involved when you decide to migrate to ASP+.

ASP+ is designed to be backwards-compatible with earlier versions of ASP, with only minor changes required in some circumstances (we explore these further in the appendices). However, more to the point, you can install ASP+ on an existing Windows 2000 server alongside ASP 3.0. This allows you to experiment with the new version, without requiring a separate 'test bed' server. You can continue using existing ASP applications, and migrate them ASP+ when you are ready, so your investment in ASP is not lost.

But simply porting your applications to ASP+ will only give you a few of the benefits the new version offers. ASP+ has many new features that provide far greater ease of use, more power and better
runtime efficiency, but to take advantage of them you will need to understand more about the way
that ASP+ works.

As we are writing this book using a preview version of ASP+, we can't be exactly sure of all the features of the final release. But thanks to the information and assistance provided by the ASP+ team at Microsoft, we can be pretty sure that the content of the book will be reliable and useful with the final version. We'll also be maintaining a special Web site that is accessible from http://www.wrox.com/beta, where we'll document changes as the beta and final release versions appear, and provide some detailed information as well.

So, in this first chapter, we'll cover:

  • How Active Server Pages has evolved since its inception

  • What the new runtime framework is

  • How ASP+ is different to ASP, and why

  • A brief guide to getting started with ASP+

  • Some of the changes expected in the final release version

We start with a look at the way that ASP and ASP+ have evolved, as this will help to set the background for understanding and working with the new product. For more information about working with COM+ and previous versions of ASP, check out Professional ASP 3.0, (ISBN 1-861002-61-0) from Wrox.


The Evolution of Active Server Pages

Although it seems to have been around forever, Active Server Pages is only some three-and-a-bit years old. Since its inception in late 1996, it has grown rapidly to become the major technique for server-side Web programming in the Windows environment (and on some other platforms using other implementations that accept the same or similar syntax, such as ChilliASP). But it didn't come from nowhere – the foundations lie much further back than that.

Dynamic Server-side Web Programming

Traditionally, dynamic Web pages have been created using server-side executable programs. A standardized Web server interface specification called the Common Gateway Interface (CGI) allows an executable program to access all the information within incoming requests from clients. The program can then generate all the output required to make up the return page (the HTML, script code, text, etc.), and send it back to the client via the Web server.

To make the programmer's life easier, and save having to create executable programs, languages such as Perl use an application that accepts text-based script files. The programmer simply writes the script, and the Web server executes it using a Perl interpreter.

Microsoft ISAPI Technologies

Microsoft introduced another Web server interface with their Web server, Internet Information Server. This is the Internet Server Application Programming Interface (ISAPI), and differs from the CGI in that it allows compiled code within a dynamic link library (DLL) to be executed directly by the Web server. As with the CGI, the code can access all the information in the client request, and it generates the entire output for the returned page.

Most developments in Microsoft's Web arena have been based on the ISAPI interface. One early and short-lived product was dbWeb, a data access technology that provided a range of searching, filtering and formatting capabilities for accessing data stored on the server, and for interacting with the client.

A second development was the Internet Database Connector (IDC). This proved a big hit with developers – not only because it was fast and efficient (unlike dbWeb), but also because it was a lot more generic and easier to program. IDC introduced the concept of templates, allowing programmers to easily adapt existing HTML pages to use its features and quickly build new applications around it.

IDC uses two text files for each 'page'. The first is a simple script that defines the way that the data should be collected from the server-based database. In essence, it is just a SQL statement plus some configuration information:

{this is the query file named getuserlist.idc}
Datasource: GlobalExampleData
Username: examples
Password: secret
Template: getuserlist.htx
SQLStatement:
+ SELECT DISTINCT UserName
+ FROM Person ORDER BY UserName;

The server executes this file to obtain the results recordset, then loads a template file:

{this is an extract from the template file named getuserlist.htx}
...
<TABLE>
  <TR>
    <TD>User name:</TD>
    <TD>
      <SELECT NAME=selUserName>
        <%BeginDetail%>
         <OPTION VALUE="<%UserName%>"><%UserName%>
        <%EndDetail%>
      </SELECT>
    </TD>
  </TR>
</TABLE>
...

The template is just an ordinary Web page, including HTML, text and other objects, but with one or more specially delimited placeholders inserted. And the syntax for these placeholders, and the other simple program code constructs that are supported, is eerily like ASP. Of course, it was from this that ASP actually evolved:

The Versions of ASP

So, it was in early 1996 that Denali (the codename for ASP) was released as a beta version 0.9 product, and it took the Web-development world by storm. The ability to execute code inline within a Web page was so simple and yet so powerful. With the provision of a series of components that could perform advanced features, most notably ActiveX Data Objects (ADO), it was almost child's play to create all kinds of dynamic pages.

The final release version of Active Server Pages 1.0, available as an add-on for IIS 3.0, was soon in use on Windows platforms all over the place. The combination of ASP with ADO enabled developers to easily create and open recordsets from a database. There's no doubt that this was one of the main factors for its rapid acceptance, because now you could create and open recordsets from a database within the script, and manipulate and output any values, in any order, almost any way you wanted.

In 1998, Microsoft introduced ASP 2.0 as part of the free Windows NT4 Option Pack. The major difference between this release of ASP and version 1.0 was in the way that external components could be instantiated. With ASP 2.0 and IIS 4.0, it is possible to create an ASP application, and within it run components in their own separate memory space (i.e. out of process). The provision of MicrosoftTransactionServer (MTS) also made it easy to build components that can partake in transactions.

Windows 2000, COM+, and ASP 3.0

Early this year (2000), Windows 2000 arrived. This contains version 5.0 of IIS, and version 3.0 of ASP. Other than some minor additions to ASP, the core difference here is actually more to do with COM+. In Windows 2000, Microsoft combined MTS with the core COM runtime to create COM+. This provides a host of new features that make the use of components easier, as well as giving a much more stable, scalable and efficient execution platform.

Other than a few minor changes to the management interface, IIS has not changed a great deal on the surface. However, underneath, it now uses COM+ Component Services to provide a better environment for components to be executed within, including out of process execution as the default and the option to run each component in its own isolated process if required.

ASP+ and the Next Generation Web Services Framework

All this brings us to the present, with ASP+. The underlying structure of ASP+ is very different to that of previous versions, although from the 'outside' (as far as the developer is concerned) it does appear to offer a very similar interface. ASP+ is almost entirely component-based and modularized, and every page, object, and HTML element you use can be a runtime component object.

For this to perform efficiently, and provide a scalable solution, the management of these objects is a very necessary prerequisite. The new runtime environment carries out this management automatically, allowing ASP+ to become far more object-oriented in nature. This lets developers build more powerful applications by accessing these component objects in a far more granular and controlled manner.

On top of that, the object orientation of ASP+ provides extensibility for the environment as a whole. Developers can add to and extend the environment, both by creating new components or inheriting from the base classes that create them, and by over-riding selected behavior as required. Under the hood, the COM+ runtime manages the instantiation, pooling, and allocation of the objects automatically.


The Next Generation Web Services Framework

So, COM+ provides a framework of operating system services. But that's not the whole story. ASP+ is actually a part of a brand new runtime framework that provides support for all kinds of applications in Windows. The framework is a key part of of Microsoft's Next Generation Web Services or NGWS. When you install this, you get ASP+ as part of the package. The NGWS framework supports all other server-side programming techniques as well, such as a new managed component service, support for building executable applications and Windows Services, access to performance counter APIs and Event Log APIs, etc.

The NGWS framework extends the Component Object Model (COM) architecture that we use to create re-usable and interoperable software components by adding new and enhanced services for scalable distributed applications:

  • A unified, rich set of programming libraries
  • A secure, multi-language runtime engine
  • Simplified application creation, deployment and maintenance
  • Increased scalability for distributed applications
  • Protection of existing software and training investments

We'll look at how it does all these things next.

What Is the NGWS Framework?

The integration of ASP into the operating system differs remarkably from earlier versions of ASP, which were basically just add-ons to the operating system. Up until now, ASP has been implemented through an ISAPI DLL named asp.dll, plus a few new system files and the ASP user components that came as part of the package (such as the Browser Capabilities component).

The NGWS framework reflects the information technology industry's changing view of the needs for creating, deploying, and maintaining Web services of all types – ranging from simple client applications to the most complex distributed architectures. The overall concept and strategy is part of the Windows Distributed Internet Applications (DNA) architecture.

However, the important part to recognize is that the framework is not just there for ASP+. It acts as a base for all kinds of applications to be built on Windows. The following diagram shows how the runtime framework supports ASP+ Applications:

The NGWS framework provides an execution engine to run code, and a family of object oriented classes/components that can be used to build applications. It also acts as an interface between applications and the core operating system. You might ask why we need such a layer, when existing applications can talk to the core operating system and services quite easily. The reason is that it allows applications to use the operating system to best advantage, in a standard way that permits faster and simpler development – something that is increasingly necessary in today's competitive commercial environment.

To achieve these aims, the runtime framework implements many of the features that the programmer, or the specific programming language environment, had to provide themselves. This includes things like automatic garbage collection, rich libraries of reusable objects to meet the needs of the most common tasks, and improved security for applications. This last point, of course, is becoming more important with the spread of networked applications – especially those that run over the Internet.

A Common Intermediate Language

However, one of the biggest advantages that the runtime framework provides is a language-neutral execution environment. All code, irrespective of the source language, is compiled automatically into a standard intermediate language (IL) – either on command or when first executed (in the case of ASP+). The runtime framework then creates the final binary code that makes up the application and executes it. The compiled IL code is used for each request until the source code is changed, at which point the cached version is invalidated and discarded.

So, whether you use Visual Basic, C#, JScript, Perl or any of the other supported languages, the intermediate code that is created is (or should be) identical. And the caching of the final binary object code improves efficiency and scalability at runtime as well.

C# is the new language from Microsoft especially designed for use with the Next Generation Web Services framework and ASP+. It combines the power and efficiency of C++ with the simplicity of Visual Basic and JScript.

One thing that this achieves is the ability to call from one language to another, and even inherit from objects created in one language and modify them within another language. For example, you can inherit an object that is written in C# in your VB program and then add methods or properties, or over-ride existing methods and properties. In fact, parts of the framework, and the entire ASP+ object model, are now implemented internally using C# rather than C++.

So, the new runtime framework introduces a true multi-language platform for programming any kind of application. As most of our current development is in the area of distributed applications, especially Internet- and Intranet-based applications, many the new features are directly aimed at this type of development.

The Web Application Infrastructure

The three sections shown highlighted in the previous diagram (and repeated in the next diagram) are those that implement ASP+ itself, and which we're interested in for this book:

Together, these three sections implement the Web Application Infrastructure – the topic that we are concerned with in this book. Together with the new runtime framework, it provides a range of exciting new features:

User Interface Support

As part of the ASP+ libraries, there is a host of intelligent server-based rich controls for building Web-based user interfaces quickly and simply. They can output HTML 3.2 code for down-level browsers, while taking advantage of the runtime libraries for enhanced interactivity on richer clients such as Internet Explorer 4 and above.

These server-based controls can be also be reused to build controls composed of other controls, inheriting implementation and logic from these constituent controls.

Data Access Support

The NGWS framework provides a new version of ADO, called ADO+, which offers integrated services for accessing data – regardless of the format or location of that data. ADO+ presents an object-oriented view of relational data, giving developers quick and easy access to data derived from distributed sources.

ADO+ also improves support for, and to some extent relies on, XML. ADO+ can automatically persist and restore recordsets (or datasets as they are now called) to and from XML. As we'll see, this is particularly useful when passing data around the Web using ASP+ Web Services.

Scalability for Distributed Applications

Two of the major requirements for any Web-based application are a robust operating platform, and scalability to allow large numbers of multiple concurrent requests to be handled. The NGWS runtime provides these features by allowing automatic error and overload detection to restart and manage the applications and components that are in use at any one time. This prevents errant code or memory leaks from soaking up resources and bringing the server to a halt.

There are also new and updated system and infrastructure services, including automatic memory management and garbage collection, automatic persistence and marshaling, and evidence based security. Together these features provide for more scalable and reliable resource allocation and application processing.

Existing Software and Training Investments

Despite all the changes to the core operating system and runtimes, great care has been taken to maintain backward compatibility with earlier versions of Windows, COM and ASP. In most cases, existing applications, COM and COM+ components, ASP pages, and other scripts and executables work under the NGWS runtime. Alternatively, you can update them in your own time as your business requirements demand.

All ASP+ pages have the .aspx file extension, and this is mapped to the ASP+ runtime framework. This allows pages that have the .asp file extension to run unchanged under the existing ASP runtime.


How is ASP+ Different from ASP?

Having seen in outline how ASP+ is now an integral part of the operating system, we need to look at the other aspect. How, and why, is ASP+ different to earlier version of ASP? And just how different is it? Well, if you just want to run existing pages and applications, you probably won't notice the differences much at all. However, once you open up the ASP+ SDK or Help files, you'll see a whole new vista of stuff that doesn't look the least bit familiar.

Don't panic! We'll work through the main differences next. We'll start with a look at why Microsoft has decided that we need a new version of ASP, and how it will help you, as a developer, to meet the needs of the future when creating Web sites and applications. We'll follow this with a checklist of the major new features of ASP+, then examine each one in a little more detail. The remainder of the book then covers the new features one by one, explaining how you can use them.

Why Do We Need a New Version of ASP?

In the Introduction to this book, we listed the main motivations that Microsoft had when designing and developing ASP+. After all, considering that ASP has been so successful, why do we need a new version? There are really four main issues to consider:

  • Currently, ASP can only be scripted using the basic non-typed languages such as VBScript and JScript (unless you install a separate language interpreter). While ASP does parse and cache the code for the page the first time it is executed, the limitations prevent more strongly-typed languages like Visual Basic and C++ from being used where this would be an advantage. ASP+ provides a true language-neutral execution framework for Web applications to use.
  • It is also very easy to create huge ASP pages containing a spaghetti-like mixture of code, HTML, text, object declarations, etc. And it's hard to re-use code, unless you place it in separate 'include' files – not the best solution. In many environments, developing a Web application utilizes the skills of a wide range of professionals, for example, you have programmers writing the code, and designers making the HMTL look good. Having both the code and the content intermixed in a single file that both of these groups need to operate on makes it difficult for them to work together. ASP+ allows true separation of code and content.
  • In previous versions of ASP, you have to write code to do almost anything. Want to maintain state in form fields? Write code. Want to validate data entered on the client? Write code. Want to emit some simple data values? Write code. Want to cache regions of pages to optimize performance? Write code. ASP+ introduces a real component model, with server-based controls and an event driven execution paradigm similar in concept to the way that a Visual Basic 'Form' works now. The new ASP+ server controls are declarative (i.e. you only have to declare them in order to get them to do something), and so you actually write less code – in fact, in many situations you don't have to write any code at all!
  • The world out there is changing. The proportion of users on the Web that will access your site through an 'Internet device' such as a mobile cellular phone, personal digital assistant (PDA), TV set-top box, games console, or whatever else, will soon be greater that the number using a PC and a traditional Web browser. This means that we probably have to be prepared to do more work at the server to tailor our pages to suit a specific device. We'll also have to create the output in a whole new range of formats such as the Wireless Markup Language (WML). And, in addition to creating WML for rendering, new Internet devices and business applications are going to want to be able to send and receive XML data from Web applications. Doing this today from ASP requires you to manually use an XML parser, convert data to and from XML schemas, etc. ASP+ Web Services makes it much easier.

Besides all of this, the rapidly changing nature of distributed applications requires faster development, more componentization and re-usability, easier deployment, and wider platform support. New standards such as the Simple Object Access Protocol (SOAP), and new commercial requirements such as business-to-business (B2B) data interchange, require new techniques to be used to generate output and communicate with other systems. Web applications and Web sites also need to provide a more robust and scalable service, which ASP+ provides through proactive monitoring and automatic restarting of applications when failures, memory leaks, etc. are discovered.

So, to attempt to meet all these needs, ASP has been totally revamped from the ground up into a whole new programming environment. While there are few tools available to work with it just yet, Visual Studio 7.0 will be providing full support to make building ASP+ applications easy (both ASP+ Pages and ASP+ Services).

The rich, component based, event driven programming model is specifically designed to be 'tools friendly', and this support will be available for all Visual Studio languages – including VB, C++, and C#. And you can be sure that third party tool manufacturers will not be far behind.

The Big Advantages with ASP+

The biggest challenges facing the Web developer today must be the continued issues of browser compatibility, and the increasing complexity of the pages that they have to create. Trying to build more interactive pages that use the latest features of each browser, whilst still making sure that the pages will work on all the popular browsers, is a nightmare that refuses to go away.

And, of course, it will only get worse with the new types of Internet device that are on the way, or here already. In particular, trying to build pages to offer the same user-level capability to cellular phones as to traditional browser clients is just about impossible. The text-only 12-character by 3-line display of many cellular phones does tend to limit creativity and user interaction.

One obvious solution is to create output that is targeted at each specific client dynamically – or create multiple versions of the same site, one for each type of client. The second option is not attractive, and most developers would prefer the first one. However, this implies that every hit from every user will require some server-side processing to figure out what output to create.

If this is the case, why not automate much of the process? To this end, ASP+ introduces the concept of server controls that encapsulate common tasks and provide a clean programming model. They also help to manage the targeting of all the different types of client.

Server-side HTML Controls – Less Code to Write

ASP has always provided the opportunity to execute components on the server, and these components can generate sections of the page that is returned to the user. ASP+ extends this concept through server controls. All that's required to turn any HTML element into a server control is the addition of an extra attribute: runat="server".

Any HTML element in a page can be marked this way, and ASP+ will then process the element on the server and can generate output that suits this specific client. And, as a by-product, we can do extra tricks – in particular with HTML <form> and the associated form control elements, where we can create the code to manage state during round trips to the server. This makes the programming experience less monotonous and dramatically more productive.

While the concept of having HTML elements that execute on the server may at first seem a little strange, as you'll see it adds a whole new layer of functionality to the pages, and makes them easier to write at the same time. What more could a programmer want?

The Problems with Maintaining State

One of the most cumbersome tasks when creating interactive Web sites and applications is managing the values passed to the server from HTML form controls, and maintaining the values in these controls between page requests. So one of the core aims of ASP+ is to simplify this programming task. This involves no extra effort on the part of the programmer, and works fine on all browsers that support basic HTML and above.

Take a look at the following section of code. This creates a simple form using HTML controls where the user can enter the name of a computer and select an operating system. OK, so this isn't a terribly exciting example in itself, but it illustrates a pretty common scenario used by almost every web application out there today. When the form page is submitted to the server, the values the user selected are extracted from the Request.Form collection and displayed with the Response.Write method. The important parts of the page are highlighted in the code listing:

<html>
  <body>
    <%
    If Len(Request.Form("selOpSys")) > 0 Then
      strOpSys = Request.Form("selOpSys")
      strName = Request.Form("txtName")
      Response.Write "You selected '" & strOpSys _
                   & "' for machine '" & strName & "'."
    End If
    %>    
    <form action="pageone.asp" method="post">
      Machine Name:
      <input type="text" name="txtName">
      <p />
      Operating System:
      <select name="selOpSys" size="1">
        <option>Windows 95</option>
        <option>Windows 98</option>
        <option>Windows NT4</option>
        <option>Windows 2000</option>
      </select>
      <p />
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Although this is an ASP page (the file extension is .asp rather than .aspx), it will work just the same under ASP+ if we changed the extension to .aspx. Remember that the two systems can quite freely co-exist on the same machine, and the file extension just determines whether ASP or ASP+ processes it.

This screenshot shows what it looks like in Internet Explorer 5. When the user clicks the Submit button to send the values to the server, the page is reloaded showing the selected values. Of course, in a real application, some the values would probably be stored in a database, or be used to perform some application-specific processing – for this example we're just displaying them in the page:

One problem is that the page does not maintain its state, in other words the controls return to their default values. The user has to re-enter them to use the form again. You can see this is the next screenshot:

To get round this situation, we have to add extra ASP code to the page to insert the values into the controls when the page is reloaded. For the text box, this is just a matter of setting the value attribute with some inline ASP code, using the HTMLEncode method to ensure that any non-legal HTML characters are properly encoded. However, for the <select> list, we have to do some work to figure out which value was selected, and add the selected attribute to that particular <option> element. The changes required are highlighted below:

<html>
  <body>
    <%
    If Len(Request.Form("selOpSys")) > 0 Then
      strOpSys = Request.Form("selOpSys")
      strName = Request.Form("txtName")
      Response.Write "You selected '" & strOpSys _
                   & "' for machine '" & strName & "'."
    End If
    %>
    <form action="pageone.asp" method="post">
      Machine Name:
      <input type="text" name="txtName"
             value="<% = Server.HTMLEncode(Request("txtName")) %>">
      <p />
      Operating System:
      <select name="selOpSys" size="1">
        <option
        <% If strOpSys = "Windows 95" Then Response.Write " selected" %>
        >Windows 95</option>
        <option
        <% If strOpSys = "Windows 98" Then Response.Write " selected" %>
        >Windows 98</option>
        <option
        <% If strOpSys = "Windows NT4" Then Response.Write " selected" %>
        >Windows NT4</option>
        <option
        <% If strOpSys = "Windows 2000" Then Response.Write " selected" %>
        >Windows 2000</option>
      </select>
      <p />
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Now, when the page is reloaded, the controls maintain their state and show the values the user selected:

This page, named pageone.asp, is in the Chapter01 directory of the samples available for the book. You can download all the sample files from our Web site at http://www.wrox.com.

Controls that Automatically Maintain Their State

So, how does ASP+ help us in this commonly met situation? The next listing shows the changes required for taking advantage of ASP+ server controls that automatically preserve their state. We still use the Response.Write method to display the selected values. However, this time some of the elements on the page have the special runat="server" attribute added to them. When ASP+ sees these elements, it processes them on the server and creates the appropriate HTML output for the client:

<html>
  <body>
    <%
    If Len(Request.Form("selOpSys")) > 0 Then
      strOpSys = Request.Form("selOpSys")
      strName = Request.Form("txtName")
      Response.Write("You selected '" & strOpSys _
                   & "' for machine '" & strName & "'.")
    End If 
    %>
   <form runat="server">
      Machine Name:
      <input type="text" id="txtName" runat="server">
      <p />
      Operating System:
      <select id="selOpSys" size="1" runat="server">
        <option>Windows 95</option>
        <option>Windows 98</option>
        <option>Windows NT4</option>
        <option>Windows 2000</option>
      </select>
      <p />
      <input type="submit"\ value="Submit">
    </form>
  </body>
</html>

You can clearly see how much simpler this ASP+ page is than the last example. When loaded into Internet Explorer 5 and the values submitted to the server, the result appears to be just the same:

This page, named pageone.aspx, is in the Chapter01 directory of the samples available for the book. You can download all the sample files from our Web site at http://www.wrox.com.

How Do the Server-Side Controls Work?

How is this achieved? The key is the runat="server" attribute. To get an idea of what's going on, take a look at the source of the page from within the browser. It looks like this:

<html>
  <body>
    You selected 'Windows 98' for machine 'tizzy'.
    <FORM name="ctrl0" method="post" action="pageone.aspx" id="ctrl0">
    <INPUT type="hidden" name="__VIEWSTATE" value="a0z1741688109__x">
      Machine Name:
      <INPUT type="text" id="txtName" name="txtName" value="tizzy">
      <p />
      Operating System:
      <SELECT id="selOpSys" size="1" name="selOpSys">
        <OPTION value="Windows 95">Windows 95</OPTION>
        <OPTION selected value="Windows 98">Windows 98</OPTION>
        <OPTION value="Windows NT4">Windows NT4</OPTION>
        <OPTION value="Windows 2000">Windows 2000</OPTION>
      </SELECT>
      <p />
      <input type="submit" value="Submit">
     </FORM>
  </body>
</html>

We wrote this ASP+ code to create the <form> in the page:

<form runat="server">
   ...
</form>

When the page is executed by ASP+, the output to the browser is:

<FORM name="ctrl0" method="post" action="pageone.aspx"
id="ctrl0">
   ...
</FORM>

You can see that the action and method attributes are automatically created by ASP+ so that the values of the controls in the form will be POSTed back to the same page. ASP+ also adds a unique id and name attribute to the form as we didn't provide one. However, if you do specify these, the values you specify will be used instead.

If you include the method="GET" attribute, the form contents are sent to the server as part of the query string instead, as in previous versions of ASP, and the automatic state management will no longer work.

Inside the form, we wrote this ASP+ code to create the text box:

<input type="text" id="txtName" runat="server">

The result in the browser is this:

<INPUT type="text" id="txtName" name="txtName" 
      value="tizzy">

You can see that ASP+ has automatically added the value attribute with the text value that was in the control when the form was submitted. It has also preserved the id attribute we provided, and added a name attribute with the same value.

For the <select> list, we wrote this code:

      <select id="selOpSys" size="1" runat="server">
        <option>Windows 95</option>
        <option>Windows 98</option>
        <option>Windows NT4</option>
        <option>Windows 2000</option>
      </select>

ASP+ obliged by outputting this HTML, which has a selected attribute in the appropriate
<option> element:

      <SELECT name="selOpSys" id="selOpSys" size="1">
        <OPTION value="Windows 95">Windows 95</OPTION>
        <OPTION selected value="Windows 98">Windows 98</OPTION>
        <OPTION value="Windows NT4">Windows NT4</OPTION>
        <OPTION value="Windows 2000">Windows 2000</OPTION>
      </SELECT>

Again, a unique id attribute has been created, and the <option> elements have matching value attributes added automatically. (If we had provided our own value attributes in the page, however, these would have been preserved.)

The Page VIEWSTATE

The other change is that ASP+ has automatically added a HIDDEN-type control to the form:

<INPUT type="hidden"
name="__VIEWSTATE" value="a0z1741688109__x">

This is how ASP+ can store ambient state changes of a page across multiple requests – i.e. things that don't automatically get sent back and forth between the browser and server between Web requests. For example, if the background color of a server control had been modified it would use the VIEWSTATE hidden field to remember this between requests. The VIEWSTATE field is used whenever you post back to the originating page. In Chapter 2, we discuss this topic in more detail.

So, as you can see, there really aren't any 'magic tricks' being played. It's all standard HTML, with no client-side script libraries, and no ActiveX controls or Java applets. An equally important point is that absolutely no state is being stored on the server. Instead, values are simply posted to the server using standard methods. Values are preserved and maintained across requests simply by the server controls modifying the HTML before the pages are sent to the client.

Server-side Code in ASP+

To display the values in the page, we used code that is very similar to that we used in the ASP example earlier on:

    ...
    If Len(Request.Form("selOpSys")) > 0 Then
      strOpSys = Request.Form("selOpSys")
      strName = Request.Form("txtName")
      Response.Write("You selected '" & strOpSys _
                   & "' for machine '" & strName & "'.")
    End If 
    ...

However, one of the other great features of ASP+ and server controls is that they are available to the code running on the server that is creating the page output. The ASP+ interpreter insists that each one has a unique id attribute, and therefore all the server controls (i.e. the elements that have the runat="server" attribute) will be available to code against. This means that we no longer have to access the Request collection to get the values that were posted back to the server from our form controls – we can instead refer to them directly using their unique id:

    ...
    If Len(selOpSys.value) > 0 Then
      Response.Write("You selected '" & selOpSys.value _
                   & "' for machine '" & txtName.value & "'.")
    End If 
    ...

Visual Basic Code in ASP+

In the ASP page we've just seen, the script was assumed to be VBScript (we didn't specify this, and VBScript is the default unless you change the server settings). In ASP+, there is no support for VBScript. Instead, the default language is Visual Basic ("VB"), which is a superset of VBScript. So, our code is being compiled into IL and executed by the runtime.

The compiler and runtime for Visual Basic that is included with ASP+ is the new version 7.0 (good news – you don't need to buy a separate copy!). There are a few implications in this, which we summarize in Appendix B of this book.

The most important thing to note straight away is that all method calls in VB7 must have the parameter list enclosed in parentheses (much like JScript and JavaScript). In VBScript and earlier versions of VB, this was not required – and in some cases produced an error. You can see that we've enclosed the parameter to the Response.Write method in parentheses in our example.

Secondly, VB7 has no concept of 'default' methods or 'default' properties, so we now must provide the method or property name. You'll probably come across this first when working with ADO recordsets where the syntax must be:

fieldvalue = objRecordset.Fields("fieldname").value

Server-side Event Processing – A Better Code Structure

Of course, if we are going to have HTML elements that execute on the server, why not extend the concept even more? ASP+ changes each page into a server-side object, and exposes more properties, methods and events that can be used within your code to create the content dynamically. Each page becomes a tree of COM+ objects that can be accessed and programmed individually as required.

Using Server-side Control Events

To see how we can take advantage of this to structure our pages more elegantly, take a look at the following code. It shows the ASP+ page we used in our previous example, but with a couple of changes. This version of the page is named pagetwo.aspx:

<html>
  <body>
    <script language="VB" runat="server">
      Sub ShowValues(Sender As Object, Args As EventArgs)
        divResult.innerText = "You selected '" _
          & selOpSys.value & "' for machine '" _
          & txtName.value & "'."
      End Sub
    </script>
    <div id="divResult" runat="server"></div>
    <form runat="server">
      Machine Name:
      <input type="text" id="txtName" runat="server">
      <p />
      Operating System:
      <select id="selOpSys" size="1" runat="server">
        <option>Windows 95</option>
        <option>Windows 98</option>
        <option>Windows NT4</option>
        <option>Windows 2000</option>
      </select>
      <p />
      <input type="submit" value="Submit" 
             runat="server" onserverclick="ShowValues">
    </form>
  </body>
</html>

Firstly, notice that we've replaced the inline ASP+ code with a <script> section that specifies VB as the language, and includes the runat="server" attribute. Inside it, we've written a Visual Basic function named ShowValues. In ASP+, functions and subroutines must be placed inside a server-side <script> element, and not in the usual <%...%> script delimiters – we'll look at this in more detail in the next chapter.

We've also added an HTML <div> element to the page, including the runat="server" attribute. So this element will be created on the server, and is therefore available to code running there. When the VB subroutine is executed, it sets the innerText property of this <div> element.

Notice also how it gets at the values required (e.g. those submitted by the user). Because the text box and <select> list also run on the server, our code can extract the values directly by accessing the value properties of these controls. When the page is executed and rendered on the client, the <div> element that is created looks like this:

<div id="divResult">You selected 'Windows NT4' for machine 'lewis'.</div>

Connecting Server-side Control Events To Your Code

By now you should be asking how the VB subroutine actually gets executed. Easy – in the <input> element that creates the Submit button, we added two new attributes:

<input type="submit" value="Submit" 
       runat="server" onserverclick="ShowValues">

The runat="server" attribute converts the HTML element into a server-side control that is 'visible' and therefore programmable within ASP+ on the server. The onserverclick="ShowValues" attribute then tells the runtime that it should execute the ShowValues subroutine when the button is clicked. Notice that the server-side event names for HTML controls include the word "server" to differentiate them from the client-side equivalents (i.e. onclick, which causes a client-side event hander to be invoked).

The result is a page that works just the same as the previous example, but the ASP+ source now has a much more structured and 'clean' format. It makes the code more readable, and still provides the same result – without any client-side script or other special support from the browser. If you view the source code in the browser, you'll see that it's just the same:

This page, named pagetwo.asp, is in the Chapter01 directory of the samples available for the book. You can download all the sample files from our Web site at http://www.wrox.com.

You'll see how we can improve the structure even more, by separating out the code altogether, in Chapter 2. And, even better (as with earlier versions of ASP) we can add our own custom components to a page or take advantage of a range of server-side components that are provided with the NGWS framework.

Many of these can be tailored to create output specific to the client type, and controlled by the contents of a template within the page.

The ASP+ Application Framework

As a by-product of the modularization of ASP+, developers can also access the underlying runtime framework if they need to work at a lower level than the ASP+ page itself. As well as the information made available through the traditional ASP objects such as Form, QueryString, Cookies and ServerVariables, developers can also access the underlying objects that perform the runtime processing.

These objects include the entire page context, the HTTPModules that process the requests, and the RequestHTTPHandler objects. It is also possible to access the raw data streams, which are useful for managing file uploads and other similar specific tasks. We look at this whole topic in detail in Chapter 6.

Compilation and Rich Language Support – Enhanced Performance

When a page or Web service is first activated by the client, ASP+ dynamically compiles the code, caches it, and then reuses this cached code for all subsequent requests until the original page is changed – at which point the compiled code version is invalidated and removed from the cache. You can see this as a delay the first time that an ASP+ page is executed, while the response to subsequent requests is almost instant.

Because the compilation is to the intermediate language (rather than the processor-level binary code), any language can be used as long as the compiler outputs code in this intermediate language. In fact, a number of independent vendors are already working on different languages (including Cobol).

And, because the intermediate language code is common across languages, each language can inherit from all others and call routines that were originally written in all the other languages. The efficient component management services provided by the runtime also ensure that the compiled code in the page executes much more efficiently than would be possible using the earlier versions of ASP.

A Checklist of the New Features

The major features that ASP+ provides over earlier versions of ASP are:

  • Pages that use the new server-side controls to automate state management in the page, and reduce the code you have to write. Because ASP+ pages have a programming model similar to VB Forms, we also refer to ASP+ pages as Web Forms.

  • HTML Server-side Controls can be used to generate the HTML elements in the page output, and allow code to be used to set the properties (i.e. attributes) of these controls at runtime. They also allow events raised by the elements to be detected and appropriate code executed on the server in response to these events.

  • Rich Controls that run on the server can be used to create more complex HTML elements and objects in the page output. ASP+ includes a calendar control and a range of grid, table, and list controls. These controls can also take advantage of server-side data binding to populate them with values.

  • Web Services allow developers to create classes that are generally not rendered as visible output, but instead provide services to the client. For example, they can include functions that return specific values in response to a request.

  • Configuration and Deployment is now easier, with the use of human-readable XML-format configuration files. Components no longer need to be registered on the server (no more regsvr32!), and applications can be deployed using file copy commands, the FrontPage server extensions or FTP.

  • Application and Session State Management is extended to provide a persistent and more scalable environment for storing values relevant to specific clients and applications. In particular, a user's session state can now easily be maintained in a Web farm.

  • Error Handling, Debugging, and Tracing features have been greatly extended and improved. Each page can have its own 'error page', and can also display values that are used in the page code as it executes – providing a 'trace' facility. Debugging can also be carried out across languages – allowing you to single step seamlessly from one language to another, for example from code in a VB page into a C++ component.

  • Security Management Features now allow many different kinds of login and user authentication to be used. Instead of the default browser login prompt (with Windows 2000 and NTLM authentication), custom login pages can be created and managed by ASP+. It is also easier to manage users depending on the role or group they belong to.

  • Custom Server-side Caching allows developers to store all kinds of values and objects locally on the server for use in ASP+ pages. The runtime can also cache the output from ASP+ pages. This can provide a huge performance boost in situations where a dynamically created page is the same for many visitors, such as a product catalog.

  • A Range of Useful Components are shipped with ASP+. These class libraries can help to make writing Web applications easier. Examples include: the 'SendMail' component, encryption/decryption components, components for defining custom performance counters, components for reading and writing to the NT event log, components for working with MSMQ, network access components (replacements for WinInet), data access components, etc.

    Features such as the intrinsic Request and Response objects (and the Form, QueryString, Cookies, and ServerVariables collections that they implement) are compatible with earlier versions of ASP. However, they have gained a lot of new properties and methods that make it easier to build applications. There is also access to the ObjectContext object for use by any existing ASP components. However, there are some new methods and properties available for the intrinsic ASP objects, as well as other issues that affect how existing pages, components and applications perform under ASP+. See Appendix A for more details.

ASP+ Pages

ASP+ Pages are described in detail in Chapters 2, 3 and 4. The four big advantages that ASP+ Pages provide are:

  • Controls can encapsulatereusable functionality. This allows them to automate and simplify a lot of the common programming tasks, such as state management, validation, data manipulation, etc. that require specific coding in previous versions of ASP.

  • Code is 'cleaner' and easier to read. The encapsulation of code in server controls, combined with the ability to use proper event handling techniques in your pages, allows a more structured design. Reusability of previously tested and optimized controls also means that development is faster.

  • There is better support for code and user interface development tools. These can provide true WYSIWYG editing of pages, management of controls properties, and easy access to methods and events of the controls.

  • It removes the dependency of ASP on non-typed script languages such as VBScript and JScript. Code can be written in any of the ASP+ supported languages, such as Visual Basic, C++, C#, Perl, etc. It can also be written as separate modules and used within the page, rather than as traditional inline code.

The ASP+ Control Families

ASP+ provides a series of new server controls that can be instantiated within an ASP+ page. From the developer's point of view, the advantage of using these controls is that server-side processing can be carried out on events raised by client-side controls.

The server controls provided with ASP+ fall into four broad categories or 'families':

  • Intrinsic controls that create HTML-style elements on the client. They can create intelligent controls that automatically maintain state and provide extra features, or just plain HTML elements.

  • List controls that can automatically produce lists of all kinds on the client. In conjunction with server-side data binding, they can also populate the lists with data from databases, XML files, etc. – using only a few lines of code.

  • Rich controls output client-side HTML, and in some cases client-side script as well, in order to create more complex types of controls or interface elements on the client. An example is the 'Calendar' control, which detects the browser type and creates corresponding code to complement the features of that browser.

  • Validation controls are non-visible controls that make it easy to do client-side or server-side validation when creating forms for the user to fill in and post back to the server. There is a range of these controls, allowing complex validation to be carried out easily.

All of these controls are designed to produce output that can run on any Web browser (you'll see this demonstrated in several places within the book). There are no client-side ActiveX controls or Java applets required. We'll look at each of these control types in more detail next.

The ASP+ Intrinsic Controls

In the example we looked at earlier in this chapter, we saw how ASP+ provides a series of Intrinsic Controls that are intelligent. In other words, they can be executed on the server to create output that includes event handling and the maintenance of state (the values the controls display). In Chapters 2, 3, and 4, we look at how we can use these controls in more detail, and explore their various capabilities.

However, to overview the aims of the new ASP+ Intrinsic Controls, we can say that they serve three main purposes:

  • They allow the developer to interact with the control on the server when the page is being created, in particular by setting the values of properties or reacting to events that are raised on the client.

  • They automatically create the appropriate HTML to preserve their current state, so that they display the correct values as selected by the user when the page is reloaded without requiring the developer to write code to do this.

  • They make development simpler and faster, and promote reusability and better page design and structure by encapsulating the repetitive code required for these tasks within the control.

The basic intrinsic controls are used by simply inserting the equivalent HTML into the page, just as you would in earlier versions of ASP, but adding the runat="server" attribute. The elements that are implemented as specific objects in the preview version of ASP+ are:

<table>

<tr>

<th>

<td>

<form>

<input>

<select>

<textarea>

<button>

<a>

<img>

As in HTML, the <input> server control depends on the value of the type attribute. The output that the control creates is, of course, different for each value.

All other HTML elements in an ASP+ page that are marked with the runat="server" attribute are handled by a single generic HTML server control. It creates output based simply on the element itself and any attributes you provide or set server-side when the page is being created.

There is also a set of new ASP+ controls that can be defined within the page, and which are prefixed with the namespace 'asp'. These controls expose properties that correspond to the standard attributes that are available for the equivalent HTML element. As with all server controls, you can set these properties during the server-side Load events of the page, or add them as attributes in the usual way, but using the special property names. When rendered to the client, the properties are converted into the equivalent HTML syntax.

For example, to create an instance of a ListBox control, we can use:

<asp:ListBox rows="3" runat="server">
  <asp:ListItem>Windows 98</asp:ListItem>
  <asp:ListItem>Windows NT4</asp:ListItem>
  <asp:ListItem>Windows 2000</asp:ListItem>
</asp:ListBox>

At runtime (in the preview version) the ASP+ code above creates the following HTML, and sends it to the client:

<SELECT name="ListBox0" size="3">
    <OPTION value="Windows 98">Windows 98</OPTION>
    <OPTION value="Windows NT4">Windows NT4</OPTION>
    <OPTION value="Windows 2000">Windows 2000</OPTION>
</SELECT>

A summary of the 'asp'-prefixed intrinsic controls looks like this:

ASP+ Intrinsic Control

HTML Output Element

<asp:Button>

<input type="submit">

<asp:LinkButton>

<a href="jscript:__doPostBack(...)">...<a>

<asp:ImageButton>

<input type="image">

Table continued on following page

ASP+ Intrinsic Control

HTML Output Element

<asp:HyperLink>

<a href="...">...</a>

<asp:TextBox>

<input type="text" value="...">

<asp:CheckBox>

<input type="checkbox">

<asp:RadioButton>

<input type="radio">

<asp:DropDownList>

<select>...</select>

<asp:ListBox>

<select size="...">...</select>

<asp:Image>

<img src="...">

<asp:Label>

<span>...</span>

<asp:Panel>

<div>...</div>

<asp:Table>

<table>...</table>

<asp:TableRow>

<tr>...</tr>

<asp:TableCell>

<td>...</td>

These controls provide more standardized property sets than the HTML controls, and make it easier to implement tools that can be used for designing and building ASP+ pages and applications.

The ASP+ List Controls

Many day-to-day tasks involve the listing of data in a Web page. In general, this data will be drawn from a data store of some type, perhaps a relational database. The aim of the ASP+ List Controls is to make building these kinds of pages easier. This involves encapsulating the functionality required within a single control or set of controls, saving development time and making the task easier.

The server-side ASP+ controls that generate the user interface can also manage tasks such as paging the list, sorting the contents, filtering the list, and selecting individual items. Finally, they can use the new server-side data binding features in ASP+ to automatically populate the lists with data. The three standard controls that are used to create lists are the Repeater, DataList, and DataGri