Make your own free website on Tripod.com

Active Server Pages (ASP) – Overview

Overview

An active server page is a standard HTML file that has been extended with additional features. Like a standard HTML file an ASP can contain HTML tags that will be interpreted and displayed by a Web Browser. However an ASP has four important features that make it unique:

  • An Active Server Page can contain server side scripts. To take an extremely simple example, you could create a Web page that displays different messages at different times of the day.
  • An ASP provides a number of built in objects. By using the built in objects accessible in ASPs, you can make your scripts much more powerful.
  • An Active Server Page can be extended with additional components. Active Server Pages comes bundled with a number of standard server-side ActiveX components. These components allow you to do such things as determine the capabilities of different browsers or include page counters on a web page.
  • An ASP can interact with a database using a special collection of objects called ActiveX Data Objects (ADOs).

What is possible with ASPs?

There is no limit as to what you can do with ASPs. Just a few and important of what ASPs can enable you to do are:

  • Include rotating banner advertisements on pages of you web site.
  • Retrieve information entered in your HTML form and store that information in a Database.
  • Create personalized web pages that display different content to different users.
  • Add hit counters to one or more pages of your Web site.
  • Display different Web Pages depending on the capabilities of the user's Web Browser.
  • Link together multiple web pages in such a way that they can be navigated easily.
  • Track information about users activity at your web site and save that information in custom log file.

Working of Active Server Pages

  1. A user enters the Internet address of an ASP file into the address bar of the Web Browser.
  2. The browser sends a request for ASP to IIS.
  3. The Web Server receives the request and recognizes that the request for an ASP files because the requested file has an .asp extension.
  4. The web server retrieves the proper ASP file from the disk or memory.
  5. The Web Server sends the file to special program called ASP.dll.
  6. The ASP file is processed top to bottom and any encountered commands are executed. The result of this process is a standard HTML file.
  7. The users Web Browser interpret the HTML file and the results are displayed in the browser window.

Active Server Page - Objects and Components

ASPs include a number of built-in objects and installable ActiveX components. These objects and components can be used to extend the power of your Active Server Page scripts.

Object: An object is a basic unit of programming in Object Oriented Programming terminology. It represents a basic software entity with several methods, properties and collections. An Objects method is used to derive the desired utility out of the objects for which they are intended. Object properties can be read or set to specify the Objects state. An objects collection constitute different sets of key value pairs related to the object.

ActiveX Component: An ActiveX component is very similar to an ASP built in Object. However, when using ASPs, there are two important different between a component and an object. First, a component may contain more than one object. Second, an instance of a component must be explicitly created before it can be used.

ASP Objects

The list of built in objects which can be extended in to scripts are as follows:

  1. The Application object: The Application object is used to store and retrieve information that can be shared among users of an application. For examples the Application object can pass information between users of your Web Site.
  2. The Request object: The Request object can be used to access all information sent in the request header from the browser to your server. You can use the Request object to retrieve the information that the user has entered into HTML forms.
  3. The Response object: The Response object is used to send information back to a browser. You can use the Response object to send the output of your script to the user.
  4. The Server object: The Server object allows you to use various utility functions on the server. For example you can use the Server object to control the length of time your scripts run on the server machine.
  5. The Session object: The Session object can be used to store and retrieve information about a particular users session. You can use the Session object to track the movement of your visitor in you Web Site over a period of time.

ASP Components

A brief description of the various ASP ActiveX components is as follows:

  1. The Ad Rotator component: The Ad Rotator component is used to display banners advertisements on the web pages of your Web Site.
  2. The Browser Capabilities component: The Browser Capabilities component can be used to display different HTML content, according to the capabilities of different browsers.
  3. The Content Linking component: Using the Content Linking component you can link together a number of HTML pages so that they can be navigated easily.
  4. The Counters component: The Counters component can be used to count the number of visitors to your Web Site.
  5. The Content Rotator component: The Content Rotator component can be used to rotate through HTML content on a page.
  6. The Page Counter component: The Page Counter component is used in your web pages to count the number of visitors to the web page.
  7. The Permission Checker component: The Permission Checker component can be used to display links to web pages only if a user has permission to see them.
  8. The ActiveX Data Objects (ADO) component: The ADO component enables you to retrieve and store data in a database such as Microsoft SQL server.

 

 

 

 

 

 

 

What are Active Server Pages?

Microsoft Active Server Pages (ASP) is a server-side scripting environment that you can use to create and run dynamic, interactive, high-performance Web server applications. When your scripts run on the server rather than on the client, your Web server does all the work involved in generating the Hypertext Markup Language (HTML) pages that you send to browsers. You need not worry whether a browser can process your pages: your Web server does all the processing for it.

You need only a working knowledge of HTML to begin using ASP.

Active Server Pages is a feature of and can be used with the following Web servers:

  • Microsoft Internet Information Server version 3.0 on Windows NT Server
  • Microsoft Peer Web Services Version 3.0 on Windows NT Workstation
  • Microsoft Personal Web Server on Windows 95

The Active Server Pages Model

An ASP script begins to run when a browser requests an .asp file from your Web server. Your Web server then calls ASP, which reads through the requested file from top to bottom, executes any commands, and sends an HTML page to the browser.

 

Writing ASP Scripts

This section introduces the basic elements of Active Server Pages (ASP) scripts.

What is an .asp File?

Active Server Pages (ASP) is built around files with the file name extension .asp. An .asp file is a text file and can contain any combination of the following:

  • Text
  • HTML tags
  • Script commands. A script command instructs your computer to do something, such as assign a value to a variable.

It’s easy to create an .asp file: Just rename any HTML file, replacing the existing .htm or .html file name extension with .asp. To make the .asp script file available to Web users, save the new file in a Web publishing directory (be sure that the associated virtual directory has Execute permissions enabled). When you view the file with your browser, you see that ASP processes and returns HTML, just as before. For more information about Web publishing, virtual directories, and setting permissions, refer to your Microsoft Web server’s online documentation.

ASP really begins to work for you, however, when you add scripts to your HTML.

What is a Script?

A script is a series of script commands. A script can, for example:

  • Assign a value to a variable. A variable is a named storage location that can contain data, such as a value.
  • Instruct the Web server to send something, such as the value of a variable, to a browser. An instruction that sends a value to a browser is an output expression.
  • Combine commands into procedures. A procedure is a named sequence of commands and statements that acts as a unit.

Executing a script sends the series of commands to a scripting engine, which interprets and relays them to your computer. Scripts are written in languages that have specific rules; thus, if you want to use a given scripting language, your server must run the scripting engine that understands the language. ASP provides scripting engines for the VBScript and JScript scripting languages. Your primary scripting language—that is, the language that ASP assumes you are using if you don't specify a language—is VBScript by default.

ASP Syntax

ASP is not a scripting language; rather, ASP provides an environment that processes scripts that you incorporate into your HTML pages. To use ASP successfully, you need to learn the syntax, or rules, by which it operates.

Delimiters

HTML tags are differentiated from text by delimiters. A delimiter is a character or sequence of characters that marks the beginning or end of a unit. In the case of HTML, these delimiters are the less than (<) and greater than (>) symbols.

Similarly, ASP script commands and output expressions are differentiated from both text and HTML tags by delimiters. ASP uses the delimiters <% and %> to enclose script commands. For example, the command <% sport = "climbing" %> assigns the value climbing to the variable sport.

ASP uses the delimiters <%= and %> to enclose output expressions. For example, the output expression <%= sport %> sends the value climbing (the current value of the variable) to the browser.

 

Single Expressions

You can include within ASP delimiters any expression valid for your primary scripting language. For example, the following line produces text ending with the current server time:

This page was last refreshed at <%= Now %>.

In this case, the Web server returns the value of the VBScript function Now to the browser along with the text.

 

Statements

A statement, in VBScript and other scripting languages, is a syntactically complete unit that expresses one kind of action, declaration, or definition. The conditional If...Then...Else statement that appears below is a common VBScript statement.

<% 
If Time >=#12:00:00 AM# And Time < #12:00:00 PM#  Then greeting = "Good Morning!" 
Else greeting = "Hello!" 
End If
%> 

This statement stores either the value "Good Morning!" or the value "Hello!" in the variable greeting. It does not send any values to the client browser. The following lines send the value, in green, to the client browser:

<FONT COLOR="GREEN"> 
<%= greeting %> 
</FONT>

Thus, a user viewing this script before 12:00 noon (in the Web server’s time zone) would see

Good Morning!

A user viewing the script at or after 12:00 noon would see

Hello!

 

Including HTML in a Statement

You can include HTML text between the sections of a statement. For example, the following script, which mixes HTML within an If...Then...Else statement, produces the same result as the script in the previous section: 
<FONT COLOR="GREEN">
<% If Time  > = #12:00:00 AM# And Time < #12:00:00 PM#  Then %> 
Good Morning!
<% Else %>
Hello!
<% End If %> 
</FONT>

If the condition is true—that is, if the time is midnight or after, and before noon—then the Web Server sends the HTML that follows the condition ("Good Morning") to the browser; otherwise, it sends the HTML that follows Else ("Hello") to the browser.

 

Script Tags

The statements, expressions, commands, and procedures that you use within script delimiters must be valid for your default primary scripting language. ASP is shipped with the default primary scripting language set to VBScript. However, with ASP you can use other scripting languages; just use the HTML script tags <SCRIPT> and </SCRIPT>, together with the LANGUAGE and RUNAT attributes, to enclose complete procedures written in any language for which you have the scripting engine.

For example, the following .asp file processes the JScript procedure MyFunction.

<HTML>
<BODY>
<% Call MyFunction %>
</BODY>
</HTML>

<SCRIPT RUNAT=SERVER LANGUAGE=JSCRIPT>
  function  MyFunction ()
  {
      Response.Write("MyFunction Called")
  }  
</SCRIPT>

Including Other Files

Server-side includes is a mechanism you can use to insert information into a file prior to processing. ASP implements only the #INCLUDE pre-processing directive of this mechanism. You can use this directive to insert the content of another file into an .asp file before ASP processes the .asp file. Use the following syntax:

<!--#INCLUDE VIRTUAL|FILE="filename"--> 

Where you must type either VIRTUAL or FILE, which are keywords that indicate the type of path you are using to include the file, and filename is the path and file name of the file you want to include.

Included files do not require a special file-name extension; however, Microsoft recommends giving included files an .inc file-name extension to distinguish them from other types of files.

 

Using the Virtual Keyword

Use the Virtual keyword to indicate a path beginning with a virtual directory. (For information about using virtual directories, refer to your Microsoft Web server’s online documentation.) For example, if a file named Footer.inc resides in a virtual directory named /Myapp, the following line would insert the contents of Footer.inc into the file containing the line:

<!--#INCLUDE VIRTUAL="/myapp/footer.inc"--> 

Using the File Keyword

Use the File keyword to indicate a relative path. A relative path begins with the directory that contains the including file. For example, if you have a file in the directory Myapp, and the file Header1.inc is in Myapp\Headers, the following line would insert Header1.inc in your file:

<!--#INCLUDE FILE="headers/header1.inc"-->

Note that the path to the included file, Headers/header1.inc, is relative to the including file; if the script containing this Include statement is not in the directory /Myapp, the statement would not work.

You can also use the FILE parameter with ../ syntax to include a file from a parent, or higher-level, directory if the EnableParentPaths registry setting is 1.

 

Including Files: Tips and Cautions

An included file can, in turn, include other files. An .asp file can also include the same file more than once, provided that the <INCLUDE> statements do not cause a loop. For example, if the file First.asp includes the file Second.inc, Second.inc must not in turn include First.asp. Nor can a file include itself. ASP detects such loop or nesting errors, generates an error message, and stops processing the requested .asp file.

ASP includes files before executing script commands. Therefore, you cannot use a script command to build the name of an included file. For example, the following script would not open the file Header1.inc because ASP attempts to execute the #Include directive before it assigns a file name to the variable name.

<!-- This script will fail -->
<% name=(header1 & ".inc") %> 
<!--#include file="<%= name %>"-->

Scripts commands and procedures must be entirely contained within the script delimiters <% and %>, the HTML tags <SCRIPT> and </SCRIPT>, or the HTML tags <OBJECT> and </OBJECT>. That is, you cannot open a script delimiter in an including .asp file, then close the delimiter in an included file; the script or script command must be a complete unit. For example, the following script would not work:

<!-- This script will fail -->
<%
For i = 1 To n
  statements in main file
  <!--#include file="header1.inc" -->
Next
%> 
The following script would work: 
<% 
For i = 1 to n
  statements in main file
%> 
<!--#include file="header1.inc" -->
<% Next %>
 

Using a Server Script to Modify a Client Script

