Warning: Cannot modify header information - headers already sent by (output started at /home/dealkhus/cosmoread.com/wp-includes/formatting.php:5100) in /home/dealkhus/cosmoread.com/wp-content/themes/cosmoread/header.php on line 18

Warning: Cannot modify header information - headers already sent by (output started at /home/dealkhus/cosmoread.com/wp-includes/formatting.php:5100) in /home/dealkhus/cosmoread.com/wp-content/themes/cosmoread/header.php on line 19

Warning: Cannot modify header information - headers already sent by (output started at /home/dealkhus/cosmoread.com/wp-includes/formatting.php:5100) in /home/dealkhus/cosmoread.com/wp-content/themes/cosmoread/header.php on line 20

Warning: Cannot modify header information - headers already sent by (output started at /home/dealkhus/cosmoread.com/wp-includes/formatting.php:5100) in /home/dealkhus/cosmoread.com/wp-content/themes/cosmoread/header.php on line 21
Home » Education » Classic ASP 101

Classic ASP 101

1. Basic authentication vs. NT Challenge and Response [liveblog]

When you password protect a web page using Internet Service Manager, you have the option of choosing either Basic authentication or NT Challenge and Response (aka: Integrated Windows authentication). The difference in the two methods is in the way the username and passwords are transmitted over the Internet. NT Challenge and Response encrypts the password so malicious snoopers can not intercept and use the information. Basic authentication sends the password as plain text. While it would be great to use NT Challenge and Response for all secured web pages, the only web browsers that currently support this protocol are Internet Explorer 3 and higher. If you might have users with other web browsers, your only choice is Basic authentication.

If you would like to have a secure website take advantage of using encrypted usernames and passwords but still want to be compatible with Netscape browsers, you can use Basic authentication over SSL. Using Secure Sockets will encrypt the user name and password but at the same time will still let Netscape browsers use your site, the best of both worlds.

Thanks to Eric Rosenblum for reminding us about Basic authentication over SSL.

2. ASP and Personal Web Server

If you develop on the run and don’t always have access to an NT box running IIS, Windows 95’s Personal Web Server (PWS) may be an excellent alternative development environment for ASP. In fact, with PWS, you can maintain a functional development environment even on a laptop. To set up a system to run Visual InterDev and ASP with PWS, simply install the following components:

Personal Web Server
Active Server Pages server extensions
FrontPage server extensions
Visual InterDev Client

Note: The same configuration also works with Peer Web Services for Windows NT Workstation.

3. ASP Code-Based Security

Using ASP code, you can implement more specialized security for your site. For example, say some annoying users plague your site. Because their IP addresses can be pulled from the server activity logs, you could use the following code to deny access:

<%If request.servervariables(“REMOTE_ADDR”) = “” then
Response.Buffer = TRUE
Response.Status = (“401 Unauthorized”)
End If%>

There are many variables available within an Active Server Page that supply information about the browser making the request, as well as the information about IIS itself. The LOGON_USER command, for example, will return the Domain\Username of authenticated users, and a blank for anonymous users. You could then use server-side code to check for specific individuals, and redirect them to other pages.

4. (<OBJECT> vs. Server.CreateObject())

When creating a server object using a server component, you have a choice between two methods. The most common method is to use the CreateObject() method of the Server object, as shown in the following code: SET NextLink = Server.CreateObject(“MSWC.NextLink”). While this method works fine, there is another way to create an object that is just a bit more resource friendly.

When you create an object using the Server.CreateObject() method, the object is created as soon as the method is called. Any threads, memory, or other resources are allocated at the point of instantiation, or creation. The syntax for creating an object using the <OBJECT> tag is shown in the following statement:

<OBJECT Runat=Sever ID=NextLink ProgID=”MSWC.NextLink”></OBJECT> By using the HTML <OBJECT>

tag with the Runat=Server attribute, you can create the object in a way that it is not actually created until the first method or property of the new object is referenced. While this may not seem like a lot of savings, when you are trying to design a system that can withstand 1,000,000 hits per day, every little bit helps.

5. Authenticating Anonymous requests

By default, when a browser requests a Web page, IIS will first try to fill the request without authenticating the user. In order to do this, IIS impersonates a special Windows NT account, named IUSR_machinename (where machinename is the name of the IIS host computer). When you install IIS, the installation program creates this account automatically. If, by impersonating the IUSR_machinename account, IIS can access the requested resource, then it serves the page to the anonymous user; otherwise, the user gets a 401 error.

A common problem with anonymous access occurs when the password for the IUSR_machinename account and the password entered in the Internet Service Manager get out of sync. When IIS tries to impersonate the IUSR_machinename account, it submits the password that was entered in the anonymous logon field to a Windows NT server. If that password is incorrect, IIS is prevented from using the IUSR_machinename account. Once anonymous access fails, IIS will attempt to authenticate everyone. Because authentication can happen silently, the site can fail, but the reason for failure isn’t always apparent. The type of authentication you’re using makes a huge difference if your pages are accessing other resources, such as databases or server-side components (DLLs).

6. Avoid unnecessary window switching

If you installed Books Online with Visual InterDev, you know that they’re a valuable resource. However, if you reference the information while working on a project, you may get tired of switching back and forth between documentation and your code. If you’d like to be able to see the documentation and your code at the same time, just follow these few simple steps. Pull down the tools and select the Options… menu item. Next, select the Workspace tab from the Options dialog. Under Docking views, select the InfoViewer Topic option, then click OK. The next time you select an InfoViewer Topic, the results will be displayed in their own window. You can either dock the window as part of your workspace or just let it float. When you’re not using the InfoViewer window, just click the close button to get rid of it. The next time you choose an InfoViewer topic, the window will reappear right where you left it.

7. Batch your code to save processing time

If you use the <%=…%> syntax to write in multiple places in your code, consider “batching” those writes by replacing multiple, interspersed <%=…%> writes with one Response.Write statement. While you are making that change, take a look at how you have your HTML code with regard to your script.

Try not to intersperse HTML and script too much; instead, try to have blocks of script and blocks of HTML. Arranging your HTML and Script code will save you valuable server process time.

8. Changing the default scripting language at the server level

The default scripting language for ASP is VBScript. However, you can change the scripting language at three levels: the server level, the page level, and the function level. Changing the default at the server level affects all applications that run on the server and requires a trip to Windows NT’s registry.

To change the default to JScript, use Windows NT’s registry editor to open the following key:


Then, change the DefaultScriptLanguage entry from VBScript to the new default, JScript. Finally, you must stop and restart IIS for the changes to take effect. When you’re finished, all scripts on the server will be processed by the JScript engine unless otherwise specified at the page or function level.

9. Changing your default scripting language

As you probably know, Visual InterDev’s default scripting language for Active Server Pages and the Scripting Wizard is VBScript. However, if you prefer using JScript, and you can eliminate the need to change the <LANGUAGE> tags on your Activer Server Pages and wizard-generated scripts. To do so, simply select Options… from the Tools menu. On the HTML tab, you’ll see the Default Languages section with customizable values for the Script Wizard and Active Server Pages. Simply select the options you prefer and click OK to apply the settings.

