Download as pdf or txt
Download as pdf or txt
You are on page 1of 102

Active Server Pages (ASP)

Outline 33.1 33.2 33.3 33.4 33.5 33.6 33.7 33.8 33.9 33.10 33.11 Introduction How Active Server Pages Work Setup Active Server Page Objects Simple ASP Examples File System Objects Session Tracking and Cookies ActiveX Data Objects (ADO) Accessing a Database from an Active Server Page Server-Side ActiveX Components Web Resources

2004 Prentice Hall, Inc. All rights reserved.

Objectives In this tutorial, you will learn:


To program Active Server Pages using VBScript. To understand how Active Server Pages work. To understand the differences between client-side scripting and server-side scripting. To be able to pass data between Web pages. To be able to use server-side include statements. To be able to use server-side ActiveX components. To be able to create sessions. To be able to use cookies. To be able to use ActiveX Data Objects (ADO) to access a database.
2004 Prentice Hall, Inc. All rights reserved.

33.1 Introduction Server-side technologies


Dynamically creates Web pages
Use client information, server information and information from the Internet

Active Server Pages (ASP)


Microsoft Server-side technology Dynamically build documents in response to client requests Deliver dynamic Web content XHTML, DHTML, ActiveX controls, client-side scripts and Java applets

2004 Prentice Hall, Inc. All rights reserved.

33.2 How Active Server Pages Work Active Server Pages


Processed by scripting engine
Server-side ActiveX control .asp file extension

Can contain XHTML tags Scripting written with VBScript


JavaScript also used Others (Independent Software Vendors)

Communication with Server


Client HTTP request to server Active server page processes request and returns results

2004 Prentice Hall, Inc. All rights reserved.

33.2 How Active Server Pages Work Active Server Pages,cont.


Communication with Server, cont.
ASP document is loaded into memory asp.dll scripting engine on server Parses (top to bottom)

2004 Prentice Hall, Inc. All rights reserved.

33.3 Setup Web Server


Need to run Web server to use Active Server Pages
IIS 5.0 (Internet Information Services) or higher

Create a virtual directory


Copy files to c:\InetPub\Wwwroot

2004 Prentice Hall, Inc. All rights reserved.

33.4 Active Server Page Objects


Built-in objects
Communicate with a Web browser Gather data sent by HTTP request Distinguish between users
Request
Get or post information Data provided by the user in an XHTML form Access to information stored on client machine Cookies File upload (binary)

Response
Sends information to client XHTML, text

Server
Access to server methods or properties
2004 Prentice Hall, Inc. All rights reserved.

33.4 Active Server Page Objects


Object Name
Request Response Server

Description Used to access information passed by an HTTP request. Used to control the information sent to the client. Used to access methods and properties on the server.

Fig. 25.1 Commonly used ASP objects.

2004 Prentice Hall, Inc. All rights reserved.

33.5 Simple ASP Examples


ASP Scripts
Scripting delimiters
<% %> @LANGUAGE directive

Option Explicit As in VBScript, forces all variables to be declared in advance FormatDateTime Time to display
Now

Format to display in

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<% @LANGUAGE = VBScript %> <% ' Fig. 33.2 :

' A simple ASP example Option Explicit %>

Scripting delimiter wraps around code clock.asp executed on the server. Processing directive specifying scripting Requires programmer explicitly 1.0 language Transitional//EN" define all variables

Outline
clock.asp (1 of 2)

10

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

11 12 <html xmlns = "http://www.w3.org/1999/xhtml"> 13 14 15 16 17 18 19 20 21 22 23 24 25 </head> p </style> strong <style type = "text/css"> td { background-color: black; color: yellow } { font-family: arial, sans-serif; font-size: 14pt; color: blue } { font-size: 14pt } <head> <title>A Simple ASP Example</title>

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 </html> </tr> <td> <% =Time() %> </td> <body>

Returns server date and time <%= is short for ( Now ) as a string formatted in Response.write <p><strong>A Simple ASP Example</strong></p> vbLongDate format <table border = "6">
<tr> <td> <% =FormatDateTime( Now, vbLongDate ) %> </td>

Outline
clock.asp (2 of 2)

11

Statement</table> is short for:


<%</body> Call Response.write( Time()) %>

2004 Prentice Hall, Inc.


All rights reserved.

12

33.5 Simple ASP Examples


Fig. 33.2 Simple Active Server Page.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Simple ASP Example</title> <style type = "text/css"> td strong p </style> </head> <body> { background-color: black; color: yellow } { font-family: arial, sans-serif; font-size: 14pt; color: blue } { font-size: 14pt }

Outline
HTML generated by clock.asp (1 of 2)

13

16 17 18 19 20

2004 Prentice Hall, Inc.


All rights reserved.

21 22 23 24 25 26 27 28 29 30 31 32 33 34

<p><strong>A Simple ASP Example</strong></p> <table border = "6"> <tr> <td> Thursday, May 24, 2001 </td> <td> 2:22:58 PM </td> </tr> </table> </body>

Outline
HTML generated by clock.asp (2 of 2)

14

35 </html>

2004 Prentice Hall, Inc.


All rights reserved.

15

33.5 Simple ASP Examples ASP processes input


Form information sent by client E-commerce Web site
Use to verify customer information

Server responds to process request Form


Using post method action attribute indicates the .asp file to which the form information is posted Request object retrieves form data

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Fig. 33.4 : name.html <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Name Request</title> </head> <body> <p style = "font-family: arial, sans-serif"> Enter your name: </p> --> <!-- XHTML document that request an ASP document -->

Outline
name.html (1 of 2)

16

12 13 14 15 16 17 18

2004 Prentice Hall, Inc.


All rights reserved.

19 20 21 22 23 24 25 26 27

<!-- request name.asp when posted --> <form action = "name.asp" method = "post"> <input type = "text" name = "namebox" size = "20" /> <input type = "submit" name = "submitButton" action value = "Enter" /> </form> </body>

Outline
name.html (2 of 2)

17

set to ASP file where information is posted.

28 </html>

2004 Prentice Hall, Inc.


All rights reserved.

18

33.5 Simple ASP Examples


Fig. 33.4 XHTML document that requests an ASP.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<% @LANGUAGE = VBScript %> <% ' Fig. 33.5 : name.asp ' Another simple ASP example Option Explicit %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Outline
name.asp (1 of 2)

19

