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. (See Appendix D for a complete list of ActiveX Data Objects.)

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), covered in Chapter 4. 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> 

Browser Capabilities Component

The Browser Capabilities component identifies the browser that is currently accessing the site and provides programmatic access to the list of features supported by the browser. This component is a tremendous asset to Web developers who are targeting both Internet Explorer and Netscape Navigator. Using this component, you can tailor the Web page to a particular browser.

The Browser Capabilities component relies on the browser's user agent string to identify the browser type. The user agent string (discussed in detail in Chapter 3) is passed by the browser to the server each time a Web page is requested. For example, the user agent string for IE 4.0 looks like this:

Mozilla 4.0 (compatible; MSIE 4.0; Windows 95)

In order to determine the supported features of a particular browser, the Browser Capabilities component attempts to match the browser's user agent string to entries in a special initialization file named BROWSCAP.INI. When the Browser Capabilities component matches a user agent string, all of the features listed for that browser are immediately accessible as properties of the component. Listing 5-10 shows the portion of BROWSCAP.INI that corresponds to IE 4.0.

Listing 5-10. BROWSCAP.INI entry for IE 4.0.


[Mozilla/4.0 (compatible; MSIE 4.0; Windows 95)] browser=IE Version=4.0 majorver=#4 minorver=#0 frames=TRUE tables=TRUE cookies=TRUE backgroundsounds=TRUE vbscript=TRUE javascript=TRUE javaapplets=TRUE ActiveXControls=TRUE Win16=False beta=False AK=False SK=False AOL=False crawler=False 

Using the Browser Capabilities component is similar to providing a conditional compilation statement in your ASP page. You can construct simple If…Then statements that greatly affect the final content. For example, Listing 5-11 sends an <OBJECT> tag to a browser that supports ActiveX controls, an <APPLET> tag to a Java-capable browser, or a text message to browsers that have neither feature.

Listing 5-11. Detecting Browser Capabilities


<%@ 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>Browser Capabilities</TITLE> </HEAD> <BODY> <CENTER> <%     ' Create Browser Capabilities component     Dim objBrowser     Set objBrowser = _         Server.CreateObject("MSWC.BrowserType")     ' Find out what features are supported %> <%     If objBrowser.ActiveXControls Then %> <H1>ActiveX Controls</H1> <SCRIPT LANGUAGE="VBScript"> <!--     Sub Window_OnLoad()         pathBall.Target = objBall.Style     End Sub --> </SCRIPT> <!-- Structured Graphics control --> <OBJECT ID="objBall"     STYLE="POSITION:ABSOLUTE;HEIGHT:70;         WIDTH:110;TOP:0;LEFT:0;ZINDEX:0"      CLASSID=         "CLSID:5FD6A143-372A-11D0-A521-0080C78FEE85">     <PARAM NAME="Line0001"          VALUE="SetLineColor(255,255,255)">     <PARAM NAME="Line0002"          VALUE="SetFillColor(255,0,0,0,0,255)">     <PARAM NAME="Line0003"          VALUE="SetFillSTYLE(1)">     <PARAM NAME="Line0004"          VALUE="SetLineSTYLE(1)">     <PARAM NAME="Line0005"          VALUE="Oval(0,-25,50,50,0)"> </OBJECT> <!-- Path control --> <OBJECT ID="pathBall"       CLASSID=         "CLSID:E0E3CC60-6A80-11D0-9B40-00A0C903AA7F">     <PARAM NAME=AutoStart VALUE=-1>     <PARAM NAME=XSeries          VALUE="0,0;30,0;45,0;52,0;55,0">     <PARAM NAME=YSeries          VALUE="0,0;30,80;45,160;52,240;55,320">     <PARAM NAME=EdgeAction VALUE="1">     <PARAM NAME=TickInterval VALUE=10> </OBJECT> <%ElseIf objBrowser.JavaApplets Then%> <H1>Java Applet</H1> <APPLET CODE="marquee.class" HEIGHT=40 WIDTH=400>     <PARAM NAME="CAPTION" VALUE="Java is Cool!"> </APPLET> <%Else%> <!-- Text-only browser --> <H1>No Components Supported!</H1> <%End If%> </CENTER> </BODY> </HTML> 

Ad Rotator Component

The Ad Rotator component is designed specifically for sites that are renting advertising space. The component provides a way of controlling the rotation of advertising images in a site. It reads information regarding advertisements from a special text file that directs which ad to show and for how long. Using the Ad Rotator is a simple matter of creating the component and reading the text file. Here is the code:

<%     Dim Ad     Set Ad = Server.CreateObject("MSWC.AdRotator")     Response.Write Ad.GetAdvertisement("ADS.TXT") %> 

The text file read by the Ad Rotator has a well-defined structure that determines the image to display, specifies the percentage of time to show the image, and provides a hyperlink that is activated when the advertisement is clicked. You simply construct the text file in the appropriate format, and the component does the rest.

Content Linking Component

The Content Linking component is designed for publication of online magazines and newspapers. The component links separate Web pages together, allowing them to be scrolled. Chapter 8 provides a complete project that uses the Content Linking component.

Like the Ad Rotator, the Content Linking component depends on a text file to create the publication. The file, known as the Content Linking List, provides a listing of the linked Web pages and a description of each. Using the Content Linking component simply requires creating the component and reading the associated text file. Here is the code:

<%Set objLinker = Server.CreateObject("MSWC.NextLink")%> 

Once the publication is created, you can use methods such as GetNextURL and GetPreviousURL to navigate the pages. Descriptions of individual pages are retrieved through the GetNextDescription and GetPreviousDescription methods. These values can be used to generate hyperlinks to other pages in the publication. Here is the code:

<A HREF="<%=objLinker.GetNextURL%>">     <%=objLinker.GetNextDescription%> </A> 

Using Other ActiveX Components

In addition to using all of the components provided by Visual InterDev, you can create your own ActiveX components for ASP. The project in Chapter 9 features a custom component created with Visual Basic 5.0 to send Internet e-mail.

Once a custom component is created, it can be accessed in the same way as any other component—through the CreateObject method of the Server object. All you have to do is provide the ProgID for the custom component. This feature is a powerful tool that allows you to extend ASP to include any functions you need.



Programming Active Server Pages
Programming Active Server Pages (Microsoft Programming Series)
ISBN: 1572317000
EAN: 2147483647
Year: 1996
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net