10. Controlling How a Page is Cached

A proxy server is used to reduce the amount of time spent retrieving documents over the Internet. It does this by caching, or storing, the document in memory and then serving it from memory the next time a client tries to retrieve the page. This can cause problems with Active Server Pages because of their dynamic nature.

By default, IIS sends web pages with headers that tell proxy servers not to cache their documents. If you need to change this, you can by placing the following line of code at the top of your ASP page:

<% Response.CacheControl=”Public” %> This will allow all proxy servers that retrieve the page to save it in their local memory and improve the speed at which it can be retrieved.

11. Don’t touch that mouse!

If you’re fond of keyboard shortcuts, you’re certainly familiar with using the Alt-Tab shortcut to cycle through the open applications in Windows. For those of you who cringe at the thought of moving your hands from the keyboard to accomplish such a simple task as switching documents, Visual InterDev offers a similar shortcut. By pressing Ctrl+Tab, you can cycle through the open Visual InterDev windows, as well as any other Developer Studio application windows you have open.

12. Dragging and dropping a Data Command DTC

You can add a Data Command design-time control (DTC) by using a simple drag and drop technique. To do so, first, click the Data View tab so you can see the database. Next, open the page to which you want to add the Data Command control. Then, drag the table you wish to add onto the page and drop it into the correct location within the page. This will load the object tag for the Data Command control. Now, to modify the settings, you can right-click the object tag for the control and select Edit Design-time Control from the context menu.

13. Fix for IIS security bug

There is a security hole in all versions of the Microsoft Internet Information Server. It allows a web browser to view the source code of your cgi and asp scripts. This can be very dangerous, because passwords and other sensitive data are often stored inside of these scripts, where browsers are not supposed to be able to go. You can fix the problem by making sure that all of your script files do not allow “read” access. For most scripts, simply enabling “execute” permissions will work. There is also a hot-fix available for IIS 3.0 and 4.0. You can find the hot-fix and other information about this serious security issue here.

14. Hiding and restoring Visual InterDev’s Workspace pane

When working in Visual InterDev, you can hide the Workspace pane anytime you don’t need it by clicking its close button (represented by an X). Then, to restore the Workspace pane when you need it again, simply right-click a blank spot on a toolbar and select Workspace from the context menu.

15. IIS and complex polygons

You’ll probably never encounter this problem, but it’s one you should know about. If you create server-side area maps for IIS, there’s an upper limit on the number of vertices you can specify. Early versions of IIS respond with an access violation if you supply more than 100 points; the current version will break at 160. So, if you’re planning to map out all the surface characteristics of a particularly complex shape, count your points carefully.

16. Image maps 101

To create precise link areas within a graphic on a web page, many web developers use image maps. If it’s important to make your image maps compatible with a wide range of browsers, you should probably use server-side image maps, which require you to use both the ISMAP attribute of the IMG tag on the client side and to create a MAP file on the server side. For example, to supply a map file named MAPFILE.MAP for an image named IMAGE.GIF, you’d use the following HTML description


The map file itself is simply a text file that provides the attributes of the image map in question. For example, the map file definition

rect /OTHERPAGE.HTM 0,0 45,45

creates a rectangular hot spot on the image, starting in the upper-left corner and terminating at pixel location 45,45.

17. Improve efficiency with server-side includes

Many web sites consist of repetitive information, such as headers, or content that rotates on a regular basis, such as a Tip of the Week. By using server-side includes, you can reduce the repetitiveness and some of the hassle that comes with rotating content, and your code will look much leaner as a result. A server-side include works in much the same way as the C/C++ #include directive, telling ASP to insert the contents of the specified file in place of the include. Your include file can contain HTML, server-side script, client-side script, or anything else you’d normally find in an Active Server page. The syntax looks like this:

<!–#include virtual=”header.asp”–> There are two flavors of includes–file and virtual. When using the file include, you must specify the file’s path in relation to the including file. With the virtual include, however, you must specify the file’s path in relation to the virtual root. Therefore, if the folder myweb is in your virtual root, and your file structure looks like this: myweb\pages\default.asp myweb\includes\header.asp you’d use the following statements for file and virtual includes, respectively. <!– #INCLUDE FILE=”../includes/header.asp” –> <!– #INCLUDE VIRTUAL=”/myweb/includes/header.asp” –>

18. Manage sessions individually in IIS4

If you’re an experienced developer, you’re probably using Session object to store information that you need for a particular user-session. As you know, variables that are stored in the Session object are not discarded when the user jumps between pages in the application; instead, these variables persist for the entire user-session. The Web server automatically creates a Session object when a user (who does not already have a session) requests a Web page from the application. The server destroys the Session object when the session expires or is abandoned.

To avoid this, you can turn off the Session feature; however, you can’t turn off the Session feature on a per application basis in IIS 3.0. Turning it off for the entire server is faster but drops a lot of functionality. Instead, be very careful to use the Session object only when you really need to. If you use the Session object at all in your application, be sure to use it as soon as possible, so you can avoid the Session object from being reset. The best solution is to use IIS 4.0, since you can enable the session state on a per-application basis and it can be disabled for specified .asp files.

Multifaceted image maps

While you may think of server-side image maps as being limited in flexibility, you can actually identify complex shapes as image hot spots. Take a look at the following map file definitions, creating a rectangle, circle, polygon, and even an individual point.

#50×50 pixel rectangle starting at 0,0
rect /page.htm 0,0 50,50

#circle with 40 pixel radius starting at 50,50
circle /page.htm 50,50 40

#polygon with 3 vertices
poly /page.htm 15,15 15,75 50,45

#individual point-great for “easter egg”
point /page.htm 100,100

Persistent Radio Buttons

ASP pages are often used to both display a form, and carry out the action once the form is submitted. One of the most annoying tasks of HTML/ASP forms programing is keeping a user’s chosen radio buttons selected when redrawing the form after it has been submitted. The following code is one way to create a one ASP page form that has persistent radio buttons:

<HEAD><TITLE>Pick a color</TITLE></HEAD>
<BODY BgColor=<%= Request.Form(“Color”)%>>
RedChecked = “”
BlueChecked = “”
YellowChecked = “”

SELECT CASE Request.Form(“Color”)
CASE “Red”
RedChecked = “CHECKED”
CASE “Blue”
BlueChecked = “CHECKED”
CASE “Yellow”
YellowChecked = “CHECKED”
Pick a color:<BR>
<FORM Method=Post>
Red: <INPUT Type=Radio Name=Color Value=Red <%= RedChecked%>>
Blue: <INPUT Type=Radio Name=Color Value=Blue <%= BlueChecked%>>
Yellow: <INPUT Type=Radio Name=Color Value=Yellow <%= YellowChecked%>>
<INPUT Type=Submit>

Previewing ASP pages in Visual InterDev 6.0