11 12 <html xmlns = "http://www.w3.org/1999/xhtml"> 13 14 15 16 17 18 19 20 21 22 </style> </head> <style type = "text/css"> p { font-family: arial, sans-serif; font-size: 14pt; color: navy } .special { font-size: 20pt; color: green } <head> <title>Name Information</title>

2004 Prentice Hall, Inc.


All rights reserved.

23 24 25 26 27 28 29 30 31 32 </html> </body> <!-- retrieve and display namebox's value --> <p>Hi <% =Request( "namebox" ) %>, </p><br /> <p class = "special">Welcome to ASP!</p> <body>

Outline
Request object retrieves

20

form data from text field namebox

name.asp (2 of 2)

2004 Prentice Hall, Inc.


All rights reserved.

21

33.5 Simple ASP Examples


Fig. 33.5 ASP document that responds to a client request.

2004 Prentice Hall, Inc. All rights reserved.

22

33.6 File System Objects File System Objects (FSOs)


Allow programmer to manipulate files, directories and drives Read and write text Microsoft Scripting Runtime Library (Fig 33.6)
FileSystemObject, File, Folder, Drive and TextStream

Use to create directories, move files, determine whether a Drive exists


FileSystemObject methods (Fig. 33.7)

File object Allows programmer to gather info about files, manipulate files, open files File properties and methods (Fig. 33.8)
2004 Prentice Hall, Inc. All rights reserved.

23

33.6 File System Objects


Object type
FileSystemObject File Folder Drive

Description Allows the programmer to interact with Files, Folders and Drives. Allows the programmer to manipulate Files of any type. Allows the programmer to manipulate Folders (i.e., directories). Allows the programmer to gather information about Drives (hard disks, RAM diskscomputer memory used as a substitute for hard disks to allow high-speed file operations, CD-ROMs, etc.). Drives can be local or remote. Allows the programmer to read and write text files.

TextStream

Fig. 33.6

File System Objects (FSOs).

2004 Prentice Hall, Inc. All rights reserved.

24

33.6 File System Objects


Methods
CopyFile CopyFolder

Description Copies an existing File.

Copies an existing Folder. CreateFolder Creates and returns a Folder. CreateTextFile Creates and returns a text File. DeleteFile Deletes a File. DeleteFolder Deletes a Folder. DriveExists Tests whether or not a Drive exists. Returns a boolean. FileExists Tests whether or not a File exists. Returns a boolean. FolderExists Tests whether or not a Folder exists. Returns a boolean. GetAbsolutePathName Returns the absolute path as a string. Fig. 33.7 FileSystemObjectmethods. (Part 1 of 2)

2004 Prentice Hall, Inc. All rights reserved.

25

33.6 File System Objects


Methods
GetDrive GetDriveName GetFile GetFileName GetFolder GetParentFolderName GetTempName MoveFile MoveFolder OpenTextFile

Description Returns the specified Drive. Returns the Drive drive name. Returns the specified File. Returns the File file name. Returns the specified File. Returns a string representing the parent folder name. Creates and returns a string representing a file name. Moves a File. Moves a Folder. Opens an existing text File. Returns a TextStream.

Fig. 33.7

FileSystemObjectmethods. (Part 2 of 2)

2004 Prentice Hall, Inc. All rights reserved.

26

33.6 File System Objects


Property/method Property
DateCreated DateLastAccessed DateLastModified Drive Name ParentFolder Path ShortName Size

Description Date. The date the File was created. Date. The date the File was last accessed. Date. The date the File was last modified. Drive. The Drive where the file is located. String. The File name. String. The Files parent folder name. String. The Files path. String. The Files name expressed as a short name. Variant. The size of the File in bytes. Copy the File. Same as CopyFile of FileSystemObject. Delete the File. Same as DeleteFile of FileSystemObject. Move the File. Same as MoveFile of FileSystemObject. Opens an existing File as a text File. Returns TextStream.

Method
Copy Delete Move OpenAsTextStream

Fig. 33.8

Some commonFile properties and methods.

2004 Prentice Hall, Inc. All rights reserved.

27

33.6 File System Objects File System Objects (FSOs)


Path property Contains File path in long name format
ShortName

property

Contains File path in short name format Folder object Allows programmer to manipulate and gather info about directories Folder properties (Fig. 33.9)

2004 Prentice Hall, Inc. All rights reserved.

28

33.6 File System Objects


Property/method Properties
Attributes DateCreated DateLastAccessed DateLastModified Drive IsRootFolder Name ParentFolder Path ShortName ShortPath Size Type

Description Integer. Value indicating Folders attributes (read only, hidden, etc.). Date. The date the folder was created. Date. The date the folder was last accessed. Date. The date the folder was last modified. Drive. The Drive where the folder is located. Boolean. Indicates whether or not a Folder is a root folder. String. The Folders name. Folder. The Folders parent folder. String. The Folders path. String. The Folders name expressed as a short name. String. The Folders path expressed as a short path. Variant. The total size in bytes of all subfolders and files. String. The Folder type.

Fig. 33.9

SomeFolderproperties and methods. (Part 1 of 2)

2004 Prentice Hall, Inc. All rights reserved.

29

33.6 File System Objects


Property/method Methods
Delete Move Copy

Description

Fig. 33.9

Delete the Folder. Same as DeleteFolder of FileSystemObject. Move the Folder. Same as MoveFolder of FileSystemObject. Copy the Folder. Same as CopyFolder of FileSystemObject. Some Folder properties and methods. (Part 2 of 2)

2004 Prentice Hall, Inc. All rights reserved.

30

33.6 File System Objects File System Objects (FSOs)


IsRootFolder property Indicates whether folder is the root folder for the Drive If not: Method ParentFolder Retrieves parent folder Method Size Returns the total bytes the folder contains (includes subfolders)

2004 Prentice Hall, Inc. All rights reserved.

31

33.6 File System Objects File System Objects (FSOs)


Drive object (Fig. 33.10)
Gather information about drives Property DriveLetter Contains drive letter Property SerialNumber Contains drive serial number Property FreeSpace Contains number of available bytes

2004 Prentice Hall, Inc. All rights reserved.

32

33.6 File System Objects


Property
AvailableSpace DriveLetter DriveType

Description Variant. The amount of available Drive space in bytes. String. The letter assigned to the Drive (e.g., C). Integer. The Drive type. Constants Unknown, Removable, Fixed, Remote, CDRom and RamDisk represent Drive types and have the values 05, respectively. String. The file system Drive description (FAT, FAT32, NTFS, etc.). Variant. Same as AvailableSpace. Boolean. Indicates whether or not a Drive is ready for use. String. The Drives path. Folder object. The Drives root Folder. Long. The Drive serial number. Variant. The total Drive size in bytes. String. The Drive volume name.

