Site hosted by Angelfire.com: Build your free website today!

Prerequisites : HTML & VB

Active Server Pages

Dynamic HTML provides the primary client-side programming tool for Microsoft Internet Explorer version 4.0. But Dynamic HTML is not supported by browsers such as Netscape Navigator. In fact, very little of the client-side functionality supported by various browsers can be considered truly cross-platform.

If you want to design an Internet site accessible to a number of different browsers, you need to move the programming from the client to the server. Microsoft Active Server Pages (ASP) allows you to create server-side applications that can be used by a variety of browsers. ASP is essentially nothing more than VBScript that runs on the server. The script code generates HTML when a page is requested. That is the key to ASP: a client never sees your code—only the resulting HTML, which can be recognized by any browser.

Active Server Pages Fundamentals

Listing 5-1 produces a simple ASP page that generates a greeting based on the time of day. In this example, the hour of the day is determined by using the code Hour(Now), where Now is a VBScript function that returns the current date/time stamp. If the hour is less than 12, a variable is assigned the greeting "Good Morning!" From noon to 6 PM, the message is "Good Afternoon!" and after 6 PM, "Good Evening!"

Listing 5-1. A simple ASP example.


<%@ LANGUAGE="VBSCRIPT"%>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<HTML>

<HEAD>
<META HTTP-EQUIV="Content-Type"
    CONTENT="text/html; CHARSET=iso-8859-1">

<META NAME="GENERATOR" 
    CONTENT="Microsoft FrontPage 2.0">
<TITLE>Simple ASP Example</TITLE>
</HEAD>

<BODY BGCOLOR="#FFFFFF">
<%
Dim strGreeting

If Hour(Now) < 12 Then
    strGreeting = "Good Morning!"
ElseIf Hour(Now) > 11 And Hour(Now) < 18 Then
    strGreeting = "Good Afternoon!"
ElseIf Hour(Now) > 17 Then
    strGreeting = "Good Evening!"
End If
%>
<H1><%=strGreeting%></H1>
</BODY>
</HTML>

