Platinum Edition Using Visual Basic 5

Previous chapterNext chapterContents


- 38 -
Working with Active Server Page Objects

Learn what objects are available in ASP and how and when to use them.
Basic input and output in Active Server Pages, the basis for any of your scripts.
Share information between pages for one or all of the visitors to your site.
Components provide prepackaged functionality you can use from your scripts.
Bring the power of Visual Basic to your ASP applications by creating reusable components. Allow your Web pages to access the same business objects as your desktop applications.

Active Server Pages (ASP) are used to create dynamic Web applications. The previous chapter introduced the basics of programming these pages, but those basics are not enough to create a truly dynamic site. Listing 38.1 in Chapter 37, "Creating Active Server Pages," created a Web page with ten lines--always ten, always the same lines. Not very dynamic.

To go beyond that level of dynamic content, you must have access to external input--more than just simple things, such as the current time. The input can be from a database, from users' actions on their browsers, or from some form of live data feed. It doesn't matter what. Using VBScript (or JavaScript) alone, you can't get that input. That is where objects come in to play; they are the window to everything that lies outside the page.

Introducing Objects

Objects in ASP are very similar to objects in VB. You probably have already seen and used objects a fair bit, so this introduction is brief. You work with objects through their properties and methods and respond to their events. What the various parts do depends on the object, but in general, properties enable you to retrieve and set values, methods perform actions, and events occur when something happens (or at least they should--see the following Note).


NOTE: If you have created your own objects by using classes in Visual Basic, you know that you can have properties or methods that behave any way you want. You can make your object perform an action when the user sets a property or provide a method that takes a parameter and just sets an internal variable. Please don't. The key to creating reusable objects is following standards; use properties and methods as they are intended and other programmers won't get annoying surprises. If you are unsure of how a certain feature should be implemented, look at the objects provided by Microsoft for good examples.

The objects can be ActiveX (COM) objects, but they don't have to be. Both VB and ASP provide a built-in set of objects (sometimes referred to as their Object Model or as intrinsic objects) that give the environment a wide range of functionality. Each of these objects can be accessed directly; they don't need to be created, declared, or initialized. External objects (discussed later) expand the functionality of the language. Later in this chapter, you will be introduced to several ASP Components that you can use as external objects in your site. The intrinsic objects are available all of the time and generally are used more often (at least when just starting out) than external objects, so you will be spending more time on intrinsic objects than on other components.


COM, OLE, ActiveX, ASP Components, Enough Already!
Throughout Visual Basic magazines and books (including this one), you can find references to ActiveX objects, COM objects, OLE Automation, and now ASP Components. If you were wondering "what are all these things?" you wouldn't be alone.

Don't worry. You're not going crazy. They're all the same thing: COM. The Component Object Model has been around for quite a while. It started out as OLE, Object Linking and Embedding, gained new power with OLE2, which included, among other new features, OLE Automation (which didn't include a lot of linking or embedding, but that darn OLE stuck around anyway). Now, due to some good marketing, COM has become known to many programmers as ActiveX. They are all parts of the whole technology that is COM, each one being some subset of the full functionality. It would be nice to use one term only through the entire book, but that can't be helped. The buzzwords are stuck in our minds.


ASP Intrinsic Objects

There are five objects built into ASP:

The following sections cover the properties, methods, and events (for those that have events) of each of the objects. You will learn what each object does and how to use it, and you will be given examples of where it is most useful. As each object is covered, some related aspects of programming Active Server Pages will also be touched on, such as the global.asa file.

The Request Object

The Request object contains information about the browser request for the current page. Each request can contain a large number of parameters in several different categories. To handle all of this information, the Request object uses collections. Collections, which are common to VB, VBA, and VBScript, generally function like linked lists or dynamic arrays, holding a list of information. You can access the information through a loop (using the For Each...Next construct), directly (using a string key), or as an ordered list (using an integer index). Chapter 10, "Using the Windows Common Controls," and Chapter 18, "Introduction to Classes," contain coverage of collections, including several examples.

See "Creating a Toolbar with Code," Chapter 10

See "Creating Classes that Contain Collections," Chapter 19

The following collections can be accessed through the Request object:

Each collection contains a set of values that are all accessed in the same manner: <Collection>("<Variable Name>"). In this section, you go through the collections (except Cookies, which are covered in a separate section) and the values they contain, but you can also quickly write ASP code that will provide a list of the available variables using For Each...Next. The code in Listing 38.1 loops through each collection and outputs all the variable names and values. You can use similar code to display the contents of any collections.

Listing 38.1 COLLECTIONS.ASP--Displaying the Content of Collections

<%@ LANGUAGE="VBSCRIPT" %>
<HTML>
<HEAD><TITLE>Collections</TITLE></HEAD>
<BODY>
<H1 align="center">Request Collections</H1>
<HR>
<H1 align="center">Query String</H1>
<% For Each item in Request.QueryString %>
<STRONG><%=item%></STRONG>=<%=Request.QueryString(item)%><BR>
<% Next %>
<HR>
<H1 align="center">Form</H1>
<% For Each item in Request.Form %>
<STRONG><%=item%></STRONG>=<%=Request.Form(item)%><BR>
<% Next %>
<HR>
<H1 align="center">ClientCertificate</H1>
<% For Each item in Request.ClientCertificate %>
<STRONG><%=item%></STRONG>=<%=Request.ClientCertificate(item)%><BR>
<% Next %>
<HR>
<H1 align="center">Server Variables</H1>
<% For Each item in Request.ServerVariables %>
<STRONG><%=item%></STRONG>=<%=Request.ServerVariables(item)%><BR>
<% Next %>
<HR>
<H1 align="center">Cookies</H1>
<% For Each item in Request.Cookies %>
<STRONG><%=item%></STRONG>=<%=Request.Cookies(item)%><BR>
<% Next %>
</BODY>
</HTML>

This is an important sample that you should try out on your own, as it will be referred to from time to time in the rest of this section. When you do run this script, you may be surprised to see that some of the collections appear to contain no items. That isn't a mistake in the code. Other than the SERVERVARIABLES collection, there shouldn't be any visible items at this point. As you go through each collection, you'll understand why this is the case.


NOTE: In Listing 38.1, there is a line that hasn't been used in any examples thus far, <%@ LANGUAGE="VBSCRIPT" %>. This line (placed at the very beginning of the .asp file) tells ASP what scripting language is being used in this file. By default, the server assumes you are using VBScript, so this is not really necessary. It is a good idea to include it anyway, both to make it clear what language you're using, and to take due precaution in case the default language of the server has been changed.