Although ASP is used primarily to process server-side scripting, you can extend its reach by using it to generate client-side scripts that are then processed by the client browser. ASP does this by combining client-side scripts that are enclosed by HTML comments with server-side scripts that are enclosed by delimiters:

<SCRIPT LANGUAGE="VBScript">	
<!--
client script
<% server script  %> 
client script
<% server script  %>
client script
...
-->
</SCRIPT>

With this functionality in your scripts, you can create exciting applications. For example, the following script uses a database to provide a particular client script as a result of the user’s actions.

In the following script, ASP retrieves data from the database (in this case, data pertaining to musical artists and albums) and generates a subroutine for each line of data. These subroutines then control what happens when a user clicks links in the page displayed in the client browser.

Note This script will not function by itself. It is shown here only to illustrate the functionality of ASP if used in conjunction with a database, server-side scripting, and client-side scripting.

<!-- This script is incomplete -->
<%
Set rsAlbums = Server.CreateObject("ADODB.Recordset")
rsAlbums.Open "SELECT Artists.*, Albums.* FROM Albums INNER JOIN Artists ON
Albums.ArtistID = Artists.ArtistID", Session("Conn"), 1, 2

Do While rsAlbums.EOF = False
%>
  <SCRIPT LANGUAGE="VBScript">
  <!--Sub Enhanced_OnLoad()
	Enhanced.DrawBuffer = 500000
  End Sub
  Sub AlbumHotSpot<%=rsAlbums("AlbumID")%>_MouseEnter()
	AlbumName.Caption = "<%= rsAlbums("AlbumName")%>"
	ArtistName.Caption = "<%= rsAlbums("ArtistName")%>"
	Divider.Visible = true
  End Sub
  Sub AlbumHotSpot<%= rsAlbums("AlbumID")%>_Click()
	Window.Location.HRef = "details.asp?Albumid=<%= rsAlbums("AlbumID")%>"
  End Sub-->
  </SCRIPT>
<%	
rsAlbums.MoveNext
Loop
%>

Scripts of this kind can be expanded to create controls that are associated with the user events. The end result is a robustly generated set of controls with dynamically generated event handlers. By writing scripts such as this, the Web developer can create functions and subroutines that manipulate database information, saving time that would otherwise be used writing detailed script procedures.

 

Using Scripting Languages

Scripting languages are an intermediate stage between HTML and programming languages such as Java, C++, and Visual Basic. HTML is generally used for formatting and linking text. Programming languages are generally used for giving a series of complex instructions to computers. Scripting languages fall somewhere in between, although scripting languages function more like programming languages than simple HTML docs. The primary difference between scripting languages and programming languages is that the syntax and rules of scripting languages are less rigid and intricate than those of programming languages.

Scripting engines are the COM (Component Object Model) objects that process scripts. Active Server Pages provides a host environment for scripting engines and distributes scripts within .asp files to these engines for processing. For each scripting language that is used in coordination with ASP scripting, the related scripting engine must be installed on the Web server. For example, VBScript is the default language of Active Server Pages, so the VBScript engine resides as an COM object accessible by Active Server Pages so that it can process VBScript scripts. Likewise, Active Server Pages can provide a scripting environment for a number of other scripting languages, including JScript, REXX, and Perl, and others.

Active Server Pages makes it possible for the Web developer to write complete procedures by using a variety of scripting languages without having to worry about whether a browser supports them all. In fact, several scripting languages can be used within a single .asp file. This can be done by identifying the script language in an HTML tag at the beginning of the script procedure.

In addition, because scripts are read and processed on the server side, the client browser that requests the .asp file does not need to support scripting.

 

Setting the Primary Scripting Language

VBScript is the default scripting language that is used for primary scripting. If you use primary scripting, which uses the <% and %> delimiters, you can place any valid VBScript command inside the scripting delimiters and Active Server Pages will process the commands inside of the delimiters as VBScript. Active Server Pages makes it possible to set any scripting language as the primary scripting language. You can set the primary scripting language on a page-by-page basis, or for all pages on your Web server.

To change the primary scripting language for all pages in all applications, you must change the value of the DefaultScriptLanguage entry in the registry to that language.

The procedure for setting the primary scripting language depends on whether the chosen language supports Object.Method syntax. The procedures are detailed below.

 

Languages That Support Object.Method Syntax

For languages that support Object.Method syntax and use parentheses to enclose parameters, such as VBScript and JScript, you can change the primary scripting language for a single page by adding a command line to the beginning of your .asp file. The syntax for this command is:

<%@ LANGUAGE = ScriptingLanguage %>

where ScriptingLanguage is the primary scripting language that you want to set for that particular page.

Follow these guidelines when setting the primary scripting language for a page:

If you do not follow these guidelines for setting the primary scripting language for a page, an error will be generated.

 

Languages That Do Not Support Object.Method Syntax

In order to use a language that does not support the Object.Method syntax as the primary scripting language, you must first create the LanguageEngines registry key with the corresponding language name subkey and values:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
 \W3SVC
  \ASP
   \LanguageEngines
    \LanguageName
       Value: Write REG_SZ: Response.WriteEquiv |
       Value: WriteBlock REG_SZ: Response.WriteBlockEquiv | 

where LanguageName is the name of the chosen language, Response.WriteEquiv is the language’s equivalent of Response.Write, and Response.WriteBlockEquiv is the language’s equivalent of Response.WriteBlock. The pipe symbol (|) is an insertion used by Active Server Pages to send expressions and HTML blocks that are normally processed with Response.Write and Response.WriteBlock methods. This may be done automatically when installing additional scripting languages.

Note Some scripting languages are sensitive to white space or newline characters; it may not be possible to use such languages as the primary scripting language by changing the registry entries as described above. An alternative to using these as primary scripting languages is to manually write HTML blocks to the browser rather than using Active Server Pages to automatically handle interleaved <% ... %> script directives and HTML. Another option is to write that language’s functions within tagged script blocks (<SCRIPT> ... </SCRIPT> ) and call them from any other language.

 

Writing Procedures with Multiple Languages

An attractive feature of Active Server Pages is the capability to incorporate several scripting language procedures within a single .asp file. With this functionality, you can use scripting languages that have particular strengths to help you get a specific job done.

 

Creating Procedures

A procedure is a group of script commands that performs a specific task. You can define your own procedures and call them repeatedly in your scripts. Procedure definitions can appear within <SCRIPT> and </SCRIPT> tags and must follow the rules for the declared scripting language. You can also define a procedure within scripting delimiters (<% and %>) as long as it is in the same scripting language as the primary script.