If you use the Quick View feature of the HTML editor in Visual InterDev 6.0, there are a few things you should keep in mind. Because the Quick View feature does not process server side script, it most likely will not display ASP pages correctly. The ASP code will be ignored by the browser, and your page may not look as it will when served from a web server. In addition, Design-time controls whose target platform is Server will not appear. To best view ASP pages, use the View in Browser command from the View menu. The Quick View feature, however, is very handy when used with HTM pages. It displays images, activates links, and processes client side script just like Internet Explorer 4.0. It is important to note that because it acts like a browser, you can not edit or debug your HTM files in Quick View mode.

Protecting your server from a crashing application

With the power of ASP, web servers have moved from simply serving up static html, to actually running Web-based applications from within their own process. As Web applications get more and more complex, and companies begin to rely more and more on these applications, your web applications need to be more and more robust. We all know, however, that no software is perfect, so we need to handle problems as gracefully as possible. One way to make sure your Web server will not be taken down if one misbehaving application crashes is to run your Web applications in their own memory space.

To do this, launch the Internet Service Manager from the Microsoft Internet Information Server menu under Windows NT 4.0 Option Pack. Open the node for your Web server and select the application you wish to modify. Right click the application node and select Properties from the pop-up menu. Check the Run in separate memory space checkbox, and click OK. This will cause any objects that the application uses to be run in their own memory space, and prevent an application error from bringing down the web server, or any other part of the system.

Quick query design

If you’re using Microsoft SQL Server and Query designer, you probably already know that you can drag a table from Data View in Visual InterDev and drop it in Query Designer. However, you can also drag a database diagram into Query Designer. This will add all the tables in the diagram to the current query.

Rating the content of your web site

You can quickly and easily place ratings on any web pages you feel may have content not suitable for children. These ratings, when combined with a properly configured web browser, can prevent unsuitable viewers from looking at your web site.

To rate a web page, right click on the page in Internet Service Manager and from the pop-up menu, click Properties. In the dialog box displayed, select HTTP Headers and click on Edit Ratings… to launch the Content Rating dialog. Select the Ratings tab and click on the Enable Ratings for this resource checkbox.

You then need to rate your page in each of the four Recreational Software Advisory Council (RASC) categories: violence, nudity, sex, and language. Highlight the category and use the slider to rate your page. Finish by entering your name and the date.

Server-Side vs. Client-Side Scripting

When you create a dynamic html page the code that makes the changes to the web page must be run in one of two places. It can be client-side code executed by the user’s web browser, or it can be server-side code executed by the server. There are advantages and disadvantages to using one over the other, and a well-planned mix of the two can have a dramatic effect on your web page.

The advantages of server-side scripting are many. Because all of the server side code is executed before the HTML is sent to the browser, your code is hidden. Server-side code is also the only choice if you want to access files and directories on the local machine. Server-side code is also browser independent. Because the HTML code returned by the server is simple HTML, you do not have to worry about the version of browser the client is using. The disadvantage to server-side scripting is that the server must use valuable resources to parse each page it sends out. This could slow down your web site.

Client-side scripting can be very useful. The major advantage is that each web browser uses its own resources to execute the code found on the web page. This eases the burden on the server. The disadvantages are that you can not prevent the user from seeing your code and that you can not use client-side code to access local files, directories, or databases.

By designing your web site to take advantage of the strengths and weaknesses of both client-side and server-side scripting, you can protect your code and get maximum performance.

HTTP Status Codes

When a server responds to an HTTP request, the first line it returns is the status line. This line contains a three-digit code and a short description of the status of the response. There are five classes of codes, explained in the following list:

1## – Informational. These codes are mainly experimental.

2## – Success. The codes in this class are returned on successfully filled requests. Status code 200 is used to indicate a successfully retrieved web page.

3## – Redirection. The status codes in this class are used to show that additional action must be taken before the request can be satisfied. For example, code 301 can be used to indicate that a page has been moved and the browser may be redirected to the new page.

4## – Client Error. These codes are returned when a browser has made a request that can’t be fulfilled. The dreaded “404–URL not found” is perhaps the most famous of status codes.

5## – Server Error. This class of status codes is used to indicate a problem on the server end. Sometimes code 503 is used to indicate a server currently has too many requests to process.

Knowing the status code classifications can sometimes make debugging web-page problems less difficult.

HTTP Status Codes

When a server responds to an HTTP request, the first line it returns is the status line. This line contains a three-digit code and a short description of the status of the response. There are five classes of codes, explained in the following list:

1## – Informational. These codes are mainly experimental.

2## – Success. The codes in this class are returned on successfully filled requests. Status code 200 is used to indicate a successfully retrieved web page.

3## – Redirection. The status codes in this class are used to show that additional action must be taken before the request can be satisfied. For example, code 301 can be used to indicate that a page has been moved and the browser may be redirected to the new page.

4## – Client Error. These codes are returned when a browser has made a request that can’t be fulfilled. The dreaded “404–URL not found” is perhaps the most famous of status codes.

5## – Server Error. This class of status codes is used to indicate a problem on the server end. Sometimes code 503 is used to indicate a server currently has too many requests to process.

Knowing the status code classifications can sometimes make debugging web-page problems less difficult.

Use the front door, please!

If you require visitors to log in to your site upon each visit, here’s a simple way to make sure that they always do so before gaining access to the information on your site. Suppose you require the user to enter their first name into a form on your default.asp page and submit it prior to moving on to main.asp. That’s a good start, assuming that your visitors all access your site via the default.asp page. However, unless you take the technique a step further, it would be easy enough to access the content of your site by pointing the browser to a specific page in your site, such as main.asp. You can prevent users from bypassing the default.asp with just a few lines of code.

First, when you process the form data containing the visitor’s first name, write the name to a Session variable, as follows:

<% Session(“FirstName”) = Request.Form(“fname”) %>

Next, add the following lines of code prior to the <HTML> tag at the top of each page in your site
(except default.asp):
If Session(“FirstName”) = “” Then
End If

If the FirstName Session variable is blank, indicating that the visitor hasn’t yet logged in, he’ll be redirected to the default.asp page to do so.

Using authorization headers

One of the advantages of requiring user authentication is that you can use the logon information in your Active Server Page (ASP). The following code comes from a page that requires user authentication:

Your name is <%=Request.ServerVariables(“LOGON_USER”)%>

This simple ASP displays the name of the user who has been authenticated by the web server. You can use this to give your ASP a personalized feel, or to change what information is displayed depending on the user.


Using Cookies in your ASP page

Cookies, those small files that live in the Temporary Internet Files folder, are a great way to personalize your ASP pages. The following ASP code creates a page that will ask a user to enter their name the first time they visit the page, then recognize and greet them by name each subsequent visit.


If Not Request.Form("Name") = "" Then
    Response.Cookies("Name") = Request.Form("Name")
    Response.Cookies("Name").Expires = "Jan 1, 2010"
End If
 <title>Welcome Page</title>
If Request.Cookies("Name") = "" Then
    Response.Write "<form method=""post"">Enter Your Name: "
    Response.Write "<input type=""text"" name=""name"">"
    Response.Write "<input type=""submit"">"
    Response.Write "</form>"
    Response.Write "Welcome back, " & Request.Cookies("Name")
End If


Variable Name Prefixes