FileSystem FreeSpace IsReady Path RootFolder SerialNumber TotalSize VolumeName

Fig. 33.10

Drive properties.

2004 Prentice Hall, Inc. All rights reserved.

33

33.6 File System Objects File System Objects (FSOs)


TextStream object (Fig. 33.11) Manipulate text files

2004 Prentice Hall, Inc. All rights reserved.

34

33.6 File System Objects


Property/Method Properties
AtEndOfLine AtEndOfStream Column Line

Description Boolean. Indicates whether the end of a line has been encountered. Boolean. Indicates whether the end of file has been encountered. Integer. Returns the characters position in a line. Integer. Returns the current line number.

Methods String. Returns a specified number of characters from the file referenced by the TextStream object. ReadAll String. Returns the entire contents of the file referenced by the TextStream object. Fig. 33.11TextStream methods and properties. (Part 1 of 2)
Read

2004 Prentice Hall, Inc. All rights reserved.

35

33.6 File System Objects


Property/Method Methods, cont.
ReadLine Write WriteBlankLines WriteLine Skip SkipLine Close

Description

String. Returns one line from the file referenced by the TextStream object. String. Writes text to the file referenced by the TextStream object. String. Writes newline characters to the file referenced by the TextStream object. String. Writes one line to the file referenced by the TextStream object. Variant. Skips a specified number of characters while reading from the file referenced by the TextStream object. Variant. Skips a line of characters while reading from the file referenced by the TextStream object. Close the file referenced by the TextStream object.

Fig. 33.11

TextStream methods and properties. (Part 2 of 2)

2004 Prentice Hall, Inc. All rights reserved.

36

33.6 File System Objects Creating a guestbook


XHTML Form hidden field
Determine if page loaded by form submission

Write data to text file


ServerVariables APPL_PHYSICAL_PATH OpenTextFile

Append mode
8

2004 Prentice Hall, Inc. All rights reserved.

37

33.6 File System Objects Creating a guestbook, cont.


Name returned as mailto: URL
Request object

Chr function Generate characters from ASCII code

Always Close files

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9

<% @LANGUAGE = VBScript %> <% ' Fig. 33.12 : guestbook.asp ' Demonstrating File System Objects Option Explicit %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Outline
guestbook.asp (1 of 5)

38

10 11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 13 14 15 16 17 18 19 20 21 22 23 24 <style type = "text/css"> hr td p </style> </head> <body> { size: 1; color: blue } { font-size: 12pt } { font-size: 14pt; color: blue } table { text-align: center } <head> <title>GuestBook Example</title>

.font { font-family: arial, sans-serif }

2004 Prentice Hall, Inc.


All rights reserved.

25 <% 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 %> 44 45 <% 46 47 48 49 ' build the mailtoUrl & & <hr /> ' Print a thank you Call Response.Write( "Thanks for your entry, " & _ Request( "username" ) & "!" ) ' Check if this request is after the user has posted the form If Request( "hiddenInput" ) = "true" Then ' instantiate a FileSystemObject Set fileObject = Server.CreateObject( _ "Scripting.FileSystemObject" ) Dim fileObject, textFile, guestBook, mailtoUrl ' get physical path for this ASP page and ' concatenate guestbook.txt to it & "\guestbook.txt"

Outline

39

Set is required to establish a

variable in VBScript

guestbook = Request.ServerVariables(

guestbook.asp Pass Request method (2 of 5) server key "APPL_PHYSICAL_PATH" ) _ ServerVariables Creating a FSO instance APPL_PHYSICAL_PATH assigned to reference
fileObject

Concatenated with file name guestbook.txt

Request object retrieves hiddenInput value and tests it against string true Prints string followed by

users name input in the form

mailtoUrl = Date() & " <a href = " & Chr( 34 ) _

Submitted name and email "mailto:" & Request( "email" ) & Chr( 34 ) _ are combined and assigned to Pass value 34 into VBScript ">" & Request( "username" ) & "</a>: " string mailtoUrl Date() assigns:current Displays a mailto link. Chr function to produce double Request email of and server retrieves date to beginning quotes () username mailtoUrl
2004 Prentice Hall, Inc.
All rights reserved.

50 51 52 53 54 55 56 57 58 59 60 61 62 %> 63 64 65 66 67 68 69 70 71 72 73 74 </tr> <!-- write form to the client --> <form action = "guestbook.asp" method = "post"> <table> <tr> <td>Your Name: </td> ' write data to guestbook.txt Call textFile.WriteLine( "<hr Request( "comment" ) ) Call textFile.Close() End If ' open the guestbook, 8 is for appending ' create the guestbook if it does not exist Set textFile = _ fileObject.OpenTextFile( guestbook, 8, True )

Outline
guestbook.asp (3 of 5)

40

Method OpenTextFile retrieves TextStream object />" & mailtoUrl & _ Contstant 8 indicates for accessing file append mode (writing to guestbook.txt the end of the file.) method Close()TextStream method closes the file WriteLine writes to guestbook.txt

<p>Please leave a message in our guestbook.</p>

Form post action to .asp page

<td><input class = "font" type = "text" size = "60" name = "username" /></td>

2004 Prentice Hall, Inc.


All rights reserved.

75 76 77 78 79 80 81 82 83 84 85 86 87 88 <tr> <td>Tell the world: </td> <td><textarea name = "comment" rows = "3" cols = "50"> </td> </tr> <tr> <td>Your email address:</td> <td><input class = "font" type = "text" size = "60" name = "email" value = "user@isp.com" />

Outline
guestbook.asp (4 of 5)

41

Form contains two text fields and text area for user input

89 Replace this text with the information 90 you would like to post.</textarea></td> 91 92 93 94 95 96 97 98 99 </form> </tr> </table>

Passes parameter
hiddenInput value true

<input type = "submit" value = "submit" /> <input type = "reset" value = "clear" /> <input type = "hidden" name = "hiddenInput" value = "true" />

2004 Prentice Hall, Inc.


All rights reserved.

100 <% 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 %> 116 117 118 119 </html> </body> End If ' read the entries from the file and write them to ' the client. Call Response.Write( "Guestbook Entries:<br />" & _ textFile.ReadAll() ) Call textFile.Close() ' check if the file exists If fileObject.FileExists( guestBook ) = True Then