QUERYSTRING The QUERYSTRING collection is used to get the values of any parameters that were sent to the ASP file. Like parameters in procedures in Visual Basic, ASP files use the parameters to pass information from one page to another. The syntax for passing parameter values is to append them in name/value pairs to the end of the page's URL. For example, if the ASP file you are calling is http://www.online-can.com/qsexample.asp and you want to send it a parameter called ID with a value of 5, you append ?id=5 onto the end of the original URL, making it http://www.online-can.com/qsexample.asp?id=5. Multiple parameters can be sent at once, separated by an ampersand (&), as follows: http://www.online-can.com/qsexample.asp?id=5&code=UT. The receiving page can retrieve these values from the QUERYSTRING collection using the parameter names as keys, as shown in Listing 38.2.

Listing 38.2 QSEXAMPLE.ASP--Retrieving Variables from the QueryString Collection

<%@ LANGUAGE="VBSCRIPT"%>
<HTML>
<HEAD><TITLE>Query String Example</TITLE></HEAD>
<BODY>
<H2>The ID is <%=Request.QueryString("ID")%></H2>
<H2>The Code is <%=Request.QueryString("CODE")%></H2>
</BODY>
</HTML>

A big difference between these parameters and parameters in VB is that in ASP the parameters are not predefined. In VB your procedure expects a certain number of parameters of certain data types in a certain order. In the preceding example, two parameters were sent to qsexample.asp, but three could have been sent, or one, without generating any sort of error.

The URLs http://www.online-can.com/qsexample.asp?ID=5&CODE=UT and http://www.online-can.com/qsexample.asp?CODE=UT&ID=5&OTHERCODE=TU would both produce the exact same output (see Figure 38.1). The example page looks in the QUERYSTRING collection for two values--it doesn't matter which order they were sent or if there were other values sent that it isn't using. If the parameter you expect hasn't been sent, http://www.online-can.com/qsexample.asp?id=5 for instance, then you'll receive an empty string when you try to retrieve it with Request.QueryString("CODE").

All parameters are treated as Variants (general purpose data type that can hold almost any type of information), but your page may still be expecting a certain type of data for each parameter. In the previous example, ID is a numeric value, but nothing prevents someone from sending a string instead. If you planned on using that ID value as a number (in a SQL statement or a calculation), you would have a problem.

FIG. 38.1
Displaying the contents of the QUERYSTRING collection.

None of these things (parameter not sent, wrong data type, and so forth) cause errors on their own, but they can cause your ASP file to produce unexpected results or (its own) errors. It is a good idea to check for the existence of a parameter before you start using the ASP file. Data type errors are difficult to check for, but the VBScript functions IsDate and IsNumeric can help. An example of this is provided in Listing 38.3, which uses the same ID parameter. Try this page out by sending it different types of values, such as http://www.online-can.com/qs_datatype.asp?id=fred or http://www.online-can.com/qs_datatype.asp?id=12.

Listing 38.3 QS_DATATYPE.ASP--Checking the Data Type of Parameters

<%@ LANGUAGE="VBSCRIPT"%>
<HTML>
<HEAD><TITLE>Data Type Example</TITLE></HEAD>
<BODY>
<%If IsEmpty(Request.QueryString("ID")) Then %>
     <H2>No ID Value Passed</H2>
<%Else%>
     <%If IsNumeric(Request.QueryString("ID")) Then %>
          <H2>Numeric ID Passed: <%=Request.QueryString("ID")%></H2>
     <%Else%>
          <H2>Non-Numeric ID Passed: <%=Request.QueryString("ID")%></H2>
     <%End If%>
<%End If%>
</BODY>
</HTML> 


NOTE: ASP doesn't format your code in any way; you don't have to indent code within If blocks or anything else. Listing 38.3 does indent, and it is recommended that you do so to keep your pages easy to read and understand.

In addition to flexibility in parameter type and order, ASP allows you to send multiple parameters of the same name, such as http://www.online-can.com/qsexample.asp?ID=5&ID=6&CODE=UT&CODE=TU. If multiple values have been set for one parameter, then the value for that parameter, Request.QueryString("ID"), becomes a collection itself. This means you can iterate through its values or determine how many values it contains, just like a regular collection (see Listing 38.4).

Listing 38.4 QS_COLLECTIONS.ASP--Working with Collections of Parameter Values

<%@ LANGUAGE="VBSCRIPT"%>
<HTML>
<HEAD><TITLE>Query String Collections Example</TITLE></HEAD>
<BODY>
<%For i = 1 to Request.QueryString("ID").Count %>
     <H2><%=i%>:<%=Request.QueryString("ID")(i)%></H2>
<%Next%>
</BODY>
</HTML>

When creating ASP-based Web sites, you use the parameters feature almost continually. Although you can type the parameters directly as part of the URL, it is more common to use them in hyperlinks from other pages. The following two listings (see Listings 38.5 and 38.6) represent two pages. The first is a standard HTML page with several links to the other file, which contains scripting code. If you want to run these pages, you should place them into the same directory (so that the hyperlinks work properly).

Listing 38.5 CALLER.HTM--Calling Page for Hyperlink Example

<HTML>
<HEAD><TITLE>Calling Page Example</TITLE></HEAD>
<BODY>
<H1>Select the Biography you wish to see:</H1>
<a href="bio_page.asp?id=1">John</a><BR>
<a href="bio_page.asp?id=2">Frank</a><BR>
<a href="bio_page.asp?id=3">Susan</a><BR>
</BODY>
</HTML>

Listing 38.6 BIO_PAGE.ASP--Page Called in Hyperlink Example

<%@ LANGUAGE="VBSCRIPT"%>
<HTML>
<%
Select Case Request.QueryString("ID")
    Case 1 `John
%>
     <HEAD><TITLE>John</TITLE></HEAD>
     <BODY bgcolor="#FFFFFF">
     <H1>John</H1>
     <P><STRONG>John is a wonderful guy who has
 been working in our production department for
 years now. He stacks the boxes during the morning,
 then unstacks them in the afternoon. He never lets
 the fact that his job is pointless make him
 depressed.</STRONG></P>
<%
    Case 2 `Frank
%>
     <HEAD><TITLE>Frank</TITLE></HEAD>
     <BODY  bgcolor="#FFFFFF" >
     <H1>Frank</H1>
     <P><STRONG>Frank has always been working here.
 Filling various positions, from the mail room
 to the board room, he is an asset to the company
 and we are sad to hear that he is retiring next
 week at the age of 105.</STRONG></P>
