Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 33 - Active Server Pages (ASP)

Similar presentations


Presentation on theme: "Chapter 33 - Active Server Pages (ASP)"— Presentation transcript:

1 Chapter 33 - Active Server Pages (ASP)
Outline Introduction How Active Server Pages Work Setup Active Server Page Objects Simple ASP Examples File System Objects Session Tracking and Cookies 33.8 ActiveX Data Objects (ADO) Accessing a Database from an Active Server Page Server-Side ActiveX Components Web Resources

2 In this tutorial, you will learn:
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.

3 Server-side technologies
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

4 33.2 How Active Server Pages Work
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

5 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)

6 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

7 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

8 33.4 Active Server Page Objects

9 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

10 Scripting delimiter wraps around code executed on the server.
Processing directive specifying scripting language clock.asp (1 of 2) Requires programmer explicitly define all variables

11 Returns server date and time (Now) as a string formatted in vbLongDate format
“<%=“ is short for Response.write clock.asp (2 of 2) Statement is short for: <% Call Response.write( Time()) %>

12 33.5 Simple ASP Examples Fig Simple Active Server Page.

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

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

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

16 name.html (1 of 2)

17 action set to ASP file where information is posted.
name.html (2 of 2)

18 33.5 Simple ASP Examples Fig XHTML document that requests an ASP.

19 name.asp (1 of 2)

20 name.asp (2 of 2) Request object retrieves form data from text field “namebox”

21 33.5 Simple ASP Examples Fig ASP document that responds to a client request.

22 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)

23 33.6 File System Objects

24 33.6 File System Objects

25 33.6 File System Objects

26 33.6 File System Objects

27 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)

28 33.6 File System Objects

29 33.6 File System Objects

30 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)

31 File System Objects (FSOs)
Drive object (Fig ) Gather information about drives Property DriveLetter Contains drive letter Property SerialNumber Contains drive serial number Property FreeSpace Contains number of available bytes

32 33.6 File System Objects

33 File System Objects (FSOs)
TextStream object (Fig ) Manipulate text files

34 33.6 File System Objects

35 33.6 File System Objects

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

37 Creating a guestbook, cont.
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

38 guestbook.asp (1 of 5)

39 Concatenated with file name guestbook.txt
Set is required to establish a variable in VBScript Pass Request method ServerVariables server key APPL_PHYSICAL_PATH guestbook.asp (2 of 5) Creating a FSO instance assigned to reference fileObject Request object retrieves hiddenInput value and tests it against string “true” Prints string followed by users name input in the form Submitted name and are combined and assigned to string mailtoUrl Pass value 34 into VBScript Chr function to produce double quotes (“”) Displays a mailto: link. Date() assigns current server date to beginning of mailtoUrl Request retrieves “ ” and “username”

40 Contstant 8 indicates append mode (writing to the end of the file.)
guestbook.asp (3 of 5) Method OpenTextFile retrieves TextStream object for accessing file guestbook.txt Contstant 8 indicates append mode (writing to the end of the file.) TextStream method WriteLine writes to guestbook.txt Close() method closes the file Form post action to .asp page

41 Form contains two text fields and text area for user input
guestbook.asp (4 of 5) Passes parameter hiddenInput value “true”

42 FSO object FileExists checks if guestbook.txt exists.
guestbook.asp (5 of 5) Response.Write writes text to client. Contains XHTML markup rendered on client browser. Read entries from guestbook.txt and write XHTML to the client TextStream and ReadAll methods read entire contents of guestbook.txt

43 33.6 File System Objects Fig Guestbook Active Server Page.

44 33.6 File System Objects Fig Guestbook Active Server Page.

45 XHTML generated by guestbook.asp (1 of 1)

46 33.6 File System Objects

47 33.7 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

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

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

50 instantpage.asp (1 of 4)

51 First time page is executed, line 35 returns true
Server-side include instantpage.asp (2 of 4) If statement tests errorMessage equality to “no error”. Return True or False. Session object retrieves variable value errorMessage never has a value unless errors are encountered errorMessage session variable used for error messages First time page is executed, line 35 returns true If true, errorMessage value is written to client Else, WelcomeBack value is written to the client welcomeBack session variable displays “welcome back” message to returning users Requests process.asp when form is posted

52 instantpage.asp (3 of 4)

53 instantpage.asp (4 of 4) Server-side include

54 33.7 Session Tracking and Cookies
Fig ASP that posts user information to process.asp.

55 33.7 Session Tracking and Cookies
Fig ASP that posts user information to process.asp.

56 33.7 Session Tracking and Cookies
Fig ASP that posts user information to process.asp.

57 header.shtml (1 of 1)

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

59 Assign message value to session variable errorMessage
process.asp (1 of 6) If field is empty or contains default string yourfilename, lines assign XHTML error message to variable message. If statement validates contents of text field. Assign message value to session variable errorMessage Server method Transfer requests instantpage.asp

60 Builds fileName by concatenating “filename” to the .asp file extension
FSO object is created if valid user name is entered and assigned reference fileObject Request.ServerVariables retrieves physical path Builds fileName by concatenating “filename” to the .asp file extension process.asp (2 of 6) Specify server path where ASP file is written If file exists, variable errorMessage value is set to XHTML containing error message filePath passed FileExists method. Determines if file exists. Server.Transfer method requests instantpage.asp