Outline
guestbook.asp (5 of 5)

42

FSO object FileExists checks if guestbook.txt ' open the guestbook, "1" is for reading exists. Set textFile = fileObject.OpenTextFile( guestbook, 1 )

TextStream and ReadAll

Read entries from methods read entire guestbook.txt and write writes contents of Response.Write guestbook.txt XHTML to the text to client client. Contains XHTML markup rendered on client browser.

2004 Prentice Hall, Inc.


All rights reserved.

43

33.6 File System Objects


Fig. 33.12 Guestbook Active Server Page.

2004 Prentice Hall, Inc. All rights reserved.

44

33.6 File System Objects


Fig. 33.12 Guestbook Active Server Page.

2004 Prentice Hall, Inc. All rights reserved.

<hr />5/24/2001 <a href = "mailto:tem@deitel.com">tem</a>:

ASP is a great tool ASP is my

for server-side development. 2 <hr />5/24/2001 <a href = "mailto:dan@bushycat.com">dan</a>: preferred server-side development tool.

Outline

45

XHTML generated by guestbook.asp (1 of 1)

2004 Prentice Hall, Inc.


All rights reserved.

46

33.6 File System Objects


Key name Description APPL_PHYSICAL_PATH Returns the physical path. HTTPS Boolean. Determines whether the request came in through SSL (Secure Sockets Layer). REMOTE_ADDR Clients DNS name or IP address. REQUEST_METHOD Request method (i.e., get and post). SERVER_NAME Servers hostname (DNS or IP address). HTTP_USER_AGENT Returns information about the client making the request. HTTP_COOKIE Returns cookies residing on the client. Fig. 33.13 Some server variable keys.

2004 Prentice Hall, Inc. All rights reserved.

47

33.7 Session Tracking and Cookies Session Tracking and Cookies


Helps server to distinguish between clients Provide custom content
Shopping cart Marketing/advertising SessionID Assigned by server to each unique session Compared with sessionIDs stored in server Session object
Timeout property

Length of session before it expires Abandon property Terminates individual session


2004 Prentice Hall, Inc. All rights reserved.

48

33.7 Session Tracking and Cookies ASP application


Multiple ASP pages linked with session variables Example
instantpage.asp

Form, requests information from the user Posted to process.asp


process.asp

Redirects user to instantpage.asp if errors exist Otherwise creates users ASP page Stores message in session variable welcomeBack Every time user submits the form

2004 Prentice Hall, Inc. All rights reserved.

49

33.7 Session Tracking and Cookies Server-side include


Commands embedded in XHTML documents Add dynamic content Places a .shtml include file within another file
Physical or virtual path
<!--#include file = includes\file.shtml -->

Not all Web servers support


Written as comment

Performed before scripting code is interpreted.


ASP page cannot determine which includes to use

Can contain scripting code


Must use <script> tag or <% %> delimiters

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<% @LANGUAGE = VBScript %> <% ' Fig. 33.15 : instantpage.asp ' ASP document that posts data to process.asp Option Explicit %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Outline
instantpage.asp (1 of 4)

50

11 12 <html xmlns = "http://www.w3.org/1999/xhtml"> 13 14 15 16 17 18 19 20 21 22 23 24 25 </head> </style> <style type = "text/css"> table { text-align: center; font-size: 12pt; color: blue; font-size: 12pt; font-family: arial, sans-serif } <head> <title>Instant Page Content Builder</title>

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 <% ' if process.asp posted an error, print the error 34 35 36 37 38 39 40 41 42 %> 43 44 45 46 47 48 ' message. If Session( "errormessage" ) <> "no error" Then Call Response.Write( Session( "errorMessage" ) ) ' otherwise, print the welcome back message, if any Else Call End If <!-- include the header <h2>Instant Page Content Builder</h2> <body>

Server-side include
-->

Outline
instantpage.asp (2 of 4)

51

<!-- #include virtual = "/includes/header.shtml" -->

value is written to client welcomeBack never session errorMessage has a variable displays value unless errors are <!-- a form Else, to get the information from the user --> WelcomeBack value iswelcome back message encountered <form action = "process.asp" method = "post"> written to the client to returning users messages
<table> <tr> <td>Your Name: </td>

First time page is executed, Session object Response.Write( Session( "welcomeBack" ) ) linevalue 35 returns true retrieves variable errorMessage session If true, errorMessage variable used for error
If statement tests errorMessage equality to no error. Return True or False.

Requests process.asp when form is posted

2004 Prentice Hall, Inc.


All rights reserved.

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

<td><input type = "text" size = "60" name = "username" /></td> </tr> <tr> <td>Enter the Filename:</td> <td><input type = "text" size = "60" name = "filename" value = "yourfilename" /></td> </tr> <tr> <td>Enter the Title:</td> <td><input type = "text" size = "60" name = "doctitle" value = "document title" /></td> </tr> <tr> <td>Enter the content:</td> <td><textarea name = "content" rows = "3"

Outline
instantpage.asp (3 of 4)

52

2004 Prentice Hall, Inc.


All rights reserved.

73

cols = "50">

74 Replace this text with the 75 information you would like to post.</textarea></td> 76 77 78 79 80 81 82 83 84 <!-- #include virtual = "/includes/footer.shtml" --> </body> </tr> </table>

Outline
instantpage.asp (4 of 4)

53

Server-side include <input type = "submit" value = "submit" />


<input type = "reset" value = "clear" /> </form>

85 </html>

2004 Prentice Hall, Inc.


All rights reserved.

54

33.7 Session Tracking and Cookies


Fig. 33.15 ASP that posts user information to process.asp.

2004 Prentice Hall, Inc. All rights reserved.

55

33.7 Session Tracking and Cookies


Fig. 33.15 ASP that posts user information to process.asp.

2004 Prentice Hall, Inc. All rights reserved.

56

33.7 Session Tracking and Cookies


Fig. 33.15 ASP that posts user information to process.asp.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5

<!-- Fig. 33.16: header.shtml <hr style = "color: blue" />

-->

<!-- Server-side include file containing XHTML --> <img height = "100" src = "/images/bug2bug.gif" alt = "Bug" /> <hr style = "color: blue" />

Outline
header.shtml (1 of 1)

57

2004 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8

<!-- Fig. 33.17: footer.shtml <hr style = "color: blue" /> <a style = "text-align: center"

