Share via

Appendix A - ASP Best Practices

The best practices presented here will help you develop Active Server Pages (ASP) applications with well-organized, secure directories and files, and with scripts that execute efficiently. Follow these guidelines to create ASP pages that are styled for consistency, readability, and ease of maintenance.

For best results, you should be familiar with the material in the IIS 5.0 online product documentation, especially the "Building ASP Pages," and "Developing Web Applications" topics in the "Active Server Pages Guide."

This appendix is presented as a sequence of topics that parallels the planning and development of an ASP authoring project. For information about developing software components, see "Developing Web Applications" in this book and in the IIS 5.0 online product documentation.

On This Page

When to Use ASP
Project Directories and Files
Style Guide for Scripts in ASP Pages
HTML Standards
Scripting for Performance

When to Use ASP

ASP is a server-side scripting environment that makes it easy to deliver dynamic Web pages to users as they request them. With ASP, you can customize the user experience in a number of ways:

  • Deliver pages that are formatted for the user's browser make and version.

  • Gather data submitted on HTML forms, and connect browsers with information resources on the server-side, by using COM components for database update or information retrieval.

  • Develop Web applications that connect browsers with data resources, such as databases on Microsoft SQL Server or IBM DB2.

Because ASP is optimized for multiple threads and multiple users, you can expect better performance with ASP compared to CGI.

Customizing Information Returned to Users

ASP makes it easy to collect data from users anywhere on the network. This data can be used to customize information, which is sent back to the users via ASP. For example, users could submit their preferences for a home (number of bedrooms, price range, location, and more) to a real estate site, by using HTML forms. ASP would submit a request to the database for only those homes that fit the customers' preferences.

Updating Records Online

ASP can use data from forms that are submitted by browsers in order to maintain databases. For example, if employees are allowed to access an online personnel database, they can update their own data within the personnel directory.

When Not to Use ASP

Do not use scripts in ASP pages in order to perform tasks that are readily accomplished by browser scripts, since ASP consumes server resources. By scripting the browser to perform tasks such as data validation, calculations, and selection of simple conditional output, you can save server resources for those tasks actually requiring ASP. For example, you could use a client-side script in order to validate the input data and to calculate monthly payments for a user who enters a loan amount and specifies the length of the repayment cycle.

To make the most efficient use of your server resources, use the .asp file name extension for pages that contain scripts or that are likely to need scripting in the future. Use the .htm extension for pages that will contain just HTML statements as well as scripts interpreted by the browser.

Project Directories and Files

Organizing Application Directories and Files

This section provides a model for storage structure and access permissions for ASP applications. Using this model will help you establish consistency, security, and ease of maintenance.

The organization and attributes given to the directories and files in the list below are more important than the names used.

/Data (not in site directory)
/DLL (not in site directory)
/Helper_Files (not in site directory)

Application Root Directory

The application root directory name should clearly convey the theme of the site. For example, an application for financial research might be named /Financial_Research. Avoid application root names that might be misidentified as standard subdirectories of a site, such as /Media or /Content. Also, avoid names that read like part numbers or codes, such as /FR98346A.

To avoid adversely affecting production sites, develop the application in a development test environment. An easy way to do this is to develop new applications under the IIS HTTP root directory, /InetPub/wwwroot, then move them to the same directory under /InetPub/wwwroot in the production environment when they are ready.

Note: /InetPub/wwwroot is the home location for all Microsoft® Visual InterDev® and Microsoft® FrontPage® Web documents. Moving a Web application to a storage location that is not under /InetPub/wwwroot makes it inaccessible to these tools.

The root directory of every application should contain at least these files:

  • Default.htm or Default.asp

  • Global.asa

Default.htm, Default.asp

Default.htm or Default.asp should be the default home page for the application, and the server default should be set accordingly using Internet Services Manager. This enables users to find sites in your organization consistently, by typing the server address plus the application root directory name. For example, a user can access MSDN Online by entering Entering the name of the home page is not necessary.