<%
    Case 3 `Susan
%>
     <HEAD><TITLE>Susan</TITLE></HEAD>
     <BODY  bgcolor="#FFFFFF" >
     <H1>Susan</H1>
     <P><STRONG>Susan, our illustrious President, was one
 of the founding members of our company, and as such
 is responsible for much of our success. Of course,
 since this is a fictional company, our success has
 been limited.</STRONG></P>
<%
    Case Else
%>
     <HEAD><TITLE>Error</TITLE></HEAD>
     <BODY  bgcolor="#FFFFFF">
     <H1>This employee doesn't exist.</H1>
<%
End Select 
%>
</BODY>
</HTML>

In the first page, Caller.htm, three links are available. They all point at the same .asp file, but with different parameter values. From the user's point of view, they can go to three separate pages (see Figures 38.2, 38.3, and 38.4), and each displays different information. However, you know that there is just one.

FIG. 38.2
This is the result of clicking the first link.

FIG. 38.3
This is the same page, requested with different parameter values.

FIG. 38.4
Here is the same page again, with a different ID value specified.

This method of having many hyperlinks to the same ASP file, each with different parameters, is very useful. It enables you to maintain one file instead of many separate pages, and it lends itself well to database-driven Web sites. This technique is used throughout the next chapter, in which an example Web site is built.

FORM The FORM collection is for use with HTML forms. An HTML form is a collection of text fields, buttons, check boxes, and other controls that are set up to allow the user to fill in and submit information. What happens when a user submits information? That is controlled by setting the action option of the <FORM> tag. The action option is set to an URL, which can point to a program or script designed to handle the results of the HTML form. This used to be limited to a CGI application or Perl script, but because the action option is just an URL, it can be the address of an Active Server Page. When the user submits the form (usually by pressing a certain button), all the information entered into the form is sent to the URL specified in the action clause. How the information is sent depends on the method option of the <FORM> tag. If it is set to GET, then the field names and values are sent in the same manner as parameters (discussed earlier) and can be retrieved from the QueryString collection. If, on the other hand, it is set to POST, then the information is embedded into the HTTP Request sent to the page and is available through the Form collection. Listing 38.7 contains an HTML form with various types of controls on it (see Figure 38.5) and the action option set to point to Collections.asp (refer to Listing 38.1, which must be located in the same directory as this page).

Listing 38.7 FORMSAMP.HTM--Sample Form for Request.Form Example

<HTML>
<HEAD>
<TITLE>Form Sample</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H1>Please Fill Out The Form Below:</H1>
<P>&nbsp;</P>
<form action="collections.asp" method="POST" name="Sample">
    <TABLE BORDER="0">
        <TR>
            <TD>Name:</TD>
            <TD><INPUT TYPE="text" size="50" name="txtName"></TD>
        </TR>
        <TR>
            <TD>Organization:</TD>
            <TD><INPUT TYPE="text" size="50" name="txtOrganization"></TD>
        </TR>
        <TR>
            <TD>Phone Number:</TD>
            <TD><INPUT TYPE="text" size="15" name="txtPhoneNumber"></TD>
        </TR>
        <TR>
            <TD>Country:</TD>
            <TD>
              <SELECT NAME="cboCountry" size="1">
                     <OPTION SELECTED>Canada</OPTION>
                     <OPTION>United States</OPTION>
                     <OPTION>Mexico</OPTION>
                     <OPTION>France</OPTION>
                </SELECT>
          </td>
        </tr>
    </table>
    <P ALIGN="center">
     <INPUT TYPE="submit" name="cmdSubmit" value="Submit">
    </P>
</form>
<P>&nbsp;</P>
<H1 ALIGN="center">Thank You</H1>
</BODY>
</HTML>


NOTE: In Listing 38.7, the method (line 8) is set to POST; if you want to see the results of the other method, you can change this to GET.

SERVERVARIABLES When a Web page is requested from a browser, the Web server is sent various pieces of information about the requester. Those pieces of information, combined with various server-side environment variables, are all contained in the Server Variables collection. Following are the more useful members of this collection, but you can always look at the others on your own (refer to Listing 38.1).

FIG. 38.5
A Simple Example HTML Form, viewed when it is submitted.

Client Certificates Certificates are digital documents that uniquely identify an object, whether that is an individual, a company, or a specific Web server. Each certificate is issued by some signing authority (Verisign is a common authority; see http://www.verisign.com) and contains a series of fields used to identify the object attached to the certificate. The fields in a particular certificate can vary, but usually include standard information such as Name, Country, Organization, and so forth. Client Certificates refer to the use of these certificates by visitors to a secure Web site as a means of identification. If certain options are selected for the virtual directory being browsed (see Figure 38.13, in the previous chapter), the server will request a certificate from the client for identification. If a certificate is provided, your pages may use the Client Certificate collection to query the values contained within the document. This provides your pages with a way to determine the client's name or other identifying information, in order to control access to secure information. More information on certificates and Secure Web Sites is available in the next chapter.

The Response Object

The Response object is used to send information to the client. Unlike Request, this object contains only one collection, Cookies. The Cookies collection is not discussed here, but is covered in-depth later in the chapter in a section on working with Cookies, which covers both the Request and Response objects. Most of the functionality of the Response object is accessed through its series of properties and methods. Each item will be covered as well, with some related examples.

Properties The Response object has several properties, each of which is used to affect the information returned to the browser in some way. Setting any of these values after information has been returned to the browser (which occurs as soon as the <HTML> tag is reached) will cause an error.

Listing 38.8 EVERCACHE.ASP--Setting Response.Expires to Zero

<%@ LANGUAGE="VBSCRIPT"%>
<%Response.Expires=0%>
<HTML>
<HEAD><TITLE>Never Cache This Page</TITLE></HEAD>
<BODY>
<H1>The Current Date and Time is:</H1>
<P align="center"><%=Now%></P>
</BODY>
</HTML>

Listing 38.9 CACHE_5MIN.ASP--Setting Response.Expires to Five Minutes

<%@ LANGUAGE="VBSCRIPT"%>
<%Response.Expires=5%>
<HTML>
<HEAD><TITLE>Cache This Page for 5 minutes</TITLE></HEAD>
<BODY>
<H1>The Current Date and Time is:</H1>
<P align="center"><%=Now%></P>
</BODY>
</HTML>

Listing 38.10 TEXT.ASP--Outputting Text from an Active Server Page

<%@ LANGUAGE="VBSCRIPT"%>
<%Response.ContentType="text/plain"
For j = 1 to 100
     Response.Write j & "," & (j * 2) & "," & (j * 3) & chr(13) & chr(10)
Next
%>

Listing 38.11 BUFFERING.ASP--Buffering Output to Allow Error Handling

<%@ LANGUAGE="VBSCRIPT"%>
<%
Response.Buffer=TRUE 
On Error Resume Next
%>
<HTML>
<HEAD><TITLE>Buffering Example</TITLE></HEAD>
<BODY>
<%
Set Obj = Server.CreateObject("SyncDateTime.clsSyncDateTime")
If Err.Number > 0 Then
     ErrorURL = "ErrorHandler.asp"
     ErrorURL = ErrorURL & "?Source=" & Server.URLEncode(Err.Source)
     ErrorURL = ErrorURL & "Number=Err.Number"
     Err.Clear
     Response.Redirect ErrorURL 
        ` Buffering allows us to do a redirect at any point in the page.