Good ASP code is easy to read and understand. A quick way to make your code self-documenting is to name your variables in a meaningful way. The IIS Resource Kit team has put together a list of variable name prefixes to be used with assorted data types. Using them will not only make your code easy to read, but it will also have a professional feel.

The prefixes are as follows:

bln: Boolean
byt: Byte
col :Collection object
cur: Currency
dtm: Date-time
dbl: Double
err: error
int: Integer
lng: Long
obj: Object
sng: Single
str: String
udt: User-defined type
vnt: Variant
cmm: ADO command
cnn: ADO connection
fld: ADO field
prm: ADO parameter
rst: ADO recordset

Simply add the prefixes to the front of your variables. For example, the variable Today becomes dtmToday. This simple habit can save you time and energy.

Use Visual InterDev

Although you can write ASP files with just about any text-editing tool, including Notepad, Microsoft’s Visual InterDev is a much better tool for building ASP-based applications. Visual InterDev is part of the Visual Studio suite and provides a tool to quickly build both HTML and ASP pages.

The RAD (Rapid Application Development) visual environment of Visual InterDev 6.0 lets you create an Active Server Page with the click of a menu item. It can generate, and help you edit, the VBScript or JavaScript for your page’s scripting logic.

Once you have created the initial ASP page, Visual InterDev’s Script Outline makes it easy to drag and drop objects such as ActiveX Controls and Java applets from the Visual InterDev toolbox onto the page.


By default, Microsoft’s VBScript lets you implicitly declare variables in your code. For example, suppose you’ve written a function that returns the square root of a number:

Function MyFunction (num)
NewNumber = abs(num)
MyFunction = sqr(NewNumber)
End Function

VBScript automatically creates the variable NewNumber without you explicitly having to declare it before you use it. This feature can cause unusual results if you accidentally misspell the variable, as shown here:

Function MyFunction (num)
NewNumber = abs(num)
MyFunction = sqr(NewNumer)
‘ NewNumer rather than NewNumber
End Function

The misspelling above causes VBScript to create two variables, one called NewNumber and another one called NewNumer. The presence of the two variables will return an incorrect value to the calling function instead of the intended square root.

To avoid this problem, use the <% OPTION EXPLICIT %> function to require that all variables be declared first, which lets the VBScript interpreter catch errors such as a misspelled variable. You simple place the <% OPTION EXPLICIT %> tag at the beginning of your ASP file:

<%@ LANGUAGE=VBScript %>
<META name=”generator” content=”Microsoft Visual Studio 6.0″>
Function MyFunction (num)
Dim NewNumber
NewNumber = abs(num)
MyFunction = sqr(NewNumber)
End Function
<P>The Square root of 64 is <% =MyFunction(64) %></P>


Because the example forces <% OPTION EXPLICIT %>, you must declare the NewNumber variable. That way, the interpreter catches any misspellings by raising an error message if it finds a variable that hasn’t been declared.

Scope out your variables

In ASP, script- or page-level variables are available across all of the code on any page for the lifetime of that page. These variables are declared outside the scope of any particular procedure or function. Procedure-level variables, on the other hand, are declared within a function or procedure and are available only within the scope of that function. That means you can access the value in the variable only within the context of its function or procedure. The code below demonstrates how to declare both script- and procedure-level variables:

<%@ LANGUAGE=”VBScript” %>
<META name=”VI60_defaultClientScript” content=”VBScript”>
<META name=”generator” content=”Microsoft Visual Studio 6.0″>
<SCRIPT id=”clientEventHandlersVBS” language=”vbscript”>
Dim MyPageVariable ‘ Script level variable
Sub document_onclick
Responsedocument.Wwrite (MyLocalVariable) & “<BR>”
‘ Out of Scope
Responsedocument.Wwrite (MyPageVariable)

End Sub

Sub MyProcedure()
Dim MyLocalVariable ‘ Procedure-level variable
MyLocalVariable = “Available in the function”
MyPageVariable = “Available in the page”
End Sub
<P> </P>

In the example, MyLocalVariable is available only to the procedure MyProcedure. When the variable is called upon to display its contents from within the calling procedure, it has nothing to display since it is out of scope. The variable MyPageVariable, on the other hand, is available to reveal its contents.

Use client-side validation

A client-side script is a script that is included in a page’s HTML and is executed on the client based on user events. Using a client-side script means the browser doesn’t have to make a round-trip to the server to perform routine client-side tasks. For example, you wouldn’t want to send the browser to the server to validate that all of the required fields on a form were filled out.

If you know that visitors to your site will be using Internet Explorer 4.0, you can use VBScript on the client side to validate objects such as HTML form fields. Client-side VBScript is similar conceptually to JavaScript–it gets sent to the browser with the page’s HTML and executes on the browser based on user events. If you want to support a broader reach of browsers, use JavaScript for your client-side scripting. A wide range of browsers, including both Navigator and Internet Explorer 4.0, support JavaScript.

Suppose you wanted to verify that a user entered a number between 1 and 10. You can create a client VBScript that will run whenever the user attempts to submit the form data:

<META name=”VI60_defaultClientScript” content=”VBScript”>
<META name=”generator” content=”Microsoft Visual Studio 6.0″>
<SCRIPT id=”clientEventHandlersVBS” language=”vbscript”>

Sub btnVerify_onclick
Dim EntryNumber
EntryNumber = window.txtNumber.value
if IsNumeric(EntryNumber) then
if EntryNumber < 1 or EntryNumber > 10 then
MsgBox (“Please enter a number between 1 and 10.”)
MsgBox (“Your entry was valid.”)
End If
MsgBox (“Please enter a numeric value.”)
End if
End Sub

This single VBScript subroutine is called btnVerify_onclick. If you’ve ever programmed in Visual Basic, you’ll recognize this as the onClick event-handler for the btnVerify object. The other object used in this routine is the window.txtNumber object, which holds the value we’re verifying. Both btnVerify and txtNumber are defined as part of the form in the body of our sample HTML page:

<P><STRONG><FONT size=6>Validating User
Input</FONT></STRONG></P><STRONG><FONT size=6> <HR>

<P><FONT size=”3″>Enter a value between 1 and 10:
<INPUT id=”txtNumber” name=”txtNumber” style=”height: 22px; width: 39px” value=”15″>
<INPUT id=”btnVerify” name=”btnVerify” style=”height: 24px; width: 56px” type=”button”

<P> </P>

<P> </P></FONT></STRONG>


When the user clicks the Verify button, the browser will run the btnVerify_onclick handler to check the number. For this example, we’ve inserted 15 into the txtNumber field so that just by clicking the Verify button you can generate the error message. Remember, this client-side VBScript works only with IE 3.0 and higher.

Separate HTML and script

You can improve the performance of your ASP pages by putting your HTML and your script in separate blocks on the page. In other words, don’t intersperse script code throughout your HTML code. When a browser requests an ASP page, the server-side script is stripped out and executed on the Web server. Then the server sends the HTML for the page. If you distribute your scripts throughout the page, the Web server will waste time separating them from the HTML.

Group related functions in your includes