Notice that the code structure in the listing is surrounded by special characters—angle brackets and percent signs (<%…%>). These symbols designate the code as server-side code, which means that the code will be evaluated before the page is actually sent to the browser. In fact, if you were to view the resulting HTML from Listing 5-1 in Internet Explorer, you would see the following (assuming it's afternoon, of course!):

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<HTML>

<HEAD>
<META HTTP-EQUIV="Content-Type"
    CONTENT="text/html; CHARSET=iso-8859-1">
<META NAME="GENERATOR" 
    CONTENT="Microsoft FrontPage 2.0">
<TITLE>Simple ASP Example</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">

<H1>Good Afternoon!</H1>
</BODY>
</HTML>

This is the point of using ASP. The result of the code is simply HTML! This page is visible in any browser and will work in Netscape Navigator as well as in Internet Explorer. ASP provides true platform independence for the Internet developer.

Listing 5-1 contains a few other features that are worth mentioning. Notice the line of code at the top of the page—the code that specifies the language that will be used for the page:

<%@ LANGUAGE="VBSCRIPT"%>

Normally, you would use VBScript as the language, but ASP also supports JavaScript. Unlike client-side scripting, the choice of language here has no impact on browser compatibility since the code is all executed on the server. You simply code using the language that makes you comfortable.

Also notice the line of code where the HTML is actually generated. The code uses the variable to write the greeting, as follows:

<H1><%=strGreeting%></H1>

The variable strGreeting is enclosed by the angle brackets and percent signs used in the rest of the server-side code, but it is also preceded by an equal sign. The equal sign plays an important role in ASP, telling ASP to insert the actual value of the variable in the page as HTML. Therefore, the value of the greeting is inserted at this point and is seen in the browser as text content.

 

Objects and Components

At the simplest level, creating an ASP page is nothing more than writing server-side code to produce the result you have in mind. VBScript, however, is not a fully functional language, and it falters when you try to create more complex pages. For example, VBScript has no intrinsic functions to allow data access, nor can it open text files. In fact, VBScript has no intrinsic functions that allow access to any external data sources. How, then, can you use ASP to perform advanced functions such as data access? The answer is that you supplement VBScript with ASP objects and components.

ASP objects and components are nothing more than ActiveX components, like any ActiveX DLLs you might use in Microsoft Visual Basic. The difference between ASP objects and ASP components lies in the way they are packaged. ASP objects are ActiveX elements that are always available to VBScript. You do not have to explicitly create ASP objects for your use. ASP supports the Application, Session, Request, Response, and Server objects. ASP components, on the other hand, are DLLs that exist outside the ASP framework. These components can be created in any language, but Microsoft has packaged several useful ASP components with Visual InterDev. ASP components are not available unless they are specifically created in code. ASP supports the Database Access, File Access, Browser Capabilities, Ad Rotator, and Content Linking components.

 

The GLOBAL.ASA File

One of the biggest concerns facing Internet developers, regardless of the technology they use, is the difficulty of creating a true application on the Internet. The interaction between a browser and a Web server is basically a stateless transaction in which the server hands a Web page to the client and then forgets that the client even exists. When the client subsequently asks for another Web page, the server has no memory of the first request. The essential problem for all Web applications is this: How do you define an application?

Defining an application in the Microsoft Windows environment is simple. The application starts when the icon is double-clicked, and the application ends when Exit is chosen from the File menu. In between these two events, data can easily be remembered in variables. However, this is not true for Internet applications. How can you determine when an application begins and ends? If a user comes to a site and views a page, you might say that the application has started. But what if the user jumps to another site and returns five minutes later? Is the application still live? What if the user leaves for an hour? Two hours?

This problem of defining the beginning and ending of an application affects the ability to correctly manage variables and work flow. Fortunately, Active Server Pages provides a solution. ASP uses a special file, named GLOBAL.ASA, to define the beginning and ending of an application as well as the beginning and ending of an individual user's session. GLOBAL.ASA is responsible for detecting four key events in your site: Application_OnStart, Application_OnEnd, Session_OnStart, and Session_OnEnd. Listing 5-2 shows a typical GLOBAL.ASA file.

Listing 5-2. GLOBAL.ASA.


<SCRIPT LANGUAGE="VBSCRIPT" RUNAT="Server">

' You can add special event handlers in this file, which 
' will be run automatically when special Active Server 
' Pages events occur. To create these handlers, add
' a subroutine with a name from the list below that 

' corresponds to the event you want to use. For example, 
' to create an event handler for Session_OnStart, you would 
' put the following code into this file (without the 
' comments):
'
' Sub Session_OnStart
'     **Put your code here **
' End Sub

' EventName               Description
' Session_OnStart         Runs the first time a 
'                         user runs any page in 
'                         your application
' Session_OnEnd           Runs when a user's session 
'                         times out or quits your 
'                         application
' Application_OnStart     Runs once when the first 
'                         page of your application 
'                         is run for the first time 
'                         by any user
' Application_OnEnd       Runs once when the Web 
'                         server shuts down

</SCRIPT>

<SCRIPT LANGUAGE=VBScript RUNAT=Server>
    Sub Session_OnStart

    End Sub

    Sub Session_OnEnd

    End Sub

    Sub Application_OnStart

    End Sub

    Sub Application_OnEnd

    End Sub

</SCRIPT>

GLOBAL.ASA contains <SCRIPT> tags to designate scripting sections. These tags contain a special attribute named RUNAT=Server, which specifies that the contained VBScript should run on the server, not on the client. RUNAT=Server is similar in functionality to the angle bracket/percent sign symbols used in the Web page to designate server-side scripting. The events in GLOBAL.ASA can be trapped on the server side using standard syntax. For example, trapping the start of an application is accomplished with the following code:

<SCRIPT LANGUAGE=VBScript RUNAT=Server>
    Sub Application_OnStart
        ` Application-specific code
    End Sub
</SCRIPT>

Although the GLOBAL.ASA file uses events to mark the beginning and ending of an application, it is still not clear what constitutes an application. One working definition, offered by Microsoft, defines an Internet application as a virtual directory and all of its pages. If a user requests a Web page from a virtual directory named Bookstore, the user has started the Bookstore application and the Application_OnStart and Session_OnStart events will fire in GLOBAL.ASA.

By this definition, an application can be used by many browsers at the same time. The Application_OnStart event fires only once—when the first user requests a Web page from the virtual directory. When other users then request pages from the same directory, only the Session_OnStart event fires.

While application can refer to multiple browsers accessing the same set of Web pages, session refers to an individual browser accessing the same Web pages. A session for an individual browser lasts as long as the user continues to request Web pages from the virtual directory. If the user stops requesting additional Web pages for 20 minutes, the session ends and the Session_OnEnd event fires. When all user sessions in the virtual directory have ended, the Application_OnEnd event fires.

As an example, consider the following scenario. Two users are about to access the Magazine application on a Web site. User1 accesses first and requests the Web page DEFAULT.ASP. At this moment, the Application_OnStart and Session_OnStart events fire.

Just 5 minutes later, User2 accesses the same application. Because User1 has been active in the last 20 minutes, the Magazine application is still live. Therefore, only the Session_OnStart event fires, signaling the beginning of a second user session. Additionally, the site will now require that both the User1 and User2 sessions end before the application can be closed.

During the next 15 minutes, User1 does not access any pages in the Magazine application. Because User1 has been inactive for 20 minutes, ASP concludes that the session for User1 has ended and the Session_OnEnd event fires. The application is still active, however, because User2 has requested a page in the last 20 minutes.

User2 remains active for an hour, reading magazine articles by requesting Web pages. Finally, though, User2 shuts down the computer, and 20 minutes after User2 leaves the site, the Session_OnEnd event fires. Because User2 is the last user of the application, the application terminates and the Application_OnEnd event fires.

Active Server Pages Objects

ASP hosts a number of built-in objects that are available to the developer. These objects help manage everything from variables to form submission. The objects are simple to use and can be called directly from code without any special syntax. In this section, we examine the ASP objects available in Visual InterDev for the Internet developer.

Application Object

The Application object allows you to create application variables, variables that are available to all users of an application. All users who request Web pages from the same virtual directory can share any application variables defined in those pages.

Listing 5-3 shows a code sample that uses the Application object. In this example, an application variable is used to track the last time the page was visited.

Listing 5-3. The Application object.


<%@ LANGUAGE="VBSCRIPT"%>
<HTML>
<HEAD>
<TITLE>Application Variables</TITLE>
</HEAD>

<BODY BGCOLOR="FFFFFF">

This page was last visited on <%=Application("Time")%>

<%Application.Lock%>
<%Application("Time") = Now%>
<%Application.Unlock%>

</BODY>
</HTML>

Creating an application variable is a simple matter of addressing the Application object with the name of the new variable you want to create. For example, the following code produces an application variable named Company and sets its value to NewTech:

Application("Company") = "NewTech"

The name is arbitrary, and the variable can contain any kind of information, whether numbers or text.

Because the variable is available to a number of users simultaneously, you must deal with concurrency; that is, you cannot guarantee that two users will not try to set the variable to different values at the same time. To deal with this situation, the Application object supports Lock and Unlock methods. The Lock method locks the entire Application object, not just the variable you are changing, so always unlock the Application object immediately after changing a variable value:

Application.Lock
Application("Company") = "NewTech"
Application.Unlock

Although application variables are useful for temporary storage of data, they can't be used to store data permanently. The data in an application variable is destroyed when the Application_OnEnd event fires. Be sure to move application variables to permanent storage, such as a database, if you want to save the values after the application terminates.

 

Session Object

In programming applications, developers are often less concerned about data shared by many users and more concerned about data related to an individual user. ASP supports variables for individual users through the Session object, which allows you to create session variables for use by individuals.

Listing 5-4 shows how to define some session variables in the GLOBAL.ASA file. Defining session variables is just as simple as defining application variables. All you have to do is address the Session object with the name of the variable you want to define. The big difference between application and session variables is the scope. Session variables are reserved for just one user and last as long as the user continues the session. Once the user stops requesting pages from a given virtual directory for 20 minutes, the data is gone.

Listing 5-4. Creating session variables.


<SCRIPT LANGUAGE="VBScript" RUNAT="Server">

' You can add special event handlers in this file, which 
' will be run automatically when special Active Server 
' Pages events occur. To create these handlers, add
' a subroutine with a name from the list below that 
' corresponds to the event you want to use. For example, 
' to create an event handler for Session_OnStart, you would 
' put the following code into this file (without the 
' comments):
'
' Sub Session_OnStart
'     **Put your code here **
' End Sub

' EventName               Description
' Session_OnStart         Runs the first time a 
'                         user runs any page in 
'                         your application
' Session_OnEnd           Runs when a user's session 
'                         times out or quits your 
'                         application
' Application_OnStart     Runs once when the first 
'                         page of your application 
'                         is run for the first time 
'                         by any user
' Application_OnEnd       Runs once when the Web 
'                         server shuts down

</SCRIPT>

<SCRIPT LANGUAGE=VBScript RUNAT=Server>
    Sub Session_OnStart
        Session("Company") = "NewTech"
        Session("EMail") = "info@vb-bootcamp.com"
    End Sub
</SCRIPT>

Session variables can be created in any Web page or GLOBAL.ASA file, and they can be accessed from any Web page in the application where the variables were originally defined. You can retrieve the values of session variables by reading them out of the Session object. The following code reads the session variables established in Listing 5-4 and displays them in text fields:

<FORM>
<P><INPUT VALUE=<%=Session("Company")%>>Company</P>
<P><INPUT VALUE=<%=Session("EMail")%>>E-Mail</P>
</FORM>

Earlier in this chapter, Internet applications were described as stateless transactions between a Web server and a browser. If Internet applications are stateless, how does ASP remember session variables for each user of an application? The answer is that the session variables are saved on the server for each client. The browser itself receives a unique identifier that tells the server which set of data belongs to that client. The client stores the identifier, called a Globally Unique Identifier (GUID), and uses it later to retrieve the data stored by the server. Thus, each client can have individual data for each application used on the Internet.

Request Object

An Internet application certainly differs in many ways from a typical client/server application, but they are similar in that the application absolutely depends upon the transfer of data between client and server. When a Web server wants to send data to a client, it does so by creating a Web page and sending it. When a client wants to return data to the Web server, the browser relies on the process of form submission.

To send data to a Web server, a client utilizes a form with <FORM> tags, which contain data input fields such as text boxes. The client packages the entered data into the data fields and subsequently submits the package to the back end.

The process of submitting a form is controlled by two attributes of the <FORM> tag: METHOD and ACTION. The METHOD attribute of the <FORM> tag determines how the data is sent to the server. This attribute has two possible values: POST and GET. POST tells the browser to package all data inside the form and send it to the server. GET, on the other hand, sends the data as an integral part of the Uniform Resource Locator for the target page. The ACTION attribute specifies the target page for the submitted data. The following code, for example, sends all data from the text fields to a page named DATA.ASP by the POST method:

<FORM METHOD="POST"
    ACTION="http://www.vb-bootcamp.com/data.asp">
<P><INPUT TYPE="TEXT" NAME="txtName"></P>
<P><INPUT TYPE="TEXT" NAME="txtEMail"></P>
<P><INPUT TYPE="SUBMIT"></P>
</FORM>

The special control designated in the form as TYPE="SUBMIT" is a button that is clicked by the user when the form is ready for submission. Clicking the button causes the browser to package the data in the text fields and submit it. The format of the submitted data is strictly defined so that the server knows what to expect from the client. The data takes the form of Field=Value pairs sent to the server in clear text format. If, in the preceding example, you typed NewTech into the txtName field and Info into the txtEMail field, the following text would be sent to the page DATA.ASP:

txtName=NewTech&txtEMail=Info

On the server side, this data could then be parsed back into fields and values and used by the server for any purpose, including data access or creating and sending e-mail. This is where the Request object comes in. The Request object is used by ASP to parse submitted data received from a client. To use the Request object, simply provide the name of the field you would like to examine, and the Request object returns the value. For example, the following code would return the value NewTech:

<%=Request.Form("txtName")%>

Request.Form is used anytime you want to examine the contents of a form submitted to an ASP page. The Request object is available only to ASP pages and can return data only from a form submitted directly to your page. You cannot access data from forms that were not submitted to your page.

Many Internet applications use sequential form submission to accomplish a task such as drilling into a database. However, there are times when a user does not need to fill out a form and submit it and would rather simply click a hyperlink to view data. This too can be accomplished by using the Request object.

Creating a hyperlink that is capable of submitting data requires an anchor, or <A>, tag. The anchor tag uses the HREF attribute to designate a target page and to carry data to the target page when the user clicks the link. A question mark (?) separates the target page and the data. Consider the example in which the form submitted txtName and txtEMail fields. If you wanted to submit the same data using a hyperlink, you might write this code:

<A HREF=
"http://www.vb-bootcamp.com/data.asp?txtName=NewTech&txtEMail=Info">
Click here to submit data!
</A>

Notice how the data attached to the hyperlink takes the format Field=Value, just as it does in a submitted form. As long as you provide the data in this format, the Request object will be able to parse it. Strangely, you cannot use the syntax Request.Form on data submitted through a hyperlink. Instead, you must use Request.QueryString, which works in the same way as Request.Form but is used on data submitted by a hyperlink. Thus, the following code returns the value NewTech from the hyperlink:

<%=Request.QueryString("txtName")%>

The Request object has several other uses as well. You can, for example, use Request to retrieve all kinds of information about the client. You can access everything from cookies sent with the client's request to the user agent string of the browser. Listing 5-5 shows a simple example of using the ServerVariables collection of the Request object to determine the Microsoft Windows NT account that the client is logged on to.

Listing 5-5. Determining the Windows NT logon account.


<%@ LANGUAGE="VBSCRIPT"%>

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual InterDev 1.0">
<META HTTP-EQUIV="Content-Type" content="text/html; 
    charset=iso-8859-1">
<TITLE>Server Variables</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">

<H1>
You are logged in under <%=Request.ServerVariables("LOGON_USER")%>
</H1>

</BODY>
</HTML>

Server variables provide a wide range of information about the client and the Web server. Complete documentation of all variables supported in this collection can be found in Visual InterDev, but accessing any particular variable is simply a matter of reading the collection. For example, the following code returns the user agent string of the client browser:

<%=Request.ServerVariables("HTTP_USER_AGENT")%> 

Response Object

The Response object manages the content returned to a browser by ASP. In fact, although you might not realize it, you use the Response object in every ASP page. When you use the angle bracket/percent sign/equal sign combination (<%=variable%>) to return ASP-generated content, the equal sign is actually shorthand for the Write method of the Response object. Therefore, the following two lines of code are equivalent:

<%="NewTech"%>
<%Response.Write "NewTech"%>

Because the Response object is used so frequently in ASP, the equal sign shorthand makes a lot of sense. Otherwise, you would have to type countless iterations of Response.Write into every ASP page.

Another useful feature of the Response object is the Expires property. Response.Expires specifies the time in minutes before the current page expires. If this property is set to zero, the Web page expires the moment it is downloaded and Internet Explorer will not cache the page.

Caching in Internet Explorer version 4.0 affects many development efforts and can prevent your site from behaving correctly. IE 4.0 actually caches pages in two ways: to disk and to memory. Most developers and users are familiar with page caching to disk and expect this to occur, but most people do not realize that IE 4.0 also caches pages to memory. In fact, IE 4.0 remembers in RAM the last five pages that were viewed. This can have a significant impact on the way your application behaves. Consider the following simple code to show a date/time stamp in a Web page:

<H1>The time is now <%Response.Write Now%>

Under normal conditions, IE 4.0 requests this page and the server script is run, causing the current time to appear on the page. However, if the browser moves to another page and then back to the page with the date/time stamp, the time will not change. This is because IE 4.0 has cached the results of the ASP page in RAM and does not request a new page when the browser returns. This behavior will continue until the user visits five different pages, after which the first page is flushed from the RAM cache.

You can prevent this caching behavior by setting the Expires property of the Response object to 0, forcing the Web page to expire. The complete code in Listing 5-6 displays the correct time whenever the page is visible—regardless of whether it is in the RAM cache.

RAM caching can cause strange effects at design time as well. Developers often make changes to a Web page in Visual InterDev, browse it, and wonder why the changes do not appear in the new page. This usually happens because the old version of the page is still in the RAM cache and IE 4.0 does not load the changed page. Therefore, when developing pages in Visual InterDev, always reload your page into the browser after making changes.

Listing 5-6. Forcing a page to expire.


<%@ LANGUAGE="VBSCRIPT"%>
<%Response.Expires = 0%>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual InterDev 1.0">
<META HTTP-EQUIV="Content-Type" content="text/html; 
    charset=iso-8859-1">
<TITLE>Forcing a Page to Expire</TITLE>
</HEAD>
<BODY BGCOLOR="white">
<H1>The time is now <%Response.Write Now%>

</BODY>
</HTML>

Server Object

The Server object is a sort of catchall object, providing functions that are not related to each other in any way except that they are useful to the Internet developer.

Perhaps the most important of all the Server object functions is the CreateObject method, which creates an instance of an ActiveX component. The component can be either a built-in component that ships with Visual InterDev (discussed in the next section) or a component you make yourself in any language. In any case, using a server-side ActiveX component requires the CreateObject method.

CreateObject takes as an argument the ProgID of the ActiveX component that you want to use. A ProgID is a descriptive name for a component such as Excel.Sheet or Word.Basic. The following code shows how you could use the CreateObject method to generate an instance of an e-mail component that has a ProgID of Mail.Connector.

Set MyObject = Server.CreateObject("Mail.Connector")

Active Server Pages Components

ASP components are really just ActiveX components—like any you might create in Visual Basic, Visual C++, or even Visual J++. These special components, however, are written by Microsoft and ship with Visual InterDev. They are designed to perform useful, generic tasks for Web sites, including data access. You create these components in your Web page by using the CreateObject method of the Server object. Once they are created, you can access their properties and methods to perform functions in your site.

Database Access Component (ActiveX Data Objects)

The most useful of all the ASP components has to be the Database Access component, also called the ActiveX Data Objects, or ADO. Database publishing on the Web utilizes this component, and the objects contained in it, to read and write to Open Database Connectivity (ODBC) data sources.

The Connection object is created through the CreateObject method of the Server object and uses a variable to receive the object reference. Once the Connection object is created, it can be used to open a connection to any ODBC data source. The following code establishes a connection to a SQL Server ODBC source named Publications:

<%
    ` Declare a variable
    Dim objConnection

    ` Create the Connection object
    Set objConnection = Server.CreateObject("ADODB.Connection")

    ` Open the data source connection
    objConnection.Open "Publications", "sa", ""
%>

In this code, objConnection is the variable used as an object reference to the instance of the Connection object. This reference can access all the properties and methods of the Connection object. The Open method establishes the data source connection and has three arguments: data source name, user ID, and password.

When the data source connection is open, you can use a Recordset object to retrieve information from the data source. The Recordset object allows you to run an SQL SELECT statement and returns a set of records matching the statement. Like the Connection object, the Recordset object is created by using the Server object. In the following example, the program runs an SQL SELECT statement on the data source represented by the variable objConnection:

<%
    ` Declare a variable
    Dim objRecordset

    ` Create the Recordset object
    Set objRecordset = Server.CreateObject("ADODB.Recordset")

    ` Run the SQL query
    objRecordset.Open "SELECT *", objConnection
%>

After the records are retrieved, you can use the MoveFirst, MoveLast, MoveNext, and MovePrevious methods to navigate the records. The Write method of the Response object can place the data onto a Web page, which is then passed to a browser. Listing 5-7 shows a complete sample ASP page that builds a list box of publishing companies contained in a Publications data source.

Listing 5-7. Building a data list with ADO.


<%@ LANGUAGE="VBSCRIPT"%>

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual InterDev 1.0">
<META HTTP-EQUIV="Content-Type" content="text/html; 
    charset=iso-8859-1">
<TITLE>Using ADO</TITLE>
</HEAD>
<BODY>


<%
    ' Declare variables
    Dim objConnection
    Dim objRecordset
    ' Create objects
    Set objConnection = Server.CreateObject("ADODB.Connection")
    Set objRecordset = Server.CreateObject("ADODB.Recordset")

    ' Open connection and run query
    objConnection.Open "Publications", "sa", ""
    objRecordset.Open "SELECT pub_name FROM Publishers", objConnection
%>

<!-- Build SELECT list from recordset -->
<SELECT SIZE=8>
<%
    Do While Not ObjRecordset.EOF
%>

<!-- Create each entry in the list -->
<OPTION><%=objRecordset("pub_name")%></OPTION>

<%
        objRecordset.MoveNext
    Loop
%>
</SELECT>

</BODY>
</HTML>

Managing the information in a Recordset object is one of the primary programming tasks in any data-driven Web application. Often a simple query returns many more rows of data than can be reasonably displayed. For example, consider what happens when you use any Internet search engine. The engine accepts a keyword and then returns links to sites with references to the requested topic. Many times, however, there are thousands of Internet sites that contain the requested keyword. Showing all the sites at once on a single Web page is obviously impossible.

The answer to large query-result sets is paging. Paging is used by all search engines to return a portion of the query results—say, 10 records at a time—so that the user can effectively manage the information returned. ADO supports paging through several properties of the Recordset object: PageSize, PageCount, and AbsolutePage.

When you use ADO to retrieve a recordset, you can specify that the records be divided into pages. Setting a value for the PageSize property specifies the number of rows from the recordset that will constitute a page. Then you can determine the total number of pages in a recordset through the PageCount property. Accessing any given page is accomplished with the AbsolutePage property.

Listing 5-8 provides a complete paging example that allows a user to browse records 10 at a time. In this example, a session variable named CurrentPage is used to track the page currently in use. The user can click two hyperlinks to navigate to the previous set or next set of 10 records.

Listing 5-8. Paging with ADO.


<%@ LANGUAGE="VBSCRIPT"%>
<%Response.Expires = 0%>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual InterDev 1.0">
<META HTTP-EQUIV="Content-Type" content="text/html; 
    charset=iso-8859-1">
<TITLE>Paging Records</TITLE>
</HEAD>
<BODY>
<%

    ' What page are we on?
    Select Case Request.QueryString("Direction")
        Case ""
            Session("CurrentPage") = 1
        Case "Next"
            Session("CurrentPage") = Session("CurrentPage") + 1
        Case "Previous"
            Session("CurrentPage") = Session("CurrentPage") - 1
    End Select

    ' Constants
    Const adOpenKeyset = 1

    ' Declare variables
    Dim objConnection
    Dim objRecordset

    ' Open database
    Set objConnection = Server.CreateObject("ADODB.Connection")
    objConnection.Open "Biblio", "", ""

    ' Create the SQL statement
    Dim strSQL
    strSQL = strSQL & "SELECT Authors.Author, Titles.Title, "
    strSQL = strSQL & "Publishers.`Company Name` FROM Authors, "
    strSQL = strSQL & "`Title Author`, Titles, Publishers "
    strSQL = strSQL & "WHERE Authors.Au_ID = `Title Author`.Au_ID "
    strSQL = strSQL & "AND `Title Author`.ISBN = Titles.ISBN "
    strSQL = strSQL & "AND (Publishers.`Company Name` LIKE "
    strSQL = strSQL & "'%Microsoft%') ORDER BY Authors.Author"

    ' Create recordset
    Set objRecordset = Server.CreateObject("ADODB.Recordset")
    objRecordset.PageSize = 10
    objRecordset.Open strSQL, objConnection, adOpenKeyset
    objRecordset.AbsolutePage = CLng(Session("CurrentPage"))

    ' Show the results
%>

<P>Page <%=Session("CurrentPage")%> of <%=objRecordset.PageCount%>
</P>

<TABLE BORDER>
        <TR>
        <TH>
        Author
        </TH>
        <TH>
        Title
        </TH>
        <TH>
        Publisher
        </TH>
        </TR>
<%
    Dim i
    For i = 1 To objRecordset.PageSize
%>

        <TR>
        <TD>
        <%=objRecordset("Author")%>
        </TD>
        <TD>
        <%=objRecordset("Title")%>
        </TD>
        <TD>
        <%=objRecordset("Company Name")%>
        </TD>
        </TR>
<%
        objRecordset.MoveNext
    Next
%>
</TABLE>

<!-- NEXT hyperlink -->
<%If CLng(Session("CurrentPage")) < objRecordset.PageCount Then %>
<P><A HREF="paging.asp?Direction=Next">Next Page</A></P>
<%End If%>

<!-- PREVIOUS hyperlink -->
<%If CLng(Session("CurrentPage")) > 1 Then %>
<P><A HREF="paging.asp?Direction=Prev">Previous Page</A></P>
<%End If%>

<%
    ' Close database
    objRecordset.Close
    objConnection.Close
    Set objRecordset = Nothing
    Set objConnection = Nothing
%>

</BODY>
</HTML>

The example utilizes several techniques that are worth discussing. Notice first that the program requires only a single ASP file to accomplish the entire paging process. The same ASP file is called again and again for each page of data. Normally, when a page is called, Internet Explorer provides the page from RAM, if available. In the example, the page will always be in RAM because it is called recursively.

The problem with retrieving a page from RAM, however, is that your query will not be executed unless you run the server-side code. You have to prevent IE 4.0 from using the ASP file already in RAM. To force a return to the server, set the Expires property of the Response object to zero. This code forces a refresh of the file on each request and results in the proper behavior.

Also note that the code runs the same query each time the page is called, changing only the AbsolutePage property. Running the same query over and over might seem wasteful, but it requires far fewer resources than storing large Recordset objects in session variables and trying to persist them across pages. Imagine a site with thousands of users, each with a Recordset object in a session variable. This would quickly eat up server-side resources.

Using ADO, you can perform data access on the server side by using any SQL statement. Queries can be retrieved using SQL server stored procedures or through hard-coded SQL SELECT statements. Updates are performed using SQL UPDATE statements and the Execute method of the Connection object. You can also use ADO on the client side in combination with the Advanced Data Control (ADC). In fact, the ADC is little more than an ActiveX control wrapper for much of the functionality of ADO. The ADC provides access to many of these features through its Recordset property.

File Access Component

The File Access component allows access to text files on your Web site. The component actually consists of two separate objects: the FileSystem object, which is used to open and close files; and the TextStream object, which is used to read and write.

To open a file for access, first create a FileSystem object with the CreateObject method of the Server object. Once the FileSystem object is instantiated, you can use the CreateTextFile method to create a new file or the OpenTextFile method to open an existing file. In either case, the result is a TextStream object that allows reading or writing. The following code shows how to use the objects to access a file named DATA.TXT:

Set objFile = Server.CreateObject("Scripting.FileSystemObject")
Set objStream = objFile.OpenTextFile("DATA.TXT")

After the TextStream object is created, you can use any number of available methods to read or write to the file. Keep in mind, however, that a file is usually opened only for reading or writing, not for both simultaneously. This can greatly affect the code in your ASP page, occasionally requiring a file to be opened, closed, and then reopened for different operations.

In addition to simple reading and writing, the File Access component is also useful for creating dynamic content. Try creating a tip-of-the-day effect, which displays a different tip or message on the page each time the page is accessed. Listing 5-9 shows a complete example that provides Visual Basic programming hints. The key to generating tips is to create a text file that has a single line for each tip. The tips are then accessed randomly by using the ReadLine method of the TextStream object. A single line is placed on the page by using the Write method of the Response object.

Listing 5-9. Generating a tip of the day.


<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<HTML>

<HEAD>
<META HTTP-EQUIV="Content-Type" content="text/html; 
    charset=iso-8859-1">
<META NAME="GENERATOR" content="Microsoft FrontPage 2.0">
<TITLE>VB Tips</TITLE>
</HEAD>

<BODY BGCOLOR="#FFFFFF">
<%

    ' Declare variables
    Dim objFile
    Dim objStream

    ' Open file
    Set objFile = _
        Server.CreateObject("Scripting.FileSystemObject")
    Set objStream = _
        objFile.OpenTextFile(Server.MapPath("/ASP") & _
                             "\Chap05\Listing 5-9\tips.txt")

    Randomize Timer
    intLine = Int(Rnd * 19)

    For i = 0 to intLine
        objStream.SkipLine
    Next

    strText = objStream.ReadLine
    objStream.Close
    Set objStream = Nothing
    Set objFile = Nothing

%>
<CENTER><H1>VB Tip of the Day</H1></CENTER>
<%=strText%>

</BODY>
</HTML>

 
 

About

Mail

Main Page



CopyLeft 2004 Arvind Mohan Sharma