-->

<!-- Server-side include file containing XHTML -->

Outline
footer.shtml
server-side include file for the document footer

58

href = "mailto:orders">ordering information</a> <a style = "text-align: center" href = "mailto:editor">contact the editor</a><br /> <hr style = "color: blue" />

2004 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9 10

<% @LANGUAGE = VBScript %> <% ' Fig. 33.18 : process.asp ' ASP document that creates user's ASP document Option Explicit %> <%

Outline
process.asp (1 of 6)

59

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

If field is empty or contains default string yourfilename, lines 19-21 Dim message, q assign XHTML error message to variable If statement validates message. q = Chr( 34 ) ' assign quote character to q Session( "errorMessage" ) = "no error"contents of text field.
' check to make sure that they have entered a ' valid filename If ( LCase( Request( "filename" ) ) = "yourfilename" ) _Assign Or Request( "filename" ) = "" Then message = "<p style = " & q & "color: red" & q & _ Session( "errorMessage" ) = message Call Server.Transfer( "instantpage.asp" ) End If Dim directoryPath, filePath, fileObject, fileName

message value to

session variable
errorMessage

">" & "Please enter a valid name or filename.</p>"

Server method Transfer requests


instantpage.asp 2004 Prentice Hall, Inc.
All rights reserved.

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 ' check if the file already exists If fileObject.FileExists( filePath ) Then message = "<p style = " & q & "color: red" & q & _ ">" & "The file name is in use.<br />" & _ "Please use a different file name.</p>" filePath Session( "errorMessage" ) = End If Call Server.Transfer( "instantpage.asp" ) ' build path for text file filePath = directoryPath & "\" & fileName fileName = Request( "filename" ) & ".asp" directoryPath = _ Request.ServerVariables( "APPL_PHYSICAL_PATH" ) ' Create a FileSystem Object Set fileObject =

Request.ServerVariables Server.CreateObject( _

retrieves)physical "Scripting.FileSystemObject"

path

FSO object is created if validOutline user name is entered and assigned Builds fileName by reference fileObject concatenating process.asp filename to the .asp (2 of 6) file extension Specify server path where ASP file is written

60

If file exists, variable errorMessage value is set to XHTML containing error message

passed FileExists message method. Determines if file exists.

Server.Transfer method requests instantpage.asp

2004 Prentice Hall, Inc.


All rights reserved.

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

' save XHTML for the welcome back message ' in a session variable message = "<p style = " & q & "color: blue" & q & _ ">" & "Welcome Back, " & Request( "username" ) & _ "</p><br />" Session( "welcomeBack" ) = message Dim header, footer, textFile, openMark, closeMark openMark = "<" & "%" closeMark = "%" & ">"

Outline
process.asp (3 of 6)

61

Construct XHTML for header Assigns XHTML for welcome back message to welcomeBack ' build the header. Assign ASP scripting ' vbCrLf inserts a carriage return/linefeed into session the text variable delimiters to string variables ' string which makes the XHTML code more readable openMark and closeMark header = openMark & " @LANGUAGE = VBScript " & closeMark _
& vbCrLf & openMark & " ' " & fileName _ & " " & closeMark & vbCrLf & vbCrLf _ & "<!DOC" & "TYPE html PUBLIC " & q & _ "-//W3C//DTD XHTML 1.0 Transitional//EN" & q & _ vbCrLf & q & "http://www.w3.org/TR/xhtml1/" & _ "DTD/xhtml1-transitional.dtd" & q & ">" & vbCrLf & _ "<html xmlns = " & q & "http://www.w3.org/1999/xhtml" & _ q & ">" & vbCrLf & "<head>" & vbCrLf _ & "<meta name = " & q & "author" & q & " content = " _ & q & Request( "username" ) & q & " />" & vbCrLf _ & "<meta name = " & q & "pubdate" & q & " content = " _

2004 Prentice Hall, Inc.


All rights reserved.

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

& q & Date() & q & " />" & vbCrLf _ & "<title>" & Request( "doctitle" ) & "</title>" _ & vbCrLf & "</head>" & vbCrLf & "<body>" & vbCrLf _ & "<!-- #" & "include " & "virtual = " & _ "/includes/header.shtml -->" _ & vbCrLf & "<h2 style = " & q & "text-align: center" & _ vbCrLf & "<br />" & vbCrLf ' build the footer using a different style for ' building the string footer = vbCrLf & "<br /><br /><br />" & vbCrLf & _ "You have requested this page on " & _ openMark & " =Date() " & closeMark & "," & _ vbCrLf & "at " & openMark & " =Time() " & _ closeMark & "." & vbCrLf & _ "<!-- #" & "include " & "virtual = " & _ "/includes/footer.shtml -->" _ & vbCrLf & vbCrLf & "</body>" & vbCrLf & "</html>"

Outline
process.asp (4 of 6)

62

footer variable q & "><em>" & Request( "doctitle" ) & "</em></h2>" & _

assigned to XHTML footer contents Form values retrieved using Request object

2004 Prentice Hall, Inc.


All rights reserved.

94 95 96 97 98 99 100 101 %> 102

' create the ASP file Set textFile = fileObject.CreateTextFile( filePath, False ) With textFile Call .WriteLine( header & Request( "content" ) & _ footer )

Outline
process.asp (5 of 6)

63

Lines Call .Close()


End With

103-129 send XHTML to client that contains link to created page

103 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 104 105 106 <html xmlns = "http://www.w3.org/1999/xhtml"> 107 108 109 110 111 112 113 114 115 116 117 118 </head> <style type = "text/css"> h2 { font-family: arial, sans-serif; text-align: center } </style> <head> <!-- use the title given by the user --> <title>File Generated: <% =fileName %></title> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

2004 Prentice Hall, Inc.


All rights reserved.

119 120 121 122 123 124 125 126 127 128

<body> <!-- #include virtual = "/includes/header.shtml" --> <h2><em>File <% =fileName %> was created successfully.</em> </h2><br /> <!-- provide a link to the generated page --> <a href = "<% =fileName %>">View your file</a> <!-- #include virtual = "/includes/footer.shtml" --> </body>

Outline
process.asp (6 of 6)

64

129 </html>

2004 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 21