Make sure that you group related functions in your server-side include (SSI) files. You don’t want to include 100 functions in a single SSI file if the Web page in question uses only two of those functions. Putting too many functions in one SSI page can creates a bottleneck for the Web page that calls the include. Since JScript and VBScript are “uncompiled” scripting languages, the calling page has to wait for each of the functions in the include file to be evaluated. Putting too many random functions into the SSI file adds unnecessary overhead if a particular page doesn’t use them all.

Utilize browser capabilities

To give your site the broadest reach, build your Web pages for the lowest common denominator. HTML 3.2 is typically a safe bet. Only if you know that your end users have a 4.0 browser should you use such features as Dynamic HTML to deliver a more powerful experience. You should query the browser capabilities of your visitors using the browser capabilities ASP object (MSWC.BrowserType). This component creates a BrowserType object that provides your scripts with the capabilities of the browser viewing them.

Start by creating an instance of the BrowserType object:

<META name=”generator” content=”Microsoft Visual Studio 6.0″>
<%Set bcObj = Server.CreateObject (“MSWC.BrowserType”)%>

Now create a table and output four properties of the BrowserType: the browser name, the version number, and whether it supports VBScript and JavaScript.

<TABLE border=”1″ cellpadding=”1″ cellspacing=”1″ width=”75″%>
<TD><%= bcObj.browser%>
<TD><%= bcObj.version%>
<TD><%= bcObj.vbscript%>
<TD><%= bcObj.javascript%>

<P> </P>


Non-VB programmers should note that -1 is a Boolean true value, so if a browser supports VBScript, the above code will return -1 to indicate that.
In your server-side ASP code you can use these browser properties to generate the appropriate HTML and client-side script depending on the user’s browser.

Use design-time controls

Unlike a run-time control, which is part of finished applications such as the ActiveX stock ticker, design-time controls (DTCs) run only within the development environment to help create a finished script. For example, Visual InterDev 6.0 includes a design-time control that lets you visually create a complex database query. It then spits out the appropriate VBScript into your ASP file. When your page is run, the script executes just like a hand-written script.

Query your database with ADO

Microsoft created ActiveX Data Objects (ADO) to serve as the central model for building database interaction within Web pages. Language-independent ActiveX Data Objects can connect your Web pages to any ODBC-compliant database. Microsoft implemented ADO specifically to provide data access across the Web. The idea behind ADO is to provide an object-based interface that makes remote objects appear as if they were local. The benefits of the ADO model include low memory overhead and high speed, important considerations for Web-based applications.

Built on top of Microsoft’s OLE database model, ADO is the successor to both Remote Data Objects (RDO) and Data Access Object (DAO).

ADO lets you use ActiveX scripting to connect to your datasource. You also can use ActiveX scripting to customize the properties and methods of an ActiveX Data Object. ADO supports transactions, cursors, error handling, and the use of stored procedures.

When using ADO, be sure to keep these three tips in mind:

  1. Create the recordset object if you are executing a single command once.
  2. Create the command object if you are executing the same command multiple times.
  3. Create the connection object if you are executing multiple commands.

Encapsulate business logic in components

It can be difficult to decide whether to access a database directly from your Active Server Pages or from a component written in a language such as C++ or Visual Basic. You may want to use the following rule of thumb: If your database access and processing logic takes up more than 20 to 30 lines of script code, it’s probably a good idea to create a separate component to handle the database access and processing logic. It’s often tempting to put a lot of complex business logic into an ASP page, but that can slow down your application. ASP scripts are interpreted, and thus aren’t as efficient as compiled components.

Whether you choose to build components and business objects using Visual Basic or a more complex language such as C/C++ or Java, the key is to find a way to integrate middle-tier business logic with your Web application. Using components this way can improve the performance and scalability of your application–and you can reuse components across your Web site and client-server applications.

Use transactions wherever possible

If you are using components, you might as well take the next step and utilize the power of transactions with a tool such as Microsoft Transaction Server (MTS). MTS lets you build components with such features as rollback and recovery, load balancing, shared data, and context. With the advent of IIS 4.0, ASP pages can now support transactions. With Visual InterDev, enabling transaction support is as simple as clicking a check box:

Connection Pooling lightens the load

If your application connects to a database, you will want to use Connection Pooling to let your users access open connections to the database. By sharing the connections to the database, you avoid having to create a unique connection for each individual user. Windows NT 4.0 provides built-in support for Connection Pooling. To make sure that your ASP application takes advantage of it, follow these five steps:

  1. Configure the driver for the database to which you are establishing a connection. SQL Server supports Connection Pooling by default.
  2. Check the Windows NT registry to verify that Connection Pooling is on, and let it handle the connection logic.
  3. If Connection Pooling is off, use Regedit32 to turn it on in the Windows NT registry.
  4. Open individual connections in your ActiveX Database Objects (ADO) code just before you need data access on each individual page.
  5. Close your connections when you complete the data-access activities.


Comment your code

Comments are very useful tool that many developers tend to over look. Adding comments to your code will make your life much easier when you need to go back and edit a script you wrote six months ago.
Make sure you keep your Script comments within your Server Side Code to prevent the comments from reaching the client’s browser.
Below is the syntax to add comments to your VBScript or JScript code:

‘ This is how you format a VBScript comment
// If you use JScript, use this format

Close and free up object references

While we’re on the topic of good coding techniques, I thought I would remind everyone to close and free up object references once they are done using them.
I tend to type in the commands to kill the object right after I create the object, and then start coding between them.

Dim objConn, objRS
Set objConn = Server.CreateObject(“ADODB.Connection”)
objConn.ConnectionString = …

Set objRS = objConn.Execute(“…”)

Set objRS = Nothing

Set objConn = Nothing


Using Response.CacheControl

Normally ASP pages are considered active content. That’s sort of the whole point of the name Active Server Pages. There are times, however, when it is desirable to use ASP to generate a page and yet its content doesn’t change very often. It’s this type of situation when caching can really boost the perceived speed of your site.

By default most proxy servers won’t cache dynamic content including your ASP pages. If you have a script in which the information rarely changes, try placing the following line at the top of your ASP script.
Response.CacheControl = “Public”
It’ll really help boost your site’s apparent speed for users who visit your site from behind a proxy.

Use variables to speed up collection access

Whenever you access a collection such as Request.ServerVariables or Request.Form, the script processor needs to go into the collection to look up the value of the item you request. While this doesn’t seem like it takes a long time, it’s actually relatively slow when compared to accessing local variables.

If you find yourself using the same item from a collection more than a couple times, declare a local variable and assign the value of the item in the collection to it the first time you need to access it. From then on you can use the local variable to retrieve the value to prevent the computer from needing to access the collection again.

The same thing goes for things like the field object of a recordset. Using a local variable saves the collection lookup time and while it may seem trivial, think about some of the loops that you’re doing it inside of. A little bit of inefficiency adds up all of a sudden when you consider the number of times you’re doing it!

You won’t notice a huge speed increase. In fact, you probably won’t even be able to tell the difference, but on a high traffic site the small amount of time saved each time the page is run can really add up.

Use VBScript’s TypeName to resolve type mismatch errors

