asp working with databases dr. awad khalil computer science department auc

62
1 ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Upload: stamos

Post on 13-Jan-2016

34 views

Category:

Documents


0 download

DESCRIPTION

ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC. Active Server Pages (ASP). Outline 1. Introduction 2. Accessing a Database from an Active Server Page 3. Server-Side ActiveX Components 4. Internet and World Wide Web Resources. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

1

ASP

Working with Databases

Dr. Awad Khalil

Computer Science Department

AUC

Page 2: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

2

Active Server Pages (ASP)

Outline1. Introduction2. Accessing a Database from an Active Server Page3. Server-Side ActiveX Components4. Internet and World Wide Web Resources

Page 3: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

3

Accessing a Database from an Active Server Page

• ASP includes the Microsoft ActiveX Data Object (ADO) library which supports database interaction in ASP with a variety of programming tools.

• In ASP, the connection object comes from a class called ADODB.Connection, which is one of the classes in the ADO library.

Page 4: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

4

ODBC (Open DataBase Connectivity)

• ODBC is a Microsoft standard for database interaction and connection that is part of the Windows operating system.

• Users can register data sources with ODBC so that applications can easily access them.

• For a Web application to use an ODBC data source, the source must be registered on the Web Server computer.

• In order for a JavaScript program to interact with a database, it must create an ADO Connection object and connect to the database. The following two lines of JavaScript code can be added to an ASP script to create a Connection object, store the object in a variable named conn, and open a connection to the database named bighitmdb.

Conn = Server.CreateObject(“ADODB.Connection”);

Conn.Open(“bighitmdb”);

Page 5: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

5

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

Page 6: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

6

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

Page 7: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

7 Executing SQL SEECT Queries with ASP

• To generate this page, the Web application would need to create and execute two SQL select queries: One fetches the first and last name of the customer from BigHit’s Customer table. The other fetches the list of all that customer’s rentals from the Rental, Video, and Movie tables.

Page 8: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline8

Clock.asp

sends Web server’s date and time to the client as XHTML markup

<% %> scripting delimeter

@LANGUAGE processing directive

Option Explicit

FormatDateTime

Now vbLongDate format

Response.write

Time

// connect to database conn = Server.CreateObject("ADODB.Connection"); conn.Open("bighitmdb"); // get parameter values

var accountId = Request.QueryString("accountID");

// construct SQL query to fetch customer namevar customerQuery = "select lastName, firstName from

Customer“ + " where accountId = "+accountId;// execute the query

var customer = conn.Execute(customerQuery);

// get the first and last names from the query result var firstName = customer(“firstName”); var lastName = customer(“lastName”); customer.close();

printHeader("Outstanding Rentals","for customer "+firstName+” “+lastName);

Page 9: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

9Fetching and Displaying Information form more than one table

// get rentals for account and print as tablevar rentalQuery = "select v.videoId, title, dateRented, dateDue"

+ " from Rental r, Video v, Movie m " + " where v.videoId = r.videoId and v.movieId = m.movieId" + " and r.accountId = "+ accountId;

//var rentals = conn.Execute(rentalQuery); var rentals = executeSQL(rentalQuery); // execute SQL and add to log%><center><table border=2>

<caption>Current Rentals for Account <%= accountId %></caption><tr>

<th>Video ID</th><th>Title</th><th>Date Rented</th><th>Date Due</th>

</tr><% while(!rentals.eof){ %>

<tr><th><%=rentals("videoId")%></th><td><%=rentals("title")%></td><td><%=rentals("dateRented")%></td><td><%=rentals("dateDue")%></td>

</tr><% rentals.movenext();

}rentals.close();rentals = null;

conn.close();%></table>

Page 10: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

10Fetching and Displaying Information form more than one table

Page 11: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

11

Creating Objects from Queries

• We can organize the processing of query results by writing functions to process queries that will occur in many Web applications.

• The following function (custlookupform) allows creating a customer object from information stored in the database:

function lookupCustomer(conn, id) { customer = new Object(); customerSQL="select * from Customer where accountId="+id; custSet = conn.Execute(customerSQL); // check to see if any row was returned if (custSet.eof) { // no customer with this accountId return customer // return empty object } customer.accountId = custSet("accountId"); customer.firstName = custSet("firstName"); customer.lastName = custSet("lastName"); customer.street = custSet("street"); customer.city = custSet("city"); customer.state = custSet("state"); customer.zipcode = custSet("zipcode"); return customer;}

Page 12: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

12

A General Purpose Query Execution Script

• Suppose that we create an HTML form that allows users to type an SQL select statement and submit a request for it to be executed.

• When the user clicks the submit button, he will expect the result to be a Web page that displays the results of executing the select statement as an HTML table.

Page 13: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

13

Sqlform.asp

<%@LANGUAGE="JScript"%><!-- sqlform.asp --><html> <!-- #include file="bighittools.js" --><% startApplication("sqlform.asp"); printHeader("Query Execution","Please enter an SQL select statement"); %> <center> <form method="GET" action="sqlexec.asp"> <table> <tr><th>Enter Select Statement</th> <td><textarea cols="40" rows="6" name="sqlQuery"></textarea></td></tr> </table><br> <input type="submit"> <input type="reset"> </form> </center>

<% printFooter("sqlform.asp"); endApplication("sqlform.asp");%></html>

Page 14: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

14

Sqlexec.asp <%@LANGUAGE="JScript"%><!-- sqlexec.asp --><html> <!-- #include file="bighittools.js" --> <% startApplication("sqlexec.asp"); // get parameter values var conn, sqlQuery, results; sqlQuery = Request("sqlQuery"); printHeader("Execution of Query",sqlQuery); // connect to database conn = Server.CreateObject("ADODB.Connection"); conn.Open("bighitmdb"); // execute query try {// we may get an error in executing the query var numRowsAffected; //results = conn.Execute(sqlQuery); results = executeSQL(sqlQuery); printTable(results,Response); } catch (exception) { Response.write("<table><center>\n"); Response.write("<caption>Unable to process query</caption>\n"); Response.write("<tr><th>Error returned from database</th><td>"); Response.write(exception.description+"<br>\n"); Response.write("</tr></table></center>\n"); //throw exception; } printFooter("sqlexec.asp"); endApplication("sqlexec.asp");%></html>

Page 15: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

15

Results of Executing Sqlexec.asp

Page 16: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

16The Recordset Object – Positioned on the first row

Page 17: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

17

The Recordset Object

• The oval in the upper left represents the variable results whose value is the Recordset object.

• The Recordset object has a collection called fields that contains one field for each column.

• Each field object contains the name, type, and value of a single attribute.

• Object fields has a property called count with value 8 – the number of fields in the row.

• Each field has two properties, a name and a value.• The information needed to generate the Web page can be

obtained as follows:– The number of columns in the result is the value of

fields.count– The name of the first column is fields(0).name, and the

value of the first column is fields(0).value.– … etc.

Page 18: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

18The Function printTable

function printTable(results) { // print the rows of the table as an HTML table // results must be an ADO RecordSet object var numCols = results.fields.count; Response.write("<center><table cellpadding=3><tr>\n"); // write names of columns for (col=0; col<numCols; col++) { Response.write("<th>"+results.fields(col).name+"</td>\n"); } Response.write("</tr>\n"); // write rows of data while (!results.eof) { Response.write("<tr>"); for (col=0; col<numCols; col++) { Response.write("<td>"+results(col).value+"</td>\n"); } results.movenext(); Response.write("</tr>"); } Response.write("</table></center><br>\n");}

Page 19: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

19 Inserting Data to a Database - newcustmerform.asp

<%@LANGUAGE="JScript"%><html><!-- #include file="bighittools.js" --> <% startApplication("newcustomerform.asp"); printHeader("Please Enter Your Information","New customer information"); %> <form method="GET" action="newcustomer.asp"><center> <table> <tr><th>First Name: </th><td><input type="text" name="firstName" size = "25">

</td></tr> <tr><th>Last Name: </th><td> <input type="text" name="lastName" size =

"25"></td></tr> <tr><th>street: </th><td><input type="text" name="street" size = "25" ></td></tr> <tr><th>City: </th><td><input type="text" name="city" size = "25"></td></tr > <tr><th>Country: </th><td><input type="text" name="state" size = "25"></td ></tr> <tr><th>Zipcode: </th><td><input type="text" name="zipcode" size = "25" ></td></tr> </table><br> <input type="submit" value="Submit"> <input type="reset"> </center></form>

<% printFooter("newcustomerform.asp"); endApplication("newcustomerform.asp");%></html>

Page 20: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

20 Inserting Data to a Database

Page 21: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

21 Confirm Entered Data to a Database – newcustomer.asp

<%@LANGUAGE="JScript"%><html><!-- #include file="bighittools.js" --> <% startApplication("newcustomer.asp"); printHeader("Please Confirm","New customer information"); firstName = Request("firstName"); lastName = Request("lastName"); street = Request("street"); city = Request("city"); state = Request("state"); zipcode = Request("zipcode"); %> <form method="GET" action="addcustomer.asp"><center> <table> <tr><th>First Name: </th><td><%=firstName %> </td></tr> <tr><th>Last Name: </th><td><%=lastName %></td></tr> <tr><th>street: </th><td><%=street %></td></tr> <tr><th>City: </th><td><%=city %></td></tr> <tr><th>Country: </th><td><%=state %></td></tr> <tr><th>Zipcode: </th><td><%=zipcode %></td></tr> </table><br> <input type="submit" value="Confirm"> <input type="reset"> <!-- hidden fields to hold customer info--> <input type="hidden" name="firstName" value="<%=firstName%>"> <input type="hidden" name="lastName" value="<%=lastName%>"> <input type="hidden" name="street" value="<%=street%>"> <input type="hidden" name="city" value="<%=city%>"> <input type="hidden" name="state" value="<%=state%>"> <input type="hidden" name="zipcode" value="<%=zipcode%>"> </center></form> <% printFooter("newcustomer.asp"); endApplication("newcustomer.asp"); %></html>

Page 22: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

22 Confirm Entered Data to a Database – newcustomer.asp

Page 23: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

23 Inserting the Data – addcustomer.asp

<%@LANGUAGE="JScript"%><!-- makecustomer.asp --><html> <!-- #include file="bighittools.js" --> <% startApplication("makecustomer.asp"); // get parameter values var customer, newId; customer = makeCustomer(Request); with (customer) { printHeader("New Customer Receipt","Welcome "+firstName+"

"+lastName); // connect to database conn = Server.CreateObject("ADODB.Connection"); conn.Open("bighitmdb"); // get new account ID as maximum current account ID plus 1 //maxId = conn.Execute("select max(accountId) from Customer"); maxId = executeSQL("select max(accountId) from Customer"); newId = maxId(0) + 1;

Page 24: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

24 Inserting the Data – addcustomer.asp

// insert customer newCustSQL = "insert into Customer " +"(accountId, firstName, lastName, street, city, state, zipcode)" +" values(" +newId+", '" +sqlString(firstName)+"','" +(lastName)+"', '" +sqlString(street)+"', '" +sqlString(city)+"', '" +sqlString(state)+"', '" +sqlString(zipcode)+"')"; //Response.write("<br>SQL: "+newCustSQL+"<br>"); //conn.Execute(newCustSQL); // replaced with function call executeSQL(newCustSQL); } // end with customer // fetch customer information from the database customer = lookupCustomer(conn,newId); if (customer.accountId!=newId) {// no new customer Response.Write("<br>No new customer with account ID: "+newId+"<p>\n"); customer = makeCustomer(Request); } printCustomerTable(customer); printFooter("addcustomer.asp"); endApplication("makecustomer.asp");%></html>

Page 25: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

25 Inserting Data to the Database – newcustomer.asp

Page 26: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

26 Displaying Inserted Data

Page 27: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

27 Displaying Inserted Data

Page 28: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

28

Server-Side ActiveX Components

Using Cookies - Login in Application– This application controls user’s access to the content builder

application through authenticating the user by username and password information which are stored in the database login.mdb. The application is made of three scripts:

• login.asp: providing the user interface, displaying the form, and error messages in case of access failure.

• database.asp: connecting to the database, executing the query to get users’ access information, communicating with login.asp through session tracking.

• submitlogin.asp: check user login information, create a cookie to store loginID information, and communicating with login.asp through session tracking.

Page 29: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline29

Database.asp

connects to, and queries an Access database

CreateObject

ADODB.Connectioncontains functionality necessary to connect to database

errorHandlerLog

1 <% @LANGUAGE = VBScript %>2 3 <% 4 ' Fig. 22 : database.asp 5 ' ASP document for interacting with the database 6 Option Explicit7 8 Dim connection, loginData9 10 ' provide error handling code11 On Error Resume Next 12 Session( "errorString" ) = ""13 14 Set connection = Server.CreateObject( "ADODB.Connection" )15 Call connection.Open( "login" )16 Call errorHandlerLog()17 18 ' create the record set19 Set loginData = Server.CreateObject( "ADODB.Recordset" )20 Call loginData.Open( Session( "query" ), connection )21 Set Session( "loginData" ) = loginData22 23 Call errorHandlerLog()2425 Sub errorHandlerLog()26 If Err.Number <> 0 Then27 Dim errorString2829 errorString = Session( "errorString" )30 errorString = errorString & "<p class = " & _ 31 Chr( 34 ) & "error" & Chr ( 34 ) & ">Error (" _32 & Err.Number & ") in " & Err.Source & "<br />" & _33 Err.Description & "</p><br />"34 Session( "errorString" ) = errorString35 End If36 End Sub37 %>

Ignores errors until end of script

Declares session variable errorString

Server method CreateObject creates ADODB.ConnectionMethod Open opens database specified by ODBC System DSN (login)errorHandlerLog processes errors

Lines 25-36 define errorHandlerLog

Err object Number property contains VBScript error number. Tests if error has occurred.If true, errorSrting variable is assigned XHTML text containing error number and message

loginData reference is set to an ADODB.recordset object

Open method is passed string containing SQL query and ADODB.Connection object

When Open finishes executing, points to first record or EOF if no records were found

Sets session variable loginData to variable loginData which references the ADODB.Recordset containing all records matching SQL query

errorHandlerLog called again

Error number and message concatenated to variable errorString

Page 30: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline30

Login.asp

Identifies users by prompting them for login name and password.

Data is stored in Access database login.mdb

submitlogin.asp validates the user’s login

1 <% @LANGUAGE = VBScript %>2 3 <% 4 ' Fig. 23 : login.asp 5 ' ASP document to login to instantpage.asp 6 Option Explicit7 8 ' create the SQL query9 Session( "query" ) = "SELECT loginID FROM Users"10 Call Server.Execute( "database.asp" )11 %>12 13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"14 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">15 16 <html xmlns = "http://www.w3.org/1999/xhtml">17 18 <head>19 <title>Login Page</title>20 21 <style type = "text/css">22 table { text-align: center; 23 font-size: 12pt; 24 color: blue;25 font-size: 12pt; 26 font-family: arial, sans-serif }27 .error { color: red }28 </style>29 30 </head>31 32 <body>33 34 <!-- #include virtual="/includes/header.shtml" -->35 <%

Assigns SQL query to session variable query

Executes database.asp to retrieve login IDs from the database

Page 31: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline31

Login.asp

Prompts user for login name and password.

Information is stored in Access database opened in database.asp

36 If Session( "errorString" ) = "" Then37 ' if this is a return after a failed attempt,38 ' print an error39 If Session( "loginFailure" ) = True Then %>40 <p class = "error">Login attempt failed, 41 please try again</p>42 <% End If43 44 ' begin the form %>45 <p>Please select your name and enter 46 your password to login:</p><br />47 48 <form action = "submitlogin.asp" method = "post">49 50 <!-- format the form using a table -->51 <table border = "0">52 <tr>53 <td>Name:</td>54 55 <td>56 <select name = "loginID">57 <option value = "noSelection">58 Select your name</option>59 60 <% 61 If Request.Cookies( "loginID" ) <> "" Then62 Call BuildReturning()63 Else64 Call BuildNewUser()65 End If66 %> 67 </select>68 </td>69 </tr>70

Tests if session variable errorString value is empty string

If false, line 89 prints error message to user

Lines 39-41 test is session variable loginFailure is True

If true, login failure message prints to user and prompts new login

select structure builds drop-down list of loginIDs

Requests loginID cookie

Build loginID options

Selects the returning user’s login ID option

Page 32: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline32

Login.asp

Prompts user for login name and password.

Information is stored in Access database opened in database.asp

71 <tr>72 <td>Password:</td>73 <td><input type = "password" 74 name = "password" /></td>75 </tr>76 77 <tr>78 <td></td>79 <td align = "left">80 <input type = "submit" value = "Log Me In" />81 </td>82 </tr>83 </table>84 </form>85 86 <!-- #include virtual="/includes/footer.shtml" -->87 <%88 Else89 Call Response.Write( Session( "errorString" ) )90 End If91 %>92 </body>93 </html>94 95 <% 96 ' builds the option items for loginIDs and writes 97 ' selected for the loginID of the returning user98 Sub BuildReturning() 99 Dim found, loginData100 101 Set loginData = Session( "loginData" )102 103 ' pull user names from the record set to populate the104 ' dropdown list

Page 33: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline33

Login.asp

Prompts user for login name and password.

Information is stored in Access database opened in database.asp

105 found = False 106 107 While Not loginData.EOF108 ' create this record's dropdown entry109 %> <option 110 <% ' if we did not write selected for any option 111 ' before 112 If ( Not found ) Then 113 114 ' if the current record's loginID is equal to 115 ' the loginID cookie, then it is the loginID of 116 ' the returning user, and thus we need to write117 ' selected for this option; in this case we also118 ' need to signal that we have written selected119 ' for an option by setting found to True. 120 If Request.Cookies( "loginID" ) _121 = loginData( "loginID" ) Then122 Call Response.Write( "selected = " & _123 Chr( 34 ) & "selected" & Chr( 34 ) )124 found = True125 End If126 End If 127 %> value = "<% =loginData( "loginID" ) %>">128 <% =loginData( "loginID" ) %></option>129 <% Call loginData.MoveNext()130 Wend 131 End Sub 132 133 ' builds the option items for loginIDs without writing 134 ' selected for any loginID135 Sub BuildNewUser() 136 Dim loginData137 138 Set loginData = Session( "loginData" )139

while loop (lines 107-130) iterates through loginData’s records

Tests for EOF

Increments the record set pointer to next record

If statement tests whether option needs to be selected

If statement writes selected for an option

found set to false before loop

Once selected is written for an option, found set to trueDetermines whether current

record’s loginID field is equal to loginID cookie

If true, lines 122-124 write selected and set found to true

Sets option value to current loginID

Writes option display as current loginID

Page 34: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline34

Login.asp

Program Output

140 ' pull user names from the record set to populate the141 ' dropdown list142 While Not loginData.EOF143 ' create this record's dropdown entry144 %> <option value = "<% =loginData( "loginID" ) %>">145 <% =loginData( "loginID" ) %></option>146 <% Call loginData.MoveNext()147 Wend148 End Sub 149 %>

Page 35: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline35

Program Output

Page 36: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline36

Submitlogin.asp

Takes values passed by login.asp and checks values against Users table in database

If match is found, user is redirected to instantpage.asp. If not, user is redirected to login.asp.

1 <% @LANGUAGE = VBScript %>2 3 <% ' Fig. 25.24 : submitlogin.asp 4 ' ASP document to check user's username and password5 Option Explicit 6 7 ' test if a user name and a password were 8 ' entered. If not, transfer back to the login page.9 If Request( "password" ) = "" Or _10 Request( "loginID" ) = "noSelection" Then11 Session( "loginFailure" ) = True12 Call Server.Transfer( "login.asp" )13 End If 14 15 Dim connection, loginData16 17 ' create the SQL query18 Session( "query" ) = _19 "SELECT * FROM Users WHERE loginID = '" & _20 Request( "loginID" ) & "'"21 22 Call Server.Execute( "database.asp" )23 Set loginData = Session( "loginData" )24 25 If Request( "password" ) = loginData( "password" ) Then 26 27 ' password is OK, adjust loginFailure28 Session( "loginFailure" ) = False29 30 ' write a cookie to recognize them the next time they31 ' go to login.asp32 Response.Cookies( "loginID" ) = Request( "loginID" )33 34 ' give it three days to expire35 Response.Cookies( "loginID" ).Expires = Date() + 3

Lines 9-13 check whether password field is empty or id loginID field contains default value

If so, variable loginFailure set to true, client redirected back to login.aspWHERE specifies a condition on which records are selectedExecutes database.asp to query database

Sets reference loginData to session variable loginData (contains records matching query.)

Checks password against the password in recordset

If true, line writes form’s loginID value as cookie named loginID

Sets session variable loginFailure value to False

Sets cookie’s expiration date to current date plus 3 days

Page 37: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline37

Submitlogin.asp

Program Output

36 37 ' send them to instantpage.asp38 Call Server.Transfer( "instantpage.asp" )39 Else40 Session( "loginFailure" ) = True41 Call Server.Transfer( "login.asp" )42 End If 43 %>

Calls Server method Transfer to redirect client to instantpage.asp

Otherwise loginFailure set to True and client is redirected to login.asp

Page 38: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline38

Program Output

Page 39: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

39

Accessing a Database from an Active Server Page

Fig. 25.25 Cookies folder before and after cookie creation.

Page 40: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

40

Accessing a Database from an Active Server Page

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

Page 41: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

41

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

Page 42: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

42

Server-Side ActiveX Components

Component Name Description

MSWC.BrowserType ActiveX component for gathering information about the client’s browser (e.g., type, version, etc.).

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 component that provide general-purpose persistent counters.

MSWC.MyInfo ActiveX component that provides information about a Web site (e.g., owner name, owner address, etc.).

Scripting.FileSystemObject ActiveX component that provides an object library for accessing files on the server or on the server’s network.

ActiveX Data Objects (ADO) Data Access Components

ActiveX components that provide an object library for accessing databases.

Fig. 27 Some server-side ActiveX components.

Page 43: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline43

Component.asp

Uses AdRotator ActiveX component to rotate one of five flag images. When user clicks flag image, country’s corresponding CIA Fact Book Web page displays.

1 <% @LANGUAGE = VBScript %>2 3 <% 4 ' Fig. 28 : component.asp 5 ' Demonstrating Server-side ActiveX Components 6 Option Explicit7 %>8 9 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"10 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">11 12 <html xmlns = "http://www.w3.org/1999/xhtml">13 14 <head>15 <title>ActiveX Component Example</title>16 </head>17 18 <body>19 20 <strong style = "font-family: arial, sans-serif">21 Server-side ActiveX Components22 </strong>23 24 <p>25 <% 26 Dim rotator, browser, information, counter27 28 ' create an AdRotator object29 Set rotator = Server.CreateObject( "MSWC.AdRotator" )30 31 ' use config.txt to send an advertisement to the client32 Call Response.Write( _33 rotator.GetAdvertisement( "config.txt" ) )34

Creates AdRotator component instance, assigns it reference rotatorSends advertisement as HTML to client. Method

GetAdvertisement called using reference rotator. Retrieves advertisements from config.txt

Page 44: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline44

Component.asp

35 ' create a BrowserType object36 Set browser = Server.CreateObject( "MSWC.BrowserType" )37 38 If browser.VBScript = True Then39 %>40 <script language = "VBScript">41 Call Msgbox( "Client browser supports VBScript!" )42 </script> 43 <%44 End If45 46 If browser.JavaScript = True Then47 %>48 <script language = "JavaScript">49 alert( "Client browser supports JavaScript!" );50 </script> 51 <%52 End If53 54 ' get client's browser information55 information = "<p>Your browser information is:<br />" & _56 Request.ServerVariables( "HTTP_USER_AGENT" ) & _57 "<br />Browser: " & browser.Browser & " Version: " & _58 browser.Version & " Minor version: " & _59 browser.MinorVer & "<br />Cookies are "60 61 If browser.Cookies Then62 information = information & "enabled</p><br />"63 Else64 information = information & "disabled</p><br />"65 End If66 67 Call Response.Write( information )68

Obtains information about user’s browser

Check property VBScript valueIf true, lines 48-50 written to client

Lines 46-52 test JavaScript property

Passes server variable key HTTP_USER_AGENT to ServerVariables, obtains string containing user information

BrowserType object’s Browser Version and MinorVer properties can obtain similar client information

Tests Cookies property to determine if browser supports cookies

Page 45: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline45

Component.asp

69 ' create Page Counter Object70 Set counter = Server.CreateObject( "MSWC.PageCounter" )71 Call counter.PageHit() ' page has been "hit"72 %> 73 </p>74 75 <p style = "color: blue; font-size: 12pt">76 This page has been visited <% =counter.Hits() %> 77 times!</p>78 </body>79 </html>

Increments number of “hits” by one

Returns number of “hits”

Page 46: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline46

Program Output

Page 47: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline47

Program Output

Page 48: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline48

Config.txt

Describes the advertisements

1 REDIRECT redirect.asp2 width 543 height 364 border 15 *6 /images/su-flag.gif7 http://www.odci.gov/cia/publications/factbook/geos/su.html8 Sudan Information9 2010 /images/eg-flag.gif11 http://www.odci.gov/cia/publications/factbook/geos/eg.html12 Egypt Information13 2014 /images/us.gif15 http://www.odci.gov/cia/publications/factbook/geos/us.html16 United States Information17 2018 /images/france.gif19 http://www.odci.gov/cia/publications/factbook/geos/fr.html20 France Information21 2022 /images/germany.gif23 http://www.odci.gov/cia/publications/factbook/geos/gm.html23 Germany Information24 2025 /images/italy.gif26 http://www.odci.gov/cia/publications/factbook/geos/it.html27 Italy Information28 2029 /images/spain.gif30 http://www.odci.gov/cia/publications/factbook/geos/sp.html31 Spain Information32 20

Header contains REDIRECT file URL

Asterisk separates header from advertisements

Advertisement dimensionsImage URL, destination URL, alt value, image display ratio

Page 49: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

Outline49

Redirect.asp

Redirects user to country’s CIA page when ad is clicked

1 <% @LANGUAGE = VBScript %>2 3 <% 4 ' Fig. 30 : redirect.asp 5 ' Redirection Page for AdRotator Component 6 Option Explicit 7 8 Call Response.Redirect( Request( "url" ) ) 9 %>

Page 50: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

50

Page 51: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

51

Page 52: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

52

Page 53: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

53

Page 54: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

54

Page 55: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

55

Page 56: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

56

Page 57: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

57

Page 58: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

58

Page 59: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

59

Page 60: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

60

Page 61: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

61

Page 62: ASP Working with Databases Dr. Awad Khalil Computer Science Department AUC

62