| The BannerCo-Op - 1-1 Exchange + Cash | |
<Chapter 12: "Enhancing Interactivity with Cookies, Headers and the Server Object" / ASP Book Home Page / Chapter 14: "Constructing Your Own Server Components">
...understand the Interactivity Through Budnled Active Server Components. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Chapter 13Interactivity Through Bundled Active Server ComponentsSo far, it has been up to you to produce any interactivity in your Active Server Pages. You have seen the Active Server's intrinsic Objects (viz., Request, Response, Server, Application, and Session Objects along with their collections, methods, and properties) that make doing this relatively easy. Having the horsepower of a well-equipped Web server means that you can deliver lots of custom features without being constrained by the Internet's current bandwidth limitations. But ASP development doesn't mean that you have to do all the work to make the best Web pages on the planet. This chapter introduces you to a cadre of tools that want nothing more from life than to spare you the drudgery of the most mundane tasks of the Webmaster. The chapter explains Server Components; specifically, the Ad Rotator, Browser Capabilities, Content Linking, and the FileAccess Components.
Delegating InteractivityUtility programs are a godsend to programmers. The utility functions provided by the Server Object (viz., CreateObject, HTMLEncode, MapPath, and URLEncode) are terrific at what they were designed to do. But their utility is limited. This chapter begins to cross the bridge from predefined utility to virtually unlimited usefulness. You are introduced to five Server Components, each more powerful and flexible than its cousin in the Server Object's methods already examined. One of these higher-level utilities, the File Access Component, permits you to do almost anything you want to a text file (contrast this capability with the Server.AppendToLog method, which adds only 80 characters and to only one file, the server log). Table 13.1 The ASP Developer's ToolBox
Chapter 14, "Constructing Your Own Server Components" introduces one other capability of the Active Server: roll your own. That's right, the Server Components that ship with the Active Server are prototypes of what you can do yourself. We use Visual Basic (you can use many other programming tools) to show how to create a DLL and use it in your Active Server Pages. This extensibility of the Active Server means that it will live a long and prosperous life as a development environment. Server Components are DLL files that run in the same address space as .asp files and IIS. They can be single-threaded or multi-threaded, but the single-threaded programs will suffer the usual limitation of being able to be run by only one client at a time. DLLs created with Visual Basic 4.0 are single-threaded. Server Components fall into two groups: HTML and database access. You could spend your whole ASP career working with only the HTML components discussed in this chapter and never touch a database. Indeed, that's how most Webmasters have spent their time; a vast majority of the content on the Web is static HTML (at least, static in the sense that it does not interface with a database). Web development is more difficult and expensive and it is less flexible when the power of the modern database is excluded from the Webmaster's toolkit. With the advent of ASP, this no longer need be necessary. All of Part IV, "Database Management with Active Server Pages," is devoted to covering this important innovation in great detail. In this chapter, you will focus on the HTML-based Server Components. Ad Rotator Component Rotates Ads (and More)Even in its earliest versions, a distinctive feature of HTML was its use of hyperlinked graphic images. Pictures, line art, virtually anything that could be painted on the screen could also be imbued with the power to transport the browser to another file. The HTML element that controlled this ability was the IMG tag. <IMG SRC="test.gif" WIDTH=430 HEIGHT=180
BORDER=1 ALT="Any picture you want to display">
The Ad Rotator Component yields the complete IMG tag of a graphic whose name and optional data are taken from a scheduling file. As the Ad Rotator's name suggests, this scheduling file may contain many images, each one assigned a relative frequency of display. In addition, the Ad Rotator Component can make the displayed image a hypertext link to another HTML page, perhaps the home page of the advertiser.
Ad Rotator Component PropertiesThe Ad Rotator Component has three properties listed and described in Table 13.3. Each property can be modified at runtime to make the behavior of the Ad Rotator dynamic. You also could use the TextStream object of the File Access Component to modify the Schedule file on the fly, but that's tricky and much more difficult than using the exposed properties of the Ad Rotator Component. Table 13.3 Ad Rotator Properties
Listing 13.1 is a typical example of how you set up an Ad Rotator Component. You only needed one <% and one %> marker to delimit the first four lines of .asp code in Listing 13.1. The GetAdvertisement method looks to the single parameter it uses to identify the file that controls how the IMG tag will be written. In Listing 13.1 this file is adrot.txt, and it gives the Ad Rotator Component all the arguments it needs when it creates the IMG tag it passes to the Active Server. The Active Server then includes that IMG tag with all the rest of the HTML source code, if any, contained in the calling program (which in our case in Listing 13.1 is adrot.asp). The contents of adrot.txt is given in Listing 13.2. Listing 13.1 adrot.asp-Setting the Default Values of the Ad Rotator Component <%
Set objAd = Server.CreateObject("MSWC.AdRotator")
objAd.Border(1)
objAd.Clickable(FALSE)
objAd.TargetFrame(FrameAd)
%>
<%= objAd.GetAdvertisement("/lab/ar/adrot.txt") %>
The Schedule File The adrot.txt file is the Schedule file, and it contains two sections of information separated by an asterisk (*). Listing 13.2 shows what a typical Schedule file looks like. Listing 13.2 ADROT.TXT-The Data Used by Ad Rotator to Display an Image Redirect /lab/ar/adredir.asp width 349 height 235 border 0 * /lab/apple.gif /lab/ar/adrot2.asp Click to go to adrot2.asp 30 /lab/pie.gif /lab/ar/adrot3.asp Click to go to adrot3.asp 70 The first section of Listing 13.2 contains optional data to control how file redirection will take place, and it controls the appearance of all the image files used by the Ad Rotator Component. The second, third, and fourth lines in the adrot.txt file control are used by the Ad Rotator Component to specify the WIDTH, HEIGHT, and BORDER parameters of the IMG tag. If you don't specify values, the default values of WIDTH 440, HEIGHT 60, and BORDER 1 are used. These size defaults produce the traditional size of a banner ad, so if your image does not conform to that shape, be sure to specify the size; otherwise, you probably won't like how it looks.
The second section of information contains URLs to the image file (a required data point) and to the hyperlinked HTML (or .asp) file. This section also includes the text for the ALT parameter of the IMG tag that Ad Rotator Component will produce. The final attribute of this second section is a number between 0 and 4,294,967,295 (no, we didn't make that number up!). This number tells Ad Rotator Component the pro rata share of display impressions. For example, if the first image had 30 and the second had 70, the first one would display 30% of the time.
The Ad Rotator Component with a TwistUp to now, we have limited the context of this section to what the designers of the Ad Rotator Component had in mind-advertising-but now we suggest another use for the tool. Keep in mind that this is just an example, but we hope it fires your imagination and helps you find even more clever ways of using this and other ASP utilities. Normally, when a reader selects an image presented by the Ad Rotator Component, that reader goes to the advertiser's Web site. But there's nothing to stop the reader from going to anther Ad Rotator .asp file on your site.
In that demo, each image is not an ad but a trivia question. Clicking it sends you to the answer and then to another question. Note that most of the adrotX.txt files have more than one question in them. This gives you a little more variety with no additional work. The system works because each file redirect goes to another adrotX.asp file, and each of those files has its own adrotX.txt file. Each adrotX.txt file instructs the Ad Rotator Component of the location of the next question, and each question tells the Ad Rotator Component the location of the next answer. There's nothing stopping you from locating these questions on other peoples servers. In this way, you could create an Internet "scavenger hunt." This kind of entertainment might be welcomed by many road-weary Internauts, and cooperating with other Webmasters can help develop relationships that have additional value for everyone involved. Another use of image files could be patterned after the popular PointCast Network model. Using AVI files or animated GIFs, you could add some splash to your advertising. The Browser Capabilities Component: To Each His OwnYou have read often in this book that as an ASP developer you have to choose between writing code to serve the widest audience and writing code for the richest possible experience. Using the Browser Capabilities Component, it is possible to have a great deal of both. With this Component, you can return code optimized for each browser or Web client that visits your site. This doesn't mean you have to maintain separate pages, e.g., one that has been optimized with ActiveX controls and another that runs straight HTML. You don't even have to worry that the browser doesn't support JavaScript or VBScript. As you know, Active Server Pages are cached on the server and run in the server's memory space. The result is pure speed. If you cache the Browser Capabilities Component as an Application property, it is available to every browser that enters your Webspace-that's every one, regardless of age or the platform upon which they run. None of these browsers needs to be able to interpret (literally) a scripting language, and all of them can get HTML optimized for their ability. Sure, you still can use a scripting language on old browsers; they will ignore the SCRIPT tag, and the scripting source code is commented out, so they won't even see that. But doing this has one limiting consequence: All browsers that can't interpret a scripting language are treated the same way, the way that the remaining HTML treats them. No other processing is possible. There's got to be a better way. Two Components of the Browser Capabilities ComponentThe Browser Capabilities Component is composed of two components: the browscap.dll file and the browscap.ini file. The browscap.dll creates instances of an object known as the Browser Capabilities Component. This object exposes the methods and properties that you will learn about in this section. The browscap.ini file is your baby. The hardest thing about using it is keeping up with the breakneck speed of Web client software development. You also have control over how many of the extant clients you want to include. You can tell the browscap.ini file which browsers you want to include and which of their features for which you want to test.
Instantiating the Browser Capabilities ComponentThe syntax for using the Browser Capabilities Component couldn't be simpler: <% Set objBC = Server.CreateObject("MSWC.BrowserType") %>
The Server Object has a method that creates objects inside the Active Server. This is why we call the Active Server extensible, because we can add to the number of objects it can use to run our Web sites. This fact has two important consequences:
The Browser Capabilities Component is a little unusual. The object created with the Server.CreateObject method has no intrinsic methods. It has no collections, either. Indeed, the only properties the Browser Capabilities Component has are the ones you define for it. That is, you list those attributes of browsers that you want to track. Those attributes are stored in the browscap.ini file, as you will see in the next section. Maintaining the browscap.ini FileThe browscap.ini file is stored in the c:\inetsrv\ASP\Cmpnts directory when IIS 3.0 is installed and in C:\Program Files\WEBSVR\SYSTEM\ASP\Cmpnts under Personal Web Server. The path in your PC may be slightly different (up to the "ASP" or the "WEBSERVER" parts). Like all .ini files, browscap.ini is a simple text file. You can add comment lines to it using a semicolon. This commonly is used to group classes of browsers in the .ini file. Each entry in the browscap.ini file (we will refer to an entry as a browser definition block) has a minimum of two parts: the name of the browser as identified in the HTTP_USER_AGENT header and at least one property. A single browscap.ini file can contain an unlimited number of browser definition blocks. Each block begins with an HTTP_USER_AGENT parameter. This parameter is always enclosed in square braces, [HTTP_USER_AGENT ]. Normally, this parameter's value is the text stored in the Request.ServerVariables("HTTP_USER_AGENT") parameter. There is one exception to these rules, which you will see in the "Default Browser Definitions" section.
Listing 13.3 shows a typical browser definition block. This one is for the Internet Explorer (IE), version 3.01, running under Windows NT. Listing 13.3 BROWSCAP.INI-A Typical Entry in the browscap.ini File [Mozilla/2.0 (compatible; MSIE 3.01; Windows NT)] parent=IE 3.0 version=3.01 minorver=01 platform=Win95 The optional parent parameter is used in the Browser Capabilities Component to refer to another browser definition block of the browscap.ini file. Listing 13.4 shows another case of a browser definition block in the browscap.ini file. Listing 13.4 BROWSCAP.HTM-The parent Definition of the Requesting Browser [IE 3.0] browser=IE Version=3.0 majorver=#3 minorver=#0 frames=TRUE tables=TRUE cookies=TRUE backgroundsounds=TRUE vbscript=TRUE javascript=TRUE ActiveXControls=TRUE Win16=False beta=False AK=False SK=False AOL=False Once it finds this block, the Browser Capabilities Component assigns all properties found in the parent section to the current browser identified in the HTTP request and stored in the HTTP_USER_AGENT variable in the Request.ServerVariables collection. IE 3.01 has its four unique properties, as well as all the 16 properties recorded for all IE 3.0 browsers. Incidentally, if any of the standard properties appear in both browser definition blocks, the one in the literal browser definition block overrides the one in the parent browser definition block. In Listing 13.3, the Browser Capabilities Component will use both the version and minorver parameters in the [Mozilla/2.0 (compatible; MSIE 3.01; Windows NT)] browser definition block. This capability to reference a block of common features makes maintenance of your browscap.ini file much easier. When a new browser version is introduced, you simply add a new browser definition block to your browscap.ini file, refer to the parent block, and then add the unique properties of the current version. Remember that you decide which properties you are going to test for any given browser. This means that your ASP source code must explicitly test for each property.
Default Browser DefinitionsYou also may have a default browser category, but you need to be careful here. If your .asp file is requested by a browser not identified in your browscap.ini file, then the Browser Capabilities Component looks for a [Default Browser Capability Settings] browser definition block, and it assigns the properties there to the undefined browser. If this undefined browser really has all of those properties, then everything works fine. If it doesn't, the reader at the other end may be in for a big surprise. For example, you are fairly safe to assume that the TABLES property can be set to True for your default browser. However, old AOL browsers don't know how to work with tables, and, if a table is encountered on the Web, the old AOL browsers display text that is difficult to read. Therefore, it is wise to err on the side of discretion. Either use a wild card to identify old browsers and set the most conservative properties for them, or make your default properties brain-dead, with everything set to False. Other Tips
Perhaps the most important use of the Browser Capabilities Component is in divining which browsers support ActiveX controls. We have written pages that seemed innocent enough, with only a few ActiveX controls installed, but they were enough to actually cause Netscape 2.0 to crash (and on a Power PC, the crash brings the entire computer to its knees!). Listing 13.5 is an example of code that would flag troublesome browsers. Listing 13.5 bcactivex.asp-Testing for ActiveX-Enabled Browsers <HTML>
<HEAD>
<TITLE>ActiveX Enabled?</TITLE>
</HEAD>
<BODY>
<% Set obj = Server.CreateObject("MSWC.BrowserType")%>
<% Set objBrowser = Server.CreateObject("MSWC.BrowserType")%>
...later in the program we insert an ActiveX control only if it
supported
<% If objBrowser.ActiveXControls = "True" Then %>
<OBJECT ...>
</OBJECT>
<% End If %>
</BODY>
</HTML>
Content Is KingThe next component in this pantheon of ASP utilities is the Content Linking Component-a very cool tool. Try to remember the number of times that you wanted a page to have a link back to a specific page or were embarrassed to instruct the reader to "select the Back button on your browser." With the Content Linking Component, those days are over. Every page can know the name and URL of the page that comes before it and the page that will follow it. Using this tool, you can turn your Web site into a book. The Content Linking Component becomes your table of contents.
Table 13.4 shows you the ingredients list for the Content Linking Component. Shows you how to instantiate the Content Linking Component. Table 13.4 What You Need to Use the Content Linking Component
Essentially, the Content Linking Component reads a text file that contains the linear listing of all the pages on your Web site. Again, if you were to read all the pages on your Web site as if the site were a book, how would you organize it? Use a word processor or spreadsheet and build a table of contents for your site. Save the file as a text file with a descriptive name. An example table of contents is given in Listing 13.6. Listing 13.6 NEXTLINK.TXT-An Example Table of Contents for a Web Site intro.asp Introduction list.asp The Linking List File methods.asp Component Methods sample.htm Sample Code
The object itself that manages the nextlink.txt file and sends the correct HTML anchor tag to the Active Server is given in Listing 13.7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
</HEAD>
<%
If Not IsObject(Session("objNextLink")) Then
Session("varLinks")="/lab/cl/nextlink.txt"
Set objNextLink = Server.CreateObject ("MSWC.NextLink")
Set Session("objNextLink")= objNextLink
Response.Write("<TITLE>Welcome!</TITLE>")
Else
Response.Write("<TITLE>Cached</TITLE>")
End If
%>
<FRAMESET ROWS="100%" COLS="40%,*">
<FRAME NAME="toc" SRC="toc.asp" SCROLLING="AUTO" MARGINWIDTH=30>
<FRAME NAME="text" SRC="intro.asp" SCROLLING="AUTO">
<NOFRAMES>
<BODY>
This demo is running under FRAMES enabled browsers.
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>
Once you have these preliminaries out of the way, you can start using the Content Linking Component. To do this, you will need to understand what the eight methods of this component do, and they are summarized below in Table 13.5. All methods used by the Content Linking Component have at least one parameter: the relative or virtual path and the file name of the table of contents file such as the one shown in Listing 13.6.
Table 13.5 Content Linking Component Methods
A basic implementation of the Content Linking Component is given in Listing 13.8. As the filename suggests, Listing 13.8 can be used in other .asp files by merely inserting a Server-Side Include directive at the bottom of the other files with the following line: <!--#INCLUDE VIRTUAL="/lab/cl/footer.ASP"--> <CENTER>
We have found the Content Linking Component extremely useful for Web sites that use what we call the "round-robin" aid to navigation. Following is an explanation of this simple-if not perfect-way to help your readers keep their bearings. While readers still can get off the trail in a complex Web site, you can give them the ability to go the next, previous, and upper (and sometimes lower) pages, given the current page they're on. At the top of each page is a graphic. The simplest method has three black arrowheads; one each for left, right, and up. More sophisticated pages call for more sophisticated icons. In any case, the trick is to apply the correct URL to the appropriate image or area of the imagemap.
Managing Text Files in Active Server PagesThe last utility you will learn about is the File Access Component. This Component gives you access to the file formats other than .html and .asp. The most common file access needed is access to text files. The File Access Component uses two groups of objects as described in Table 13.6. The TextStream Objects turn text files into objects so that you can manipulate their contents by reading and changing their properties and invoking methods on their contents. Table 13.6 Objects used by the File Access Component
Each property listed in Table 13.7 describes the basic structure of all text files. Namely, all text files have a beginning and an end, and they all consist of rows and columns. The beginning of a file is defined by the Line property equals 1, and the end of the TextStream Object is defined when a special property, the AtEndOfStream property, is true. When you access these properties you can monitor your position within the file as well as you could if you were using a mouse cursor on a visible file. All the properties of the TextStream object are read-only. Table 13.7 TextStream Object Properties
The methods exposed by the TextStream object are in four logical groups, though they are listed in Table 13.8 in alphabetical order for your convenience. There are three reading methods, three writing methods, two skipping methods, and the Close method. Table 13.8 The Methods of the TextStream Object
Syntax of Required ObjectsIf you forget to instantiate the objects required to manipulate the File Access Component, you get a run-time error saying Object Required. This usually means that you failed to use the Server.CreateObject method to create a working object. When you see this error, double-check your ASP source code; to work properly, it should look something like Listing 13.9. Listing 13.9 DEMO.ASP-Required File Access Component Objects <%
The OpenTextFile method of the FileSystemObject has one required parameter-the file name-and three optional ones. The second parameter is the I/O mode and can take on two possible constant values: ForReading (the default) and ForAppending. The next parameter, create, is a Boolean value that's True when it's okay to create a file if the method attempts to open a non-extant file; otherwise, (by default) it's False. The last parameter, format, is used to specify something called a tristate: TristateTrue means that the file can be opened as Unicode; TristateFalse means that only ASCII files are supported; and TristateUseDefault uses the system default.
The FileSystemObject's CreateTextFile method obviously is quite similar to the FileSystemObject's OpenTextFile method. The differences are the lack of a Tristate value and the fact that the Boolean value controls whether a new file overwrites an extant file with the same name. There is no need for the CreateTextFile method to distinguish between ForReading and ForAppending. Likewise, there is no Tristate value because you are creating the file and decide which character set to use. In spite of their differences, both the CreateTextFile and the OpenTextFile methods give you a TextStream Object or two (or as many as you want). TextStream ObjectsIn Listing 13.10, you have three methods and two properties to work with: the AtEndOfStream and Line properties and the WriteLine, ReadLine, and Close methods. Listing 13.10 DEMO.ASP-The File Access Component Demo <FONT
SIZE="+1"><STRONG>TextStream Object Demo</STRONG></FONT> The two properties are straightforward. The AtEndOfStream property is False until the last byte is read from the input file. The Do Until command exploits this value. The Line property is helpful in this case, because you want to insert the <PLAINTEXT> tags at strategic points in the input file, list.asp. This property watches your progress through the file for you; when you hit the line that you need, you insert the tags. The two methods also are self-evident. The WriteLine method does just what it says. Incidentally, this method belongs to the output file's TextStream object. Note that the only parameter that this method needs is a string. The string can be literal, a variable, or, as in this case, the output of the second method, ReadLine. The ReadLine method needs no parameters, but we find that we often forget to append the object reference to it; namely, the input file's TextStream object. In that case, the ReadLine method simply reads the current line (referenced by the Line property). The final method, Close, needs to be called by each of the objects in turn. (When the .asp file closes, the objects lose scope anyway, but using the Close method is better style.) Some Suggested Uses of the File Access ComponentThe OpenTextFile method can access and report on the contents of files like server log files, application program .ini files, and miscellaneous text files of your own design. For example, you could have a "Tip of the Day" file that you could access with the File Access Component. You can also use low-level file access to get at data in legacy databases. For example, our firm used a portfolio management program for twelve years before it was replaced with a Microsoft Access database. In order to continue to use the same reporting format our clients had become accustomed to, we had to incorporate the data from those old tables. The program was old enough that it did not include the usual format of comma-delimited ASCII text files we take for granted today. We had to write a low-level file access program that converted the text export files into a row and column format that Access needed to import the data. A similar procedure could have been used to access that data directly through a Web client if we needed to report on that legacy data in real-time using an intranet system instead of a desktop database system. Using the CreateTextFile method, on the other hand, enables you to create your own .ini files. Storing persistent data in this fashion is appropriate when using the Data Access Component is overkill. Storing session data in this way is more persistent than relying on storing the data on the Session Object. It is also more accessible than using the Cookies collection (that is, the data you store about a client is stored on the server, and in simple text, and not on the client). Indeed, the global.asa file in the Adventure Works sample application, which ships with Active Server Pages, opens a text file to see how many people have visited the site and updates the total when the application ends by storing the new total in the same visitors.txt file. The main point is that text file access can be a very useful data storage and retrieval system, occupying a position between the Cookies collection and formal databases. From Here...This chapter showed you the Server Components that ship with Active Server Pages. You learned how to use the Ad Rotator Component to place hyperlinked images on your Web site. You learned how you could display one image randomly selected from a collection of images. The Ad Rotator, then, helps you keep your Web site fresh, and it helps you increase your revenue base of paying advertisers. You also saw how you might use the Ad Rotator Component in a novel way to link the Web sites of independent but related organizations and almost make a game out surfing the Net. Another Server Component you learned about in this chapter was the Browser Capabilities Component. You now know how this tool helps you identify each browser that visits your site. You now know how to identify the feature set of each browser so that you can return HTML optimized for each feature set. Browsers, for example, that can support VBScript or JavaScript can receive server-generated client-side scripts. Now you can sense when a browser can use ActiveX controls, and you can build HTML that includes those advanced user interface features without having to ask the user to go to another ActiveX-enabled page themselves. In a sense, the Browser Capabilities Component enables you to create customized pages for each kind of browser on the planet and to accomplish this feat in far less time than it took to write standard HTML in the first place. You also learned about the Content Linking Component. You learned how it can save hours of editing the URLs you add at the bottom of your Web pages that move the reader from one page to the next. You learned that all you have to do is maintain one text file that lists each page URL and title on your Web site. You learned how to instruct the Content Linking Component to navigate around this table of contents text file and to use the file information it finds on each row of that text file as ASP constructs your HTML on-the-fly. Finally, you learned how to access text files using the File Access Component. You learned how to display the contents of other files in your Web browser, and you saw other uses for text file access (e.g., accessing server logs and .ini files). This chapter also brings you to the end of Part III. From here, you'll move to the high ground of interactivity: database programming. Here's what's coming in Part IV:
© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company. |
<Chapter 12: "Enhancing Interactivity with Cookies, Headers and the Server Object" / ASP Book Home Page / Chapter 14: "Constructing Your Own Server Components">
Last update: 30.10.99. Created by Konstantin Chapkanov.