TypeName can be a lifesaver when it comes to resolving type mismatch errors. With VBscript’s exclusive use of the variant and a lot of code out there that doesn’t use type prefixes, it’s amazing these errors don’t happen more often. Unfortunately that doesn’t make them any less annoying or easier to troubleshoot. Too often it’s just a typo or a “That’s what I meant” type of error, but checking the variable types of the variables on the offending line can often help you find the culprit more quickly so you can get back to work faster!

Cache commonly used values in application variables

With all the hype over not using session scope objects unless you absolutely have to, a lot of people are automatically assuming the same goes for application scope objects. Well it doesn’t and if you’re not already, you should be using them! It’s a great place to store commonly used values and it’s a heck of a lot faster then storing them in text file or a database. Look for things that you use a lot and whose values don’t change very much and you’ll find some prime candidates that when moved into an application variable will help make your code fly!

Don’t use ODBC for your database connections

When ASP was introduced everyone used ODBC for their data connections because it was the only real choice and that’s how all the samples showed it being done. Well that was then and this is now! OLE DB is faster, more stable, just as easy to use, and most importantly works with almost all your previously written code!

To use OLE DB all you need to do is change the connection string that you use to connect to your database.

In ODBC it would look something like this:

"DBQ=C:\data\database.mdb; DRIVER={Microsoft Access Driver (*.mdb)}"

To switch to OLE DB all you need to do is change it to something like this:

"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\data\database.mdb;"
"Provider=SQLOLEDB; Data Source=sql_server; Initial Catalog=sql_database; " _
& "User Id=username; Password=password;"


Navigation Stars *

For all the great content we have on the site, one of the most popular questions we get has nothing to do with the content. Once people realize that we’re using one template for the entire site, they inevitably ask: “How do you get the little star in the navigation bar to appear next to the name of the section the user is currently in?”

Well, the first step is determining where the user is. To do this we use the value of URL from the Request.ServerVariables collection. That gives us a absolute path without the server name like /samples/index.asp. From there we strip out just the first level directory name and use that as our locator.

From that information we know what directory the page the user has requested is in and because we’ve kept the site somewhat well organized, that takes care of the bulk of it since our directory structure closely resembles the logical structure of the site.

From there it’s just a matter of some conditionals determining where to show the star.

Here’s a simplified version of the code in case you actually want to try something similar on your site:


Const STAR_HTML = "<FONT COLOR=""#FF0000""><B><CODE>*</CODE></B></FONT> "
Dim strSection
' Get full path
strSection = Request.ServerVariables("URL")
' Pull out first level directory.  Defaults to "home" if we're on the root
If InStr(2, strSection, "/", 1) = 0 Then
        strSection = "home"
        strSection = Mid(strSection, 2, Instr(2, strSection, "/", 1) - 2)
End If
' Convert to lower case for ease of comparison
strSection = LCase(strSection)
 <TD><% If strSection = "home"    Then Response.Write STAR_HTML %></TD>
 <TD><A HREF="/index.asp">Home</A></TD>
 <TD><% If strSection = "news"    Then Response.Write STAR_HTML %></TD>
 <TD><A HREF="/news/index.asp">News</A></TD>
 <TD><% If strSection = "tips"    Then Response.Write STAR_HTML %></TD>
 <TD><A HREF="/tips/index.asp">Tips</A></TD>
 <TD><% If strSection = "samples" Then Response.Write STAR_HTML %></TD>
 <TD><A HREF="/samples/index.asp">Samples</A></TD>


Recompiling components without rebooting

It is stated in a lot of articles that in order to change a DLL one must reboot the computer to save to it. If you write a batch file and put in it the following code, it’s all you need to “release” the file, so one can recompile it – without having to reboot the computer. This is for IIS 4.0 but will work with 5.0 except mtxstop isn’t needed.

Here’s the code for the batch file:

net stop iisadmin /y
net start w3svc
net start ftpsvc


Hope this helps… sure beats rebooting a server! 🙂

Thanks to mail@abdicate.net for this tip

Send Email from an ASP Page

Have you ever needed to send email from a web page? Perhaps to build a “Send this to a Friend” link? Have no fear, CDONTS is here. You can easily send email (and attachments!) with the Collaboration Data Objects for NT server. Note that this requires SMTP, which usually requires NT Server.

Let?s assume you?ve made a form for a user to fill out. Here?s the code for the email:

Set objMail = Server.CreateObject("CDONTS.NewMail")
objMail.From = Request.Form("From")
objMail.To = Request.Form("To")
objMail.CC = Request.Form("CC")
objMail.BCC = Request.Form("BCC")
objMail.Subject = Request.Form("Subject")
msgBody = "Dear Friend, this email is coming to you from CDONTS!"
objMail.Body = msgBody
Set objMail = nothing

That?s it! For more detailed information.


Transactions in ASP

Transactions are often very helpful for database manipulation. They allow an all-or-none approach – if something, anything, fails then have the whole process fail rather than just part of it. This can ensure proper data manipulation – you won’t get half modified rows.

Well, you can do transactions with active server pages too. Just add the directive:

<%@ TRANSACTION = value %>

to the top of your ASP page, and voila! Transactions the easy way, without involving Microsoft Transaction Server (MTS). “value” can be one of the following:


The script will use a transaction, and will participate in any open transaction or create a new one if none are open.


The script will always start a new transaction.


The script will use any open transaction but will not start a new one if none are currently open.


The script will neither initiate nor participate in a transaction.

Upgrade to the 5.5 Scripting Engine

Not only is it more powerful, offering better VBScript support for Regular Expressions and ECMA improvements for JScript, it may also reduce memory leaks in IIS 4.

Read the VBscript Documentation

Not sure of a function name or its syntax? What about the properties or methods of an object? Use the Windows Script Documentation for examples and function references. It covers JScript, VBScript, the Scripting Runtime Objects, Windows Scripting Host, and even Windows Script Components. There’s nothing like going to the source to be sure you’re getting the right information.

You can refer to it online or download a copy to your own computer for convenient reference whenever you need it.

Date Delimiter for Access and SQL Server

As most ASP developers quickly discover, Microsoft’s two most popular databases (Access and SQL Server) implement SQL differently. The most significant difference for many users is the difference in date delimiter characters. Access likes # while SQL Server expects ‘. This can make writing a query difficult when you’re not sure what platform it’ll end up running on or you want it to run on both.

This tip will show you how to determine, from an existing connection, what delimiter you should use. This function checks for Access and if it finds it sets the delimiter to #. If it doesn’t it defaults to ‘ for SQL Server.

' This function takes an open ADODB.Connection object and will
' return the appropriate date delimiter to be used for queries.
' Only Access is checked for... ' is returned o/w. (SQL Server)
Function DateDelimiter(ByRef cnnOpenConnectionObject) ' As String
        Dim strDBMSName
        Dim strDateDelimiter
        strDateDelimiter = "'"
        strDBMSName = cnnOpenConnectionObject.Properties("DBMS Name").Value
        If InStr(1, strDBMSName, "access", 1) Then strDateDelimiter = "#"
        If InStr(1, strDBMSName, "jet", 1) Then strDateDelimiter = "#"
        DateDelimiter = strDateDelimiter