The file Global.asa specifies event scripts, declares objects that have application or session scope, and declares type libraries. For example, Global.asa scripts make application- and session-scope variables available at startup. Global.asa must be stored in the application root directory.


The /Classes directory holds Java classes used by the application.


The /Content directory holds all pages (except Default.htm) and media that might be retrieved by a user of the site.


The /ASP subdirectory of /Content contains all pages with server-side scripting. This directory must contain execute permissions so that ASP can execute the page scripts; storing all scripted pages here simplifies permissions management and site security.


The /HTM subdirectory of /Content holds all pages containing only standard HTML. This directory is read-only and does not have execute permissions. A page containing server-side scripts that is stored here will not execute.


The /Images subdirectory of /Content contains graphics that are used independently of theme-related images, such as standard buttons and icons.


The /Media subdirectory of /Content contains subdirectories for audio, images, animation files, .avi files, and similar items used throughout the application.


The /Themes subdirectory of /Content is used in order to enable application-wide changes to the look of a site. The subdirectory contains style sheets, bullets, buttons, icons, rules, and similar items, and should be organized so that you can easily change the look of an application by modifying any or all the theme-related items. Each item in the /Themes subdirectory can be linked dynamically by setting an application variable to its virtual path.


The /Data directory contains all database access information such as SQL scripts, file­based dataset names or similar data needed by the application. Do not place this directory under the site directory, as this could enable an unauthorized user to access business rules and private data.


The /DLLs directory contains Microsoft® Component Object Model (COM) components and Microsoft® Visual Basic® 6.0 run-time DLLs, such as Vbrun500.dll and Msvbvm50.dll. Do not place this directory under the site directory, as this could enable an unauthorized user to access business rules and private data.

Helper Files

Helper files are server-side include files or text files that make HTML-coded information available across the application. For security reasons, the directory containing helper files should not be stored in the published Web space (the Web site directories identifiable to users).

Using File Name Extension Standards

This section presents conventions for standardizing file name extensions, accounting for the types of files containing scripts, or a combination of HTML and scripts, including Microsoft® Visual Basic® Scripting Edition (VBScript) or Microsoft® JScript®.

Extensions for Page Files


.asp—for ASP pages containing scripts

.htm—for static HTML pages

You must use the .asp extension for pages that contain server-side scripting, or that are likely to in the future. In order to save time and resources when serving pages, use the .htm extension for files that do not, and will not, require server-side script execution.

Extensions for Included Files

For consistency, use include files in order to make specific information available to more than one referring page (changes to include files are distributed to all the pages that include them).


.inc—for large amounts of data with client-side scripting

.txt—for text-formatted data files without scripting

Do not use .inc for pages containing server-side scripts. If a user manages to display them, any business rules in the scripts will be exposed. Use the .asp extension for all pages containing scripting, or for which scripting is planned, in order to avoid displaying proprietary information coded as scripts in ASP pages.

Style Guide for Scripts in ASP Pages

The following conventions, which apply to the development of ASP pages containing scripts written in VBScript or JScript, are designed to enhance consistency, readability, and ease of maintenance.

In this guide:

  • Blank Lines in Files

  • Comments in Scripts

  • Constant Names

  • Context Switching

  • Delimiting Lines of Script

  • Indentation

  • Language Default

  • Layout Order of Scripts

  • Object and Procedure Call Names

  • Paths, Using MapPath

  • Select Case Statement

  • Spaces in Scripts

  • Statement Styles

  • String Concatenation

  • String Function

  • Variables: Case Values, Declaration, Names, Value Trimming

Blank Lines in Files

In general, use blank lines sparingly. You should remove all blank lines at the beginning and end of each file, but you might want to include one blank line between statements to increase readability.

Comments in Scripts

Comments should help any script author looking at code begin to understand it immediately. In addition, they should explain the intent of the code or summarize what the code does, not simply repeat what the code says.

General Comments

Write consistent comment blocks near the top of each page. In these blocks, list the file name, the group developing the file (not the person—e-mail should go to a group alias), the date the file was developed, the HTML and scripting standards followed, and dated descriptions of all changes made.

