Professional Documents
Culture Documents
4.2 ASP Basics
4.2 ASP Basics
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
Response
Sends information to client XHTML, text
Server
Access to server methods or properties
2004 Prentice Hall, Inc. All rights reserved.
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.
Option Explicit As in VBScript, forces all variables to be declared in advance FormatDateTime Time to display
Now
Format to display in
1 2 3 4 5 6 7 8 9 10
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
"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>
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
12
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
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>
15
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
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
28 </html>
18
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>
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
name.asp (2 of 2)
21
22
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
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
24
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)
25
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)
26
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
27
property
Contains File path in short name format Folder object Allows programmer to manipulate and gather info about directories Folder properties (Fig. 33.9)
28
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
29
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)
30
31
32
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.
Fig. 33.10
Drive properties.
33
34
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
35
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
36
Append mode
8
37
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>
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
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
Request object retrieves hiddenInput value and tests it against string true Prints string followed by
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
<td><input class = "font" type = "text" size = "60" name = "username" /></td>
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" />
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 )
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.
43
44
for server-side development. 2 <hr />5/24/2001 <a href = "mailto:dan@bushycat.com">dan</a>: preferred server-side development tool.
Outline
45
46
47
48
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
49
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>
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
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.
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
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
85 </html>
54
55
56
1 2 3 4 5
-->
<!-- 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
1 2 3 4 5 6 7 8
<!-- Fig. 33.17: footer.shtml <hr style = "color: blue" /> <a style = "text-align: center"
-->
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" />
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
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
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 = " _
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
' 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
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">
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>
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 -->
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>
67
68
69
70
Application or Browser
ADO OLE DB ODBC Relational data sources Non-relational data sources Legacy data
71
72
Fig. 33.24
73
74
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
77
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
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>
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,
' begin the form %> <p>Please select your name and enter your password to login:</p><br />
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
cookie
If Request.Cookies( "loginID" ) <> "" Then Call BuildReturning() Else Call BuildNewUser() End If </select> </td> </tr>
<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
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
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
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()
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
85
86
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
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
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
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 %>
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
89
90
91
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)
93
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>
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" ) )
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
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 "
73 74 75 76 77 78
</p>
Outline
97
component.asp (4 of 4)
79 </html>
98
99
100
1 2 3 4 5 6 7 8 9
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
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