You can place procedure definitions in the same .asp file that calls the procedures, or you can put commonly used procedures in a shared .asp file and use a server-side include statement (that is, <!--#INCLUDE FILE= ...) to include it in other .asp files that call the procedures. Alternatively, you could package the functionality in an ActiveX server component.

 

Calling Procedures

To call procedures, include the name of the procedure in a command.

For VBScript, you can also use the Call keyword when calling a procedure. However, if the procedure that you are calling requires arguments, the argument list must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around the argument list. If you use Call syntax to call any built-in or user-defined function, the function’s return value is discarded. If you are calling JScript procedures from VBScript, you must use parentheses after the procedure name; if the procedure has no arguments, use empty parentheses.

The following example illustrates creating and calling procedures by using two different scripting languages (VBScript and JScript).

<HTML> 
<BODY>
<TABLE> 
<% Call Echo %> 
</TABLE> 
<% Call PrintDate %>
</BODY>
</HTML>

<SCRIPT LANGUAGE=VBScript RUNAT=Server> 
Sub Echo 
  Response.Write _ 
  "<TR><TD>Name</TD><TD>Value</TD></TR>" 
  Set Params = Request.QueryString 
  For Each p in Params 
  Response.Write "<TR><TD>" & p & "</TD><TD>" & _ 
  Params(p) & "</TD></TR>" 
  Next 
End Sub 
</SCRIPT> 

<SCRIPT LANGUAGE=JScript RUNAT=Server> 
function PrintDate() 
{ 
  var x
  x = new Date() 
  Response.Write(x.toString()) 
} 
</SCRIPT>

Note To pass an entire array to a procedure in VBScript, use the array name followed by empty parentheses; in JScript, use empty square brackets.

 

Using VBScript and JScript

When using VBScript on the server with ASP, two VBScript features are disabled. Because Active Server Pages scripts are executed on the server, the VBScript statements that present user-interface elements, InputBox and MsgBox, are not supported. The VBScript functions CreateObject and GetObject are also not supported. Use of these statements will cause an error.

 

Working with Built-In Objects

Scriptwriters often find that they need to accomplish certain tasks in their scripts on a regular basis. For example, you might have a number of scripts, all of which ultimately perform different tasks, but all of which need to get information from a user. Objects save you the labor of "reinventing the wheel" every time you need to perform such a common task. An object is a combination of programming and data that can be treated as a unit.

To use most objects, you must first create an instance of that object. However, Active Server Pages (ASP) includes five objects that do not require instantiation. The following table summarizes these built-in objects, the tasks they are used for, and where to look for examples.

Object

Task

Examples

Request object

Get information from a user.

Getting Information from a User

Response object

Send information to a user.

Sending Information to a User

Server object

Control the ASP execution environment.

Working with ActiveX Server Components

Session object

Store information about a user’s session.

Developing ASP-Based Applications

Application object

Share information among users of an application.

Developing ASP-Based Applications

Object Syntax

The syntax by which you gain access to an object depends on the scripting language you are using. Because the default primary scripting language of ASP is VBScript, the examples that appear in this guide use VBScript syntax, except where noted otherwise.

The Request and Response objects contain collections. A collection is a set of related pieces of information that are accessed the same way. You can also gain access to information in a collection by using the For...Each statement. This statement is useful in debugging scripts.

You gain access to objects from a script by using methods and properties.

 

Using Methods

A method is a procedure that acts on an object. The general syntax is

Object.Method parameters

Where parameters may be a variant, data, a string, or a URL, depending on the method.

 

Using Properties

A property is a named attribute of an object. Properties define object characteristics, such as size, color, and screen location; or the state of an object, such as enabled or disabled. The general syntax is

Object.Property parameters

Where parameters may be a value, string, or flag, depending on the property.

 

The Request Object

Often you want to get information about a user, for example, the type of browser the user is running. You might also want to get information from a user, for example, when the user submits information in forms. The ASP Request built-in object makes getting this information easy.

The Request object gives you access to any information that is passed with an HTTP request. This includes:

The Request object has five associated collections:

  • QueryString
  • Form
  • Cookies
  • ServerVariables
  • ClientCertificate

You can use the following general syntax to access the information in the Request object:

Request.CollectionName(variable)

Where CollectionName can be QueryString, Form, Cookies, ServerVariables, or ClientCertificate, and variable is the name of the variable in the collection that you want to access.

You can use the following general syntax to access variables in the Request object without including the collection name:

Request(variablename)

The collections are searched in this order: QueryString, Form, Cookies, ServerVariables, ClientCertificate. The first variable that matches variablename is returned.

Note If an HTML page might have more than one variable with the same name, make sure you include the collection name between Request and the variable name.

 

Getting Information from HTML Forms

An HTML form is the most frequently used medium for getting information from a Web user. A form’s text boxes, option buttons, and check boxes, displayed on an HTML page in a browser, provide the user an easy way of submitting information. When the user clicks the Submit button, the browser sends the collected information to the Web server.

You can use .asp files to collect or process HTML form values in three ways:

  • A static .htm file can contain a form that posts its values to an .asp file.
  • An .asp file can create a form that posts information to another .asp file.
  • An .asp file can create a form that posts information to itself, that is, to the .asp file that contains the form.

The first two methods operate in the same way as forms that interact with other gateway programs, except that, with ASP, you can include commands that read and respond to user choices.

Creating an .asp file that contains a form definition that posts information to itself is a slightly more complicated but very powerful means of working with forms.

 

Using the QueryString Collection

Although you could use the QUERY_STRING server variable to process QUERY_STRING information from a user request, ASP provides the QueryString collection to make this information readily accessible. If the form method is POST, the QueryString collection contains all the information passed as a parameter after the question mark in the URL. If the form method is GET, the QueryString collection contains all the information passed in the form.

For example, when a user sends the following URL request, the Request.QueryString collection would contain two values: name and age.

<A HREF="myasp.asp?name=Satish+Sharma&age=30"> 

The following script uses the Request object to access these values.

Welcome, <%= Request.QueryString("name") %>. 
Your age is <%= Request.QueryString("age") %>. 

In this case, the following text would be sent back to the user:

Welcome, Satish Sharma. Your age is 30. 

The QueryString collection also automatically handles the case of multiple variables with the same name. When parsing a query string such as name=Gaurav&name=Anand&name=Ajay, for example, ASP creates a new collection called name that in turn contains three values: Andrew, Aaron, and Eric. Each of these values is indexed by an integer, with the following results:

Reference

Value

Request.QueryString("name")(1)

Gaurav

Request.QueryString("name")(2)

Anand

Request.QueryString("name")(3)

Ajay

A collection created in this manner supports the Count property. The Count property describes how many items a collection contains. In this example, the value of Request.QueryString("name") is 3 , because there are three separate values stored in the name collection.

If you were to use the Response.QueryString method to gain access to the variable name, the output would become a comma-delimited string. In the above example, the value of Request.QueryString("name") would be "Andrew, Aaron, Eric".

 

Using the Form Collection

The Form collection contains all the values that a user entered in a form submitted with the POST method. For example, when the user fills in and submits the following form:

<form action="/scripts/submit.asp" method="post">
<p>Your first name: <input name="firstname" size=48>
<p>What is your favorite ice cream flavor: <select name="flavor">
<option>Vanilla <option>Strawberry <option>Chocolate <option>Rocky Road 
</select>
<p><input type=submit>
</form>

The following request is sent:

firstname=Sandeep+Agarwal&flavor=Strawbery

and the following script is returned by a results page (such as submit.asp):

Welcome, <%= Request.Form("firstname") %>.
Your favorite flavor is <%= Request.Form("flavor") %>. 

The Form collection treats multiple parameters with the same name in the same way that the QueryString collection does.

 

Using the ServerVariables Collection

The ServerVariables collection provides information from the HTTP headers that are passed along with a user’s request as well as certain Web server environment variables. You can use this information to provide customized responses to users. This script accesses the SERVER_PORT server variable defined by the Common Gateway Interface (CGI) standard:

This HTTP request was received on 
  TCP/IP port <%=  Request("SERVER_PORT") %>. 

The following script, which provides content based on the user’s language, accesses the HTTP_ ACCEPT_LANGUAGE HTTP header variable:

<% language = Request.ServerVariables("HTTP_ACCEPT_LANGUAGE") 
If language = "en" Then %> 
  <!--#INCLUDE FILE="myapp/Englishpage.asp"--> 
<% Else %> 
  <!--#INCLUDE FILE="myapp/Otherlang.asp"--> 
<% End If %> 

Posting Information to the Originating .Asp File

With ASP, you have the flexibility to define a form in an .asp file that posts its input values back to itself; that is, a form that posts values back to the .asp file that contains the form. When a user fills in and submits form values, you can use the Request object to read these values. If you receive an invalid value, you can send a message back to the user, pointing out the problem and asking for a different value.

If the page that you send to the user contains only a message, the user must return to the page that contains the form. You can save the user this step by sending your message and defining the form asgain.

If you post form input messages to the same file that originally defined the form, however, you can send informational messages along with the content of the form; thus, you need only define the form once.

For example, suppose you define a form that allows a user to submit an email address, and you want to verify that the information a user submits is valid according to your criteria. If the value does not contain @, it is probably incomplete. The following script in GetEmail.asp checks for this. This script is the source of the form, and it includes an error message if appropriate.

<HTML> 
<BODY> 

<!-- This is GetEmail.asp --> 

<% 
If IsEmpty(Request("Email")) Then 
  Msg = "Please enter your email address." 
ElseIf InStr(Request("Email"), "@") = 0 Then 
  Msg = "Please enter an email address" & _
  " in the form username@location."
Else
  Msg = "This script could process the " & _
  "valid Email address now."
End If
%>

<FORM METHOD="POST" ACTION="GetEmail.asp">
<PRE>
Email: <INPUT TYPE="TEXT" NAME="Email" SIZE=30 
VALUE="<%= Request("Email") %>">
<%= Msg %> <P> 
<INPUT TYPE="SUBMIT" VALUE="Submit">
</PRE>
</FORM>
</BODY> 
</HTML>

Using the Cookies Collection with the Request Object

A cookie is a token that either a client browser sends to a Web server, or that a Web server sends to a client browser. Cookies allow a set of information to be associated with a user. ASP scripts can both get and set the values of cookies by using the Cookies collection.

This section discusses how to gain access to cookies a browser sends to your Web server.

To get the value of a cookie, use the Request.Cookies collection. For example, if the client HTTP request sets animal=elephant, then the following statement retrieves the value elephant:

<%= Request.Cookies("animal") %> 

If an HTTP request sends multiple values for the same cookie, ASP creates an indexed cookie. Each value is assigned a key; you can retrieve a particular cookie key value by using the syntax Request.Cookies("name)("key"). For example, if a client sends the following HTTP request:

animal=elephant&elephant=African

The following script command returns the value African:

<%= Request.Cookies("animal")("elephant") %> 

 

 

The Response Object

You can use the ASP built-in object Response to control the information you send to a user by using the:

  • Response.Write method to send information directly to a browser.
  • Response.Redirect method to direct a user to a URL other than the requested URL.
  • Response.ContentType method to control the type of content you send.
  • Response.Cookies method to set cookie values.
  • Response.Buffer method to buffer information.

 

Syntax

Response.collection|property|method

 

Collections

Cookies

Specifies cookie values. Using this collection, you can set cookie values.

Properties

Buffer

Indicates whether page output is buffered.

ContentType

Specifies the HTTP content type for the response.

Expires

Specifies the length of time before a page cached on a browser expires.

ExpiresAbsolute

Specifies the date and time on which a page cached on a browser expires.

Status

The value of the status line returned by the server.

Methods

AddHeader

Sets the HTML header name to value.

AppendToLog

Adds a string to the end of the Web server log entry for this request.

BinaryWrite

Writes the given information to the current HTTP output without any character-set conversion.

Clear

Erases any buffered HTML output.

End

Stops processing the .asp file and returns the current result.

Flush

Sends buffered output immediately.

Redirect

Sends a redirect message to the browser, causing it to attempt to connect to a different URL.

Write

Writes a variable to the current HTTP output as a string.

 

Sending Text to a User

The Write method is the most commonly used method of the Response object. You can use the Write method to send information to a user from within ASP delimiters.

Response.Write variant

Where variant can be any data type supported by your default primary scripting language.

For example, the following statement sends a greeting to the user:

<% 
If user_has_been_here_before Then 
  Response.Write "<H3 ALIGN=CENTER>Welcome Back to the Overview Page</H3>" 
Else 
  Response.Write "<H3 ALIGN=CENTER>Welcome to the Overview Page</H3>"
End If 
%>

The Response.Write method is especially useful if you want to send content back to the user from within a procedure.

You do not have to use Response.Write to send content back to the user. Content that is not within scripting delimiters is sent directly to the browser, which formats and displays this content accordingly. For example, the following script produces exactly the same output as the previous script:

<H3 ALIGN=CENTER> 
<% If user_has_been_here_before Then %> 
Welcome Back to the Overview Page. 
<% Else %> 
Welcome to the Overview Page. 
<% End If %> 
</H3>

Redirecting a User to Another URL

Instead of sending content to a user, you can redirect the browser to another URL with the Redirect method.

Response.Redirect URL

For example, if you want to make sure users have entered your application from a particular page, you can check to see if they have been to that page; if they have not, you can send them there.

<%
If Not Session("Been_to_Home_Page") Then 
  Response.Redirect "homepage.asp" 
End If
%> 

Note If you use Response.Redirect from an .asp file after content has already been sent back to the user, an error message is generated.

Setting the HTTP Content Type

You can use the ContentType property of the Response object to set the HTTP content type string for the content you send to a user. The general syntax is

Response.ContentType = ContentType

where ContentType is a string describing the content type. For a full list of supported content types, see your Web browser documentation or the current HTTP specification.

For example, if you want to send source (that is, the .asp file from which an ASP page is generated) to a browser, set ContentType to text/plain:

<% Response.ContentType = "text/plain" %> 

The browser then displays the page as text, rather than interpreting the page as HTML.

 

Using the Cookies Collection with the Response Object

A cookie is a token that either a client browser sends to a Web server or a Web server sends to a client browser. Cookies allow a set of information to be associated with a user. ASP scripts can both get and set the values of cookies by using the Cookies collection.

This section discusses how to set the value of cookies your Web server sends to a client browser.

To set the value of a cookie, use Response.Cookies. If the cookie does not already exist, Response.Cookies creates a new one:

<% Response.Cookies("animal")="elephant" %> 

Similarly, to set the value of a cookie key:

<% Response.Cookies("animal")("elephant")="African" %> 

If an existing cookie has key values but Response.Cookies does not specify a key name, then the existing key values are deleted. Similarly, if an existing cookie does not have key values but Response.Cookies specifies key names and values, the existing value of the cookie is deleted and new key-value pairs are created.

 

Buffering Response

The default setting for buffering of all ASP pages is off. However, you can set the Buffer property of the Response object to True to process all of the script on a page before sending anything to the user:

<% Response.Buffer = True %> 

You can use buffering to determine at some point in the processing of a page that you do not want to send previous content to a user. You can, instead, redirect the user to another page with the Redirect method of the Response object, or clear the buffer with the Clear method of the Response object and send different content to the user. The following example uses both of these methods.

<% Response.Buffer = True %>
<html>
<body>
.
.
.
<%
If Request("FName") = "" Then
  Response.Clear
  Response.Redirect "/aspsamp/samples/test.html"
  Response.End
Else
  Response.Write Request("FName")
End If
%>
</body>
</html>

When you call the Buffer method in a script and do not call the Flush method in the same script, the server will maintain Keep-Alive requests made by the client. The benefit of writing scripts in this manner is that server performance is improved because the server does not have to create a new connection for each client request (assuming that the server, client, and any proxies all support keep-alive requests). However, a potential drawback to this approach is that buffering prevents any of the response from being displayed to the user until the server has finished all script processing for the current .asp file. For long involved scripts, the user might be forced to wait a considerable amount of time before the script is processed.

Buffering is turned off by default for all ASP pages in all applications by setting the BufferingOn registry setting to 0.

 

Application Object

You can use the Application object to share information among all users of a given application. An ASP-based application is defined as all the .asp files in a virtual directory and its subdirectories. Because the Application object can be shared by more than one user, there are Lock and Unlock methods to ensure that multiple users do not try to alter a property simultaneously.

 

Syntax

Application.method

 

Methods

Lock

The Lock method prevents other clients from modifying Application object properties.

Unlock

The Unlock method allows other clients to modify Application object properties.

 

Events

Application_OnEnd

Application_OnStart

Scripts for the preceding events are declared in the Global.asa file.

Remarks

You can store values in the Application object. Information stored in the Application object is available throughout the application and has application scope. The following script demonstrates storage of two types of variables.

<% 
   Application("greeting") = "Welcome to My Web World!"
   Application("num") = 25
%>
 

However, if you store an object in the Application object, and use Visual Basic® Scripting Edition as your primary scripting language, you must use the Set keyword. This is illustrated in the following script.

<% Set Application("Obj1") = Server.CreateObject("MyComponent") %>
 

You can then reference the methods and properties of MyObj on subsequent Web pages, by using the following:

<% Application("Obj1").MyObjMethod %>
 

Or by extracting a local copy of the object and using the following:

<% 
Set MyLocalObj1 = Application("Obj1") 
MyLocalObj1.MyObjMethod
%>
 

Another way to create objects with application scope is by using the <OBJECT> tag in the Global.asa file. You cannot, however, store a built-in object in the Application object. For example, each of the following lines returns an error.

<%
Set Application("var1") = Session
Set Application("var2") = Request
Set Application("var3") = Response
Set Application("var4") = Server
Set Application("var5") = Application
%>
 

Before you store an object in the Application object, you should know what threading model it uses. Only objects marked as both free- and apartment-threaded can be stored in the Application object.

If you store an array in a Application object, you should not attempt to alter the elements of the stored array directly. For example, the following script does not work:

<% Application("StoredArray")(3) = "new value" %>
 

This is because the Application object is implemented as a collection. The array element StoredArray(3) does not receive the new value. Instead, the value is indexed into the collection, overwriting any information stored at that location.

It is strongly recommended that if you store an array in the Application object, you retrieve a copy of the array before retrieving or changing any of the elements of the array. When you are done with the array, you should store the array in the Application object all over again, so that any changes you made are saved. This is demonstrated in the following example:

---file1.asp---
<%
'Creating and initializing the array
dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"

'Storing the array in the Application object
Application.Lock
Application("StoredArray") = MyArray
Application.Unlock

Response.Redirect("file2.asp")
%>

---file2.asp---
<%
'Retrieving the array from the Application Object
'and modifying its second element
LocalArray = Application("StoredArray")
LocalArray(1) = " there"

'printing out the string "hello there"
Response.Write(LocalArray(0)&LocalArray(1))

'Re-storing the array in the Application object
'This overwrites the values in StoredArray with the new values
Application.Lock
Application("StoredArray") = LocalArray
Application.Unlock
%>
  
Example
<% 
Application.Lock
Application("NumVisits") = Application("NumVisits") + 1
Application.Unlock
 %>  
 
This application page has been visited 
<%= Application("NumVisits") %> times!
 

The preceding example uses the application variable NumVisits to store the number of times that a particular page has been accessed. The Lock method is called to ensure that only the current client can access or alter NumVisits. Calling the Unlock method then enables other users to access the Application object.

 

Session Object

You can use the Session object to store information needed for a particular user-session. Variables 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 Web page from the application is requested by a user who does not already have a session. The server destroys the Session object when the session expires or is abandoned.

One common use for the Session object is to store user preferences set on a previous visit to the Web application, such as high, medium, or low graphics.

Note Session state is only maintained for browsers that support cookies.

 

Syntax

Session.property|method

 

Properties

SessionID

Returns the session identification for this user.

Timeout

The timeout period for the session state for this application, in minutes.

Methods

Abandon

This method destroys a Session object and releases its resources.

Remarks

You can store values in the Session object. Information stored in the Session object is available throughout the session and has session scope. The following script demonstrates storage of two types of variables.

<% 
   Session("username") = "Janine"
   Session("age") = 24
%>
 

However, if you store an object in the Session object and use Visual Basic® Scripting Edition as your primary scripting language you must use the Set keyword. This is illustrated in the following script.

<% Set Session("Obj1") = Server.CreateObject("MyComponent") %>
 

You can then call the methods and properties of MyObj on subsequent Web pages, by using the following:

<% Session("Obj1").MyObjMethod %>
 

Or by extracting a local copy of the object and using the following:

<% 
Set MyLocalObj1 = Session("Obj1") 
MyLocalObj1.MyObjMethod
%>
 

Another way to create objects with session scope is by using the <OBJECT> tag in the Global.asa file. You cannot, however, store a built-in object in a Session object. For example, each of the following lines would return an error.

<%
Set Session("var1") = Session
Set Session("var2") = Request
Set Session("var3") = Response
Set Session("var4") = Server
Set Session("var5") = Application
%>
 

Before you store an object in the Session object, you should know what threading model it uses. Only objects marked as both free- and apartment-threaded can be stored in the Session object without locking the session to a single thread.

If you store an array in a Session object, you should not attempt to alter the elements of the stored array directly. For example, the following script will not work:

<% Session("StoredArray")(3) = "new value" %>
 

This is because the Session object is implemented as a collection. The array element StoredArray(3) does not receive the new value. Instead, the value is indexed into the collection, overwriting any information stored at that location.

It is strongly recommended that if you store an array in the Session object, you retrieve a copy of the array before retrieving or changing any of the elements of the array. When you are done with the array, you should store the array in the Session object all over again, so that any changes you made are saved. This is demonstrated in the following example:

---file1.asp---
<%
'Creating and initializing the array
dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"

'Storing the array in the Session object
Session("StoredArray") = MyArray

Response.Redirect("file2.asp")
%>

---file2.asp---
<%
'Retrieving the array from the Session Object
'and modifying its second element
LocalArray = Session("StoredArray")
LocalArray(1) = " there"

'printing out the string "hello there"
Response.Write(LocalArray(0)&LocalArray(1))

'Re-storing the array in the Session object
'This overwrites the values in StoredArray with the new values
Session("StoredArray") = LocalArray
%>
 

Examples

<% 
Session("name") = "MyName" 
Session("year") = 96 
Set Session("myObj") = Server.CreateObject("someObj") 
%> 
 

Events

Scripts for the following events are declared in the Global.asa file.

Session_OnEnd

Session_OnStart

 

 

The ASP ActiveX Components

You can create dynamic, interactive Web pages by using the following server components in your scripts.

Advertisement Rotator

Automatically rotates advertisements displayed on a page according to a specified schedule.

Browser Capabilities

Determines the capabilites, type, and version of each browser that accesses your Web site.

Database Access

Provides access to databases.

Content Linking

Creates tables of contents for Web pages, and links them together sequentially like pages in a book.

TextStream

Provides access to file input and output.

Advertisement Rotator Component

The Advertisement Rotator component automates the rotation of advertisement images on a Web page. Each time a user opens or reloads the Web page, the Advertisement Rotator component displays a new advertisement based on information you specify in a Rotator Schedule File.

You can record how many users click each advertisement by setting the REDIRECT parameter in the Rotator Schedule file. When you specify this parameter, each jump to an advertiser's URL is recorded in the Web server activity logs.

File Names

Adrot.dll

The Advertisement Rotator component.

Redirection File

An optional file that implements redirection and enables the Advertisement Rotator component to record how many users click on each advertisement.

Rotator Schedule File

A text file that contains the display schedule and file information for advertisements. This file must be available on a Web server virtual path.

Syntax

Set AdRotator = Server.CreateObject("MSWC.AdRotator")

Parameters

AdRotator Specifies the name of the object created by the call to Server.CreateObject.

Registry Entries

None.

Properties

Border

Specifies the size of the border around the advertisement.

Clickable

Specifies whether the advertisement is a hyperlink.

TargetFrame

Specifies the name of the frame in which to display the advertisement.

Methods

GetAdvertisement

Gets the specifications for the next scheduled advertisement from the data file and formats it as HTML.

Example

The following example displays a different advertisement each time a user views the Web page.

<%  Set ad = Server.CreateObject("MSWC.AdRotator") %>  
 
<%= ad.GetAdvertisement("/ads/adrot.txt") %>  
 

The following HTML is generated by the GetAdvertisement method and added to the page's output, displaying the next advertisement in the Rotator Schedule file.

 

 

Rotator Schedule File

The Rotator Schedule file contains information that the Advertisement Rotator component uses to manage and display the various advertisement images. In it you specify the details for the advertisements, such as the size of the advertisement space, the image files to use, and the percentage of time that each file should be displayed.

The Rotator Schedule file has two sections. The first section sets parameters that apply to all advertisement images in the rotation schedule. The second section specifies file and location information for each individual advertisement and the percentage of display time that each advertisement should receive. The two sections are separated by a line containing only an asterisk (*).

In the first section there are four global parameters, each consisting of a keyword and a value. All are optional. If you do not specify values for the global parameters, the Advertisement Rotator uses default values. In this case, the first line of the file must contain only an asterisk (*).

Syntax[REDIRECT URL]

[WIDTH numWidth]

[HEIGHT numHeight]

[BORDER numBorder]

*

adURL

adHomePageURL

Text

impressions

Parameters

The following describes the global parameters in the first section of the Rotatator Schedule file.

URL Specifies the path to the dynamic-link library (.dll) or application (.asp) file that implements redirection. This path can be specified either fully (http://MyServer/MyDir/redirect.asp) or relative to the virtual directory (/MyDir/redirect.asp). numWidth Specifies the width of the advertisement on the page, in pixels. The default is 440 pixels. numHeight Specifies the height of the advertisement on the page, in pixels. The default is 60 pixels. numBorder Specifies the thickness of the hyperlink border around the advertisement, in pixels. The default is a 1-pixel border. Set this parameter to 0 for no border.

The following describes the individual advertisement parameters in the second section of the Rotator Schedule file. Each advertisement requires four lines of information.

adURL The location of the advertisement image file. adHomePageURL The location of the advertiser's home page. If the advertiser does not have a home page, put a hyphen (-) on this line to indicate that there is no link for this ad. Text Alternate text that is displayed if the browser does not support graphics, or has its graphics capabilities turned off. impressions A number between 0 and 4,294,967,295 that indicates the relative weight of the advertisement. For example, if a Rotator Schedule file contains three ads with impressions set to 2, 3, and 5, the first advertisement is displayed 20 percent of the time, the second 30 percent of the time, and the third 50 percent of the time.

Example

---ADROT.TXT---
REDIRECT /scripts/adredir.asp 
WIDTH 440 
HEIGHT 60 
BORDER 1 
*
http://kabaweb/ads/homepage/chlogolg.gif 
http://www.bytecomp.com/
Check out the ByteComp Technology Center
20 
http://kabaweb/ads/homepage/gamichlg.gif 
-
Sponsored by Flyteworks
20 
http://kabaweb/ads/homepage/ismodemlg.gif 
http:// www.proelectron.com/
28.8 internal PC modem, only $99 
80 
http://kabaweb/ads/homepage/spranklg.gif 
http://www.clocktower.com/
The #1 Sports site on the net 
10 
 

Redirection File

The redirection file is a file that you create. It usually includes script to parse the query string sent by the Advertisement Rotator component and redirect the user to the URL associated with the advertisement that they clicked on.

You can also include script in the Redirection file to count the number of users that have clicked on a particular advertisement, and save this information to a file on the server.

The following example simply redirects the user to the advertiser's home page.

---ADREDIR.ASP---
<%  Response.Redirect(Request.QueryString("url")) %>  

Browser Capabilities Component

The Browser Capabilities component provides your scripts with a description of the capabilities of the client's Web browser.

When a browser connects to the Web server, it automatically sends a User Agent HTTP header. This header is an ASCII string that identifies the browser and its version number. The Browser Capabilities component compares the this header to entries in a Browscap.ini file.

If it finds a match, the Browser Capabilities component assumes the properties of the browser listing that matched the User Agent header.

If the component does not find a match for the header in the Browscap.ini file, it takes on the default browser properties. If the component does not find a match and default browser settings have not been specified in the Browscap.ini file, it sets every property to the string "UNKNOWN".

You can add properties or new browser definitions to this component simply by updating the Browscap.ini file.

File Names

Browscap.dll

The Browser Capabilities component.

Browscap.ini

A text file that maps browser capabilites to the HTTP User Agent header. This file must be in the same directory as Browscap.dll.

Syntax

Set BrowserType = Server.CreateObject("MSWC.BrowserType")

Parameters

BrowserType
Specifies the name of the object created by the call to Server.CreateObject.

Registry Entries

None.

Example

The following example uses the Browser Capabilities component to display a table showing some of the capabilities of the current browser.

<%  Set bc = Server.CreateObject("MSWC.BrowserType") %>  
<table border=1> 
<tr><td>Browser</td><td>  <%= bc.browser  %>  
<tr><td>Version</td><td>  <%= bc.version  %>  </td></TR> 
<tr><td>Frames</td><td>
<%  if (bc.frames = TRUE) then  %>  TRUE
<%  else  %>  FALSE
<%  end if  %> </td></TR> 
<tr><td>Tables</td><td>
<%  if (bc.tables = TRUE) then  %>  TRUE 
<%  else  %> FALSE
<%  end if  %> </td></TR> 
<tr><td>BackgroundSounds</td><td> 
<%  if (bc.BackgroundSounds = TRUE) then  %>  TRUE 
<%  else  %> FALSE
<%  end if  %> </td></TR> 
<tr><td>VBScript</td><td> 
<%  if (bc.vbscript = TRUE) then  %>  TRUE 
<%  else  %> FALSE
<%  end if  %> </td></TR> 
<tr><td>JScript</td><td> 
<%  if (bc.javascript = TRUE) then  %>  TRUE 
<%  else  %> FALSE
<%  end if  %> </td></TR> 
</table> 

Content Linking Component

The Content Linking component manages a list of URLs so that you can treat the pages in your Web site like the pages in a book. You can use the functionality of the Content Linking component to automatically generate and update tables of contents, and navigational links to previous and following Web pages. This is ideal for applications such as online newspapers and forum message listings.

The Content Linking component references a Content Linking List file that contains the list of the linked Web pages. This list is stored on the Web server.

File Names

Nextlink.dll

The Content Linking component.

Content Linking List

A text file that contains a list of Web pages in the order in which they should be displayed. This file must be available on a Web server virtual path.

Syntax

Set NextLink = Server.CreateObject("MSWC.Nextlink")

Parameters

NextLink
Specifies the name of the object created by the call to Server.CreateObject.

Registry Entries

None.

Methods

GetListCount

Counts the number of items linked in the Content Linking List file.

GetNextURL

Gets the URL of the next page listed in the Content Linking List file.

GetPreviousDescription

Gets the description line of the previous page listed in the Content Linking List file.

GetListIndex

Returns the index of the current page in the Content Linking List file.

GetNthDescription

Gets the description of the Nth page listed in the Content Linking List file.

GetPreviousURL

Gets the URL of the previous pages listed in the Content Linking List file.

GetNextDescription

Gets the description of the next page listed in the Content Linking List file.

GetNthURL

Gets the URL of the Nth page listed in the Content Linking List file.

Example

The following example builds a table of contents.

<ol>
<%  Set NextLink = Server.CreateObject ("MSWC.NextLink") %>  
<%  count = NextLink.GetListCount ("/data/nextlink.txt") %> 
<%  I = 1 %> 

<ul>
<%  Do While (I <= count)  %>  
<li><a href=" <%= NextLink.GetNthURL ("/data/nextlink.txt", I)  %>  "> 
<%= NextLink.GetNthDescription ("/data/nextlink.txt", I) %>  </a> 
<%  I = (I + 1)  %>  
<%  Loop  %>  
</ul>
</ol>
 

The following script adds the next- and previous-page buttons to an HTML file.

<%  Set NextLink = Server.CreateObject ("MSWC.NextLink") %>  
<%  If (NextLink.GetListIndex ("/data/nextlink.txt") > 1) Then %> 
<a href="  <%= NextLink.GetPreviousURL ("/data/nextlink.txt")  %>  ">
Previous Page</a> 
<%  End If  %>  
<a href="  <%= NextLink.GetNextURL ("/data/nextlink.txt")  %>  ">Next Page</a> 

Database access objects

ADO Overview

ActiveX Data Objects (ADO) enables you to write a client application to access and manipulate data in a database server through a provider. ADO's primary benefits are ease of use, high speed, low memory overhead, and a small disk footprint. This help file is for ADODB, an implementation of ADO optimized for use with Microsoft OLE DB providers, including the Microsoft ODBC Provider for OLE DB.

In ADO, the Recordset object is the main interface to data. An example of the minimal Microsoft® Visual Basic® Scripting Edition code to generate a Recordset from an ODBC data source is as follows:

set rstMain = CreateObject("ADODB.Recordset")
rstMain.Open "SELECT * FROM authors", _
    "DATABASE=pubs;UID=sa;PWD=;DSN=Publishers"

This generates a forward-only, read-only Recordset object. A slightly more functional Recordset can be generated as follows:

set rstMain = CreateObject("ADODB.Recordset")
rstMain.Open "SELECT * FROM authors", _
    "DATABASE=pubs;UID=sa;PWD=;DSN=Publishers",
    adOpenKeyset, adLockBatchOptimistic

This creates a fully scrollable and batch-updatable Recordset.

Note For applications that use Visual Basic Scripting Edition (for example, Microsoft® Active Server Pages), you must include the Adovbs.inc file in your code in order to call ADO constants by name. (Use Adojavas.inc for Microsoft JScript™.) In your code, you should always refer to constants by name rather than by value since the values may change from one version to the next.

In ADO, the object hierarchy is de-emphasized. Unlike Data Access Objects (DAO) or Remote Data Objects (RDO), you no longer have to navigate through a hierarchy to create objects because most ADO objects can be independently created. This allows you to create and track only the objects you need. This model also results in fewer ADO objects and thus a smaller working set.

ADO supports key features for building client/server and web-based applications, including the following:

  • Independently-created objects
  • Batch updating
  • Support for stored procedures with in/out parameters and return values
  • Different cursor types, including the potential for support of back-end–specific cursors
  • Advanced recordset cache management
  • Support for limits on number of returned rows and other query goals
  • Support for multiple recordsets returned from stored procedures or batch statements
  • Free-threaded objects for efficient web server applications

 

Connection Object

A Connection object represents an open connection to an OLE DB data source.

Remarks

You can create Connection objects independently of any other previously defined object.

A Connection object represents a unique session with a data source. In the case of a client/server database system, it may be equivalent to an actual network connection to the server. Depending on the functionality the provider exposes, some collections, methods, or properties of a Connection object may not be available.

Using the collections, methods, and properties of a Connection object, you can do the following:

 

Command Object

A Command object is a definition of a specific command that you intend to execute against a data source.

Remarks

You can create a Command object independently of a previously defined Connection object by setting its ActiveConnection property to a valid connection string. ADO still creates a Connection object, but it doesn't assign that object to an object variable. However, if you are associating multiple Command objects with the same connection, you should explicitly create and open a Connection object; this assigns the Connection object to an object variable. If you do not set the Command objects' ActiveConnection property to this object variable, ADO creates a new Connection object for each Command object, even if you use the same connection string.

Use Command objects to obtain records and create a Recordset object, to execute a bulk operation, or to manipulate the structure of a database. Depending on the functionality the provider exposes, some collections, methods, or properties of a Command object may generate an error when you call them.

With the collections, methods, and properties of a Command object, you can do the following:

 

Parameter Object

A Parameter object represents a parameter or argument associated with a Command object based on a parameterized query or stored procedure.

Remarks

Parameter objects represent parameters associated with parameterized queries, or the in/out arguments or return values of stored procedures. Depending on the functionality the provider exposes, some collections, methods, or properties of a Parameter object may not be available.

With the collections, methods, and properties of a Parameter object, you can do the following:

If you know the names and properties of the parameters associated with the stored procedure or parameterized query you wish to call, you can use the CreateParameter method to create Parameter objects with the appropriate property settings and use the Append method to add them to the Parameters collection. This lets you set and return parameter values without having to call the Refresh method on the Parameters collection to retrieve the parameter information from the provider, a potentially resource-intensive operation.

To refer to a Parameter object in a collection by its ordinal number or by its Name property setting, use any of the following syntax forms:

command.Parameters.Item(0)

command.Parameters.Item("name")

command.Parameters(0)

command.Parameters("name")

command(0)

command("name")

command![name]

 

Recordset Object

A Recordset object represents the entire set of records from a base table or the results of an executed command. At any time, the Recordset object only refers to a single record within the set as the current record.

Remarks

You can create Recordset objects independently of a previously defined Connection object by passing a connection string with the Open method. ADO still creates a Connection object, but it doesn't assign that object to an object variable. However, if you are opening multiple Recordset objects over the same connection, you should explicitly create and open a Connection object; this assigns the Connection object to an object variable. If you do not use this object variable when opening your Recordset objects, ADO creates a new Connection object for each new Recordset object, even if you pass the same connection string.

You use Recordset objects to manipulate data from a provider at the record level. When you use ADO, you manipulate data almost entirely using Recordset objects. All Recordset objects are constructed using records (rows) and fields (columns). Depending on the functionality the provider exposes, some collections, methods, or properties of a Recordset object may not be available.

You can use one of four different cursor types when opening a Recordset object:

  • Dynamic cursor — allows you to view additions, changes, and deletions by other users, and allows all types of movement through the Recordset that don't rely on bookmarks; allows bookmarks if the provider supports them.
  • Keyset cursor — behaves like a dynamic cursor, except that it prevents you from seeing records that other users add, and prevents access to records that other users delete from your recordset; always allows bookmarks and therefore allows all types of movement through the Recordset. Data changes by other users will still be visible.
  • Static cursor — provides a static copy of a set of records for you to use to find data or generate reports; always allows bookmarks and therefore allows all types of movement through the Recordset. Additions, changes, or deletions by other users will not be visible.
  • Forward-only cursor — behaves identically to a static cursor except that it allows you to scroll only forward through records. This improves performance in situations where you need to make only a single pass through a recordset.

Set the CursorType property prior to opening the Recordset object to choose the cursor type of the Recordset object. You can also pass a CursorType argument with the Open method.

If you don't specify a cursor type, ADO opens a forward-only cursor by default.

You can create as many Recordset objects as needed. Different Recordset objects can access the same tables and fields without conflicting.

When you create a Recordset object, the current record is positioned to the first record (if any) and the BOF and EOF properties are set to False. If there are no records, the RecordCount property setting is 0, and the BOF and EOF property settings are True.

You can use the MoveFirst, MoveLast, MoveNext, and MovePrevious methods, as well as the Move method, and the AbsolutePosition, AbsolutePage, and Filter properties to reposition the current record, assuming the provider supports the relevant functionality. Forward-only Recordset objects support only the MoveNext method. When you use the Move methods to visit each record (or enumerate the Recordset), you can use the BOF and EOF properties to see if you've moved beyond the beginning or end of the Recordset object.

Recordset objects may support two types of updating: immediate and batched. In immediate updating, all changes to data are written immediately to the underlying data source once you call the Update method. You can also pass arrays of values as parameters with the AddNew and Update methods and simultaneously update several fields in a record.

If a provider supports batch updating, you can have the provider cache changes to more than one record and then transmit them in a single call to the database with the UpdateBatch method. This applies to changes made with the AddNew, Update, and Delete methods. After you call the UpdateBatch method, you can use the Status property to check for any data conflicts in order to resolve them.

Note You should use batch updating only with either a keyset or static cursor.

 

Field Object

A Field object represents a column of data with a common data type.

Remarks

A Recordset object has a Fields collection made up of Field objects. Each Field object corresponds to a column in the Recordset. You use the Value property of Field objects to set or return data for the current record. Depending on the functionality the provider exposes, some collections, methods, or properties of a Field object may not be available.

With the collections, methods, and properties of a Field object, you can do the following:

To refer to a Field object in a collection by its ordinal number or by its Name property setting, use any of the following syntax forms:

recordset.Fields.Item(0)

recordset.Fields.Item("name")

recordset.Fields(0)

recordset.Fields("name")

recordset(0)

recordset("name")

recordset![name]

 

 

 

Important Methods and Properties

  1. Open Method

Applies To

Connection : Opens a connection to a data source.

Recordset : Opens a cursor.

Syntax

For a Connection object:

connection.Open ConnectionString, UserID, Password

For a Recordset object:

recordset.Open Source, ActiveConnection, CursorType, LockType, Options

The Open method syntax has these parts.

Part

Description

Connection

An object variable representing an existing Connection object.

Recordset

An object variable representing an existing Recordset object.

ConnectionString

Optional. A String containing connection information. See the ConnectionString property for details on valid settings.

UserID

Optional. A String containing a user name to use when establishing the connection.

Password

Optional. A String containing a password to use when establishing the connection.

Source

Optional. A Variant that evaluates to a valid Command object variable name, an SQL statement, a table name, or a stored procedure call.

ActiveConnection

Optional. A Variant that evaluates to a valid Connection object variable name or a String containing a definition for a connection.

CursorType

Optional. A CursorTypeEnum value that determines the type of cursor that the provider should use when opening the Recordset. Can be one of the following constants:

  • adOpenForwardOnly, 0 (Default)
  • adOpenKeyset, 1
  • adOpenDynamic, 2
  • adOpenStatic, 3

LockType

Optional. A LockTypeEnum value that determines what type of locking (concurrency) the provider should use when opening the Recordset. Can be one of the following constants:

  • adLockReadOnly, 1
  • adLockPessimistic, 2
  • adLockOptimistic, 3
  • adLockBatchOptimistic, 4

Options

Optional. A CommandTypeEnum value that indicates how the provider should evaluate the Source argument if it represents something other than a Command object. Can be one of the following constants:

  • adCmdText, 1 — Evaluate Source as a textual definition of a command.
  • adCmdTable, 2 — Evaluate Source as a table name.
  • adCmdStoredProc, 4 — Evaluate Source as a stored procedure.
  • adCmdUnknown, 8 — The type of command in the Source argument is not known.

Remarks

Use the Open method on a Connection object or a Recordset object to activate the object for use. When you have concluded your operations over an open Connection object or in an open Recordset object, use the Close method to free any associated system resources. Closing an object does not remove it from memory; you may change its property settings and use the Open method to open it again later. To completely eliminate an object from memory, set the object variable to Nothing.

Connection

Using the Open method on a Connection object establishes the physical connection to a data source. After this method successfully completes, the connection is live and you can issue commands against it and process results.

Use the optional ConnectionString argument to specify a data source name (DSN) or a detailed connection string containing a series of argument = value statements separated by semicolons. If the argument contains an equal sign ("="), ADO assumes you are providing a connection string rather than a DSN. The ConnectionString property automatically inherits the value used for the ConnectionString argument. Therefore, you can either set the ConnectionString property of the Connection object before opening it, or use the ConnectionString argument to set or override the current connection parameters during the Open method call.

If you pass user and password information both in the ConnectionString argument and in the optional UserID and Password arguments, the results may be unpredictable; you should only pass such information in either the ConnectionString argument or the UserID and Password arguments.

Recordset

Using the Open method on a Recordset object opens a cursor that represents records from a base table or the results of a query.

Use the optional Source argument to specify a data source using one of the following: a Command object variable, an SQL statement, a stored procedure, or a table name.

The ActiveConnection argument corresponds to the ActiveConnection property and specifies in which connection to open the Recordset object. If you pass a connection definition for this argument, ADO opens a new connection using the specified parameters.

For the arguments that correspond directly to properties of a Recordset object (Source, ActiveConnection, CursorType, and LockType), the relationship of the arguments to the properties is as follows:

  • The property is read/write before the Recordset object is opened.
  • The property settings are used unless you pass the corresponding arguments during the Open method. If you pass an argument, it overrides the corresponding property setting, and the property setting is updated with the argument value.
  • After you open the Recordset object, these properties become read-only.

Note For Recordset objects whose Source property is set to a valid Command object, the ActiveConnection property is read-only, even if the Recordset object isn't open.

If you pass a Command object in the Source argument and also pass an ActiveConnection argument, an error occurs. The ActiveConnection property of the Command object must already be set to a valid Connection object or connection string.

If you pass something other than a Command object in the Source argument, you can use the Options argument to optimize evaluation of the Source argument. If the Options argument is not defined, you may experience diminished performance because ADO must make calls to the provider to determine if the argument is an SQL statement, a stored procedure, or a table name. If you know what Source type you're using, setting the Options argument instructs ADO to jump directly to the relevant code. If the Options argument does not match the Source type, an error occurs.

If the data source returns no records, the provider sets both the BOF and EOF properties to True, and the current record position is undefined. You can still add new data to this empty Recordset object if the cursor type allows it.

 

  1. BeginTrans, CommitTrans, RollbackTrans Methods

The transaction methods manage transaction processing within a Connection object as follows:

  • BeginTrans begins a new transaction.
  • CommitTrans saves any changes and ends the current transaction. It may also start a new transaction.
  • RollbackTrans cancels any changes made during the current transaction and ends the transaction. It may also start a new transaction.
Syntax

[level = ] connection.BeginTrans

connection.{CommitTrans | RollbackTrans}

The connection placeholder is an object variable representing an open Connection object.

The level placeholder represents a Long variable to which the BeginTrans method can return a value indicating the nesting level of the transaction. The CommitTrans and RollbackTrans methods do not return any value.

Remarks

Use these methods with a Connection object when you want to save or cancel a series of changes made to the source data as a single unit. For example, to transfer money between accounts, you subtract an amount from one and add the same amount to the other. If either update fails, the accounts no longer balance. Making these changes within an open transaction ensures either all or none of the changes goes through.

Once you call the BeginTrans method, the provider will no longer instantaneously commit any changes you make until you call CommitTrans or RollbackTrans to end the transaction.

For providers that support nested transactions, calling the BeginTrans method within an open transaction starts a new, nested transaction. The return value indicates the level of nesting: a return value of "1" indicates you have opened a top-level transaction (that is, the transaction is not nested within another transaction), "2" indicates that you have opened a second-level transaction (a transaction nested within a top-level transaction), and so forth. Calling CommitTrans or RollbackTrans affects only the most recently opened transaction; you must close or rollback the current transaction before you can resolve any higher level transactions.

Calling the CommitTrans method saves changes made within an open transaction on the connection and ends the transaction. Calling the RollbackTrans method reverses any changes made within an open transaction and ends the transaction. Calling either method when there is no open transaction generates an error.

Depending on the Connection object's Attributes property, calling either the CommitTrans or RollbackTrans methods may automatically start a new transaction. If the Attributes property is set to adXactCommitRetaining, ADO automatically starts a new transaction after a CommitTrans call. If the Attributes property is set to adXactAbortRetaining, ADO automatically starts a new transaction after a RollbackTrans call.

 

  1. Close Method
  2. Closes an open object and any dependent objects.

    Syntax

    object.Close

    The object placeholder is an object variable representing an open Connection or Recordset object.

    Remarks

    Use the Close method to close either a Connection object or a Recordset object to free any associated system resources. Closing an object does not remove it from memory; you may change its property settings and open it again later. To completely eliminate an object from memory, set the object variable to Nothing.

    Connection

    Using the Close method to close a Connection object also closes any active Recordset objects associated with the connection. A Command object associated with the Connection object you are closing will persist, but it will no longer be associated with a Connection object, that is, its ActiveConnection property will be set to Nothing. Also, the Command object's Parameters collection will be cleared.

    You can later call the Open method to reestablish the connection to the same or another data source. While the Connection object is closed, calling any methods that require an open connection to the data source generates an error.

    Closing a Connection object while there are open Recordset objects on the connection rolls back any pending changes in all of the Recordset objects. Explicitly closing a Connection object (calling the Close method) while a transaction is in progress generates an error. If a Connection object falls out of scope while a transaction is in progress, ADO automatically rolls back the transaction.

    Recordset

    Using the Close method to close a Recordset object releases the associated data and any exclusive access you may have had to the data through this particular Recordset object. You can later call the Open method to reopen the recordset with the same or modified attributes. While the Recordset object is closed, calling any methods that require a live cursor generates an error.

    If an edit is in progress while in immediate update mode, calling the Close method generates an error; call the Update or CancelUpdate method first. If you close the Recordset object during batch updating, all changes since the last UpdateBatch call are lost.

    If you use the Clone method to create copies of an open Recordset object, closing the original or a clone does not affect any of the other copies.

     

  3. Execute Method

Syntax

On a Command object:

Set recordset = command.Execute(RecordsAffected, Parameters, Options)

command.Execute RecordsAffected, Parameters, Options

On a Connection object:

Set recordset = connection.Execute(CommandText, RecordsAffected, Options)

connection.Execute CommandText, RecordsAffected, Options

 

 

 

 

 

The Execute method syntax has these parts.

Part

Description

Recordset

An object variable representing the Recordset object in which the results of the query are stored.

Command

An object variable representing a Command object whose CommandText property contains the query to execute.

Connection

An object variable representing a Connection object on which the query is executed.

RecordsAffected

Optional. A Long variable to which the provider returns the number of records that the operation affected.

Parameters

Optional. A Variant array of parameter values passed with an SQL statement. (Output parameters will not return correct values when passed in this argument.)

CommandText

A String containing the SQL statement, table name, or stored procedure to execute.

Options

Optional. A CommandTypeEnum value that indicates how the provider should evaluate the CommandText argument. Can be one of the following constants:

  • adCmdText, 1 — Evaluate CommandText as a textual definition of a command.
  • adCmdTable, 2 — Evaluate CommandText as a table name.
  • adCmdStoredProc, 4 — Evaluate CommandText as a stored procedure.
  • adCmdUnknown, 8 — The type of command in the CommandText argument is not known.

Remarks

Use the Execute method to execute an existing Command object or a query of your choosing. You can also specify a Recordset object in which to store the results, if any.

Command

Using the Execute method on a Command object executes the query specified in the CommandText property of the object. If the CommandText property specifies a row-returning query, any results the execution generates are stored in a new Recordset object. If the command is not a row-returning query, the provider returns a closed Recordset object. Most application languages allow you to ignore this return value if no Recordset is desired.

If the query has parameters, the current values for the Command object's parameters are used unless you override these with parameter values passed with the Execute call. You can override a subset of the parameters by omitting new values for some of the parameters when calling the Execute method. The order in which you specify the parameters is the same order in which the method passes them. For example, if there were four (or more) parameters and you wanted to pass new values for only the first and fourth parameters, you would pass Array(var1,,,var4) as the Parameters argument.

Note Output parameters will not return correct values when passed in the Parameters argument.

Connection

Using the Execute method on a Connection object executes whatever query you pass to the method in the CommandText argument on the specified connection. If the CommandText argument specifies a row-returning query, any results the execution generates are stored in a new Recordset object. If the command is not a row-returning query, the provider returns a closed Recordset object.

The contents of the CommandText argument are specific to the provider and can be standard SQL syntax or any special command format that the provider supports.

 

  1. CreateParameter Method
  2. Creates a new Parameter object with the specified properties.

    Syntax

    Set parameter = command.CreateParameter(Name, Type, Direction, Size, Value)

    The CreateParameter method syntax has these parts:

    Part

    Description

    Parameter

    An object variable representing the Parameter object you want to create.

    Command

    An object variable representing the Command object for whose Parameters collection you want to create a new Parameter object.

    Name

    A String representing the name of the Parameter object.

    Type

    Optional. A Long value specifying the data type of the Parameter object. See the Type property for valid settings.

    Direction

    Optional. A Long value specifying the type of Parameter object. See the Direction property for valid settings.

    Size

    Optional. A Long value specifying the maximum length for the parameter value in characters or bytes.

    Value

    Optional. A Variant specifying the value for the Parameter object.

     

    Remarks

    Use the CreateParameter method to create a new Parameter object with the specified name, type, direction, and value. Any values you pass in the arguments are written to the corresponding Parameter properties.

    This method does not automatically append the Parameter object to the Parameters collection of a Command object. This lets you set additional properties whose values ADO will validate when you append the Parameter object to the collection.

    If you specify a variable-length data type in the Type argument, you must either pass a Size argument or set the Size property of the Parameter object before appending it to the Parameters collection; otherwise, an error occurs.

     

  3. AddNew Method
  4. Creates a new record for an updatable Recordset object.

    Syntax

    recordset.AddNew Fields, Values

    The AddNew method syntax has these parts:

    Part

    Description

    Recordset

    An object variable representing the Recordset object to which you want to add a new record.

    Fields

    Optional. A Variant representing a single name or a Variant array representing names or ordinal positions of the field or fields in the new record.

    Values

    Optional. A Variant representing a single value or a Variant array representing values for the field or fields in the new record.

    Remarks

    Use the AddNew method to create and initialize a new record. Use the Supports method to verify whether you may add records to the current Recordset object.

    After you call the AddNew method, the new record becomes the current record and remains current after you call the Update method. If the Recordset object supports bookmarks, the new record is added to the end of the Recordset and remains visible. If the Recordset object does not support bookmarks, you may not be able to access the new record once you move to another record. To make the new record accessible, you must call the Requery method.

    If you call AddNew while editing the current record or while adding a new record, ADO calls the Update method to save any changes and then creates the new record.

    If Fields is an array, Values must also be an array with the same number of members; otherwise, an error occurs. The order of field names must match the order of field values in each array.

    The behavior of the AddNew method depends on the updating mode of the Recordset object and whether or not you pass the Fields and Values arguments.

    In immediate update mode (the provider writes changes to the underlying data source once you call the Update method), calling the AddNew method without arguments sets the EditMode property to adEditAdd. ADO caches any field value changes locally. Calling the Update method posts the new record to the database and resets the EditMode property to adEditNone. If you pass the Fields and Values arguments, ADO immediately posts the new record to the database (no Update call is necessary); the EditMode property value does not change (adEditNone).

    In batch update mode (the provider caches multiple changes and writes them to the underlying data source only when you call the UpdateBatch method), calling the AddNew method without arguments sets the EditMode property to adEditAdd. ADO caches any field value changes locally. Calling the Update method adds the new record to the current recordset and resets the EditMode property to adEditNone, but the provider does not post the changes to the underlying database until you call the UpdateBatch method. If you pass the Fields and Values arguments, ADO sends the new record to the provider for storage in a cache; you need to call the UpdateBatch method to post the new record to the underlying database.

     

  5. Delete Method

Deletes the current record in an open Recordset object or an object from a collection.

Syntax

For a Recordset object:

recordset.Delete AffectRecords

The Delete method syntax for Recordset objects has these parts:

Part

Description

Recordset

An object variable representing an open Recordset object.

AffectRecords

Optional. An AffectEnum value that determines how many records the Delete method will affect. Can be one of the following constants:

  • adAffectCurrent, 1 (Default) — Delete only the current record.
  • adAffectGroup, 2 — Delete the records that satisfy the current Filter property setting. You must set the Filter property to one of the valid predefined constants in order to use this option.

For a collection:

collection.Delete Index

The collection placeholder represents the collection from which you want to delete an object. The Index argument is a String representing the name of the object you wish to delete.

Remarks

Use the Delete method with a Recordset object to remove the current record or a group of records, or with a collection to remove one of its objects.

Recordset

Using the Delete method marks the current record or a group of records in a Recordset object for deletion. If the Recordset object doesn't allow record deletion, an error occurs. If you are in immediate update mode, deletions occur in the database immediately. Otherwise, the records are marked for deletion from the cache and the actual deletion happens when you call the UpdateBatch method. (Use the Filter property to view the deleted records.)

Retrieving field values from the deleted record generates an error. After deleting the current record, the deleted record remains current until you move to a different record. Once you move away from the deleted record, it is no longer accessible.

If you nest deletions in a transaction, you can recover deleted records with the RollbackTrans method. If you are in batch update mode, you can cancel a pending deletion or group of pending deletions with the CancelBatch method.

If the attempt to delete records fails because of a conflict with the underlying data (for example, a record has already been deleted by another user), the provider returns warnings to the Errors collection but does not halt program execution. A run-time error occurs only if there are conflicts on all the requested records. Use the Filter property (adFilterAffectedRecords) and the Status property to locate records with conflicts.

Collection

Using the Delete method on a collection lets you remove one of the objects in the collection. This method is available only on the Parameters collection of a Command object. You must use the Parameter object's Name property when calling the Delete method — an object variable is not a valid argument.

 

  1. GetRows Method
  2. Retrieves multiple records of a Recordset into an array.

    Syntax

    Set array = recordset.GetRows(Rows, Start, Fields)

    The GetRows method syntax has the following parts.

    Part

    Description

    Array

    A Variant variable in which to store the returned data.

    Recordset

    An object variable representing a Recordset object.

    Rows

    Optional. A Long expression indicating the number of records to retrieve. Default is adGetRowsRest (-1).

    Start

    Optional. A String or Variant that evaluates to the bookmark for the record from which the GetRows operation should begin.

    Fields

    Optional. A Variant representing a single field name or ordinal position or an array of field names or ordinal position numbers. ADO returns only the data in these fields.

    Remarks

    Use the GetRows method to copy records from a Recordset into a two-dimensional array. The first subscript identifies the field and the second identifies the record number. The array variable is automatically dimensioned to the correct size when the GetRows method returns the data. The returned data is read-only.

    If you do not specify a value for the Rows argument, the GetRows method automatically retrieves all the records in the Recordset object. If you request more records than are available, GetRows returns only the number of available records.

    If the Recordset object supports bookmarks, you can specify at which record the GetRows method should begin retrieving data by passing the value of that record's Bookmark property.

    If you want to restrict the fields the GetRows call returns, you can pass either a single field name/number or an array of field names/numbers in the Fields argument.

    After you call GetRows, the next unread record becomes the current record, or the EOF property is set to True if there are no more records.

  3. Move Method
  4. Moves the position of the current record in a Recordset object.

    Syntax

    recordset.Move NumRecords, Start

    The Move method syntax has these parts.

    Part

    Description

    recordset

    An object variable representing the Recordset object whose current record position you want to move.

    NumRecords

    A signed Long expression specifying the number of records the current record position moves.

    Start

    Optional. A String or Variant that evaluates to a bookmark.

    Remarks

    The Move method is supported on all Recordset objects.

    If the NumRecords argument is greater than zero, the current record position moves forward (toward the end of the recordset). If NumRecords is less than zero, the current record position moves backward (toward the beginning of the recordset).

    If the Move call would move the current record position to a point before the first record, ADO sets the current record to the position before the first record in the recordset (BOF is True). An attempt to move backward when the BOF property is already True generates an error.

    If the Move call would move the current record position to a point after the last record, ADO sets the current record to the position after the last record in the recordset (EOF is True). An attempt to move forward when the EOF property is already True generates an error.

    Calling the Move method from an empty Recordset object generates an error.

    If you pass the Start argument, the move is relative to the record with this bookmark assuming the Recordset object supports bookmarks. If not specified, the move is relative to the current record.

    If you are using the CacheSize property to locally cache records from the provider, passing a NumRecords that moves the current record position outside of the current group of cached records forces ADO to retrieve a new group of records starting from the destination record. The CacheSize property determines the size of the newly retrieved group, and the destination record is the first record retrieved. ADO will also retrieve a new set of records if you are using a local cache and you pass the Start argument.

    If the Recordset object is forward-only, a user can still pass a NumRecords less than zero as long as the destination is within the current set of cached records. If the Move call would move the current record position to a record before the first cached record, an error will occur. Thus, you can use a record cache that supports full scrolling over a provider that only supports forward scrolling. Because cached records are loaded into memory, you should avoid caching more records than is necessary. Even if a forward-only Recordset object supports backward moves in this way, calling the MovePrevious method on any forward-only Recordset object still generates an error.

     

  5. MoveFirst, MoveLast, MoveNext, MovePrevious Methods
  6. Move to the first, last, next, or previous record in a specified Recordset object and make that record the current record.

    Syntax

    recordset.{MoveFirst | MoveLast | MoveNext | MovePrevious}

    The recordset placeholder is an object variable representing an open Recordset object.

    Remarks

    Use the MoveFirst method to move the current record position to the first record in the recordset.

    Use the MoveLast method to move the current record position to the last record in the recordset. The Recordset object must support bookmarks; otherwise, the method call will generate an error.

    Use the MoveNext method to move the current record position one record forward (towards the bottom of the Recordset). If the last record is the current record and you call the MoveNext method, ADO sets the current record to the position after the last record in the Recordset (EOF is True). An attempt to move forward when the EOF property is already True generates an error.

    Use the MovePrevious method to move the current record position one record backward (towards the top of the Recordset). The Recordset object must support bookmarks or backward cursor movement; otherwise, the method call will generate an error. If the first record is the current record and you call the MovePrevious method, ADO sets the current record to the position before the first record in the Recordset (BOFadproBOF is True). An attempt to move backward when the BOF property is already True generates an error. If the Recordset object does not support either bookmarks or backward cursor movement, the MovePrevious method will generate an error.

    If the recordset is forward-only and you want to support both forward and backward scrolling, you can use the CacheSize property to create a record cache that will support backward cursor movement through the Move method. Because cached records are loaded into memory, you should avoid caching more records than is necessary. You can call the MoveFirst method in a forward-only Recordset object; doing so may cause the provider to re-execute the command that generated the Recordset object.

     

  7. Update Method

Saves any changes you make to the current record of a Recordset object.

Syntax

recordset.Update Fields, Values

The Update method syntax has these parts:

Part

Description

Recordset

An object variable representing an open, updatable Recordset object.

Fields

Optional. A Variant representing a single name or a Variant array representing names or ordinal positions of the field or fields you wish to modify.

Values

Optional. A Variant representing a single value or a Variant array representing values for the field or fields in the new record.

Remarks

Use the Update method to save any changes you make to the current record of a Recordset object since calling the AddNew method or since changing any field values in an existing record. The Recordset object must support updates.

To set field values, do one of the following:

When you use arrays of fields and values, there must be an equal number of elements in both arrays. Also, the order of field names must match the order of field values. If the number and order of fields and values do not match, an error occurs.

If the Recordset object supports batch updating, then you can cache multiple changes to one or more records locally until you call the UpdateBatch method. If you are editing the current record or adding a new record when you call the UpdateBatch method, ADO will automatically call the Update method to save any pending changes to the current record before transmitting the batched changes to the provider.

If you move from the record you are adding or editing before calling the Update method, ADO will automatically call Update to save the changes. You must call the CancelUpdate method if you want to cancel any changes made to the current record or to discard a newly added record.

The current record remains current after you call the Update method.

Important Properties

 

  1. ConnectionString Property
  2. Contains the information used to establish a connection to a data source.

    Settings and Return Values

    Sets or returns a String value.

    Remarks

    Use the ConnectionString property to specify a data source by passing a data source name (DSN) or a detailed connection string containing a series of argument = value statements separated by semicolons. If the property value contains an equal sign ("="), ADO assumes you are providing a connection string rather than a DSN.

    ADO supports five arguments for the ConnectionString property; any other arguments pass directly to the provider without any processing by ADO. The arguments ADO supports are as follows:

    Argument

    Description

    Provider

    Specifies the name of a provider to use for the connection.

    Data Source

    Specifies the name of a data source for the connection, for example, a SQL Server database registered as an ODBC data source.

    User

    Specifies the user name to use when opening the connection.

    Password

    Specifies the password to use when opening the connection.

    File Name

    Specifies the name of a provider-specific file (for example, a persisted data source object) containing preset connection information.

    After you set the ConnectionString property and open the Connection object, the provider may alter the contents of the property, for example, by mapping the ADO-defined argument names to their provider equivalents.

    The ConnectionString property automatically inherits the value used for the ConnectionString argument of the Open method, so you can override the current ConnectionString property during the Open method call.

    Because the File Name argument causes ADO to load the associated provider, you cannot pass both the Provider and File Name arguments.

    The ConnectionString property is read/write when the connection is closed and read-only when it is open.

     

  3. ConnectionTimeout Property
  4. Indicates how long to wait while establishing a connection before terminating the attempt and generating an error.

    Settings and Return Values

    Sets or returns a Long value that indicates, in seconds, how long to wait for the connection to open. Default is 15.

    Remarks

    Use the ConnectionTimeout property on a Connection object if delays from network traffic or heavy server use make it necessary to abandon a connection attempt. If the time from the ConnectionTimeout property setting elapses prior to the opening of the connection, an error occurs and ADO cancels the attempt. If you set the property to zero, ADO will wait indefinitely until the connection is opened. Make sure the provider to which you are writing code supports the ConnectionTimeout functionality.

    The ConnectionTimeout property is read/write when the connection is closed and read-only when it is open.

     

  5. ActiveConnection Property
  6. Indicates to which Connection object the specified Command or Recordset object currently belongs.

    Settings and Return Values

    Sets or returns a String containing the definition for a connection or a Connection object reference. Default is Null.

    Remarks

    Use the ActiveConnection property to set or return an open Connection object over which the specified Command object should execute or the specified Recordset should be opened. If you pass a connection string for this argument, ADO opens a new connection using the specified parameters.

    Command

    For Command objects, the ActiveConnection property is read/write.

    If you attempt to call the Execute method on a Command object before setting this property to an open Connection object or valid connection string, an error occurs.

    Setting this property to Nothing disassociates the Command object from the current Connection and causes the provider to release any associated resources on the data source. You can then associate the Command object with the same or another Connection object. If the Parameters collection of the Command object contains parameters supplied by the provider, the collection is cleared if you set the ActiveConnection property to Nothing or to another Connection object. If you manually create Parameter objects and use them to fill the Parameters collection of the Command object, setting the ActiveConnection property to Nothing or to another Connection object leaves the Parameters collection intact.

    Closing the Connection object with which a Command object is associated sets the ActiveConnection property to Nothing. Setting this property to a closed Connection object generates an error.

    Recordset

    For open Recordset objects or for Recordset objects whose Source property is set to a valid Command object, the ActiveConnection property is read-only. Otherwise, it is read/write.

    You can set this property to a valid Connection object or to a valid connection string. In this case, the provider creates a new Connection object using this definition and opens the connection. Additionally, the provider may set this property to the new Connection object to give you a way to access the Connection object for extended error information or to execute other commands.

    If you use the ActiveConnection argument of the Open method to open a Recordset object, the ActiveConnection property will inherit the value of the argument.

    If you set the Source property of the Recordset object to a valid Command object variable, the ActiveConnection property of the Recordset inherits the setting of the Command object's ActiveConnection property.

     

  7. CommandTimeout Property
  8. Indicates how long to wait while executing a command before terminating the attempt and generating an error.

    Settings and Return Values

    Sets or returns a Long value that indicates, in seconds, how long to wait for a command to execute. Default is 30.

    Remarks

    Use the CommandTimeout property on a Connection object or Command object to allow the cancellation of a command due to delays from network traffic or heavy server use. If the time from the CommandTimeout property setting elapses prior to execution of the command, an error occurs and ADO cancels the command. If you set the property to zero, ADO will wait indefinitely until the execution is complete. Make sure the provider and data source to which you are writing code supports the CommandTimeout functionality.

    For Connection objects, the CommandTimeout property is read/write.

    When you use CommandTimeout on a Connection object, you set a global value for all commands executed and all recordsets opened on that connection. You can override this value for a specific command by setting the CommandTimeout property of the appropriate Command object.

     

  9. BOF, EOF Properties

Return Values

The BOF and EOF properties return Boolean values.

Remarks

Use the BOF and EOF properties to determine whether a Recordset object contains records or whether you've gone beyond the limits of a Recordset object when you move from record to record.

The BOF property returns True (-1) if the current record position is before the first record and False (0) if the current record position is on or after the first record.

The EOF property returns True if the current record position is after the last record and False if the current record position is on or before the last record.

If either the BOF or EOF property is True, there is no current record.

If you open a Recordset object containing no records, the BOF and EOF properties are set to True, and the Recordset object's RecordCount property setting is zero. When you open a Recordset object that contains at least one record, the first record is the current record and the BOF and EOF properties are False.

If you delete the last remaining record in the Recordset object, the BOF and EOF properties may remain False until you attempt to reposition the current record.

This table shows which Move methods are allowed with different combinations of the BOF and EOF properties.

MoveFirst,
MoveLast

MovePrevious,
Move < 0


Move 0

MoveNext,
Move > 0

BOF=True,
EOF=False

Allowed

Error

Error

Allowed

BOF=False,
EOF=True

Allowed

Allowed

Error

Error

Both True

Error

Error

Error

Error

Both False

Allowed

Allowed

Allowed

Allowed

Allowing a Move method doesn't guarantee that the method will successfully locate a record; it only means that calling the specified Move method won't generate an error.

Calling the Delete method, even if it removes the only remaining record from a Recordset, won't change the setting of the BOF or EOF property.

The following table shows what happens to the BOF and EOF property settings when you call various Move methods but are unable to successfully locate a record.

BOF

EOF

MoveFirst, MoveLast

Set to True

Set to True

Move 0

No change

No change

MovePrevious, Move < 0

Set to True

No change

MoveNext, Move > 0

No change

Set to True

 

  1. CursorType Property
  2. Indicates the type of cursor used in a Recordset object.

    Settings and Return Values

    Sets or returns one of the following CursorTypeEnum values:

    Constant

    Value

    Description

    adOpenForwardOnly

    0

    Forward-only cursor. Identical to a static cursor except that you can only scroll forward through records. This improves performance in situations when you only need to make a single pass through a recordset. (Default.)

    adOpenKeyset

    1

    Keyset cursor. Like a dynamic cursor, except that you can't see records that other users add, although records that other users delete are inaccessible from your recordset. Data changes by other users are still visible.

    adOpenDynamic

    2

    Dynamic cursor. Additions, changes, and deletions by other users are visible, and all types of movement through the recordset are allowed, except for bookmarks if the provider doesn't support them.

    adOpenStatic

    3

    Static cursor. A static copy of a set of records that you can use to find data or generate reports. Additions, changes, or deletions by other users are not visible.

    Remarks

    Use the CursorType property to specify the type of cursor that should be used when opening the Recordset object. The CursorType property is read/write when the recordset is closed and read-only when it is open.

    If a provider does not support the requested cursor type, the provider may return another cursor type. The CursorType property will change to match the actual cursor type in use when the Recordset object is open. To verify specific functionality of the returned cursor, use the Supports method. After you close the Recordset, the CursorType property reverts to its original setting.

    The following chart shows the functionality of each cursor type with respect to the Supports method constants.

    CursorType

    Supports

    adOpenForwardOnly

    none

    adOpenKeyset

    adBookmark, adHoldRecords, adMovePrevious, adResync

    adOpenDynamic

    adMovePrevious

    adOpenStatic

    adBookmark, adHoldRecords, adMovePrevious, adResync

    Note Although Supports(adUpdateBatch) may be true for dynamic and forward-only cursors, you should use batch updating only with either a keyset or static cursor.

     

  3. LockType Property

Indicates the type of locks placed on records during editing.

Settings and Return Values

Sets or returns one of the following LockTypeEnum values:

Constant

Value

Description

AdLockReadOnly

1

Read-only — you cannot alter the data.

AdLockPessimistic

2

Pessimistic locking, record by record — the provider does what is necessary to ensure successful editing of the records, usually by locking records at the data source immediately upon editing.

AdLockOptimistic

3

Optimistic locking, record by record — the provider uses optimistic locking, locking records only when you call the Update method.

AdLockBatchOptimistic

4

Optimistic batch updates — required for batch update mode as opposed to immediate update mode.

 

 

 

Remarks

Use the LockType property to determine what type of locking the provider should use when opening a Recordset object or to return the type of locking in use on an open Recordset object. The LockType property is read/write when the Recordset is closed and read-only when it is open.

Providers may not support all lock types. If a provider cannot support the requested LockType setting, it will substitute another type of locking. To determine the actual locking functionality available in a Recordset object, use the Supports method.

Note To use batch updating (adLockBatchOptimistic), you should select either a keyset or static cursor.

 

 

Developing ASP-Based Applications

An ASP-based application consists of a virtual directory on a Web server and all the folders and files within that virtual directory. For more information about virtual directories, refer to your Microsoft Web server online documentation.

An application can be a simple home page; it can include a number of dynamic elements, such as the custom home page of the MSN™ online service (www.msn.com); or it can consist of a complex set of interrelated pages and logic.

When you use ASP-based applications, you are able to maintain state. State is the ability to retain information. You can use ASP to maintain two types of state:

  • Application state, in which all information pertaining to an application is available to all users of an application.
  • Session state, in which information is available only to a user of a specific session.

The ASP tools you use to manage state are the Session and Application built-in objects.

Using the Session and Application Objects

You can use the ASP built-in objects Session and Application to extend the functionality of your ASP-based applications.

Use the Session object to manage information for a user when that user is using an application. A session belongs, in effect, to a single user. The Application object is used to store common information that can be shared between all users of a single ASP-based application.

Using the Global.asa File

Each ASP-based application can have one Global.asa file. (The file name extension .asa stands for "Active Server Application.") This file must be stored in the root directory of the application. ASP reads a Global.asa file when:

  • The Web server receives the first post-startup request for any .asp file in a given application; that is, after the Web server starts, the first request for any .asp file in an application causes ASP to read the Global.asa file for that application.
  • A user who does not have a session requests an .asp file in an application.

You can include the following in a Global.asa file:

Refer to Global.asa Reference for more information.

Application-Start and Session-Start Events

The application-start and session-start events are Application_OnStart and Session_OnStart, respectively. You should include in these procedures scripts that you want to run whenever an application or session starts. If an application and a session start at the same time, ASP processes the application-start event before it processes the session-start event.

Use the following syntax to define an application-start event:

<SCRIPT LANGUAGE=VBScript RUNAT=Server> 
Sub Application_OnStart
  ' This is where you would insert script for an application-start event.
End Sub
</SCRIPT> 

To create an instance of the Ad Rotator component whenever a session starts, you could define the following procedure:

<SCRIPT LANGUAGE=VBScript RUNAT=Server> 
Sub Session_OnStart
  Set Session("MyAd")=Server.CreateObject("MSWC.Adrotator")
End Sub 
</SCRIPT> 

Application-End and Session-End Events

The application-end and session-end events are Application_OnEnd and Session_OnEnd, respectively. Like the application-start and session-start events, these events are procedures that you include in a Global.asa file. Unlike start events, end events occur only when a session or application ends; thus, you should include in them any scripts that you want to run at those times. If a session and an application end at the same time, ASP processes the session-end event before it processes the application-end event.

Use the following syntax to define a session-end event:

<SCRIPT LANGUAGE=VBScript RUNAT=Server> 
Sub Session_OnEnd
  ' This is where you would insert script for a session-end event.
End Sub
</SCRIPT> 

Use the following syntax to define an application-end event:

<SCRIPT LANGUAGE=VBScript RUNAT=Server> 
Sub Application_OnEnd
   'This is where you insert script for an application ending event.
End Sub 
</SCRIPT> 

Ending a Session

A session automatically ends if a user has not requested or refreshed a page in an application for a specified period of time. This value is 20 minutes by default. (Refer to Configuring Registry Entries for information about changing the default value).

You can explicitly end a session with the Abandon method of the Session object. For example, you can provide a Quit button on a form with the ACTION parameter set to the URL of an .asp file that contains the following command.

<% Session.Abandon %> 

If, for a specific session, you want to set a timeout interval that is longer than the 20-minute default, you can set the Timeout property of the Session object. For example, the following script sets a timeout interval of 30 minutes.

<%  Session.Timeout = 30  %> 

Note You cannot set the timeout interval to be less than the default value.

Ending an Application

An application ends when the Web server is shut down.

Managing Sessions

You can use the Session object to set objects or variables to have session scope. Scope is the extent to which a component instance, object, or variable is available within Active Server Pages. A variable that has session scope, then, is accessible only within that session.

A session can begin in three ways:

SessionID and Cookies

The first time a user requests an .asp file within a given application, ASP generates a SessionID, then sends a response to the user’s browser to create a cookie for the SessionID. The SessionID is a number produced by a complex algorithm that identifies the user’s session. The SessionID cookie is a token sent to a client browser that is not stored on the client computer's hard disk because it does not set an expiration date.

Note While most browsers support cookies, some do not. If a user’s browser does not support cookies, ASP does not support the Session object for that browser.

The SessionID cookie is similar to a locker key in that, as the user interacts with an application during a session, ASP can store information for the user in a "locker" on the server. The user’s SessionID cookie, which it sends in the HTTP request header, enables access to this information in the way that a locker key enables access to a locker’s contents. Each time that ASP receives a request for a page, it checks the HTTP request header for a SessionID cookie.

Storing Variables in the Session Object

You need only reference a new variable in order to create and store the variable in the Session object. For example, the following commands store three new variables in the Session object:

<% 
Session("Initiated") = Now 
Session("Fidelity") = "Low" 
Set Session("myObj") = Server.CreateObject("someObj") 
%>
 

Remembering User Preferences

You can store user preferences in the Session object. For example, you can allow a user to specify a text-only version of your content in the first page of the application and apply this choice on all subsequent pages that the user visits in this application.

<%If Session("Fidelity") = "Low" Then %> 
This is the text version of the page.
<% Else %> 
This is the multimedia version of the page.
<% End If %> 

Managing Applications

You can use the Application object to set properties that are accessible to every user in an ASP-based application.

Posting Messages to Application Users

You can use the Application object to post a message that each user of the application sees on entering the application. This section shows an example in which you define an application property called message in an Application_OnStart procedure, then enable subsequent users to modify the message.

The application-wide message is given a default value in Global.asa:

<SCRIPT LANGUAGE=VBScript RUNAT=Server> 
Sub Application_OnStart
  Application("Message") = "This is the default message." 
End Sub
</SCRIPT> 

A.asp displays the message. Every user who requests A.asp can see the global message.

<HTML> 
<BODY>
This is the message: <p> 
<%= Application("Message") %>
</BODY>
</HTML> 

B.asp provides a way for a user to type a new message and submit the change.

<HTML> 
<BODY>
<form method="post" action="C.asp"> 
Enter a new value for the application-wide message:<BR> 
<input type="text" name="newmsg" size=60><p> 
<input type="submit" value="Submit"> 
</form> 
</BODY>
</HTML> 

C.asp resets the global message to the value received from a user in B.asp and redirects the user to A.asp to see the new value.

<% 
If Not IsEmpty(Request.Form("newmsg")) Then 
  Application.Lock
    Application("Message") = Request.Form("newmsg") 
  Application.Unlock
End If 
Response.Redirect("A.asp") 
%>

Setting Component Scope

An ASP-based application can set ActiveX server components to have application, session or page scope.

  • An application-scope component instance is a single instance of a component that is created when the application starts. This instance is shared by all client requests.
  • A session-scope component instance is created for each new session in an application and released when the session ends; thus, there is one instance per active session.
  • A page-scope component instance is created for the processing of a page for one client; it is available through the processing of that page; and is then released when the response is sent back to the client. A component instance has page scope by default.

You can use either the <OBJECT> tag in a Global.asa file or the Server.CreateObject method to store instances of ActiveX server components in Session and Application objects.

Using the <OBJECT> Tag

You can declare component instances with session or application scope in a Global.asa file by using the <OBJECT> tag, extended with RUNAT attribute (which must be set to Server) and SCOPE attribute (which can be set to Session or Application). You can accomplish this by using either the registered name (PROGID) method or the registered number (CLASSID) method.

The following example uses the registered name (PROGID) method to create a session-scope instance of the Ad Rotator Component:

<OBJECT RUNAT=Server SCOPE=Session ID=MyAd PROGID="MSWC.Adrotator">
</OBJECT>

The following uses the registered number (CLASSID) method to create an application-scope instance of the Ad Rotator Component:

<OBJECT RUNAT=Server SCOPE=Application ID=MyAd 
CLASSID="Clsid:00000293-0000-0010-8000-00AA006D2EA4"></OBJECT> 

When you declare a session-scope or application-scope instance of a component by using the <OBJECT> tag, the variable you assign to the component goes into the session or application namespace, respectively. This means that you do not need to use the Session or Application built-in objects to access the component instance. For example, the following script command, issued from within any .asp file that is part of the application containing the examples shown above, would open the instance of the Ad Rotator component declared in those examples:

<%= MyAd.GetAdvertisement("addata.txt") %> 

You can also use the <OBJECT> tag to create ActiveX server component instances in a particular .asp file. In this case the SCOPE attribute can be omitted, or set to PAGE. All such component instances have page scope.

Using the Server.CreateObject Method

You can use the Server.CreateObject method to store an instance of a component in the Session object. The following example stores an instance of the Ad Rotator component in the Session object.

<% Set Session("MyAd") = Server.CreateObject("MSWC.Adrotator") %> 

To display an ad, you would include the following:

<% Set MyAd = Session("MyAd") %> 
<%= MyAd.GetAdvertisement("addata.txt") %> 

Performance Issues

ASP does not instantiate a component that you declare with the <OBJECT> tag until that component is referenced by a script command from an .asp file. The Server.CreateObject method instantiates the component immediately. Thus, the <OBJECT> tag offers better performance than the Server.CreateObject method for session-scope components.

For creating page-scope components, the <OBJECT> tag and the Server.CreateObject method offer equivalent performance.

You can use the <OBJECT> tag to store single-threaded, free-threaded, or apartment-threaded objects in both the Session and the Application objects. You can use the Server.CreateObject method to store single-threaded, free-threaded, and apartment-threaded objects in the Session object. However, whether you use the <OBJECT> tag or the Server.CreateObject method, unless the object you store is marked "both," ASP treats the application or session containing this object as "single-threaded." Thus, storing objects that are not marked "both" may have performance implications, particularly for high-volume sites. Refer to Creating Components for ASP for more information on threading models.