Comments To Explain Obscure Code

Use comments to explain obscure or complex code—any coding that would take a script author more than a few seconds to decipher. Do not leave a phrase such as the following without a comment:

If Err = LOCK Then

Scripts that are commented out should be deleted unless they are placeholders, in which case they should be labeled as such.

Comment Placement

Insert each comment with its corresponding code.

  • Inline comments should appear two spaces after the corresponding code.

  • Comments beginning on a new line should be set off with a blank line.


Dim intVariable 'Explicitly declare variable.
'Assign the variable an integer value. 
intVariable = 5 

Blocked Comments in VBScript

If a single comment spans multiple lines, each line must begin with the standard VBScript comment symbol ('). Large, multistatement comment blocks should be formatted as in the example below.


Sub ShowIt()
'This procedure is called when the 
'user selects a language. 
'It displays an appropriate select 
'item based on their language choice.
'The method choices are each contained 
'in a separate div.
Dim vntCurrLang 
vntCurrLang = document.all.langselect.value
Select Case vntCurrLang
Case "C" = "" 
Case "VB" = "" 
Case "J" = ""
End Select
End Sub

Blocked Comments in JScript

Multiline comments in JScript begin with /* and end with */. Large, multistatement comment blocks should be formatted as in the example below.


function showIt()
** This is a large comment block. 
** This procedure is called when the user 
** selects a language. 
** It displays an appropriate select item 
** based on their language choice. 
** The method choices are each contained 
** in a separate div. 
var vntCurrLang = document.all
Constant Names

Use all uppercase when naming constants to distinguish them from other elements. An underscore can be used to separate terms when necessary.


Const MIN_QUAL = 25
Context Switching

For readability, try to minimize switching between HTML and scripts. When possible, use a few large blocks of script on a page instead of several scattered fragments.

Delimiting Lines of Script

Lines of script should be blocked between a pair of delimiters, which are placed on a separate line, rather than written with delimiters on each line.

Instead of this:

<% strEmail = Session("Email") %>
<% strFirstName = Request.Form ("FirstName") %>
<% strLastName = Request.Form ("LastName") %>

do this:

strEmail = Session("Email")
strFirstName = Request.Form ("FirstName")
strLastName = Request.Form ("LastName")

For a single stand-alone line of script, keep the delimiters on the same line as the script.


<% strEmail = Session("Email") %>

If the line of script is an ASP output directive (consisting of an equal sign and a variable), do not use a space between the equal sign and the delimiter.


<%= strSubscrLName %>

If the line of script specifies an ASP language directive, do not leave a space between the @ and the delimiter. Do not leave spaces around the equal sign.


<%@ LANGUAGE=VBScript %>

Indentation makes the logical structure of the code more clear.

Once again, place a script consisting of more than one line on a line below the script delimiter, blocking and indenting it two spaces. Place a single-line script on the same line as the delimiter.

Indent everything between ASP delimiters (<% & %>) at least two spaces, except procedures (functions and subroutines).

Also indent two spaces:

  • Each break in logic

  • Nested statements and HTML elements

  • The body of a function

  • The body of a loop from its controlling code

The following examples illustrate some of the indentation rules for scripts written in either VBScript or JScript.

Single-Line Script

<% Dim strLastName %>

Script with Nested Logic

'This example demonstrates a script with 
'a nested block of logic. 
Dim vntOutput 
Set vntExample = Server.CreateObject("MyComponents.Component.1") 
vntOutput = varExample.Text 
If vntOutput = "" Then
Response.Write "An error has occurred" 
Response.Write vntOutput
End If

Function in VBScript

Function CalcMortgageRate()
End Function

Function in JScript

//This is an example of a function.
function calcMortgageRate() 
Language Default

Override the server's default scripting language (VBScript) by using the @LANGUAGE directive. For example, to ensure that the default language is JScript, put the following code at the top of each ASP page:

<%@ LANGUAGE=JScript %>

To use the <SCRIPT> tag for server-side processing, use the RUNAT attribute:

Script Language

Note that no spaces are used adjacent the equal signs.

Layout Order of Scripts

The following list summarizes the recommended layout of scripts in an .asp file, proceeding fromtop to bottom on the page. Well-ordered scripts produce more readable pages and, in some cases, cleaner execution. The list applies to both VBScript and JScript unless otherwise noted.

  • Specify the language.

  • Use the Option Explicit statement (VBScript only).

  • List function library includes.

  • Declare page-scoped variables.

  • Assign values to page-scoped variables.

  • Write HTML and inline scripting.

  • List functions called by inline scripts.

Layout Order

<%@ LANGUAGE=VBScript %>
<% Option Explicit %>
<TITLE>Variable Sample</TITLE> 
<BODY BGCOLOR="White" topmargin="10" leftmargin="10"> 
<!-- Display Header --> 
<FONT SIZE="4" FACE="Arial, Helvetica"> <B>Variable Sample</B></FONT> 
<H3>Integer Manipulation</H3> 
'Declare variable. 
Dim intVariable 
'Assign the variable an integer value. 
intVariable = 5 

For VBScript, use Option Explicit to force explicit variable declaration. This prevents misspelled variables from causing unexpected results when the script executes.

To declare a transactional page, add the <%@ TRANSACTION=value %> directive to the first line on the page.

Transactional Page

<% Option Explicit %>
Object and Procedure Call Names

To distinguish object names and procedure calls from elements such as variables, begin each object name or procedure call with a verb. Use initial capitalization for each term within an object name or procedure call. Table A.1 suggests some naming conventions that could be used to name objects for some typical activities.

Table A.1 Naming Conventions for Objects and Procedures





Adds new records



Edits records



Deletes records



Returns row from database



Returns multiple rows


To specify returns from methods that return information, use From and For with a method or function name.





Returns criteria-based row



Returns criteria-based multiple rows


Object Naming

Use initial capitalization for each term when naming objects, including built-in objects. Use descriptive names for objects, even though this requires more characters per name.

The following example conforms to this naming convention ("cnn" is the prefix for an ADO connection variable):

Set cnnSQL = Server.CreateObject("ADODB.Connection")
Set cnnSQLServer = Server.CreateObject("ADODB.Connection")

These names do not conform:

Set cnnS = Server.CreateObject("ADODB.Connection")
Set cnnsql = Server.CreateObject("ADODB.Connection")
Paths, Using MapPath

Consider using the MapPath method instead of literal paths in ASP applications. The ASP Server.MapPath method allows you to physically relocate an ASP application without recoding scripts. This saves program modification and maintenance effort.

Performance is affected slightly, because every time you use MapPath in a script, IIS must retrieve the current server path. Consider placing the result of the method call in an application variable in order to avoid retrieving the server path.

Select Case Statement

For readability and efficiency, use the Select Case statement in place of If&Else in order to repeatedly check for the same variable for different values. For example:

Select Case intYrsService
Case 0 to 5
strMessage = "You have ten days paid leave this year."
Case 6 to 15
strMessage = "You have fifteen days paid leave this year."
Case 16 to 30
strMessage = "You have twenty days paid leave this year."
Case 31 to 100
strMessage = "Will you never leave?"
End Select
Spaces in Scripts

To enhance script readability, use spaces before and after operators, such as plus (+), minus (-), and equal (=).


intYearsService = intYearCurrent — intYearFirst

Also use spaces after commas, as when passing parameters or declaring more than one variable.


Dim intYearsService, intYearCurrent, intYearFirst

Note: The use of spaces between arguments in ADO connection strings is invalid and will result in an error.

Statement Styles

Each scripting language has its own conventions for capitalization, indentation, and other style-related characteristics. Since VBScript is case-insensitive, capitalization conventions can be devised to improve readability, as the following suggestions illustrate.

If&Then&Else&End If statements:

  • Capitalize the first letter of If, Then, Else, and EndIf.

  • Indent the statements following If, Then, or Else two spaces.

  • Put spaces at each end of an equal (=) sign.

  • Avoid using unnecessary parentheses.

Correct example:

If Request("FName") = "" Then
Response.Clear 'Not required if Response is buffered.
Response.Redirect "test.html"
Response.Write Request("FName")
End If

Similarly, capitalize the first letters of function and subroutine statements, and indent their definitions two spaces.


Sub SessionOnStart
Session("MyId") = Request.ServerVariables(&)
End Sub

Avoid underscores.


Dim FirstName, LastName
String Concatenation

For the sake of consistency and to achieve the intended interpretation, use the string concatenator (&) instead of a plus (+) sign in VBScript strings.

Instead of this:

WholeName = FirstName + " " + LastName

do this:

WholeName = FirstName & " " & LastName
String Function

Use the String(number,character) function to create a character string consisting of repeated characters. For example, to create a string of 12 asterisks:

Dim strAstString
strAstString = String(12,"*")

The String() function takes character codes and string expressions as arguments, but is less verbose than the For& loop.

Variable Case Values

Keep cases consistent in both variable assignment and logical tests by using UCase() or LCase(). This is especially important when assigning and logically testing HTML intrinsic form controls, such as check boxes and radio buttons.

Variable Declaration

Explicitly declaring variables helps expose errors, such as misspelled variable names. To make code more reliable and readable, use the Option Explicit statement in VBScript.

When you want to use strong variable typing, the logic should be programmed into a component built with a language that supports it, such as Visual Basic 6.0 or Microsoft® Visual J++®. Loosely typed variables (not typed until run time), such as variants in VBScript, can affect performance, especially when mathematical computations are involved.

Variable Names

To make the intended use of a variable clear to others reading your script, use three-character prefixes in lowercase to indicate data type. Even though explicit data typing is not supported in either VBScript or JScript, the use of such prefixes is recommended.

For consistency in naming variables, use initial capital letters in variable names. Do not capitalize prefixes. For example, to denote the data type of the variable named "SwitchOn" as Boolean, use the prefix "bln," as found in Table A.2, to name the variable "blnSwitchOn".

Table A.2 Suggested Prefixes for Indicating the Data Type of a Variable

Data Type


ADO command


ADO connection


ADO field


ADO parameter


ADO recordset






Collection object




















User-defined type




To keep variable name lengths reasonable, use standardized abbreviations. For clarity, keep abbreviations consistent throughout an application or group of related applications.

Instead of:



Variable Value Trimming

Be consistent when trimming values. Trim numeric values to the desired length before putting them in state. This will eliminate errors in processing caused by inconsistencies in trimming schemes. For example, a value such as 9.997 used repeatedly as a multiplier would accumulate a different result than the trimmed value 9.9. Trim unneeded leading and trailing spaces from strings by using LTrim, RTrim, or Trim, to eliminate the possibility of a space causing a processing error or a display misalignment.

HTML Standards

ASP applications serve dynamic information in standard HTML format, allowing you to customize information for an audience that uses a wide range of browsers.

Supporting Text-Only Browsing

Many users browse the Web in text-only mode in order to speed up the display of information to their browsers. To ensure that you present as much content as possible to these users, take the following steps to support text-only display:

  • Include text-only navigation objects, such as menus.

  • Include the alternative (ALT) parameter with each image tag to provide information about images.

For example:

<IMG SRC="gravity.jpg" ALT="Picture of apple falling">

When providing client-side image maps, add a text-only list of the mapped areas, with links to the information that would have been loaded if the user had clicked on a map link.

Checking HTML Files

You should check and debug your HTML code, using either a dedicated HTML checker or an HTML editor that has code-checking features. Choose an editor that helps enforce your HTML version standard. Check each new HTML file as it is developed. Then debug your files again each time after they are modified.

To debug a page that contains scripts

  1. Run the page that contains scripts.

  2. View the source.

  3. Save the output, which is pure HTML.

  4. Run the saved output through an HTML checker.

This process is especially important for scripts in ASP pages that include forms. In these cases, HTML errors might corrupt the browser collection values sent from the browser to the server, causing a run-time error.

Using the 216-Color Palette

Color palette mismatches are ever-present concerns when you are creating images for a multiplatform Web. Even images in formats that require compact palettes, such as GIF (256 colors maximum), often display disparate colors when viewed on different platforms, such as Macintosh operating system, Windows 95, and UNIX.

To ensure that your images display the same colors, regardless of browser or platform, use the browser-safe, 216-color palette (also called the safety palette or the 6x6x6 palette). This palette allows nearly as many colors to be viewed as a GIF image can display, and displays them consistently across different systems.

For more information about the browser-safe palette, see Alternatively, enter "216 color palette" into the search field of any popular Web search engine.

Designing for Small Screens

Small-screen formats are still the standard for many users. Although larger formats are making progress, even 800 x 600 pixels is too large to fit on millions of displays. For example, there are millions of older Macintosh-compatible displays currently in use, many of which display a maximum of 640 x 480 pixels.

To accommodate a broad spectrum of users, including those using small screens, design for 640 x 480 pixels. For usability with small screens, keep the average line of text to approximately 12 words.

Displaying Standard Error Messages

To ensure consistency and to make error messages informative, use standard Response.Status values, such as "401 Unauthorized — Logon failed" and other IIS standard responses in your pages. For more information about how to customize error messages, see the IIS 5.0 online product documentation.

Using Object Statements with Embed Statements

To effectively deliver interactive objects to multiple browser types, write for browsers that do not support the HTML <OBJECT> tag.

To script the use of interactive objects, Microsoft® ActiveX® controls, or Java applets in HTML pages designed for a wide range of browsers:

  • Use the <OBJECT> tag to place the object on the page.

  • Add the <EMBED> tag for browsers that do not support the <OBJECT> tag.

  • Add a display object using the <NOEMBED> tag for browsers that cannot "play" the object.

The following example places a ShockWave control onto a page, and provides for the contingencies just mentioned.

<OBJECT ID="ShockedPMDauntless"
<PARAM NAME="swURL" VALUE="dauntless.dcr">
<EMBED SRC="dauntless.dcr" ALT="Movie of Fabrikam Dauntless model in action"
<IMG SRC="dauntless.gif" ALT="Picture of Fabrikam Dauntless model in action"

Scripting for Performance

Object and Variable Initialization

The following information will help you to initialize and set dimensions for objects and variables, in order to achieve faster execution and efficient use of server resources. Unless stated otherwise, VBScript is assumed.

Scoping Variables

Using Page Scope for Best Performance

Local variables reside within functions and subroutines. Give page scope (also called local scope) to variables unless you have a compelling reason to use a broader scope. For example, you might want to assign session scope to a variable that is used in more than one script in a user session. Local variables are compiled into table entries. At run time, references to local variables are resolved with fast-executing table lookups, giving local variables faster performance than global variables.

Using Global Variables Sparingly and Efficiently

Global variables are resolved at run time, and execute much more slowly than local variables. An undeclared global variable is the slowest, requiring a search of the entire variable list the first time it is used. When you need to give global scope to variables, declare them using the Dim statement before using them. This saves valuable time on first use by eliminating a search of the entire variable list.

Avoiding the Use of Public Variables

Do not use variables defined as Public. The Public keyword is under review to determine future use. Use Dim instead.

Using Application Scope for Objects

Information stored in variables with application-wide scope is in memory and is cached for access by any page in the application. Give application scope to variables used often within an application, if the values do not change frequently.

Whatever the potential benefits, use caution in deciding whether or not to give application scope to an object. It can potentially affect performance and decrease reliability (your application could stop responding). To get the best performance using objects with application scope, set threading at BOTH.

Avoiding the Use of Server Variables

It is a best practice to avoid using server variables if your application does not need them. Whenever your ASP application accesses a server variable, your Web site makes a request that retrieves the server's entire variable collection—not just the variable to be used. This causes a performance hit the first time a server variable is used. You can enforce this restriction by setting the ENABLESESSIONSTATE directive to FALSE.

Declaring Objects with the <OBJECT> Tag

For objects that may or may not be used in an application, it's often most efficient to declare the objects without creating them.