BUY THIS BOOK
Add to Cart

Print Book $29.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £20.95

What is this?

Looking to Reprint this content?


Designing Active Server Pages
Designing Active Server Pages Scott Mitchell's Guide to Writing Reusable Code

By Scott Mitchell
Price: $29.95 USD
£20.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
As the Web has become a more integral part of everyday life and business, web sites have matured from small, static sites into rich, data-driven, complex applications. Several technologies, including dynamic scripting technologies, like Active Server Pages and Perl, have aided along the way, making the Web a more viable application medium. This book focuses on using Active Server Pages to quickly and easily build powerful and dynamic web sites.
Although the server-side tools for building web sites have experienced a nice maturation, the processes used for building these sites have not. What, specifically, is Active Server Page design? What is currently wrong with ASP design? Why hasn't the art of designing ASP pages advanced? What can be done to improve ASP design? The first three questions will be answered in this chapter. The last one, however, is a meaty one; it is addressed in this chapter, and answered over the next seven chapters.
This chapter not only addresses these questions, but also introduces functions and programming styles that will be used extensively throughout this book.
Designing a single ASP page is trivial. The challenges involved in designing ASP pages arise when large web sites with hundreds of web pages are being crafted. These large web sites are, in their own rights, full-scale applications. Therefore, before we examine Active Server Page design, we will first take a step back and discuss application design. As we'll see shortly, application design is a long, arduous process, involving much more than simply punching out code.
Imagine that you have just been assigned the task of creating a new program that will be deployed to all of the employees in your company. This program will allow the users to query a centralized database and place the results into a number of formats that correspond to various interoffice forms your company uses. What do you do first? How do you get started?
Designing, coding, testing, and deploying an application is known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is Application Design?
Designing a single ASP page is trivial. The challenges involved in designing ASP pages arise when large web sites with hundreds of web pages are being crafted. These large web sites are, in their own rights, full-scale applications. Therefore, before we examine Active Server Page design, we will first take a step back and discuss application design. As we'll see shortly, application design is a long, arduous process, involving much more than simply punching out code.
Imagine that you have just been assigned the task of creating a new program that will be deployed to all of the employees in your company. This program will allow the users to query a centralized database and place the results into a number of formats that correspond to various interoffice forms your company uses. What do you do first? How do you get started?
Designing, coding, testing, and deploying an application is known as application development . Temporally, it can be viewed as the time span from when the program was first conceptualized to when its first stable version was available for use. (Of course, application development does not end with the first, stable release of a product. Rather, it continues as long as updates and enhancements of the given product are being made.) An entire branch of the computer science discipline is dedicated to studying various application-development methodologies. While there are a number of different methodologies, they all usually share a certain number of phases, which include:
  • Design
  • Coding
  • Testing
  • Deployment
In classical software development, developers usually follow this flow, working on the application's design before moving on to writing the actual code. For example, large software companies draft very detailed plans for their software projects before a developer writes a single line of code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's Wrong with ASP Design?
In my consulting experience, I have found that many developers don't spend any time working on the design of their scripts. Rather, they just start coding once they have an understanding of what the web site needs to look like and what tasks it needs to accomplish.
Such an approach is inefficient and error-prone. If no thought is dedicated to determining the design of the ASP scripts before they are actually written, then for each similar script, the developer essentially reinvents the wheel. For example, imagine the developer has four ASP scripts that need to make modifications to a database. While these scripts may not be identical, assume they all have many functional similarities. Why should the developer spend the time to create each page separately, when one generic page would do?
There is a direct correlation between the amount of code you write and the number of bugs in your program. Typos and silly mistakes catch us all, and they occur proportionally to the amount of raw source code actually written. If we can reduce the number of total ASP scripts that need to be written by generalizing certain scripts to handle the functionality present in the previous four, we will create less buggy ASP applications.
Furthermore, intelligent ASP script design will not only save time and bugs in our current project, but also in future projects. Once a robust module is written to handle a specific task, if that task needs to be completed in a future project, we need only reuse our existing code! With hasty design techniques, code is often written without looking toward the future.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Hasn't ASP Design Advanced?
Despite the advantages of a lengthy ASP design stage, ASP pages are still typically designed hastily. Rigorous ASP design hasn't gained wide acceptance due to three reasons:
  • Businesses are operating on Internet time. Due to the fact that businesses must operate at Internet time to stay competitive, many of the lengthier software development phases that are enjoyed in classical software development are rushed through or sidestepped completely for web applications.
  • Active Server Pages are created using scripting languages. Scripting languages are meant to solve small, discrete problems. Rarely does a developer consider using a scripting language to tackle a formidable programming challenge. Therefore, when coding with a scripting language, it may seem and feel unjustifiable to spend any significant amount of time working on the design of the script.
  • Active Server Pages are easy to use, and can build powerful, dynamic web sites quickly. This, of course, is an advantage of using ASP to develop a web site, but it is a bit of a double-edged sword. Due to developers' expectations concerning the ease of development and quick time frame for creating an ASP web site, a lengthy design process may seem out of place.