<% @LANGUAGE = VBScript %> <% ' aboutme.asp %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta name = "author" content = "tem" /> <meta name = "pubdate" content = "2/27/2001" /> <title>About Me</title> </head> <body> <!-- Fig. 33.16: header.shtml <hr style = "color: blue" /> <img height = "100" src = "/images/bug2bug.gif" alt = "Bug" /> <hr style = "color: blue" /> <h2 style = "text-align: center"><em>About Me</em></h2> <br /> <br /><br /><br /> --> <!-- Server-side include file containing XHTML -->

Outline
aboutme.asp (1 of 2)

65

20 This page contains lots of exciting and interesting information about me! 22 You have requested this page on 10/15/2003, 23 at 11:45:47 AM. 24 25 <!-- Fig. 33.17: footer.shtml --> <!-- Server-side include file containing XHTML -->

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33

<hr style = "color: blue" /> <a style = "text-align: center" href = "mailto:orders">ordering information</a> <a style = "text-align: center" href = "mailto:editor">contact the editor</a><br /> <hr style = "color: blue" /> </body>

Outline
aboutme.asp (2 of 2)

66

34 </html>

2004 Prentice Hall, Inc.


All rights reserved.

67

33.7 Session Tracking and Cookies


Fig. 33.20 Welcome back message displayed by instantpage.asp.

2004 Prentice Hall, Inc. All rights reserved.

68

33.7 Session Tracking and Cookies


Fig. 33.21 Error message generated by instantpage.asp.

2004 Prentice Hall, Inc. All rights reserved.

69

33.8 ActiveX Data Objects (ADO) ADO


Enables database connectivity Part of Universal Data Access architecture
OLE DB provides low-level access ODBC allows C programs to access databases ADO allows web applications to access databases

Provides pre-built objects for use in ASP and VBScript


Collections

2004 Prentice Hall, Inc. All rights reserved.

70

33.8 ActiveX Data Objects (ADO)


Fig. 33.22 Microsofts UDA architecture.

Application or Browser

ADO OLE DB ODBC Relational data sources Non-relational data sources Legacy data

2004 Prentice Hall, Inc. All rights reserved.

71

33.8 ActiveX Data Objects (ADO)


Fig. 33.23 Portion of the ADO object model.

Connection Command Errors RecordSet Parameters Error Fields Field Parameter

2004 Prentice Hall, Inc. All rights reserved.

72

33.8 ActiveX Data Objects (ADO)


Object/Collection Description
Connection object Command object Parameter object Parameters collection Error object Errors collection Recordset object Field object Fields collection Property object Properties collection Record object Stream object Connects to the data source. Contains the query that interacts with the database (the data source) to manipulate data. Contains information needed by a Command object to query the data source. Contains one or more Parameter objects. Created when an error occurs while accessing data. Contains one or more Error objects. Contains zero or more records that match the database query. Collectively, this group of records is called a recordset. Contains the value (and other attributes) of one data source field. Contains one or more Field objects. Contains a characteristic of an ADO object. Contains one or more Property objects. Contains a single row of a Recordset. Contains a stream of binary data.

Fig. 33.24

Some ADO object and collection types.

2004 Prentice Hall, Inc. All rights reserved.

33.9 Accessing a Database from an Active Server Page Web applications


Communicating with databases
Use ActiveX Data Objects (ADO) Provides uniform way for programs to connect with databases

73

Three-tier distributed applications


User interface Created with XHTML, DHTML or XML Contains ActiveX controls, client-side scripts, Java applets Communicate directly with business logic Business logic Database access May reside on separate computers
2004 Prentice Hall, Inc. All rights reserved.

33.9 Accessing a Database from an Active Server Page


Web applications, cont.
Three-tier distributed applications, cont.
Web servers build middle tier Provide business logic Manipulates databases Communicates with client Web browsers

74

ASP communications with databases


Use SQL-based queries ADO handled specifics Through OLE DB Databases provide data source for dynamic content Allows users who are not familiar with Web languages to create Web pages Restrict access Password protection Query Access database
2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12

<% @LANGUAGE = VBScript %> <% ' Fig. 33.25 : database.asp ' ASP document for interacting with the database Option Explicit

Outline
database.asp (1 of 2)

75

13 14 15 16 17 18 19 20 21 22 23 24

Ignores errors until end of script Dim connection, loginData Server method When Open finishes CreateObject creates executing, points to first ' provide error handling code ADODB.Connection Declares session record Method Open opensor EOF if no On Error Resume Next variable records database specified bywere found Session( "errorString" ) = "" errorString ODBC System DSN errorHandlerLog loginData(login reference to ) is set Set connection = Server.CreateObject( "ADODB.Connection" ) processes errors an ADODB.recordset object Call connection.Open( "login" ) Open method is passed string Call errorHandlerLog() containing SQL query and ADODB.Connection object errorHandlerLog ' create the record set called again
Set loginData = Server.CreateObject( "ADODB.Recordset" ) Call loginData.Open( Session( "query" ), connection ) Set Session( "loginData" ) = loginData Call errorHandlerLog()

Sets session variable loginData to variable loginData which references the ADODB.recordset containing all records matching SQL query
2004 Prentice Hall, Inc.
All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 %>

Sub errorHandlerLog()

Outline If true, errorString Dim errorString variable is assigned XHTML text containing errorString = Session( "errorString" ) Error numberdatabase.asp and message error number and message (2 2) errorString = errorString & "<p class = " & _ concatenated to of variable Chr( 34 ) & "error" & Chr ( 34 ) & ">Error (" _ errorString Err object Number property & Err.Number & ") in " & Err.Source & "<br />" & _ contains VBScript error Err.Description & "</p><br />" number. Tests if error has Session( "errorString" ) = errorString occurred.
If Err.Number <> 0 Then End If End Sub

76

2004 Prentice Hall, Inc.


All rights reserved.

33.9 Accessing a Database from an Active Server Page


Fig. 33.26 Error messages sent to login.asp by database.asp.

77

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<% @LANGUAGE = VBScript %> <% ' Fig. 33.27 : login.asp ' ASP document to login to instantpage.asp Option Explicit ' create the SQL query Session( "query" ) = "SELECT loginID FROM Users" Call Server.Execute( "database.asp" )

Outline
login.asp (1 of 7)

78

11 %> 12 14 15 13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

Assigns SQL query to session variable "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Executes database.asp to retrieve query login IDs from the database