Else
     Obj.DateTime = Now
     Response.Write Obj.DateString
End If
%>
</BODY>
</HTML>


CAUTION: Regardless of how you plan to use buffering, setting the Response.Buffer property must occur at the very beginning of your page, before any other commands or any content.

The other reasons for choosing to turn buffering on or off are mostly aesthetic; buffering affects the apparent speed of your page. Buffering can hide the fact that the generation of one particular section of the page is taking longer than the rest but can also make the entire page seem to take too long. If the page takes a long time to execute, this can result in a long wait before any part of the page is displayed at the client end.

Methods The Response object's methods allow you to directly affect the return of information to the browser. Several of these methods involve the concept of buffering, see the Buffer property previously discussed for more information.

See "The Basics," Chapter 37

Listing 38.12 REDIRECT.ASP--Redirection Based on Client OS

<%@ LANGUAGE="VBSCRIPT"%>
<% Select Case Request.ServerVariables("HTTP_UA_OS")
     Case "Windows95"
          Response.Redirect "Win95.htm"
     Case "WindowsNT"
          Response.Redirect "WinNT.htm"
     Case "MacOS"
         
          Response.Redirect "MacOS.htm"
     Case Else
          Response.Redirect "Other.htm"
End Select
%>
<HTML>
<HEAD><TITLE>Redirection</TITLE></HEAD>
<BODY>
</BODY>
</HTML>


CAUTION: Response.Redirect modifies the HTTP headers, so it must occur before any content is returned to the browser (see Response.Buffer in Listing 38.11 for more information).

Listing 38.13 END.ASP--Stopping Execution of an Active Server Page

<HTML>
<HEAD><TITLE>Stopping an ASP</TITLE></HEAD>
<BODY>
<% For j = 1 to 200 %>
<P><%=j%></P>
<% 
    If j > 40 Then
       Response.End
    End If
Next
%>
</BODY>
</HTML>
207.161.119.76, -, 7/3/97, 21:23:17, W3SVC, WWW, 
205.200.204.200, 30, 413, 259, 200, 0, GET,
/append.asp, This is a test of the AppendToLog method, 

Of course, some fields (such as the IP address) will contain different values if you try out this example yourself.

Listing 38.14 APPEND.ASP--Appending Text to the Web Server's Log

<%Response.AppendToLog "This is a test of the AppendToLog method" %>
<HTML>
<HEAD><TITLE>Example Page</TITLE></HEAD>
<BODY>
</BODY>
</HTML>


CAUTION: Web Server log entries are comma-delimited, so the string you append cannot contain any commas.

Suppose you create an employee directory for a large company. For each employee, you would go to an Active Server Page to display his/her information, sending a parameter of the employee's ID. Your database would also include pictures for each employee, stored as binary data in a field of the employee table. In this case, you would need to create another .asp file, called picture.asp, for example, and in your details page, use it as the source for your picture, such as <img src="picture.asp?id=<%=EmpID%>">. The picture page (see Listing 38.15) would use RESPONSE.CONTENTTYPE="image/jpeg" to tell the browser that it should be treated like a picture and would then call RESPONSE.BINARYWRITE to output the contents of the picture field from the database.

Listing 38.15 PICTURE.ASP--Outputting Binary Data