You may have noted a slight contradiction in the last couple of pages. In Section 1.2 I mention that ASP scripts can be used to build large, data-driven web sites, yet in the second bulleted item above, I state that rarely will a scripting language be used for a large project.
For large web projects, compiled components should be created in a high-level programming language like Visual C++, Java, or Visual Basic, and used within ASP pages. In Chapter 7, we'll look at combining ASP development with compiled components.
While ASP design has been lacking, it is not because ASP makes such design difficult. In fact, quite the opposite is true; several techniques can be used to create robust, reusable ASP scripts.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Can Be Done to Improve ASP Design?
Even though ASP scripts are, obviously, scripts, there are several approaches that can be taken to modularize your source code and encapsulate complex tasks. These include using server-side includes, taking advantage of VBScript classes, and making calls to the Server.Execute and Server.Transfer methods.
One of the most common approaches to creating modularized code is to use server-side includes (SSI). Server-side includes are used to import ASP code into an ASP page. The benefit of being able to import code from one ASP page to another is you can create individual ASP pages with common functions or classes, and have these functions and class definitions imported into the pages that require their use. Instead of having to cut and paste a particular function that is needed in several ASP web pages, you can place that function in a single file, and then use a server-side include to import the function definition into each ASP page that needs to make use of that particular function.
For example, imagine that you run an e-commerce site. Conceivably, there are a number of ASP pages in which you need to compute the sales tax. Rather than hardcode a sales tax percentage in each of these pages, you could create a single function—ComputeTotalWithSalesTax—that would accept the total less the sales tax as a parameter, returning the new total including sales tax. Example 1.1 contains an example of the ComputeTotalWithSalesTax function.
Example 1.1. Determining the Sales Tax
Function ComputeTotalWithSalesTax(curTotalLessSalesTax)
  Const curSalesTax = 0.0695
  ComputeTotalWithSalesTax = curTotalLessSalesTax + _
          curTotalLessSalesTax * curSalesTax