16 <html xmlns = "http://www.w3.org/1999/xhtml"> 17 18 19 20 21 22 23 24 25 <style type = "text/css"> table { text-align: center; font-size: 12pt; color: blue; font-size: 12pt; <head> <title>Login Page</title>

2004 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32 33 34 35 <% 36 37 38 39 40 41 42 <% 43 44 45 46 47 End If <body> </head> </style>

font-family: arial, sans-serif } .error { color: red }

Outline
login.asp (2 of 7)

79

<!-- #include virtual="/includes/header.shtml" --> If Session( "errorString" ) = "" Then ' if this is a return after a failed attempt, ' print an error If Session( "loginFailure" ) = True Then %> <p class = "error">Login attempt failed,

Tests please try again</p>

if session variable errorString value is empty string

' begin the form %> <p>Please select your name and enter your password to login:</p><br />

Lines 39-41 test is session variable loginFailure is True

2004 Prentice Hall, Inc.


All rights reserved.

48 49 50 51 52 53 54 55 56 57 58 59 60 <% 61 62 63 64 65 66 %> 67 68 69 70

<form action = "submitlogin.asp" method = "post"> <!-- format the form using a table --> <table border = "0"> <tr> <td>Name:</td> <td> <select name = "loginID"> <option value = "noSelection">

Outline
login.asp (3 of 7)

80

select structure builds drop-down list of loginIDs

Requests loginID Select your name</option>

cookie

If Request.Cookies( "loginID" ) <> "" Then Call BuildReturning() Else Call BuildNewUser() End If </select> </td> </tr>

Selects the returning users login ID option Build loginID options

2004 Prentice Hall, Inc.


All rights reserved.

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 <% 88 89 90 91 %> 92 94 </body> 93 </html> Else

<tr> <td>Password:</td> <td><input type = "password" name = "password" /></td> </tr> <tr> <td></td> <td align = "left"> <input type = "submit" value = "Log Me In" /> </td> </tr> </table> </form> <!-- #include virtual="/includes/footer.shtml" -->

Outline
login.asp (4 of 7)

81

Call Response.Write( Session( "errorString" ) ) End If

If false, print error message to user

2004 Prentice Hall, Inc.


All rights reserved.

95 <% 96 97 98 99 100 101 102 103 104 105 106 107 108 109 %> 110 <% 111 112 113 114 115 116 117 118 119 ' if the current record's loginID is equal to ' the loginID cookie, then it is the loginID of ' the returning user, and thus we need to write ' selected for this option; in this case we also ' need to signal that we have written selected ' for an option by setting found to True. While Not loginData.EOF ' create this record's dropdown entry <option ' if we did not write selected for ' before If ( Not found ) Then ' pull user names from the record set to populate the ' dropdown list found = False Set loginData = Session( "loginData" ) ' builds the option items for loginIDs and writes ' selected for the loginID of the returning user Sub BuildReturning() Dim found, loginData

Outline
login.asp (5 of 7)

82

Tests for EOF


found set to False If statement tests whether before needs loop to be option any option selected

2004 Prentice Hall, Inc.


All rights reserved.

120 121 122 123 124 125 126 127 %> 128 129 <% 130 131 132

If Request.Cookies( "loginID" ) _ = loginData( "loginID" ) Then Call Response.Write( "selected = " & _ Chr( 34 ) & "selected" & Chr( 34 ) ) found = True End If End If

Outline If statement writes selected for an


option login.asp (6 of 7)

83

Once selected is Determines whether current written for an option, value = "<% =loginData( "loginID" ) %>"> records loginID field is found set to true <% =loginData( "loginID" ) %></option> equal to loginID cookie
Call loginData.MoveNext()

Wend End Sub

2004 Prentice Hall, Inc.


All rights reserved.

133 134 135 136 137 138 139 140 141 142 143 144 %> 145 146 <% 147 148 149 %>

' builds the option items for loginIDs without writing ' selected for any loginID Sub BuildNewUser() Dim loginData Set loginData = Session( "loginData" ) ' pull user names from the record set to populate the Increments ' dropdown list While Not loginData.EOF ' create this record's dropdown entry <option value = "<% =loginData( "loginID" ) %>"> <% =loginData( "loginID" ) %></option> Call loginData.MoveNext() Wend End Sub

Outline
login.asp (7 of 7) the record set pointer to next record

84

Writes option display as while loop (lines 107-130) iterates current login ID through loginDatas records Sets option value to current login ID

2004 Prentice Hall, Inc.


All rights reserved.

33.9 Accessing a Database from an Active Server Page


Fig. 33.27 ASP document that allows the user to log in to a site.

85

2004 Prentice Hall, Inc. All rights reserved.

33.9 Accessing a Database from an Active Server Page


Fig. 33.27 ASP document that allows the user to log in to a site.

86

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

<% @LANGUAGE = VBScript %> <%

Check whether password ' Fig. 33.28 : submitlogin.asp field is empty or id ' ASP document to check user's username and password loginID field contains Option Explicit default value If so, variable ' test if a user name and a password were
If Request( "password" ) = "" Or _ Request( "loginID" ) = "noSelection" Session( "loginFailure" ) = True Call Server.Transfer( "login.asp" ) End If Dim connection, loginData ' create the SQL query Session( "query" ) = _ "SELECT * FROM Users WHERE loginID = '" & _ Request( "loginID" ) & "'" Call Server.Execute( "database.asp" ) Set loginData = Session( "loginData" )

Outline
submitlogin.asp
(1 of 2)

87

loginFailure ' entered. If not, transfer back to the login page.

set to true, client redirected back to login.asp Then

Checks password against the WHERE specifies a password in recordset condition on which records are selected Sets reference loginData to Executes database.asp to session variable loginData query database (contains records matching query.)

21 22 23 24

2004 Prentice Hall, Inc.


All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 %>

If Request( "password" ) = loginData( "password" ) Then

Sets cookies expiration date to ' password is OK, adjust loginFailure current date plus 3 days
Session( "loginFailure" ) = False

Sets session variable If true, line writes forms loginID loginFailure value submitlogin.asp value as cookie named loginID to False
(2 of 2)

Outline

88

' write a cookie to recognize them the next time they ' go to login.asp Response.Cookies( "loginID" ) = Request( "loginID" ) ' give it three days to expire

Response.Cookies( "loginID" ).Expires = Date() + 3 ' send them to instantpage.asp Otherwise loginFailure Call Else Session( "loginFailure" ) = True Call Server.Transfer( "login.asp" ) End If

Calls Server method Transfer to redirect client to instantpage.asp

set to True Server.Transfer( ) and client is "instantpage.asp" redirected to login.asp