<%
`Create ADODB Object, Connect to Database and execute query
Set conn = Server.CreateObject("ADODB.Connection")
Conn.Open "DSN=EmployeeDB"
SQL = "SELECT Employee.Picture FROM Employee "
SQL = SQL & "Where Employee.ID=" & Request.QueryString("ID")
Set RSPicture = Conn.Execute(SQL)
Response.ContentType="image/JPEG"
Response.BinaryWrite RSPicture("Picture")
%>


NOTE: The example shown in Listing 38.15 isn't complete: the database access involved has been skipped. This is to allow you to focus on the particular feature without bringing in a lot of unrelated code. If you want to try out this specific type of example in full, you will need an ODBC connection to a database that supports BLObs (Binary Large Objects) and has a table set up that contains JPEG format binary data.

Controlling State, the Application and Session Objects, and the Global.asa File

Variables used in ASP or in any programming environment have a certain scope, meaning that variables created inside a procedure exist for that procedure only. These types of variables are fine for most things you do, in any language, but occasionally you need to keep some piece of information available in all of your procedures. A good example is the user IDs of the logged-on users. They may have logged on at the very beginning of the program, but you need to know that information throughout your application.

This situation is usually handled by creating a global variable (for example, Public Userid as string), which can then be used anywhere you want without having to pass it to any procedure. To do this in ASP, you first have to determine what global means in the context of Active Server Pages. In Visual Basic, it means that the variable has Application-level scope or, more clearly, that the variable is available to every part of that VB Application. In ASP, because there is no project file to define your application, you have to use a different method to determine what global means.

An ASP application is defined as all of the ASP files within one Virtual Root (refer to Chapter 37, "Creating Active Server Pages"). Two different levels of variables are supported for ASP: Session variables, which are closest to VB global variables, and Application variables. Session variables exist on a user-by-user basis, while Application variables are available to all users of that application. The Session and Application objects, which enable you to create and access the different types of global variables, are discussed later in the chapter. Unlike the objects previously discussed (such as the Request object), these objects have more than just properties and methods; they also have events.

See "Security Settings in Windows NT, IIS, and ASP," Chapter 37

In Visual Basic, code is written to be executed on an event by placing that code into special procedures that are defined at the same level as the object. ASP handles the Application and Session events in the same fashion, and the code is placed into a special file named "global.asa," which must be located at the root of the ASP application. These events, and the "global.asa" file, will be described later.

The Application Object

Variables are placed into and accessed in the Application object in the same manner as other collections. Any type of variable, even instances of objects, may be placed into the Application and Session objects (with the single exception of ASP Intrinsic objects) so that the line Application("Test")=Response would cause an error.

This code, APPLICATION("STARTDATE")=Now would store the date and time into an application variable named StartDate. To access this information again is equally straightforward. The code RESPONSE.WRITE APPLICATION("STARTDATE") would output that date to the browser. Because of the multiuser nature of the Application object, two methods are provided: Lock and Unlock. These methods are similar to the idea of locking a database record before updating it because they allow you to prevent anyone else from modifying the Application object at the same time as you. You should try to minimize the amount of code that occurs while you've locked the Application object, as no other users can modify any Application level variable during that time. Listing 38.16 and Listing 38.17 show two possible ways to assign the results of a complex function to the Application object. The second method is preferred, as it performs the calculation outside of the Lock/Unlock, reducing the amount of time the lock is in effect.

Listing 38.16 LOCKSAMP1.ASP--Locking the Application Object for a Long Time

<%
Application.Lock
Application("MyResult")=ComplexFunction(3,223,29)
Application.Unlock
%>

Listing 38.17 LOCKSAMP2.ASP--Locking the Application Object for the Shortest Time Possible

<%
TempValue = ComplexFunction(3,223,29)
Application.Lock
Application("MyResult")=TempValue
Application.Unlock
%>

A single instance of the Application object is created when the first person accesses any Active Server Page in that ASP application and is released when the Web service is shut down or restarted. At each of these times, an OnStart or OnEnd event is triggered, as appropriate. Code that you want to run at either of these times can be placed into the global.asa, as shown in Listing 38.18.

Listing 38.18 GLOBAL.ASA--Working with Application Events

<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_OnStart
      Application("StartDate") = Now
      Application("Counter") = 0
End Sub
</SCRIPT>


NOTE: In Listing 38.18, the <SCRIPT> tag is used, which you may have seen when dealing with client-side scripting (refer to Chapter 35, "Internet Programming with VBScript"). This is required in the global.asa file because that file is not really a true ASP file and doesn't support the use of the script delimiters (<% and %>).

See "Using the HTML <FORM> Elements," Chapter 35

See "The <SCRIPT> Element," Chapter 35

The Session Object

Like the Application object, the Session object uses the same syntax to store and retrieve values, and its two event routines, Session_OnStart and Session_OnEnd, are handled in the global.asa file (refer to Listing 38.18). There are two differences between the two objects--when the instances of them are created or destroyed, and who can access those instances.

A Session starts when a user requests any page within an ASP application. It ends when the session times out, or when a script Abandons the session (see the following sections, Abandon and Timeout). All values/objects stored in Session variables are lost when the session ends.

Variables stored in the SESSION object are available only to the user who owns the session, whereas the APPLICATION object is available to all users. This difference allows the Session object to function safely without any form of the Lock/Unlock methods present in the Application object.

Abandon The SESSION.ABANDON method ends the current session immediately. This causes any script in the SESSION_ONEND procedure to be called and the destruction of any session-level variables or objects.

Timeout Each Session instance is maintained on the server until it is explicitly closed (as with the preceding Abandon method) or until a certain amount of time has passed since the application received the last request for that session (any page access within that ASP application). The second condition is known as a timeout. This property returns or sets the number of minutes before the current session times out. The default is 20 minutes, and modifying the value for this property changes only the timeout for the current session. Changing this, or any other default ASP setting, involves modifying the Web server's Registry entries.

SessionID This property is read-only and holds the ID used to uniquely identify a session (see the "Oh, It's Just You Again" sidebar). This value is unique only across the current Application instance, and it may repeat after the Web service has been restarted.


Oh, It's Just You Again
When a user first requests a page inside an ASP application, he/she has started a Session. Values stored into Session variables are kept at the server and are made available to that user for the duration of his/her session. To accomplish this task, the server has to keep track of who owns which session. Communication between the server and the browser consists of requests and responses; there is no permanent connection. Every time the user requests the page, the server has to determine if the user already has a session or if a new session should be created.

It manages this little trick by using a cookie. This cookie stores (at the client side) a unique ID that it sends to the server every time it requests a page. The server then uses this ID to find the user's current session. If the ID isn't present on the client, or the session has been removed on the server, a new session is started, and a new ID is stored into the cookie.

If the client's browser doesn't support cookies, or the user chooses not to accept the cookie containing the SessionID, then no Session can be set up for that client, and session-based variables and objects will not work.


Cookies

Cookies are a unique feature in the world of HTML and HTTP. They allow pages and sites to store information on the client. This capability became a need as Web sites attempted to become more customized. Sites, such as http://home.microsoft.com, that show you personalized content immediately upon your arrival to the page (without any form of login) are using cookies to determine who you are. When you first go to the page, they create a server-side record of you (in a database or something similar) and store a unique identifier into a cookie on your machine. When you return to that page, it looks at the cookie to get your unique ID, uses it to retrieve the server-side information, and then creates a page that is customized for you. If cookies didn't exist, you would have to identify yourself (most likely through a logon screen) every time a site wanted to show you a personalized appearance.

FIG. 38.6
Disabling Cookies in Internet Explorer 3.01.

Most browsers support cookies, so that isn't usually an issue, but many (including Microsoft's and Netscape's browsers) give users the option not to accept cookies (see Figure 38.6). If users take this option, then when they go to sites that attempt to send out a cookie, they have the option to not accept it (see Figure 38.7). Without that cookie, the sites (which could potentially include yours) will be unable to work as expected. With ASP, this means more than just requiring a logon screen--it means that Session variables are not available. Many sites rely heavily on storing information in the Session object and, therefore, depend on cookies to function. Even if you are not using the Session features of ASP, it still creates a session for you and thus still sends out cookies.

FIG. 38.7
Cookie Security Warning when accessing an ASP site.

Now that you have an idea what cookies are and what problems can exist with them, you may want to use them in your own ASP applications. If so, you are in luck because it is very easy to use them. The Response.Cookies collection enables you to create cookies and place values into them, and the Request.Cookies collection enables you to retrieve values from the cookies. The following example shows how to place a value into a cookie and then retrieve it. Each time you refresh or return to this page, the value increases. Try disabling cookies or turning on the "warn before sending" option of Internet Explorer when viewing this page to see what effect it has on the script (refer to Figure 38.6).

Listing 38.19 demonstrates setting individual values in a cookie (Response.Cookies ("Counter")), but you can also set and access individual subkeys of a Cookie by using a second index. This example--Response.Cookies("Counter")("main")=6--would set the "main" subkey of this Cookie to 6. A cookie cannot have both types of values--if you used the storage method, setting the value using one index would overwrite any subkeys that were in use, and vice versa. The read-only property HasKeys (as in Response.Cookies("Counter").HasKeys) can be used to determine if subkeys are in use for a particular Cookie. When setting the Cookie's value by using the Response objects, several other properties of the cookie are available, such as Expires, Domain, Path, and Secure.

Listing 38.19 COOKIES.ASP--Demonstration of Setting and Retrieving Cookie Values

<%
Counter = Request.Cookies("Counter")
If len(Counter) = 0 Then
     Counter = 0
Else
     Counter = Counter + 1
End If
Response.Cookies("Counter") = Counter
%>
<HTML>
<HEAD><TITLE>Cookie Demonstration</TITLE></HEAD>
<BODY>
<H1>Cookie Value: <%=Counter%></H1>
</BODY>
</HTML>

The Server Object

This object's name suggests that it gives access to the Web server itself, which is not quite true. The properties and methods are more related to the Web server than the other intrinsic objects but are really just general utility functions.

ScriptTimeout This property controls how long an ASP script can execute on the server before it is considered to have timed out and an error message is returned to the browser. The default value for this property, which is contained in the Registry, is usually 90 seconds. This property can be used only to increase that value, and if you set the timeout to a value less than the default, the default will still be used.

CreateObject This method of the Server object is the most powerful aspect of ASP, providing the capability to create instances of COM objects. Using the VBScript Set command, you can create an instance of a component and assign it to a variable for use in your pages. You can also take these instances and store them into the Application or Session objects to allow those objects to be used across your ASP application. The example script in Listing 38.20 shows the creation of a component that is used to output lines back to the browser. Later, in the sections dealing with external objects, you will see this method in every Active Server Page used. The syntax of the method is straightforward, and is identical to the CreateObject statement in VB because it takes just one parameter (the ProgID.ClassId string of the object you are trying to create).

Listing 38.20 TOC.ASP--Example Using the CreateObject Method

<%
Response.ContentType = "text/plain"
Set NAV = Server.CreateObject("Navigation.clsWebDirUtils")
TOCLine = "1 -t main.htm " & """" & "Employee Policy Manual" & """"
Response.Write TOCLine
Response.Write vbNewLine
NAV.FilePath = Server.MapPath(".")
NAV.OutputFormat = NAV.obsTOC
NAV.ListFiles 2
i = 0
if NAV.LineCount > 1 Then
     for i = 2 to NAV.LineCount
          
          OutputString = NAV.lines(i + 1 - 1) & " "
          Response.write OutputString & vbNewLine
    ext
end if
%>

HTMLEncode Certain characters can't be written out directly to the browser. These characters, including < and >, as well as both double and single quotes, have special meaning to the browser and will not be displayed as you would expect. If you are entering text into a Web page editor, such as FrontPage, then these characters are automatically converted into special character combinations (such as &lt for <) for you. If, as is more often the case in ASP, you are pulling text out of a database or other external source, then you need to perform this conversion yourself (at run time). It is possible to write a VBScript routine to do this or to create an external object in VB or VC++ for this purpose, but you don't have to do so. Server.HTMLEncode will take any string as a parameter and output the converted value for use in your page. The example Active Server Page in Listing 38.21 produces the HTML output shown in Listing 38.22.

Listing 38.21 HTMLENCODE.ASP--Converting Text with Server.HTMLEncode

<HTML>
<HEAD>
<TITLE><%=Server.HTMLEncode("John & Debbie's Web Page")%></TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H1 align="center">
<%=Server.HTMLEncode("Welcome to John & Debbie's Place")%>
</H1>
<H2 align="center">
<%=Server.HTMLEncode("Where it's <COOL> to use tags!")%>
</H2>
<P><%=Server.HTMLEncode("John specializes in " & _
"creating Web pages. Using only the <BODY>")%><BR>
<%=Server.HTMLEncode("and </BODY> tags he is able to " & _
"generate a complete site in minutes.")%></P>
<HR>
<P><%=Server.HTMLEncode("Debbie prefers to create" & _
" graphics.  Wherever you have an <IMG> tag,")%><BR>
<%=Server.HTMLEncode("you could use Debbie's " & _
"""" & "Special Touch" & """")%></P>
</BODY>
</HTML>

Listing 38.22 HTMLRESULTS.HTM--Results of HTML Encode

<HTML>
<HEAD>
<TITLE>John &amp; Debbie's Web Page</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H1 align="center">Welcome to John &amp; Debbie's Place</H1>
<H2 align="center">Where it's &lt;COOL&gt; to use tags!</H2>
<P>John specializes in creating Web pages.
 Using only the &lt;BODY&gt;<BR>
and &lt;/BODY&gt; tags he is able to generate 
a complete site in minutes.</P>
<HR>
<P>Debbie prefers to create graphics. 
Wherever you have an &lt;IMG&gt; tag,<BR>
you could use Debbie's &quot;Special Touch&quot;</P>
</BODY>
</HTML>

The HTML output, now properly encoded, is returned to the browser and produces the desired output, as you can see in Figure 38.8.

FIG. 38.8
Output from HTMLEncode.asp.

URLEncode Similar to the encoding just described for text inside an HTML page, text attached to an URL (as a parameter, for instance) also cannot use certain characters. In an URL, characters such as a space or a backslash take on other meanings. URLEncode takes any string and, using special escape characters, converts it into a string suitable for use in an URL. For example, see the following line of scripting code:

<A HREF="collections.asp?text="
<%=Server.URLEncode("Why do we need to encode things?")%>
">Test</A>

results in the following line of text in the resulting page:

<A HREF=
"collections.asp?text=Why+do+we+need+to+encode+things%3F"
>Test</A>

MapPath The paths used to request a page ("http://www.online-can.com/webtest.asp") are usually not the same as the physical path to that page on the Web server. The Server Variable (discussed early in this chapter) PATH_TRANSLATED provides the corresponding physical path for the current page. This Server method, MapPath, performs that translation on any virtual (such as a request) path, whether it is the current page or not. Many objects and IIS add-ons (such as Index Server) require physical paths to function correctly. This function enables you to provide those paths without having to hard code them into your page. If you look back at Listing 38.20, the example provided for Create Object, you will see this method in use to translate the current directory from a virtual path to a physical one.

Using External Objects in ASP

In the preceding section, "ASP Intrinsic Objects," you saw the Server.CreateObject command. This command, like the CreateObject command in Visual Basic, enables you to create instances of COM objects and assign them to variables in your programs (or pages). Any COM object that exposes a public interface can be used with ASP, but not all of these objects are suitable. Each of the five external components that are included with ASP will be briefly reviewed next. After those objects have been covered, you will learn about other COM objects, how to determine if an object is suitable for use with ASP, and some guidelines on creating your own component for that purpose.

Objects Included with ASP

Microsoft has included five useful components with the current release of Active Server Pages:

Each of these objects is installed automatically with ASP and, therefore, it is assumed for this discussion that they are present in your system. Three of these objects will be discussed in-depth, including a discussion of their use and a corresponding example. For the remaining two objects, the TextStream object and the ADO, only a brief description is presented because the Textstream object is not as commonly used as the others, and ADO is already covered in detail in its own chapter.

Browser Capabilities Object Chapter 37, "Creating Active Server Pages," discussed the idea of browser independence and how ASP is capable of being completely independent of the browser used because you can use server-side scripting to do all of the fancy work and output only standard HTML tags. Doing this would guarantee that your page could be viewed by any browser (that supported that version of HTML), but would limit you from using any of the advanced features of the new browsers. Another approach is to put a disclaimer on your first page that says your page will only work with one type of browser and then use any feature of that browser that you want. Neither of those methods are really great and both put limits, on you or on your audience. A better approach, and one that is more in line with the concept of a dynamic Web site, is to customize your output when it is requested. Doing this would enable you to base your content on the browser being used in each instance. The Server Variable HTTP_USERAGENT provides enough information about a browser for you to figure out what brand and version it is, based on which you can determine the features it supports. This involves parsing the User Agent string and maintaining a large case statement containing the features supported by each potential browser. This wouldn't be easy to create or to maintain. A better solution is to let someone else do the work and, in this case, someone already has. The Browser Capabilities component, when instantiated, reads in that same string and then, using an .ini file that Microsoft updates, determines the features of the current browser.

Your page can then query this component's properties (listed in Table 38.1) and customize the page accordingly. An example of this is shown in Listing 38.23.

Table 38.1 Properties of the Browser Capabilities Component

Property Meaning
Tables Whether the browser supports tables
Frames Whether the browser supports frames
VBScript Whether the browser supports client-side scripting using VBScript
JavaScript Whether the browser supports client-side scripting using JavaScript
Browser Returns the name of the browser; can be used for your own processing
Version Returns the browser's version numbers.
Backgound Whether the browser supports background sounds (specified in the
Sounds <BODY> tag)

Listing 38.23 BROWCAP.ASP--Example of Using the Browser Capabilities Component

<%Set BrowCap = CreateObject("MSWC.BrowserType")%>
<HTML>
<HEAD><TITLE>Example Page</TITLE></HEAD>
<BODY>
<H1>Results of the big game</H1>
<%If (BrowCap.Tables=TRUE) Then%>
<TABLE>
  <TR>
    <TD>
      <STRONG>The Dynamite Dynamics</STRONG>
    </TD>
    <TD>
      187
    </TD>
  </TR>
  <TR>
    <TD>
      <STRONG>The Sluggish Statics</STRONG>
    </TD>
    <TD>
      12
    </TD>
  </TR>
</TABLE>
<% Else %>
<STRONG>The Dynamite Dynamics</STRONG>&nbsp 187<BR>
<STRONG>The Sluggish Statics</STRONG>&nbsp 12
<% End If %>
</BODY>
</HTML>

Content Linking Object Many Web sites have a series of pages that users move through in sequential order, such as pages in an online article, sections of help information, or other similar groups of pages. To handle navigation through these pages, Web site designers usually present a table of contents page (or frame) or a series of forward-and-back links on each page. Both of these methods work well but are difficult to maintain. If pages are being added, removed, or moved around, then the table of contents quickly becomes out-of-date and a large number of the forward/backward links will need to be changed. This component, the Content Linking object, solves all of these problems in one shot. To use this component, you must first create a text file that contains all of the URLs and descriptions of the pages you want to link together (see Listing 38.24). Then, create an instance of this object in your page by using Server.CreateObject("MSWC.Nextlink"). Now you can use its methods to access each URL or description in sequence, or directly by index. Each method takes the relative path to the text file you created as one of its parameters.

Listing 38.24 URL_LIST.TXT--File of Relative URLs for Use by the Content Linking Object

welcome.asp Introduction to our wonderful cyber-magazine
article.asp?id=43 1001 uses for red sweaters
article.asp?id=21 Knitting a red sweater from scratch
article.asp?id=75 The benefits of red wool over other colors
article.asp?id=32 Scientists succeed in cloning red sheep

This object has several methods, but they are all similar, so using them is very straightforward. To move through the pages in order, there are four functions (GetNextURL, GetPreviousURL, GetNextDescription, and GetPreviousDescription), each taking only one parameter (the relative URL of the list text file). It is also possible to go directly to any portion of the list, using GetNthDescription and GetNthURL, two methods that both take two parameters; the relative URL of the text file, as was mentioned previously, and the index for which you want to retrieve information. The remaining method, GetListCount, takes the text file's URL as a parameter and returns a count of the number of items in that list.

On your Web site, there are two main ways to use this component to automate the creation of forward-and-back links on your pages (see Listing 38.25 for an example of code that you would include on each page) and to create a table of contents (see Listing 38.26).

Listing 38.25 BACK_FWD.ASP--Links to Move Between Pages, Using the Content Linking Object

<%Set Content = CreateObject("MSWC.NextLink")%>
<a href="<%=Content.GetPreviousURL("URL_List.txt")%>">Back</a><BR>
<a href="<%=Content.GetNextURL("URL_List.txt")%>">Next</a>

Listing 38.26 TOC_EXAMPLE.ASP--Creating a Table of Contents, Using the Content Linking Object

<HTML>
<HEAD><TITLE>Table of Contents</TITLE></HEAD>
<BODY>
<% Set Content=Server.CreateObject("MSWC.NextLink") %>
<TABLE>
<% For j = 1 to Content.GetListCount("URL_List.txt") %>
  <TR>
    <TD>
     <STRONG><%=Content.GetNthDescription("URL_List.txt",j)%></STRONG>
    </TD>
    <TD>
     <a href="<%=Content.GetNthURL("URL_List.txt",j)%>">
        <%=Content.GetNthURL("URL_List.txt",j)%>
     </a>
    </TD>
  </TR>
<% Next %>
</TABLE>
</BODY>
</HTML>


You Know You're Lazy When...
Okay, so the Content Linking object automates a lot of the nasty, time-consuming details of navigating through a group of Web pages, but it isn't enough. You have avoided having to update links when adding, deleting, or moving a page, but still have to update that text file every single time! This is certainly a reduction in work. But if you have more than one Web site; many groups of linked files; or pages being added, deleted, or moved on a regular basis; this little bit of remaining work can grow into quite a chore. There is a solution to this problem, however; in fact, there is more than one.

Your first option is to create an ASP Component (using VB 5 or VC++, for instance) that generates the list of files. The list can be created by looking at the contents of a certain directory, the path to which could be set at run time. Replace the text file with an Active Server Page and output the results of your component in a format suitable to be read in by the Content Linking object. (An example of using an external object to perform a similar task is shown in Listing 38.20.) Your table of contents and page links would remain exactly the same.

Another option is to duplicate the functionality described in the first option, but to do so without the intermediate step of generating the content list. An ASP component can be created that performs all of the functions of the Content Linking object, but that obtains its list of pages without using the text file. The list would still be generated based on a directory listing, as in the previous example, but this would occur inside our component.


Ad Rotator Object This object provides for the automatic selection of advertisements from a text file for insertion into a Web page. The ads are chosen from the file in a semi-random fashion. For each ad, a weight can be specified that determines how often (in relation to the other ads) it is shown. In the text file, known as the Rotator Schedule File, each ad has the following information specified:

The schedule file can also contain settings for the properties of the object. In the first few lines of the file, values can be specified for the file used to process redirects (REDIRECT <URL>), the default width of the ads (WIDTH <value>), the default height (HEIGHT <value>), and the width of border to place around the ads (BORDER <value>). Between these lines and the actual ads, there should be an asterisk (*) on a line by itself.


NOTE: When a user clicks an ad that has an URL specified, whatever URL is specified to process redirects is called with the destination URL of the ad specified as a parameter. This processing script just has to do a Response.Redirect to the URL specified in the parameter.

The example text file shown in Listing 38.27 contains three ads.

Listing 38.27 SCHEDULE.TXT--Rotator Scheduler File

REDIRECT redirection.asp 
WIDTH 270
HEIGHT 30 
BORDER 0
*
http://www.kazoo.com/ads/image1.gif
http:// www.kazoo.com /
We have the best Kazoo's in the world.
10
http://www.burgerqueen.com/ad1.gif
http://www.burgerqueen.com
Boy our burgers are good.
40 
images/ads/wood1.gif
-
Buy our wood, it burns well
50

In this example file, the three ads had weights of 10, 40, and 50. This means the Web server will attempt to display the first ad 10 percent of the time, the second ad 40 percent of the time, and the remaining ad 50 percent of the total time available. To use an ad from this file, you simply place the following lines from Listing 38.28 on your page.

Listing 38.28 AD_SAMP.ASP--Demonstration of the Ad Rotator Object

<%
Set objAdRotator = Server.CreateObject("MSWC.AdRotator")
Response.Write objAdRotator.GetAd("schedule.txt")
%>

Like the Content Linking object, this component could be improved. The method it uses would work well for a small number of ads, but probably not for a commercial Web site that deals with hundreds of advertisers. There are two suggested options to make this a better solution. The first option is to have an .asp file replace the Rotator Scheduler File, pull ads from another source, such as a database, and then calculate the weight values at run time. The other option is just to pull the ads directly from a database, either in script or by using a custom component of your own creation. If you use the second option, all of the frequency tracking and calculations can be performed internally.

The TextStream Object and the Database Access Component The TextStream object is designed to give your ASP scripts access to the file system on the Web server. By using its methods and properties, you can open text files and then read data from the file or write data to it. The ActiveX Data Objects component is used to gain access to databases from ASP. This object actually consists of several related components (connections, record sets, and commands) that allow access to ODBC-compliant data sources. Chapter 34, "Database Access with ActiveX Data Objects (ADO)", is devoted entirely to ADOs, so they will not be covered at this point. In the next chapter, "Using the Web, Databases, and Visual Basic," there are many examples of the objects being used in Active Server Pages, which will provide you with all of the information you need to start using them yourself.

Using Other COM Objects in ASP

You can use any object in ASP that you can create with the CreateObject command in Visual Basic, which means basically any COM object except ActiveX controls, which require a visual interface and are not available from ASP. Some of these objects may have been created specifically for use in ASP (like the Content Linking object, previously discussed), but they also could have been intended for use in Visual Basic, Visual C++, Access, or even Excel. Just because you can create an object, however, does not mean that it will perform properly or provide any useful function inside your page. It is possible to find, or create, objects that follow the COM standards but do not work well in a server-side scripting environment.

Determining Whether an Object Is Suitable for Use in ASP Existing COM objects often are designed for use in "regular" applications, programs that execute on the client machine and that have a visual interface. Existing components might not be suitable for ASP for several reasons:

Objects that are well-suited for use in ASP share several common characteristics--they have no visual interface, they report errors by raising them to the calling program, and they function by simply returning values.

A Brief Overview of Creating Your Own ASP Components The same points discussed in the preceding section apply to creating your own components for use in ASP. At all times during the design, coding, and testing of your object, you must remember where and when your object will be running. If you keep these facts in mind, then creating this type of object is no different than creating any other objects. Of the various types of components you can create with VB 5, you will want to use the ActiveX DLL because it is the type that will function best with ASP. If the object you are creating is destined for use only with ASP, then there are additional features that you should take advantage of. It is possible to gain access to all of the intrinsic ASP objects (Request, Response, Server, Application, Session, and so forth) from within your component. Having access to those objects enables you to see all of the information, such as the page's query string, that is available to the page itself. In Visual Basic you can gain access to those objects by adding a reference to the Microsoft Active Server Pages Object Library (asp.dll), as shown in Figure 38.9. Once you have added the reference, the object browser in VB will show you all of the objects, properties, and methods you have available from this library (see Figure 38.10). These objects are also available when creating ASP Components using Visual C++.

FIG. 38.9
Adding a reference to ASP.DLL in Visual Basic 5.0.

FIG. 38.10
The Active Server Pages Object Library.

From Here...

Using objects in Active Server Pages is the key to creating true dynamic content. ASP provides access to both intrinsic and external objects, giving your applications almost limitless potential. Many such objects are available from Microsoft and from third-party vendors that provide functionality in a variety of areas. The ability to create your own components by using Visual Basic, versions 4 or 5, completes the picture: It is now relatively easy to build anything you can't buy. ASP without objects is interesting; with objects, it is a powerful tool for building complete Web-based applications.

Now that you have seen a sample of ASP's capabilities, it is time to apply them.


Previous chapterNext chapterContents


Macmillan Computer Publishing USA

© Copyright, Macmillan Computer Publishing. All rights reserved.