End Function

This allows you to write code like this that will run against either database without any changes.

' Assuming there's an open connection named cnnOpenConnection,
' the following will produce the appropriate SQL query for
' either Access or SQL Server without any code changes!
Dim strDD
Dim strSQL
strDD = DateDelimiter(cnnOpenConnection)
strSQL = "SELECT * FROM table_name " & _
        "WHERE date_field < " & strDD & Now() & strDD & ";"

How to Empty an Array

I recently got this question from a user working with arrays.

How do I easily assign an array to null? It’s a string array, and I’ve tried: Array = Null, Array = Empty, Array = “” and I always get a Type Mismatch error.

I suppose I could build a custom function to cycle through the array and assign each part to “”, but is there a VBScript function that already does this?

Well, while there isn’t a built in VBScript array emptying mechanism, if you ReDim the array to the samne size without using the PRESERVE keyword, it achieves the desired result. So, assuming arrTest is your array, this code:

ReDim arrTest(UBound(arrTest))

will get the job done and you don’t even have to loop through the array to do it.

Note: That just goes to show what I know… there actually is a VBScript array emptying mechanism! It’s the Erase statement. It works with fixed arrays as well (which the ReDim statement doesn?t). So now you’ve got a choice of how to empty your arrays. Thanks to Zack Jones for giving me the heads up.

Check More Than Just Your ASP Code

I frequently get questions about pages that seem to work fine in IE, but end up not showing anything in Netscape or other browsers. Almost every time it ends up being a missing </table> tag or some other client side issue.

When you’re writing ASP scripts, it’s easy to forget that there’s more than ASP involved in getting a web page working.

There are two really helpful tools to help troubleshoot this type of thing:

  1. The View Source function of most browsers
  2. The World Wide Web Consortium‘s (W3C) HTML Validation Service

Both of these can help you make short work of HTML errors and get back to fixing any ASP problems you might have.

Use Response.Write Instead of Building Strings

When you’re building a lot of text to display, it’s much more efficient to Response.Write things out to the browser than to build a string variable containing the text to output later.

While it may not make a big difference for some uses, every little bit helps and for when those times when you need to do it inside a loop, saving a little time on each iteration can really add up.

Don’t use the Default Web Site

When you install IIS, it automatically sets up a “Default Web Site” on port 80 of the primary IP address of your server. If you take a look at this web site’s properties in the IIS management console, you’ll see it has all sorts of unneeded stuff in it. My Windows 2000 Server has IISHelp, IISAdmin, IISSamples, MSADC, Printers, and so on. On top of that, a lot of components take the liberty of setting up their samples and documentation in the “Default Web Site” as well.

So how do you keep these files, settings, and the potential security problems they bring with them away from your web site? Don’t use the “Default Web Site”. Change the settings on it to not allow any users and move it to an unused port. Then set up a new web site on port 80 and configure it the way you want. That way you’ll have a brand new and clean space in which to build your site.

Don’t Forget that Final /

While this isn’t really an ASP tip, it’s important just the same. When you’re trying a hyperlink to another location and aren’t specifying a file name, be sure to include a trailing /. Without it the client will need to do two roundtrips to the server to arrive at the right page. The first to check for the existence of an extensionless file and the second to get the default page you were intending.

For example, if you’re trying to reach the default document in the test directory,

<a href="/test">

will result in two requests while

<a href="/test/">

will arrive at the same page with just one!

Watch your Paths with Server.Transfer

Server.Transfer is one of the great new commands you can use if you’ve got ASP 3.0. It allows you to move processing to another ASP page to fulfill a client request. It’s much more efficient and eliminates the redirect command being sent to the browser and the browser needing to make another request that occurs with Response.Redirect. There is one little catch however…

Since the client was never told they were moved, you need to be careful when using relative links. If you’ve moved the client to a directory different from where they started, you need to be sure the document you redirected them to can still find any support files it needs. This usually shows up as broken images on the client and while it can easily be fixed by using absolute paths in the target file, it can easily catch you off guard if you’re transitioning from Response.Redirect commands and were’t expecting it.

Scriptless ASP Pages

Whenever you’re adding a new page to your web site, you have a decision to make. Should it be a plain HTML page or should it be an ASP script? Even if the page doesn’t do any processing, can you guarantee it’ll stay that way? The last thing you want to do is start renaming files and causing your users’ bookmarks to become invalid. So what should you do…

Make everything an ASP file even if it contains no ASP! In times gone by this was a very bad idea. IIS 4 and earlier processed every file with an ASP extension regardless of whether or not it contained script. So making every file an ASP file resulted in a large amount of unnecessary processing and worse yet caused pages to take longer to serve.

Fortunately, Microsoft has fixed this in IIS 5. When IIS 5 opens an ASP page, before it starts the actual processing, it does a very quick check to ensure the file actually contains script. If it doesn’t it simply sends it on it’s merry way to the client. As a result, on IIS 5 and later, there’s really no reason why you can’t make every page an ASP page. Just leave the ASP out of the file!

Watch Your Whitespace

While this isn’t technically an ASP tip, it’s worth mentioning anyway. What’s the difference between these two sets of HTML?

Set 1

        <title>Page Title</title>
        <p>This is some text</p>

Set 2

<html><head><title>Page Title</title></head><body><p>This is some text</p></body></html>

I know what you’re thinking… “That’s easy… the first one’s readable!” and you’re absolutely right, but readable by who? While I whole-heartedly support readable code, most HTML is meant to be read by browsers and not people. To a browser, the two sets of code above are identical except for the fact that the first one is over 50% larger (142 bytes vs. 90 bytes) and takes that much longer to download and display!

Don’t get me wrong, I’m not saying you should take out all your spacing and carriage returns, but poorly written ASP can add a lot of extra whitespace to the resulting HTML. This whitespace not only slows everything down, it actually causes more work for your web server and uses more bandwidth. So take a look at your site’s HTML every once and a while and make sure it’s not getting out of hand.


Note: I realize a lot of you are rolling your eyes and shaking your head at this, but it really can make a difference. I was recently working with a community-based portal site who was having some performance problems. The HTML to their home page was just under 33k. I was amazed to find that without even breaking a sweat (and leaving almost all the formatting intact!), we were able to cut it down to 24k! Almost a third of the page was totally worthless spacing. They were reluctant to strip all whitespace, but I’m sure we could have gotten that page down to under 20k pretty easily without really changing anything!

And if that doesn’t convince you, take a look at the source to Yahoo’s homepage sometime. You’ll find very few extraneous tabs, spaces, and carriage returns. The most popular site on the internet needs to do all they can to optimize and they certainly took this tip to heart!

Update Your ADO Components

Keeping your ADO components up to date may seem like a trivial thing, but it’s really not. In addition to new features that can make your coding easier, the latest drivers almost always contain bug fixes and performance enhancements over the previous version.

While you may not want to be on the “bleeding” edge and update your MDAC stack the day the new versions come out, you should try and stay somewhat current.