End Function
The above snippet of code places business logic—determining the sales tax—within an ASP page. As we'll discuss in Chapter 7, business logic should be placed in custom components. The above code snippet only serves to show an example of using server-side includes.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Further Reading
At the end of each chapter you'll find a "Further Reading" section. These sections include links to articles that relate to the topics discussed within the chapter. These articles aren't prerequisites to understanding the topics covered in the chapter; rather, they are auxiliary readings, either describing some of the chapter topics in finer detail or providing information on related topics. In either case, I think you'll find these suggested readings worthwhile and beneficial.
  • For an incredibly thorough discussion on server-side includes, be sure to check out "The low-down on #includes," available at http://www.4guysfromrolla.com/webtech/080199-1.shtml.
  • For a good summary of the new features added to IIS 5.0 and ASP 3.0, visit http://www.microsoft.com/mind/0499/iis5/iis5.htm.
  • Interested in learning more about HTML design? Check out this article: http://webreview.com/pub/98/10/30/bookends/index.html. Also, every developer should often visit Jakob Nielsen's usability site, http://www.useit.com/.
  • Server-side includes form just one facet of server-side directives. To learn more about the other server-side directives (which, unfortunately, can't be used through an ASP page), be sure to check out, "Using Server-Side Directives" at http://www.4guysfromrolla.com/webtech/082599-1.shtml.
  • For more information on using Server.Execute and Server.Transfer to alter flow control between ASP pages, be sure to read http://msdn.microsoft.com/library/psdk/iisref/eadg4d9v.htm.
  • Need to brush up on the FileSystemObject? If so, check out the FileSystemObject FAQ at http://www.aspfaqs.com/webtech/faq/faqtoc.shtml#FileSystemObject.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Choosing a Server-Side Scripting Language
When creating ASP pages, developers have a number of scripting languages to choose from. The most frequently used server-side scripting language is VBScript, but ASP is not limited to VBScript alone. In fact, any ActiveX scripting engine can be used as the scripting language for ASP. Microsoft provides two ActiveX scripting engines: VBScript and JScript. PerlScript and Python are two additional server-side scripting languages that can be used in an ASP page.
This chapter introduces these rarely used scripting languages, demonstrating how to accomplish some common ASP tasks. This chapter is not a language reference or tutorial. Extensive online resources and reference books covering the details of these scripting languages already exist.
If you've read many other Active Server Pages books or are a regular at any of the large ASP resource sites on the Internet, you've no doubt noticed that the vast majority of code examples use VBScript as the server-side scripting language. In fact, this book uses VBScript for its code examples. I believe the reason that VBScript is used so frequently in code examples is that a large number of ASP developers were previous Visual Basic developers. Also, a good number of beginning ASP developers are web developers with extensive HTML skills but few programming skills. VBScript is relatively easy to learn and understand, especially for those who are new to programming.
VBScript did not achieve such popularity among ASP developers solely because it is a simple language. When ASP started to grow into a widely used tool for creating dynamic web sites, there were only two scripting engines: VBScript and JScript. At the time, VBScript had several advantages over JScript. For one thing, VBScript allowed for error handling, while earlier versions of JScript did not.
Current versions of VBScript and JScript, though, both contain error handling, as well as a number of other enhancements. Several notable improvements were added to the Version 5.0 scripting engines; in fact, Chapter 4, discusses these improvements in detail.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Popularity of VBScript
If you've read many other Active Server Pages books or are a regular at any of the large ASP resource sites on the Internet, you've no doubt noticed that the vast majority of code examples use VBScript as the server-side scripting language. In fact, this book uses VBScript for its code examples. I believe the reason that VBScript is used so frequently in code examples is that a large number of ASP developers were previous Visual Basic developers. Also, a good number of beginning ASP developers are web developers with extensive HTML skills but few programming skills. VBScript is relatively easy to learn and understand, especially for those who are new to programming.
VBScript did not achieve such popularity among ASP developers solely because it is a simple language. When ASP started to grow into a widely used tool for creating dynamic web sites, there were only two scripting engines: VBScript and JScript. At the time, VBScript had several advantages over JScript. For one thing, VBScript allowed for error handling, while earlier versions of JScript did not.
Current versions of VBScript and JScript, though, both contain error handling, as well as a number of other enhancements. Several notable improvements were added to the Version 5.0 scripting engines; in fact, Chapter 4, discusses these improvements in detail.
Just because VBScript is the most popular server-side scripting language does not mean VBScript is the right scripting language for you. Each scripting language offers its own strengths and weaknesses. Also, by supporting a plethora of languages, ASP does not favor only those developers who have experience in a particular language. If your strengths lie in Perl, use PerlScript as the server-side scripting language. If you are a JavaScript guru, use JScript instead.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Specifying the Scripting Language
Since any compliant ActiveX scripting engine can be used to parse an ASP page, when a web server receives a request for an ASP page, it must first determine what ActiveX scripting engine needs to be used to parse the ASP page's code. If the ASP code consists of valid JScript syntax, but the web server attempts to have the ASP page parsed with the VBScript engine, errors will abound.
An ASP page can explicitly indicate what scripting language was used through the Language directive. For example, the following ASP snippet uses the Language directive to indicate that JScript is the scripting language used:
            <% @LANGUAGE = "JScript" %>
<%
  var strQuote;
  strQuote = "Hello, world!";
  Response.Write(strQuote);
%>
The Language directive, like all other ASP directives, is preceded by @ . Furthermore, directives must appear before all other ASP code. Failure to do so will result in the following error:
Active Server Pages error 'ASP 0140' 

Page Command Out Of Order 

The @ command must be the first command within the Active Server Page
If the Language directive is excluded (which it commonly is), the default scripting language is used. When first installed, both IIS and PWS set the default scripting language to VBScript. The default scripting language can be changed, though. To change the default scripting language in IIS, visit the Internet Information Services by going to Start Programs Administrative Tools Internet Services Manager. The web sites on your machine should be listed. Right-click and select Properties for the web site whose default scripting language you wish to change. A tabbed dialog box should appear; select the tab titled "Home Directory." Figure 2.1 shows this dialog box with the correct tab selected.
Figure 2.1: The Home Directory tab contains home directory and web application options
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating ASP Pages with JScript
Web developers who are familiar with writing client-side JavaScript code already have a good understanding of JScript's syntax and structure. JScript's syntax and control structures are also very similar to C's. For example, JScript's control structures — if ... else, switch, while, do ... while, and for statements — are syntactically identical to C's.
JScript handles its statement termination a bit differently than C. In C, a semicolon is needed to end a statement; in JScript, either a semicolon or a newline character will suffice. Therefore, you can have a JScript statement end without a semicolon as long as the next statement begins on a new line. You can have multiple statements on one line, but then a semicolon must delimit each of these statements. For example, the following code fragment illustrates the legal and illegal use of semicolons and newline characters:
<% @LANGUAGE = "JScript" %>
<% 
   Response.Write("Each new-line character represents")
   Response.Write("a new statement in JScript.  So does a semicolon.<P>")

   // This is legal code:
   Response.Write("Hello, "); Response.Write("World!");

   // This is not:
   Response.Write("Hello, ")  Response.Write("World!");
%>
I highly recommend always ending each statement with a semicolon, regardless of whether the next statement starts on a new line. JScript code examples in this book will adhere to this strict use of semicolons.
JScript does not require that you explicitly declare your variables. There is no Option Explicit-type command in JScript. To declare a variable, use the var keyword. Variable names must begin with a letter, an underscore ( _ ), or a dollar sign ($ ); subsequent characters can be letters, numbers, underscores, or dollar signs.
JScript, like VBScript, is a loosely typed language. That is, every variable is of type Variant, meaning a single variable can be a string, an object, a number, or any other type. There are six datatypes available with JScript: string, number, object, Boolean, null, and undefined. The first five datatypes are fairly straightforward. The undefined datatype, however, warrants further discussion.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating ASP Pages with PerlScript
If you are an experienced Perl developer, you may find PerlScript more comfortable to use than VBScript or JScript. PerlScript is syntactically similar to Perl. The PerlScript scripting engine is maintained by ActiveState, a company that describes its role as "assist[ing] with the transition of [Perl] scripts between Windows and Unix based systems" (http://www.activestate.com/corporate/). The PerlScript engine can be downloaded for free from ActiveState's web site, http://www.activestate.com.
With PerlScript, like with Perl and C/C++, each statement must end with a semicolon. PerlScript's control structures, which are identical to Perl's, include if ... elsif ... else, for, while, foreach, and foreach ... until. If you are new to Perl, I highly recommend that you obtain a copy of O'Reilly's Learning Perl, Second Edition by Randal Schwartz and Tom Christiansen.
Each PerlScript variable needs to contain a certain prefix. The prefix determines the variable's datatype. With PerlScript, as with Perl, there are three major datatypes, as illustrated by Table 2.1.
Table 2.1: PerlScript's Datatypes
Datatype
Prefix
Description
Scalar
$
Contains simple datatypes, such as strings and numbers
Array
@
Contains a variable number of scalar elements indexed by number; arrays are indexed starting at zero
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating ASP Pages with Python
Python is an object-oriented scripting language that incorporates the best features from an array of languages, such as Java, C/C++, Perl, and awk. If you're not familiar with object-oriented programming, you may find the Python syntax a bit daunting. Python is the only scripting language discussed in this chapter that requires you to write object-oriented code! PerlScript and VBScript have object-oriented capabilities, but do not require that you use such techniques.
To use Python in your ASP pages, you need to download the latest Python ActiveX scripting engine. You can download this for free from http://www.python.org/download/. Be sure to download and install both the Python interpreter and the Win32 COM extensions. Also, you have to register the Python ActiveX scripting engine on the web server before you can use it. Consult the online Python documentation for more information.
To learn more about Python, be sure to visit http://www.python.org. Extensive documentation exists at http://www.python.org/doc/. Finding good references on using Python with ASP is far from easy. There are a couple of short articles available at Python.org, but those articles are targeted for experienced Python developers interested in learning ASP as opposed to experienced ASP developers interested in learning Python!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Further Reading
Unfortunately, there is little in the way of documentation on these alternative server-side scripting languages. While there are a vast number of ASP-related web sites, nearly all of them focus exclusively on VBScript. The vast majority of ASP-related books focus on VBScript as well. Despite this, there are some useful articles, tutorials, and sites that deal with these alternative scripting languages.
  • This tutorial is geared towards those who are more familiar with Perl than with ASP. Nevertheless, it is a very thorough tutorial on PerlScript and worth a read: http://www.fastnetltd.ndirect.co.uk/Perl/Articles/PSIntro.html.
  • If you want to ask your Jscript questions with fellow ASP developers, be sure to sign up for the JScript ListServ at http://www.asplists.com/learn/javascript.asp.
  • Read a good tutorial discussing JScript in terms of objects at http://www.asptoday.com/articles/19990316.htm.
  • Learn how to incorporate both VBScript and JScript code in your ASP pages. This article, available at http://www.asptoday.com/articles/19990420.htm, even demonstrates how to call VBScript functions from JScript code and vice versa.
  • One of VBScript's advantages is its many inherent formatting functions, such as FormatCurrency, FormatDateTime, and others. Mosey on over to http://www.4guysfromrolla.com/webtech/vb2java.shtml to see some JScript translations of some of the more common and useful VBScript formatting functions.
  • For more information on the order in which SCRIPT blocks execute within an ASP page, refer to http://msdn.microsoft.com/workshop/server/feature/morqa.asp#order.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Exception Handling
Errors happen. Regardless of how skilled a given programmer might be, there is no way he can create truly bug-free code. Programming errors can be broken down into two broad categories: logical errors and implementation errors. Before starting to actually write code, a developer must have a solid understanding of what application she is creating, and the logic behind this application.
For example, when creating an e-commerce web application, a developer might decide that once a user decides to purchase an item, he is taken directly to a page to enter his billing and shipping information. Many users today are used to a shopping cart system, in which they can purchase multiple items online and then proceed to a "check out" page, where they can review a summary of the goods being purchased and enter the needed billing and shipping information. By not providing a shopping cart system, your users may find your site confusing and burdensome to use. Logical errors are often high-level errors, costing immense time and money to fix, since they are usually not caught until late in the product development cycle.
Implementation errors are those errors residing in the actual code. In an e-commerce site, if not all of the items selected by the user appear in the summary listing on the "check out" page, an implementation error has occurred. To summarize: flaws existing within the high-level view of the application are logical errors; errors or bugs resulting from the implementation of an idea or feature into code are implementation errors. Implementation errors are easy to detect: if the program crashes or produces incorrect output, an implementation error is at fault. Logical errors, however, are much more sinister and difficult to detect.
This chapter does not focus on how to reduce the number of errors you, as a developer, commit when writing code. Rather, it looks at how to gracefully handle these errors when they inevitably occur. We've all seen the patented Microsoft Blue Screen of Death one too many times, and all know the frustration involved when a program fails to gracefully handle an error. Since bugs and errors in any decent-sized application are certain, it is vitally important to be able to respond to these errors smoothly when they occur.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Bit of Terminology
We've already looked at the two broadest categories of errors: logical and implementation errors. Implementation errors are often described in terms of halting errors and non-halting errors. Halting errors cause the premature termination of a running program, whereas nonhalting errors produce unreliable or unpredicted output but allow the continuation of the program. Halting errors can be further divided into runtime errors and compile-time errors. Runtime errors are those errors that occur during the execution of a program, while compile errors occur during the compilation process of the program.
When an ASP script is requested, it goes through a two-phase process. First, the script is compiled into an executable version. Any syntactical errors are caught here; these are referred to as compile-time errors. For example, the following VBScript syntax, which is illegal, will generate a compile-time error:
<% @LANGUAGE="VBSCRIPT"%>
<%
  Dim strScott
  strScott = "Mitchell     'This will cause a compile-time error since the
                           'assignment to the string strScott is missing a
                           'closing quotation mark
%>
A syntactically correct script may be free of compile-time errors, but it can still contain runtime errors. Runtime errors occur when some unexpected event happens during the execution of the script. For example, dividing a number by zero is legal syntax in VBScript (therefore not generating a compile-time error), but will nevertheless generate a runtime error since the result of division by zero is undefined. The following code snippet will generate a runtime error:
<% @LANGUAGE="VBSCRIPT"%>
<%
  Dim iUndefined
  iUndefined = 1 / 0       'This will cause a runtime error since the division by
                           'zero is undefined
%>
Runtime errors are not always the fault of the programmer who developed the script that generates an error. For example, imagine that you create an ASP page to display the contents of a particular SQL Server database table. Even though your script may be flawless, containing no logic or implementation errors, if the database table being queried is renamed or the entire database is deleted, your once-perfect script will now abruptly terminate when attempting to query a non-existent database table.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Detecting When Exceptions Occur
To be able to handle errors gracefully, it is imperative that some mechanism exists to inform us developers when an error arises. Errors occurring in an ASP page can be detected in one of two ways: through the scripting language's error-handling interface, or through ASP 3.0's new ASPError object.
The VBScript and JScript 5.0 scripting engines both contain robust runtime error-detection mechanisms. ASP pages (or other scripts) created using either of these scripting languages can use the scripting language's inherent error-handling capabilities to detect when errors occur. As we'll see in Section 3.2.1, using either VBScript's or JScript's error-handling mechanisms often results in verbose, inelegant, and unreadable code when compared to the elegance of the ASPError object.
The ASPError object, which we'll detail in Section 3.2.2, provides detailed information about an error that just occurred in an ASP page, including a description and line number. However, the ASPError object can only be used with IIS 5.0/ASP 3.0, which, of course, requires Windows 2000 as the web server. Therefore, if you are using Windows NT as your web server's operating system, you must rely on the scripting languages' error-handling techniques to detect and gracefully respond to exceptions.
If you are using Windows 2000, though, you are in luck. To use the ASPError object, a separate error-handling web page is needed. This separate page is responsible for receiving the detailed error information and providing an understandable error message to the end user. Using this approach, an error that occurs on any line in any ASP page will result in a call to the error-handling web page. Furthermore, the ASPError object provides more detailed information on the error that occurred than either of the VBScript or JScript error-handling objects.
Using the ASPError object approach alone makes it next to impossible to detect an error, circumvent it, and continue processing. Once an error-handling web page is set up, when an error occurs, the user is sent to the error-handling web page via a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Responding to Exceptions
In Section 3.2, we examined two methods to determine when exceptions occurred: through the server-side scripting language, and for ASP 3.0, through the ASPError object. Exception handling involves more than just detecting when an exception occurs; it also involves an appropriate response. In this section, we'll look at various ways to respond to an exception.
We'll start with a look at displaying understandable error messages. Next, a means for notifying the technical support team of the error's details is covered. Finally, we'll look at ways to recover from an error. Of course, these three approaches to responding to exceptions are not mutually exclusive. That is, when an exception occurs, you can display a readable error message, notify the support team, and attempt to recover from the error.
Errors are inevitable . They will happen. Your code contains errors. Therefore, be ready to respond to errors gracefully. Do not trivialize exception handling, expecting your code to be error-free. The worst thing that can happen when an error occurs is premature termination of the script followed by an illegible error message. As we discussed earlier, it is vitally important to provide readable, understandable error messages for your users.
Good error messages, in my opinion, contain the following four elements:
  • Acknowledgement that an error occurred.
  • A high-level explanation of the error.
  • An apology.
  • Links to other sections on a site. Links are how the Web is navigated. An error message without links to other site resources serves as a dead end, encouraging the user to leave your site altogether.
For example, a good error message for a database connection exception would be something like:
"Ah! We could not display the information you requested due to a temporary database problem. Our development team has been notified of this problem and is working diligently to resolve it as quickly as possible. We apologize for this inconvenience. In the meantime, why not check out these sections on our web site?"
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Custom HTTP Error Pages
As discussed in Section 3.2.2 earlier, when an ASP error occurs on a web page, an HTTP 500;100 error is signaled. If you correctly set up an error-handling web page through the Internet Services Manager, IIS will automatically send the user to the specified error-handling web page via a Server.Transfer.
Of course there are several other types of HTTP errors besides 500;100. One of the most common errors is the HTTP 404 error, which results when a client requests a page not found on the web server. There is nothing as annoying or frustrating as the default HTTP 404 error page, which is shown in Figure 3.8.
Figure 3.8: The default 404 error page serves as a dead end, frustrating users
The default 404 error page is ugly and serves as a dead end for your users. A much better approach is to provide your visitors with a custom 404 error page that apologizes for the page not being found and provides links to relevant sections on the site. Relevant sections might include a search page or a listing of popular resources on the site. The vast majority of large web sites realize the importance of custom 404 error pages. You can see some examples of real-world custom 404 error pages at the following URLs:
  • http://www.yahoo.com/NotAValidURL
  • http://espn.go.com/NotAValidURL
  • http://www.4guysfromrolla.com/NotAValidURL
Custom 404 pages, unlike custom HTTP 500;100 error pages, can be implemented in both IIS 4.0 and IIS 5.0. As with creating a custom HTTP 500;100 error page, to create a custom HTTP 404 error page, start by going to the Internet Services Manager. You should see a listing of all of the web sites on your web server. Right-click on the web site for which you'd like to create a custom 404 error page and choose Properties. Choose the Custom Errors tab and locate the 404 HTTP error, as seen in the screenshot in Figure 3.9.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Further Reading
While there are many good online articles on VBScript error handling, there are far too few JScript error-handling articles. Part of the reason, of course, is error handling wasn't available in JScript until Version 5.0. Furthermore, there are not many online articles discussing how to use the ASPError object for exception handling, also due, no doubt, to its relative newness. Keeping that in mind, here are some selected readings on the various exception-handling approaches discussed throughout this chapter.
  • For a good read on using VBScript error-handling techniques to present understandable error messages to your visitors, check out "Error Handling in ASP," at http://www.4guysfromrolla.com/webtech/060399-1.shtml.
  • A rather detailed discussion of JScript's error handling can be seen on Microsoft's site at http://msdn.microsoft.com/workshop/languages/jscript/handling.asp.
  • On Microsoft's site, there is a rather lengthy article on new ASP 3.0 features. Unfortunately, only a short part of the article discusses using the ASPError object for exception handling. The article, "Internet Information Services 5.0," can be found at http://www.microsoft.com/mind/0499/iis5/iis5.htm.
  • The most thorough article on the ASPError object I could find was at http://www.asptoday.com/articles/19990308.htm, in a piece entitled "Error Handling in IIS 5.0."
  • To learn more on creating custom 404 error pages, be sure to read "Creating a Custom 404 Error Page," at http://www.4guysfromrolla.com/webtech/061499-1.shtml.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Regular Expressions, Classes, and Dynamic Evaluation and Execution
With the introduction of the VBScript 5.0 scripting engine, VBScript developers now have three very powerful techniques at their disposal which were previously unavailable with VBScript:
  • The availability of a Regular Expression object, RegExp. Regular expressions provide for advanced string matching and parsing. If you are new to regular expressions, you'll soon realize their tremendous advantages and wonder how you lived without them!
  • The ability to create object-oriented code! VBScript now supports classes! I am very excited about this new feature, for it allows the creation of robust and reusable ASP pages. It's also great for those working in large development teams where certain developers aren't as experienced as others with ASP. The more experienced developers can create classes that encapsulate some of the more difficult functionality, and the more novice developers can simply use these classes to accomplish the common ASP tasks!
  • Dynamic evaluation and execution. Dynamic evaluation allows a code snippet contained in a string to be evaluated as though it had been entered directly by the programmer creating the script. Dynamic execution allows a code snippet contained in a string to be executed as through it had been entered directly by the programmer. By employing the use of dynamic evaluation and execution, a script can achieve flexibility not previously available. We'll discuss how to perform dynamic evaluations and executions in Section 4.3.
If you are running ASP 3.0, you already have the VBScript 5.0 scripting engine. If you are running an older version of ASP/IIS, be sure to download the latest Microsoft scripting engines from: http://msdn.microsoft.com/scripting/.
The RegExp object provides the VBScript engine with a means to perform regular expression pattern matching. We've discussed regular expressions previously; in Chapter 2, a discussion on using regular expressions in JScript and PerlScript was presented.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using the RegExp Object
The RegExp object provides the VBScript engine with a means to perform regular expression pattern matching. We've discussed regular expressions previously; in Chapter 2, a discussion on using regular expressions in JScript and PerlScript was presented.
Take a moment to look back at Chapter 2 to see JScript's implementation of regular expressions. Note that the regular expression syntax contains a pattern and an optional switch. The switch can have one of three values:
i
Ignore case
g
Perform a global search for all occurrences of pattern
gi
Perform a global search for all occurrences of pattern, ignoring case
The RegExp object contains three properties that allow you to set the pattern and these switches for regular expression usage in VBScript. These three properties are Pattern, IgnoreCase, and Global. Pattern expects a string, and is the regular expression pattern to search for. Global is a Boolean value indicating whether the regular expression search should match all occurrences in a string or just the first one. If not specified, Global defaults to False. IgnoreCase is also a Boolean value, indicating whether or not a regular expression search is case-sensitive. By default, IgnoreCase is set to False.
The Pattern property contains the regular expression. A regular expression pattern is not restricted to just simple strings. The pattern can also contain special characters, which allow for much more sophisticated searches. Table 4.1 contains a listing of these special characters and their meanings.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Object-Oriented Programming with VBScript
With the introduction of the VBScript 5.0 scripting engine, developers now have the ability to create classes in VBScript, much as they can in VB. The next section is intended for those new to object-oriented programming, and provides a quick introduction on the topic. The section following that discusses the VBScript syntax for creating and using classes.
Object-oriented programming (OOP) is a programming methodology in which entities known as objects are used. Objects contain properties and methods; as the names suggest, a property describes the features of the object, while a method performs some action involving the object.
True object-oriented programming is further defined as the ability for new objects to inherit properties and methods from existing objects, and for dynamic binding of derived object methods. VBScript's implementation of OOP doesn't support these two additional requirements, and is therefore not a true object-oriented programming language.
As an ASP developer, you've already used object-oriented code written by others. For example, ADO is nothing more than a collection of objects that can be used to access a database. Having the ability to treat a complex task as a black box is indeed beneficial. When using ADO, you don't have to worry about what protocol is required to establish a connection to a database; rather, you simply use the Open method of the ADO Connection object.

Section 4.2.1.1: An object and an instance

To fully understand object-oriented programming, it is essential to understand the difference between an object and an instance of an object.
An object , such as ADO's Connection object, is an abstraction. It does not physically exist. Rather, it simply serves as a template for creating instances.
An instance is a physical entity of an object. For example, in the following code,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Dynamic Evaluation and Execution
As a programmer, you have performed static evaluation and static execution countless times. For example, the following code snippet performs both static evaluation and static execution:
<% @LANGUAGE="VBSCRIPT" %>
<%
  Dim iAnswer
  iAnswer = 22 / 7   'A rough approximation of pi
%>
The first line, Dim iAnswer, is an example of static execution. When a browser visits the ASP page that the above code snippet resides in, the first line of code is executed, causing a memory location to be set aside to store the value of iAnswer. The second line, iAnswer = 22 / 7, is an example of both static evaluation and static execution. Initially, the expression 22 / 7 is evaluated, returning the result 3.14285714285714. The execution occurs when this value is stored into the variable iAnswer.
This type of code evaluation and execution is referred to as static because the statement being evaluated and the commands being executed are hardcoded into the script. The only way the expression 22 / 7 will change is if a developer edits the actual ASP file by entering a new expression.
The VBScript 5.0 scripting engine offers two functions that facilitate dynamic evaluation and execution. Let us examine each of these issues separately.
Imagine you wanted to present your users with a form with a single text box, into which they could enter a mathematical expression. Once the form was submitted, the result would be displayed. For example, the user might enter something like (8 * (5 / 3.5)) - 34. Example 4.7 contains the code to create this form, and Figure 4.4 displays the form when viewed through a browser.
Example 4.7. A Form to Solve a Mathematical Expression
<HTML>
<BODY>
  <FORM METHOD=POST ACTION="SolveMathProblem.asp">
     Enter a mathematical expression (like
     <CODE>5 + 4 * (9 / 4 - 10.5) + 45/2</CODE>):<BR>
     <INPUT TYPE=TEXT NAME=Expression SIZE=40>
     <P>
     <INPUT TYPE=SUBMIT VALUE="Solve this Expression!">
  </FORM>
</BODY>
</HTML>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Further Reading
To learn more about the topics covered in this chapter, be sure to read these additional resources:
  • For a full list of the VBScript scripting engine version in which particular VBScript language features were implemented, check out http://msdn.microsoft.com/scripting/default.htm?/scripting/vbscript/doc/vbsversion.htm.
  • To learn more about object-oriented programming, be sure to check out http://java.sun.com/docs/books/tutorial/java/concepts/. While the site does focus on Java technology, it contains worthwhile articles on OOP design and concepts.
  • For a good beginner-level discussion on regular expressions, visit http://hotwired.lycos.com/webmonkey/geektalk/97/33/index3a.html.
  • The best article I could find on Microsoft's site discussing regular expressions and VBScript is at http://msdn.microsoft.com/workshop/languages/clinic/scripting051099.asp. This article contains a good explanation on how to use the RegExp object with VBScript, and supplies some basic regular expression theory.
  • To obtain the latest version of the VBScript and JScript scripting engines, visit http://msdn.microsoft.com/scripting/default.htm?/scripting/vbscript/download/vbsdown.htm.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Form Reuse
In general, the Web would be a pretty useless place if it weren't for HTML forms. Forms provide an interface for the client to submit information to the web server. The most common form interfaces include search engine interfaces, e-commerce interfaces, and data administration interfaces.
This chapter and the next focus primarily on data administration interface forms. Data administration interfaces are common in many data-driven web sites. For example, if you ran a web site that sold widgets, you'd have a pretty extensive database structure, comprised of many tables containing an assortment of relevant information. This site would also likely contain an extensive set of administration pages, where each administration page permitted administrators to update, insert, and delete records into the various database tables.
This chapter does not focus on creating HTML forms, or reading form variables through an ASP page—it's assumed you are familiar with those topics. (If you are a little rusty, don't worry; there's a brief discussion on each of these topics early in the chapter.) What we will be focusing on heavily throughout this chapter and the next is the art of form reuse.
Code reuse has many advantages, the paramount one being that developers who practice code reuse bec