So 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.
Find out where Server Components fit in the overall architecture of the Active Server.
The Ad Rotator Component makes the most of precious advertising real estate on your Web page, and more.
It's important that you understand the needs and limitations of the client software that visits your site.
The Content Linking Component helps you easily maintain a site map-an important aid to navigation for your Web site.
Always useful, text files can be a bear to manipulate-unless you have this handy tool at your side.
Utility 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
Component | Enables You To |
Ad Rotator | Randomly display hyperlinked images |
Browser Capabilities | Optimize HTML for any browser |
Content Linking | Create Web site table of contents |
File Access | Manipulate text files |
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.
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 Ironic Component Presenting the Server Components in alphabetical order, we come first to the Ad Rotator Component-and think it's ironic that we talk first of this tool. Advertising was one of the earliest forms of revenue for Web sites, but a vast majority of advertising revenue goes to a mere handful of Web sites. Clearly, volume controls the flow of advertising revenue, and only a handful of Web sites generate the volume necessary to justify the overhead of an advertising business model. What can the rest of us do to attract traffic? What can we do to keep visitors coming back?
Perhaps a richer, more interactive and personal experience is what the rest of us need to make adding ads to our business plans a feasible complement to our current strategy. Perhaps ASP gives everyone, even the smallest Web studios, the tools needed to reach a new level of excitement and loyalty in their readers. Time will tell. Meanwhile, let's see how these Server Components work.
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. Figure 13.1shows the generic parts of the Ad Rotator Component and how everything works together. Table 13.2 maps the figure elements with the files used in Listing 13.1.
Table 13.2 Cross-referencing Figure 13.1 and Listing 13.1
Figure 13.1 Element | Listing 13.1 Filename |
ASP File | adrot.asp |
Rotation Schedule File | adrot.txt |
Advertiser's Home Page | adrot2.asp |
Ad Rotator Component | MSWC.AdRotator |
Redirect Client | adredir.asp |
Figure 13.1![]()
At the end of this section, after specifying details of the scheduling file and related programs, we suggest a novel use of the Ad Rotator Component. Perhaps our suggestion will inspire you to an equally novel offering on your own Web site that helps you compete with the big guys.
This displays all of the moving parts of the Ad Rotator Server Component.
The 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
Property | Use |
Border | Change the width of a border surrounding your image. Set this property to 0 for an invisible border. Border width is measured in pixels. |
Clickable | This Boolean property dictates whether or not the image is hyperlinked. If true, then when you click the image you will go to another page and image. False, and you only have a static image. |
TargetFrame | This is the name of FRAME defined in the .asp or .html file that defined the FRAMESET. This property serves the same function as the TARGET argument in the A HREF tag. Use it to display your image in the frame named with this property. |
![]()
Setting the Border property to a negative number will yield a BORDER argument in the IMG tag of the resulting HTML file to 65535! Now that's a big border. It effectively makes your HTML page blank. The text is there-you just have to scroll way down and over to see it.
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") %>
![]()
Be sure to use the <%=...%> tag when calling the GetAdvertisement method; otherwise, if you forget the "=" you will not see an image in your .asp file.
![]()
Keeping Track of Your Files The path used by the GetAdvertisement method to find the Ad Rotator Schedule file is the alias of the virtual directory that holds your ASP application, assuming your application is in its root directory. This also is the same value used in the Schedule file itself to find the image file.
Of course, these files can be anywhere; for example, the adredir.asp file can be in a utility directory of another ASP application that you created, and the file that is linked to the ad itself can be anywhere on the Internet.
If you're not sure what the alias is, run the IIS Manager applet, select the WWW service, and then point to the Directories tab. You'll find the value under the Aliases column.
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.
![]()
Some text editors will include the actual values for an image's WIDTH and HEIGHT parameters when you drag and drop the image into an .asp file. Most graphics editors also display the size of an image somewhere in their user interface, so you shouldn't have any problem coming up with the actual size of your image.
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.
![]()
You can use the ALT text as a sort of ToolTip, instead of merely as text to display if the client does not support or has disabled graphics. This way, when the mouse is over the image, the reader can get a clue about what will happen when the image is selected. Choose this text wisely to compliment the other visual clue, the URL that usually will display somewhere on the client's status bar.
Up 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.
ON THE WEB |
http://www.quecorp.com/aspOn this book's Web site, you will find a demo of a trivia game that we concocted from the pieces of the Ad Rotator Component. |
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.
You 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.
The 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.
![]()
The Browser Has Grown Up Call us picky, but we find it increasingly difficult to refer to a Web client as a browser. It was appropriate even a year ago, when virtually all content on the Web was static, but the advent of Java, ActiveX controls, and client-side scripting has changed all that forever-and there's no turning back. The term browser is anachronistic.
Nevertheless, the Browser Capabilities Component uses the term, so we use it, too, but only when we have no choice. Whenever we say "Web client", we are referring to "browser."
We recall reading an article last summer that said it was an offense to both Microsoft and Netscape to use the term browser. That must have been urban legend, no?
The 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.
The 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.
![]()
See "ServerVariables Collection" for more information about the HTTP_USER_AGENT header, in Chapter 12.
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.
![]()
If you refer to a property that is undefined for the browser being interrogated, the Browser Capabilities Component returns Unknown if the property has never been used in the browscap.ini; otherwise, it returns 0 (an implicit False). The parameter names are not case-sensitive.
ON THE WEB |
For more information about the HTTP_USER_AGENT header, see the HTTP/1.0 specification RFC 1945, Section 10.15. It is available at: |
![]()
The Browser Capabilities Component accepts wild cards (for example, *) in the HTTP_USER_AGENT parameter. The component first searches in the HTTP_USER_AGENT parameter for an exact match of all browser definition blocks (while ignoring the wild card). If the Browser Capabilities Component fails to find a match, it searches using the wild card (see the following Tip).
![]()
If there is a wild card in the HTTP_USER_AGENT parameter of more than one browser definition block in the browscap.ini field, the Browser Capabilities Component stops at the first block that it finds. So be sure to enter your browser definition blocks in the order that you expect to encounter them.
You 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.
![]()
One of the least pleasant aspects of the Browser Capabilities Component is maintaining the browscap.ini file. Microsoft is on record with a promise to keep an up-to-date version of the browscap.ini file available on their Internet Information Server Web site. Keep your eyes peeled to:
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>
The 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.
ON THE WEB |
http://www.quecorp.com/aspThis is one of those Server Components that is much easier to demonstrate than to describe. You will find an intriguing ASP application that demonstrates how to use the Content Linking Component on this book's Web site. Click on the Show Me How link and select the "Content Linking Component" option. |
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
Item | Use |
Table of Contents File | Make a list of all the pages you have on your site, and put them in the order you would read them if your Web site was a book. |
A Content Linking Component object | This is the object whose properties you access and methods you invoke to return selected lines from the table of contents file for use by the Active Server when it builds your HTML on-the-fly. By making hyperlinks in that HTML output based on the URL and file name supplied by the table of contents file, you can get specific hyperlinks between pages without having to code the links yourself. |
Files to link to | These are, in fact, the files you already have on your Web site. Their URLs and page titles are stored in the table of contents file so that the Content Linking Component can make complete HTML anchor tags in the HTML output stream returned to the client by the Active Server. |
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
![]()
Separate the two columns in the table of contents file with a TAB.
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>
![]()
Put ASP Source Code Around the FRAMESET Tag Strictly speaking, files that create a FRAMESET do not output HTML directly. FRAMESET files instruct the browser how to display the HTML included in all the files it uses in its FRAME tags' SRC argument. However, an .asp file that contains the FRAMESET tag does produce HTML output. In the case of Listing 13.7 the .asp file also caches the instance of the Content Linking Component on the Session Object. So don't be afraid to put real source code in FRAMESET files.
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.
![]()
When you create your table of contents file, do not include the prefix "HTTP:" or "//" or "\\" in the URLs for the files listed in the table of contents. These are absolute paths. You can only use relative or virtual paths.
![]()
See "The Server Object" for more information about virtual paths, in Chapter 12.
Table 13.5 Content Linking Component Methods
Method | Use |
GetListCount | This method returns the number of links stored in the table of contents file. Use this property when you want to be able to go from the first entry in the table of contents directly to the last entry. See Listing 13.8 for an example. |
GetListIndex | This method retrieves the current index into the list of links. Use this method to determine if you are on the first entry in the table of contents so that you can go to the last item in the table when the user selects the "Previous Page" link in the HTML returned to the Web client by the Active Server. |
GetNextDescription | This method increments the file pointer to the next line in the table of contents file and returns the text in the second column of the table of contents, the Web page title. |
GetNextURL | This method acts on the table of contents file in the same way as the GetNextDescription method except it returns the first string in the table of contents, the URL. |
GetNthDescription | This method ignores the current file pointer and instead retrieves the file indicated by the second parameter to this method, the index number. The return value is the Web page title of the file selected. |
GetNthURL | This method is the same as the GetNthDescription except that it returns a file's URL. |
GetPreviousDescription | Like the GetNextDescription, this method moves back in the table of contents file by one line to retrieve the previous Web page title. |
GetPreviousURL | This method behaves like the GetPreviousDescription method but returns a file's URL. |
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> <HR ALIGN="CENTER" SIZE="1" WIDTH="300" NOSHADE> | <a href=" <% If (Session("objNextLink").GetListIndex (Session("varLinks")) > 1) Then %> <%= Session("objNextLink").GetPreviousURL (Session("varLinks")) %> <%Else%> <%= Session("objNextLink").GetNthURL (Session("varLinks"), Session("objNextLink").GetListCount( varLinks )) %> <% End If %> ">Previous Page</a> || <a href=" <%= Session("objNextLink").GetNextURL (Session("varLinks"))%> ">Next Page</a> | </CENTER>
![]()
A Linear Tool in a Non-linear Space It's important to keep in mind that while the Content Linking Component treats a Web site as if it were a book to be read from beginning to end, hypertext makes this behavior a limiting assumption. That is, a richly interrelated Web site is anything but linear, and to assume that readers will follow the Content Linking Component's lead is a dubious practice.
On the other hand, hypertext's nonlinearity can be detracting. There are times when a reader needs to be guided-getting lost in hyperspace is common and unpleasant. The Content Linking Component offers you a powerful way to have your hypertext and guidance, too.
Still, think carefully about the problems of hypermedia communication when you incorporate this useful tool into your work.
![]()
The Content Linking Component is the forerunner to the sitemap specification currently under review by the W3 Consortium and in the beta version of IE 4.0. Much of the work that you do with this component will be useful when the sitemap initiative takes hold. The sitemap and the Content Linking Component can coexist, because each serves slightly different functions.
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, as shown in Figure 13.2. More sophisticated pages call for more sophisticated icons; our favorite is the one depicted in Figure 13.2. In any case, the trick is to apply the correct URL to the appropriate image or area of the imagemap.
Content-linking icons suggest what to do by their appearance.
The 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
Object | Purpose |
FileSystemObject | Instantiates TextStream Objects |
TextStream Object | To instantiate an object for either reading or writing to a file system file. |
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
Property | Use |
AtEndOfLine | Enables you to read a line in a TextStream object one character at a time. Use it with the Read method. It can only be used on a TextStream object opened in read-only mode. |
AtEndOfStream | Enables you to read a line in a TextStream object one line at a time. Use it with the ReadLine method. It can only be used on a TextStream object opened in read-only mode. |
Column | This is an integer that tells you how for into a line the file pointer has moved. This property can be accessed for all TextStream object types and modes. |
Line | This integer tells you how far down a TextStream object you are. When a file is initially opened the Line property is set to 1. |
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
Method | Use |
Close | Explicitly close a TextStream object. Once the TextStream object looses scope, such as when the user links to another Web page, the close method is automatically called. |
Read | This method accepts one parameter, the number of characters, in order to get data out of the TextStream object. To read a single line one character at a time, use the AtEndOfLine property to end the program loop. |
ReadAll | Moves the entire contents of a TextStream object into memory. For large files, this may not be the best use of memory. |
ReadLine | This method moves the contents of each row of TextStream object into memory. To loop through a whole file, use the AtEndOfStream to sense when to close the loop. |
Skip | Like the Read method, the Skip method moves the file pointer an indicated number of characters in a file. |
SkipLine | Discards all the characters between the current position of the file pointer and the newline character at the end of a given number of rows in the TextStream object. |
Write | A method that writes a string of characters (but not including the newline character) to the TextStream object. This method only works if the TextStream object was opened ForAppending. |
WriteLine | Basically the same as the Write method, except the WriteLine method includes a newline character. If you invoke this method without a string parameter then only a newline character is appended to the TextStream object. |
WriteBlankLines | Basically the same as the WriteLine method without a parameter, the WriteBlankLines method requires a parameter indicating the number of newline characters to append to the TextStream object. |
If 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
<% Set objFileSys = Server.CreateObject("Scripting.FileSystemObject") Set objTextStreamIn = objFileSys.CreateTextFile(Server.MapPath("/lab") + "/ts/demo.htm") %>
![]()
How to Avoid Losing New Files It's nearly always a good idea to liberally use the Server.MapPath method in File Access Component source code because with it you always know where your source code is.
If you don't use fully qualified paths, you never know where your newly created text file was created (other than that it was created in Windows' current directory). Now quick, without touching you keyboard, if your computer is running right now, tell us: what's your current directory?
See what we mean? You know where your file is, you just don't know its location.
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.
![]()
Unicode In a nutshell, Unicode is an alternative to the ASCII character set. Contrary to popular opinion, the Internet is not solely the domain of America. International languages need some way to be displayed, and Unicode is the ticket.
In ASP development, Unicode can be problematic. Some software supports it, and others don't. Some operating systems support it (Windows NT), and others don't (Windows 95).
For more detailed information, take a look at an excellent Web page from Microsoft at:
http://www.microsoft.com/opentype/unicode/cscp.htm
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).
In 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> <P> <% ' Create a single FileSystemObject and use that object to create ' as many TextStream objects as you need. This program needs two. Set objFileSys = Server.CreateObject("Scripting.FileSystemObject") ' Without a fully qualified path, the output file could land almost ' anywhere; e.g., the c:\windows\system32\ directory (or whatever ' happens to be the last directory you ran a program in, viz., the ' Windows current directory). varOutputFile=Server.MapPath("/lab") + "\ts\demo.htm" ' It's also helpful to output the result of the MapPath %> <%="Creating output file: " + varOutputFile + "<P>"%> <% Set objTsOut = objFileSys.CreateTextFile(varOutputFile,True) ' To demonstrate the consequences of not using MapPath, ' we'll create another output file. Good luck finding this one: Set objTsOutThere = objFileSys.CreateTextFile("lostdemo.htm",True) objTsOutThere.WriteLine("It's not pretty, but we were demonstrating non-qualified paths, not formatted HTML...") ' It's generally best to use the MapPath method to create a fully ' qualified path to your target file too. varInputFile=Server.MapPath("/lab") + "\cl\list.asp" %> <%="Reading input file: " + varInputFile + "<P>"%> <% Set objTsIn = objFileSys.OpenTextFile(varInputFile) Do Until objTsIn.AtEndOfStream objTsOut.WriteLine(objTsIn.ReadLine) If objTsIn.Line=10 Then objTsOut.WriteLine("<PLAINTEXT>") ElseIf objTsIn.Line=30 Then objTsOut.WriteLine("</PLAINTEXT>") End If objTsOutThere.WriteLine(objTsIn.ReadLine) Loop objTsIn.Close objTsOut.Close objTsOutThere.Close %> Examine the <A HREF="demo.htm"></A> file (you may need to Refresh). <P> See if you can find the file created without using the MapPath method.<BR> If it's <A HREF="lostdemo.htm">here</A>, you're lucky; if it's not, try FileFind and use "lostdemo.htm" as the filename.
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.)
The 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.
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:
ON THE WEB |
http://www.quecorp.com/aspLook in the Chapter 13, "Interactivity Through Bundled Active Server Components" section of the Web site. By seeking, you'll find cool code that uses many of the tricks that we have sprinkled throughout the book. E-mail us and let us know what you discover. |
© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.