You can get the latest version from Microsoft’s Universal Data Access webpage. If you’re not sure what version you have, this little ASP script can help you find out.

<%@ Language=VBScript %>
Option Explicit
Dim cnnVersionTest
Set cnnVersionTest = Server.CreateObject("ADODB.Connection")
Response.Write "ADO Version: " & cnnVersionTest.Version
Set cnnVersionTest = Nothing

For more detail on your installed drivers or to troubleshoot your installation, you might want to download Microsoft’s Component Checker Tool.

On Error Don’t Resume Next

Often you want to do some error handling in an ASP page. The only way to do this in VBScript has traditionally been by using On Error Resume Next, which leaves quite a bit to be desired in terms of error handling, but there is one little known feature that makes it a little more bearable.

Most people think that once you turn on On Error Resume Next, you’re stuck with it, but that’s actually not the case. You can tell the script to resume breaking on errors by using the command On Error Goto 0.

While it’s still not a great error handling system, this makes it a little easier to live with if you’re stuck using it.

ByVal Vs. ByRef

Did you know that you can pass a parameter to a Sub or Function in two different ways? You can either do it ByVal (By Value) or ByRef (By Reference). So what’s the difference?

Well when you pass a variable ByVal a new instance of the variable is created and given to the routine being called. Any changes made to the value of this variable have no effect on the value of the original variable that was passed in.

If you instead pass in a variable ByRef, any changes you make to this variable also change it’s value outside the routine. (Note: This is often considered bad practice because it makes code difficult to follow and even harder to understand.)

So you want an example huh? Take a look at the following piece of code.

' This sub look like it just swaps the values
' in the two variables, but does it?
Sub SwapValues(ByVal iFirst, ByRef iSecond)
        Dim iTemp
        iTemp = iFirst
        iFirst = iSecond
        iSecond = iTemp
End Sub
' Declare two vars and set their initial values.
Dim iFirst, iSecond
iFirst = 1
iSecond = 2
' Call our Sub.
SwapValues iFirst, iSecond
' Both values are now 1!
' iSecond was changed because it was passed ByRef
' while iFirst was not since it was passed ByVal.
' Don't believe me? ...see for yourself:
Response.Write "<p>First: " & iFirst & "</p>"
Response.Write "<p>Second: " & iSecond & "</p>"
' In order to actually swap the values you'd need
' to make both parameters ByRef.

So which should you use? Well that depends! (How did you know I would say that?) The default is ByRef and for the most part that makes sense. Why use the additional memory to make a copy of the variable? When you’re passing variables to components however, ByVal should really be the method of choice. It’s much easier to just give the component a copy of the value then to have it need to worry about sending back any changes it might make to the variable. Imagine if this component was on a different computer and the point becomes clear pretty quickly. Every time a change was made to the value, the component would have to go back to the first computer to change the value!

VBScript’s Line Continuation Character

Did you ever have a really long line of code to write and get sick of scrolling left and right trying to read it? Well VBScript has this neat little invention that makes that really unnecesary. It’s called the line continuation character and it’s simply an underline ( _ ). It allows you to nicely split your lines into a more manageable form.

Instead of:

 strSQL = "SELECT field FROM table WHERE field = 'value' ORDER BY field ASC"

You could just as easily use:

strSQL = "SELECT field " _
        & "FROM table " _
        & "WHERE field = 'value' " _
        & "ORDER BY field ASC"

Both of the above will acheive the same result, but the second one will keep your neck from getting sore from looking back and forth.

(Ok… so I’m exagerating this simple and relatively short-lined example a little, but you get the point.)

Use Descriptive Naming Of Files And Directories

How often do you go to a site only to find things named like this:


or even:


While to a computer those make perfect sense, can you even start to tell me what’s you’d think would be found on those pages without actually going to them? If you’re like me, probably not.

How about this one:


While it’s not perfect, at least it gives you a chance.

(If you’re interested, that’s the URL to an article on this site written by myself about the adovbs include file. Oh and if you didn’t guess based on the URL, my name’s John)

While computers can deceipher just about anything… you’re visitors probably can’t. There’s really no reason not to name your files so your visitors will know what they are. You’d be surprised how helpful it can be to a user who’s looking for that page they were “just at” on your site. Now that browsers will display a list of URLs you’ve been to recently, looking through a list of documents in the address bar can actually be quite helpful, but only if the addresses actually mean something.

There’s actually a good article on this located at http://www.asp101.com/articles/wayne/extendingnames/default.asp. And the URL illustrates this tip in action… while it may not be the perfect URL, you can at least tell that it’s an article by Wayne about “Extending Page Names.”

Is The User Still There?

There are times when it’s necessary to do rather complex queries in an ASP page. While you can warn a user that a request might take a while, that doesn’t always stop them from clicking on it and then not waiting to get the results.

Before starting that next call to your DB for the even more data you’ve just decided you’re going to need, you might want to just pop your head up and check to see if the user still cares about the result.

By default, ASP scripts continue to run to completion even if the user has left. By checking the Response.IsClientConnected propery, you can check to be sure the user still wants the result before embarking on that CPU-killing query you need to run to get it.

Microsoft has a nice simple “How To” on the topic in their Knowledge Base:

<%@ LANGUAGE=”VBSCRIPT” %> <% ‘ ‘ !!! WARNING !!! ‘ ‘ This page has code in it that may use 580px CPU cycles for at least ‘ 30 seconds. Do not run this code on a production server; restrict ‘ its use to a test server. ‘ Function IsConnectedAfter(Seconds) Dim StartTime ‘time the function started Dim PauseTime ‘time the pause loop started ‘ Use PerfMon to monitor the CPU cycles on the Web server. You ‘ will notice that if you click stop in the browser, the CPU ‘ will settle down sooner than if the loop had continued. IsConnectedAfter = True StartTime = Now Do While DateDiff(“s”, StartTime, Now) < Seconds PauseTime = Now Do While DateDiff(“s”, PauseTime, Now) < 1 ‘Do Nothing Loop Response.Write “.” If Response.IsClientConnected = False then IsConnectedAfter = False Exit Function End If Loop End Function %> <HTML> <HEAD> <META NAME=”GENERATOR” Content=”Microsoft Visual InterDev 1.0″> <META HTTP-EQUIV=”Content-Type” content=”text/html; charset=iso-8859-1″> <TITLE>Document Title</TITLE> </HEAD> <BODY> <h1>!!! WARNING !!!</h1> <p>This page has code in it that may use <b>580px CPU cycles</b> for at least 30 seconds. Do not run this code on a production server; restrict its use to a test server. <p>Use PerfMon to monitor the CPU cycles on the Web server. Press STOP in the Web browser, and you will see that the CPU cycles will settle down sooner than they would have without checking the IsClientConnected property. <HR> <% If IsConnectedAfter(30) then Response.Write “<p>The client is still connected</p>” Else ‘The browser is no longer connected. This would be a ‘good place to abort any transactions, clean up any ‘variables, and so forth. End If %> </BODY> </HTML>

Check Also

ASP.NET Interview FAQs

What is view state and use of it? The current property settings of an ASP.NET …