2004 Prentice Hall, Inc.


All rights reserved.

33.9 Accessing a Database from an Active Server Page


Fig. 33.28 ASP document that validates user login.

89

2004 Prentice Hall, Inc. All rights reserved.

33.9 Accessing a Database from an Active Server Page


Fig. 33.28 ASP document that validates user login.

90

2004 Prentice Hall, Inc. All rights reserved.

33.9 Accessing a Database from an Active Server Page


Fig. 33.29 Cookies folder before and after cookie creation.

91

2004 Prentice Hall, Inc. All rights reserved.

92

33.10 Server-Side ActiveX Components ActiveX controls on the server with no GUI
Make features available in ASP AdRotator ActiveX component
Rotates advertisements on a Web page Randomly displays one of several advertisements Minimizes space on a Web page committed to advertisements Client does not have to support ActiveX technologies (on the server)

PageCounter ActiveX component


Page hit counter

2004 Prentice Hall, Inc. All rights reserved.

93

33.10 Server-Side ActiveX Components


Description MSWC.BrowserType ActiveX component for gathering information about the clients browser (e.g., type, version). MSWC.AdRotator ActiveX component for rotating advertisements on a Web page. MSWC.NextLink ActiveX component for linking Web pages together. MSWC.ContentRotator ActiveX component for rotating HTML content on a Web page. MSWC.PageCounter ActiveX component for storing the number of times a Web page has been requested. MSWC.Counters ActiveX components that provide general-purpose persistent counters. MSWC.MyInfo ActiveX component that provides information about a Web site (e.g., owner name, owner address). Scripting.FileSystemObje ActiveX component that provides an object library for ct accessing files on the server or on the servers network. ActiveX Data Objects (ADO) ActiveX components that provide an object library Data Access Components for accessing databases. Fig. 33.30 Some server-side ActiveX components. Component name

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<% @LANGUAGE = VBScript %> <% ' Fig. 33.31 : component.asp ' Demonstrating Server-side ActiveX Components Option Explicit %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Outline
component.asp (1 of 4)

94

11 12 <html xmlns = "http://www.w3.org/1999/xhtml"> 13 14 15 16 17 18 19 20 21 22 23 24 <p> <strong style = "font-family: arial, sans-serif"> Server-side ActiveX Components </strong> <body> <head> <title>ActiveX Component Example</title> </head>

2004 Prentice Hall, Inc.


All rights reserved.

25 <% 26 27 28 29 30 31 32 33 34 35 36 37 38 39 %> 40 41 42 43 <% 44 45 46 47 %> 48 49 50 <script language = "JavaScript"> alert( "Client browser supports JavaScript!" ); </script> If browser.JavaScript = True Then End If If browser.VBScript = True Then ' create a BrowserType object Set browser = Server.CreateObject( "MSWC.BrowserType" ) Dim rotator, browser, information, counter

Outline
component.asp (2 of 4)

95

Sends advertisement as HTML to client. Method ' create an AdRotator object GetAdvertisement called using reference rotator. Set rotator = Server.CreateObject( "MSWC.AdRotator" ) Retrieves advertisements from config.txt
' use config.txt to send an advertisement to theCreates client Call Response.Write( _ rotator.GetAdvertisement( "config.txt" ) )

AdRotator component instance, assigns it reference rotator

Obtains information about users browser


<script language = "VBScript"> Call Msgbox( "Client browser supports VBScript!" ) </script>

Check property VBScript value

Test JavaScript property

2004 Prentice Hall, Inc.


All rights reserved.

51 <% 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 %> ' create Page Counter Object Set counter = Server.CreateObject( "MSWC.PageCounter" ) Call counter.PageHit() ' page has been "hit" If browser.Cookies Then information = information & "enabled</p><br />" Else information = information & "disabled</p><br />" End If End If

' get client's browser information

BrowserType objects Browser, Version and MinorVer properties

Outline
Passes server variable key component.asp HTTP_USER_AGENT(3 toof 4) ServerVariables, obtains string containing user information

96

information = "<p>Your browser information is:<br />" & _ Request.ServerVariables( "HTTP_USER_AGENT" ) & _ "<br />Browser: " & browser.Browser & " Version: " & _ browser.Version & " Minor version: " & _ browser.MinorVer & "<br />Cookies are "

can obtain similar client information

Tests Cookies property to determine if browser supports cookies

Call Response.Write( information )

Increments number of hits by one

2004 Prentice Hall, Inc.


All rights reserved.

73 74 75 76 77 78

</p>

Returns number of hits


<p style = "color: blue; font-size: 12pt"> This page has been visited <% =counter.Hits() %> times!</p> </body>

Outline

97

component.asp (4 of 4)

79 </html>

2004 Prentice Hall, Inc.


All rights reserved.

98

33.10 Server-Side ActiveX Components


Fig. 33.31 Demonstrating server-side ActiveX components.

2004 Prentice Hall, Inc. All rights reserved.

99

33.10 Server-Side ActiveX Components


Fig. 33.31 Demonstrating server-side ActiveX components.

2004 Prentice Hall, Inc. All rights reserved.

100

33.10 Server-Side ActiveX Components


Fig. 33.31 Demonstrating server-side ActiveX components.

2004 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9

REDIRECT redirect.asp width 54 height 36 border 1 * /images/us.gif United States Information 20

Header contains REDIRECT file URL Image URL, destination URL, Advertisement dimensions Asterisk separates header alt value, image display ratio from advertisements

Outline
config.txt (1 of 1)

10 1

http://www.odci.gov/cia/publications/factbook/geos/us.html

10 /images/france.gif 11 http://www.odci.gov/cia/publications/factbook/geos/fr.html 12 France Information 13 20 14 /images/germany.gif 15 http://www.odci.gov/cia/publications/factbook/geos/gm.html 16 Germany Information 17 20 18 /images/italy.gif 19 http://www.odci.gov/cia/publications/factbook/geos/it.html 20 Italy Information 21 20 22 /images/spain.gif 23 http://www.odci.gov/cia/publications/factbook/geos/sp.html 24 Spain Information 25 20

2004 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9

<% @LANGUAGE = VBScript %> <% ' Fig. 33.33 : redirect.asp ' Redirection Page for AdRotator Component Option Explicit Call Response.Redirect( Request( "url" ) ) %>

Outline
redirect.asp (1 of 1)

10 2

2004 Prentice Hall, Inc.


All rights reserved.

You might also like