61 process.asp (3 of 6) Assigns XHTML for “welcome back” message to welcomeBack session variable Assign ASP scripting delimiters to string variables openMark and closeMark Construct XHTML for header

62 Form values retrieved using Request object process.asp (4 of 6)
footer variable assigned to XHTML footer contents

63 process.asp (5 of 6) Lines send XHTML to client that contains link to created page

64 process.asp (6 of 6)

65 aboutme.asp (1 of 2)

66 aboutme.asp (2 of 2)

67 33.7 Session Tracking and Cookies
Fig Welcome back message displayed by instantpage.asp.

68 33.7 Session Tracking and Cookies
Fig Error message generated by instantpage.asp.

69 33.8 ActiveX Data Objects (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

70 33.8 ActiveX Data Objects (ADO)
Fig Microsoft’s UDA architecture. ADO OLE DB Legacy data Relational data sources Application or Browser Non-relational data sources ODBC

71 33.8 ActiveX Data Objects (ADO)
Fig Portion of the ADO object model. Connection Command Parameters Parameter Errors Error RecordSet Fields Field

72 33.8 ActiveX Data Objects (ADO)

73 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 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

74 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 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

75 Ignores errors until end of script
database.asp (1 of 2) Ignores errors until end of script Server method CreateObject creates ADODB.Connection When Open finishes executing, points to first record or EOF if no records were found Declares session variable errorString Method Open opens database specified by ODBC System DSN (login) loginData reference is set to an ADODB.recordset object errorHandlerLog processes errors Open method is passed string containing SQL query and ADODB.Connection object errorHandlerLog called again Sets session variable loginData to variable loginData which references the ADODB.recordset containing all records matching SQL query

76 Error number and message concatenated to variable errorString
If true, errorString variable is assigned XHTML text containing error number and message Err object Number property contains VBScript error number. Tests if error has occurred. database.asp (2 of 2) Error number and message concatenated to variable errorString

77 33.9 Accessing a Database from an Active Server Page
Fig Error messages sent to login.asp by database.asp.

78 login.asp (1 of 7) Assigns SQL query to session variable query Executes database.asp to retrieve login IDs from the database

79 login.asp (2 of 7) Tests if session variable errorString value is empty string Lines test is session variable loginFailure is True

80 Requests loginID cookie
login.asp (3 of 7) select structure builds drop-down list of loginIDs Requests loginID cookie Selects the returning user’s login ID option Build loginID options

81 login.asp (4 of 7) If false, print error message to user

82 login.asp (5 of 7) Tests for EOF found set to False before loop
If statement tests whether option needs to be selected

83 Once selected is written for an option, found set to true
Determines whether current record’s loginID field is equal to loginID cookie If statement writes selected for an option login.asp (6 of 7) Once selected is written for an option, found set to true

84 Increments the record set pointer to next record
login.asp (7 of 7) Increments the record set pointer to next record while loop (lines ) iterates through loginData’s records Sets option value to current login ID Writes option display as current login ID

85 33.9 Accessing a Database from an Active Server Page
Fig ASP document that allows the user to log in to a site.

86 33.9 Accessing a Database from an Active Server Page
Fig ASP document that allows the user to log in to a site.

87 Checks password against the password in recordset
Check whether password field is empty or id loginID field contains default value submitlogin.asp (1 of 2) If so, variable loginFailure set to true, client redirected back to login.asp Checks password against the password in recordset WHERE specifies a condition on which records are selected Executes database.asp to query database Sets reference loginData to session variable loginData (contains records matching query.)

88 Sets cookie’s expiration date to current date plus 3 days
Sets session variable loginFailure value to False If true, line writes form’s loginID value as cookie named loginID submitlogin.asp (2 of 2) Calls Server method Transfer to redirect client to instantpage.asp Otherwise loginFailure set to True and client is redirected to login.asp

89 33.9 Accessing a Database from an Active Server Page
Fig ASP document that validates user login.

90 33.9 Accessing a Database from an Active Server Page
Fig ASP document that validates user login.

91 33.9 Accessing a Database from an Active Server Page
Fig Cookies folder before and after cookie creation.

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

93 33.10 Server-Side ActiveX Components

94 component.asp (1 of 4)

95 Sends advertisement as HTML to client
Sends advertisement as HTML to client. Method GetAdvertisement called using reference rotator. Retrieves advertisements from config.txt component.asp (2 of 4) Creates AdRotator component instance, assigns it reference rotator Obtains information about user’s browser Check property VBScript value Test JavaScript property

96 Tests Cookies property to determine if browser supports cookies
BrowserType object’s Browser, Version and MinorVer properties can obtain similar client information Passes server variable key HTTP_USER_AGENT to ServerVariables, obtains string containing user information component.asp (3 of 4) Tests Cookies property to determine if browser supports cookies Increments number of “hits” by one

97 Returns number of “hits”
component.asp (4 of 4)

98 33.10 Server-Side ActiveX Components
Fig Demonstrating server-side ActiveX components.

99 33.10 Server-Side ActiveX Components
Fig Demonstrating server-side ActiveX components.

100 33.10 Server-Side ActiveX Components
Fig Demonstrating server-side ActiveX components.

101 Header contains REDIRECT file URL
Image URL, destination URL, alt value, image display ratio Advertisement dimensions Asterisk separates header from advertisements config.txt (1 of 1)

102 redirect.asp (1 of 1)


Download ppt "Chapter 33 - Active Server Pages (ASP)"

Similar presentations


Ads by Google