0% found this document useful (0 votes)
43 views

Web Enabled Business Process - 3

This document provides information about using ASP (Active Server Pages) to connect databases to web pages. It discusses: - What ASP is and how it differs from HTML by executing scripts on the server-side before returning the page. - How to install and use IIS (Internet Information Services) or PWS (Personal Web Server) on different Windows operating systems to host ASP pages locally for testing purposes. - Steps for creating a basic "Hello World" ASP page connected to a local database, and viewing it by accessing "localhost" in a web browser. The document outlines the basics of setting up a local web server environment for learning and testing ASP functionality like dynamically connecting to databases behind the scenes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Web Enabled Business Process - 3

This document provides information about using ASP (Active Server Pages) to connect databases to web pages. It discusses: - What ASP is and how it differs from HTML by executing scripts on the server-side before returning the page. - How to install and use IIS (Internet Information Services) or PWS (Personal Web Server) on different Windows operating systems to host ASP pages locally for testing purposes. - Steps for creating a basic "Hello World" ASP page connected to a local database, and viewing it by accessing "localhost" in a web browser. The document outlines the basics of setting up a local web server environment for learning and testing ASP functionality like dynamically connecting to databases behind the scenes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Database Connectivity using ASP 63

Notes

Unit 3: Database Connectivity using ASP

Structure:
3.1 What is ASP?
3.1.1 ASP Compatibility
3.1.2 What is an ASP File?
3.1.3 How Does ASP Differ from HTML?
3.1.4 What Can ASP Do for You?
3.2 IIS – Internet Information Server
3.3 PWS – Personal Web Server
3.3.1 Windows Web Server Versions
3.4 Programming for Database Connectivity
3.4.1 Create a Data Source Name
3.4.2 For a Database Program
3.4.3 For a Database Server
3.5 Troubleshooting
3.6 Store and Retrieve Session Variables
3.6.1 Remove Session Variables
3.7 Summary
3.8 Check Your Progress
3.9 Questions and Exercises
3.10 Key Terms
3.11 Check Your Progress: Answers
3.12 Case Study
3.13 Further Readings

Objectives
After going through this unit, you should be able to know:
Ɣ Dynamically edit, change, or add any content of a Web page
Ɣ Respond to user queries or data submitted from HTML forms
Ɣ Access any data or databases and return the results to a browser
Ɣ Customize a Web page to make it more useful for individual users
Ɣ The advantages of using ASP instead of CGI and Perl, are those of simplicity and
speed
Ɣ Provide security – since ASP code cannot be viewed from the browser
Ɣ Clever ASP programming can minimize the network traffic
Ɣ A Case Study based on this Unit

Amity Directorate of Distance and Online Education


64 Web-Enabled Business Processes

Notes 3.1 What is ASP?


z ASP stands for Active Server Pages.
z ASP is a Microsoft Technology.
z ASP is a program that runs inside IIS.
z IIS stands for Internet Information Services.
z IIS comes as a free component with Windows 2000.
z IIS is also a part of the Windows NT 4.0 Option Pack.
z The Option Pack can be downloaded from Microsoft.
z PWS is a smaller – but fully functional – version of IIS.
z PWS can be found on your Windows 95/98 CD.
3.1.1 ASP Compatibility
z To run IIS, you must have Windows NT 4.0 or later.
z To run PWS, you must have Windows 95 or later.
z ChiliASP is a technology that runs ASP without Windows OS.
z InstantASP is another technology that runs ASP without Windows.
3.1.2 What is an ASP File?
z An ASP file is just the same as an HTML file.
z An ASP file can contain text, HTML, XML, and scripts.
z Scripts in an ASP file are executed on the server.
z An ASP file has the file extension “.asp”.

3.1.3 How Does ASP Differ from HTML?


z When a browser requests an HTML file, the server returns the file.
z When a browser requests an ASP file, IIS passes the request to the ASP
engine. The ASP engine reads the ASP file, line by line, and executes the
scripts in the file. Finally, the ASP file is returned to the browser as plain HTML.

3.1.4 What Can ASP Do for You?


z Dynamically edit, change, or add any content of a Web page.
z Respond to user queries or data submitted from HTML forms.
z Access any data or databases and return the results to a browser.
z Customize a Web page to make it more useful for individual users.
z The advantages of using ASP instead of CGI and Perl, are those of simplicity
and speed.
z Provide security – since ASP code cannot be viewed from the browser.
z Clever ASP programming can minimize the network traffic.

Run ASP on Your Own PC


You can run ASP on your own PC.

Your Windows PC as a Web Server


z Your own PC can act as a web server if you install IIS or PWS.
z IIS or PWS turns your computer into a web server.
z Microsoft IIS and PWS are free web server components.

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 65

3.2 IIS – Internet Information Server Notes


IIS is a set of Internet-based services for servers created by Microsoft for use with
Microsoft Windows.
IIS comes with Windows 2000, XP, Vista, and Windows 7. It is also available for
Windows NT.
IIS is easy to install and ideal for developing and testing web applications.

3.3 PWS – Personal Web Server


PWS is for older Windows system like Windows 95, 98, and NT.
PWS is easy to install and can be used for developing and testing web applications
including ASP.
We don’t recommend running PWS for anything else than training. It is outdated and
has security issues.

3.3.1 Windows Web Server Versions


z Windows 7 (all editions) come with IIS 7.5.
z Windows Vista Business, Enterprise and Ultimate come with IIS 7.
z Windows Vista Home Premium comes with IIS 7.
z Windows Vista Home Edition does not support PWS or IIS.
z Windows XP Professional comes with IIS 5.1.
z Windows XP Home Edition does not support IIS or PWS.
z Windows 2000 Professional comes with IIS 5.0.
z Windows NT Professional comes with IIS 3 and also supports IIS 4.
z Windows NT Workstation supports PWS and IIS 3.
z Windows ME does not support PWS or IIS.
z Windows 98 comes with PWS.
z Windows 95 supports PWS.

How to Install IIS on Windows 7 and Windows Vista?


Follow these steps to install IIS:
1. Open the Control Panel from the Start menu.
2. Double-click Programs and Features.
3. Click “Turn Windows features on or off” (a link to the left).
4. Select the check box for Internet Information Services (IIS), and click OK.
After you have installed IIS, make sure you install all patches for bugs and security
problems. (Run Windows Update).

How to Install IIS on Windows XP and Windows 2000?


Follow these steps to install IIS:
1. On the Start menu, click Settings and select Control Panel.
2. Double-click Add or Remove Programs.
3. Click Add/Remove Windows Components.
4. Click Internet Information Services (IIS).
5. Click Details.

Amity Directorate of Distance and Online Education


66 Web-Enabled Business Processes
6. Select the check box for World Wide Web Service, and click OK.
Notes
7. In Windows Component selection, click Next to install IIS.
After you have installed IIS, make sure you install all patches for bugs and security
problems. (Run Windows Update).

Test Your Web


After you have installed IIS or PWS, follow these steps:
1. Look for a new folder called Inetpub on your hard drive.
2. Open the Inetpub folder, and find a folder named wwwroot.
3. Create a new folder, like “MyWeb”, under wwwroot.
4. Write some ASP code and save the file as “test1.asp” in the new folder.
5. Make sure your Web server is running (see below).
6. Open your browser and type “http://localhost/MyWeb/test1.asp”, to view your
first web page.
Note: Look for the IIS (or PWS) symbol in your start menu or task bar. The program
has functions for starting and stopping the web server, disable and enable ASP, and
much more.

How to Install PWS on Windows 95, 98, and Windows NT?


For Windows 98: Open the Add-ons folder on your Windows CD, find the PWS
folder and run setup.exe to install PWS.
For Windows 95 or Windows NT: Download “Windows NT 4.0 Option Pack” from
Microsoft, and install PWS.
Test your web as described above.

How to Install IIS on Windows Server 2003?


1. When you start the Windows Server 2003, you should see the Manage Your
Server wizard.
2. If the wizard is not displayed, go to Administrative Tools, and select Manage
Your Server.
3. In the wizard, click Add or Remove a Role, click Next.
4. Select Custom Configuration, click Next.
5. Select Application Server role, click Next.
6. Select Enable ASP.NET, click Next.
7. Now, the wizard may ask for the Server 2003 CD. Insert the CD and let it run
until it is finished, then click the Finish button.
8. The wizard should now show the Application Server role installed.
9. Click on Manage This Application Server to bring up the Application Server
Management Console (MMC).
10. Expand the Internet Information Services (IIS) Manager, then expand your
server, and then the Websites folder.
11. You should see the Default Website, and it should not say (Stopped).
12. IIS is running!
13. In the Internet Information Services (IIS) Manager click on the Web Service
Extensions folder.
14. Here, you will see that Active Server Pages are Prohibited (this is the default
configuration of IIS 6).

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 67

15. Highlight Active Server Pages and click the Allow button.
Notes
16. ASP is now active!

ASP Basic Syntax Rules


In our ASP tutorial, every example shows the hidden ASP source code. This will
make it easier for you to understand how it works.

Write Output to a Browser


An ASP file normally contains HTML tags, just like an HTML file. However, an ASP
file can also contain server scripts, surrounded by the delimiters <% and %>.
Server scripts are executed on the server, and can contain any expressions,
statements, procedures, or operators valid for the scripting language you prefer to use.

The response.write Command


The response.write command is used to write output to a browser. The following
example sends the text “Hello World” to the browser:

Example
<!DOCTYPE html>
<html>
<body>
<%
response.write(“Hello World!”)
%>
</body>
</html>
There is also a shorthand method for the response.write command. The following
example also sends the text “Hello World” to the browser:

Example
<!DOCTYPE html>
<html>
<body>
<%
=“Hello World!”
%>
</body>
</html>

Using VBScript in ASP


You can use several scripting languages in ASP. However, the default scripting
language is VBScript:
<!DOCTYPE html>
<html>
<body>

Amity Directorate of Distance and Online Education


68 Web-Enabled Business Processes
<%
Notes
response.write(“Hello World!”)
%>
</body>
</html>
The example above writes “Hello World!” into the body of the document.

Using JavaScript in ASP


To set JavaScript as the default scripting language for a particular page, you must
insert a language specification at the top of the page:
<%@ language=“javascript”%>
<!DOCTYPE html>
<html>
<body>
<%
response.write(“Hello World!”)
%>
</body>
</html>
Note: JavaScript is case-sensitive! You will have to write your ASP code with
uppercase letters and lowercase letters when the language requires it.

Example
<!DOCTYPE html>
<html>
<body>
<%
response.write(“My first ASP script!”)
%>
</body>
</html>

Building and Processing Web Forms

ASP Forms and User Input


The Request.QueryString and Request.Form commands are used to retrieve user
input from forms.

Examples
A form with method=“get”
How to interact with the user, with the Request.QueryString command.
A form with method=“post”
How to interact with the user, with the Request.Form command.
A form with radio buttons

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 69

How to Interact with the User, through Radio Buttons, with the Request.Form Notes
Command?

User Input
The Request object can be used to retrieve user information from forms.
User input can be retrieved with the Request.QueryString or Request.Form
command.

Request.QueryString
The Request.QueryString command is used to collect values in a form with
method=“get”.
Information sent from a form with the GET method is visible to everyone (it will be
displayed in the browser’s address bar) and has limits on the amount of information to
send.

Example of HTML Form


<form method=“get” action=“simpleform.asp”>
First Name: <input type=“text” name=“fname”><br>
Last Name: <input type=“text” name=“lname”><br><br>
<input type=“submit” value=“Submit”>
</form>
If a user typed “Bill” and “Gates” in the HTML form above, the URL sent to the server
would look like this:
http://www.w3abc.com/simpleform.asp?fname=Bill&lname=Gates
Assume that “simpleform.asp” contains the following ASP script:
<body>
Welcome
<%
response.write(request.querystring(“fname”))
response.write(“ ” & request.querystring(“lname”))
%>
</body>
The browser will display the following in the body of the document:
Welcome Bill Gates
Request.Form
The Request.Form command is used to collect values in a form with method=“post”.
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
Example of HTML Form
<form method=“post” action=“simpleform.asp”>
First Name: <input type=“text” name=“fname”><br>
Last Name: <input type=“text” name=“lname”><br><br>
<input type=“submit” value=“Submit”>
</form>
Amity Directorate of Distance and Online Education
70 Web-Enabled Business Processes
If a user typed “Bill” and “Gates” in the HTML form above, the URL sent to the server
Notes
would look like this:
http://www.w3abc.com/simpleform.asp
Assume that “simpleform.asp” contains the following ASP script:
<body>
Welcome
<%
response.write(request.form(“fname”))
response.write(“ ” & request.form(“lname”))
%>
</body>
The browser will display the following in the body of the document:
Welcome Bill Gates

Form Validation
User input should be validated on the browser whenever possible (by client scripts).
Browser validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a
database. A good way to validate a form on the server is to post the form to itself, instead
of jumping to a different page. The user will then get the error messages on the same
page as the form. This makes it easier to discover the error.

Response Object
The ASP Response object is used to send output to the user from the server. Its
collections, properties, and methods are described below:
Collections
Collection Description
Cookies Sets a cookie value. If the cookie does not exist, it will be created, and take
the value that is specified

Properties
Property Description
Buffer Specifies whether to buffer the page output or not
CacheControl Sets whether a proxy server can cache the output generated by ASP or not
Charset Appends the name of a character-set to the content-type header in the
Response object
ContentType Sets the HTTP content type for the Response object
Expires Sets how long (in minutes) a page will be cached on a browser before it
expires
ExpiresAbsolute Sets a date and time when a page cached on a browser will expire
IsClientConnected Indicates if the client has disconnected from the server
Pics Appends a value to the PICS label response header
Status Specifies the value of the status line returned by the server

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 71

Methods Notes
Method Description
AddHeader Adds a new HTTP header and a value to the HTTP response
AppendToLog Adds a string to the end of the server log entry
BinaryWrite Writes data directly to the output without any character conversion
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Flush Sends buffered HTML output immediately
Redirect Redirects the user to a different URL
Write Writes a specified string to the output

Request Object
When a browser asks for a page from a server, it is called a request. The Request
object is used to get information from a visitor. Its collections, properties, and methods
are described below:

Collections
Collection Description
ClientCertificate Contains all the field values stored in the client certificate
Cookies Contains all the cookie values sent in a HTTP request
Form Contains all the form (input) values from a form that uses the post method
QueryString Contains all the variable values in a HTTP query string
ServerVariables Contains all the server variable values

Properties
Property Description
TotalBytes Returns the total number of bytes the client sent in the body of the request

Methods
Method Description
BinaryRead Retrieves the data sent to the server from the client as part of a post
request and stores it in a safe array

ASP Application Object


A group of ASP files that work together to perform some purpose is called an
application. The Application object is used to tie these files together.

Application Object
An application on the Web may consists of several ASP files that work together to
perform some purpose. The Application object is used to tie these files together.
The Application object is used to store and access variables from any page, just like
the Session object. The difference is that ALL users share ONE Application object (with
Sessions, there is ONE Session object for EACH user).

Amity Directorate of Distance and Online Education


72 Web-Enabled Business Processes
The Application object holds information that will be used by many pages in the
Notes
application (like database connection information). The information can be accessed
from any page. The information can also be changed in one place, and the changes will
automatically be reflected on all pages.
The Application object’s collections, methods, and events are described below:

Collections
Collection Description
Contents Contains all the items appended to the application through a script
command
StaticObjects Contains all the objects appended to the application with the HTML
<object> tag

Methods
Method Description
Contents.Remove Deletes an item from the Contents collection
Contents.RemoveAll() Deletes all items from the Contents collection
Lock Prevents other users from modifying the variables in the Application
object
Unlock Enables other users to modify the variables in the Application object
(after it has been locked using the Lock method)

Events
Event Description
Application_OnEnd Occurs when all user sessions are over, and the application ends
Application_OnStart Occurs before the first new session is created (when the Application
object is first referenced)

Session Object
When you are working with an application on your computer, you open it, do some
changes and then you close it. This is much like a Session. The computer knows who
you are. It knows when you open the application and when you close it. However, on the
internet, there is one problem: the web server does not know who you are and what you
do, because the HTTP address doesn’t maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is
sent to the user’s computer and it contains information that identifies the user. This
interface is called the Session object.
The Session object stores information about, or change settings for a user session.
Variables stored in a Session object hold information about one single user, and are
available to all pages in one application. Common information stored in session variables
are name, ID, and preferences. The server creates a new Session object for each new
user, and destroys the Session object when the session expires.
The Session object’s collections, properties, methods, and events are described
below:

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 73

Collections Notes
Collection Description
Contents Contains all the items appended to the session through a script command
StaticObjects Contains all the objects appended to the session with the HTML <object>
tag

Properties
Property Description
CodePage Specifies the character set that will be used when displaying dynamic
content
LCID Sets or returns an integer that specifies a location or region. Contents like
date, time, and currency will be displayed according to that location or
region
SessionID Returns a unique ID for each user. The unique ID is generated by the server
Timeout Sets or returns the timeout period (in minutes) for the Session object in this
application

Methods
Method Description
Abandon Destroys a user session
Contents.Remove Deletes an item from the Contents collection
Contents.RemoveAll() Deletes all items from the Contents collection

Events
Event Description
Session_OnEnd Occurs when a session ends
Session_OnStart Occurs when a session starts

Server Object
The ASP Server object is used to access properties and methods on the server. Its
properties and methods are described below:

Properties
Property Description
ScriptTimeout Sets or returns the maximum number of seconds a script can run before it
is terminated

Methods
Method Description
CreateObject Creates an instance of an object
Execute Executes an ASP file from inside another ASP file
GetLastError() Returns an ASPError object that describes the error condition that occurred
HTMLEncode Applies HTML encoding to a specified string

Amity Directorate of Distance and Online Education


74 Web-Enabled Business Processes

Notes MapPath Maps a specified path to a physical path


Transfer Sends (transfers) all the information created in one ASP file to a second
ASP file
URLEncode Applies URL encoding rules to a specified string

3.4 Programming for Database Connectivity


This step-by-step process describes how to connect to a database by using an
Active Server Pages (ASP) Web page.

3.4.1 Create a Data Source Name


To connect to a database by using ASP pages, you must first create a Data Source
Name (DSN) on the Web server for the type of database to which you want to connect.
To do so, use one of the following methods.

3.4.2 For a Database Program


To create a DSN for a database program (such as Microsoft Access):
1. Log on to the Web server computer as administrator.
2. Click Start, point to Settings, and then click Control Panel.
3. Double-click Administrative Tools, and then double-click Data Sources
(ODBC).
4. Click the System DSN tab, and then click Add.
5. Select the database driver that you want (for example, Microsoft Access
Driver (*.mdb), and then click Finish.
6. In the Data Source Name box, type the name that you want to use when you
refer to this DSN in your ASP code. For example, Northwind.
7. In the Description box, type an optional description for the DSN. For example,
Northwind DSN.
8. Click Select.
9. In the Select Database dialog box, browse to and select the database that you
want. For example, Northwind.mdb.
NOTE: If the database is not on the Web server, click Network, and then click
Browse. Locate the shared network folder that contains the database, and then
click OK. Click Finish, and then select the database that you want.
10. Click OK.
11. Click Advanced.
12. If you want to automatically provide login credentials to the database when you
use this DSN, type them into the Login name and Password boxes. Click OK.
13. Click OK, and then click OK.

3.4.3 For a Database Server


To create a DSN for an SQL Server:
1. Log on to the Web server computer as administrator.
2. Click Start, point to Settings, and then click Control Panel.
3. Double-click Administrative Tools, and then double-click Data Sources
(ODBC).
4. Click the System DSN tab, and then click Add.

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 75

5. Select SQL Server, and then click Finish.


Notes
6. In the Name box, type the name that you want to use when you refer to this
DSN in your ASP code. For example, Northwind.
7. In the Description box, type an optional description for the DSN.
8. In the Server list, do one of the following:
– Select the name of an SQL Server on the network.
– Select (local) if the SQL Server that you want is running on the Web
server computer.
– Type a name (alias) for a server that does not appear in the Server list.
9. Click Next.
10. Under how should SQL Server verify the authenticity of the login ID, click
the authentication method that you want. For example, with Windows NT
authentication using the network login ID. Click Next.
11. Click to select the Change the default database to check box, select the
database that you want from the list (for example, NorthWind), and then click
Next.
12. Click Finish, click OK, and then click OK.

Create an ASP Script to Connect to the Database by Using the DSN


In your ASP Script, create a connection to the database by using the ActiveX Data
Objects (ADO) Database Access Component (DAC):
z Use the Connection ADO object to create a connection to the database.
z Use the Recordset object to retrieve, update, and delete existing database
records.

Example
The following example illustrates how to connect to the Microsoft Access NorthWind
sample database by using an ASP Script.
NOTE: This example assumes the default installation of Windows 2000 on drive C,
as well as the default installation of Microsoft Access along with the NorthWind sample
database.

Step 1: Create a DSN


Follow the steps in the For a Database Program section of this article to create a
DSN to the Microsoft Access Northwind.mdb sample database.
NOTE: By default, the Northwind.mdb file is located in the C:\Program
Files\Microsoft Office\Office\Samples folder.

Step 2: Create an ASP Page


1. Start Notepad.
2. In Notepad, type the following code:
3. <HTML>
4. <HEAD><TITLE>ASP Database Connection</TITLE></HEAD>
5. <BODY BGCOLOR=white>
6. <H1>Northwind Database Contacts</H1>
7. <%
8. Dim Connect, selectSQL, RecSet

Amity Directorate of Distance and Online Education


76 Web-Enabled Business Processes
9. Set Connect = CreateObject (“ADODB.Connection”)
Notes
10. Connect.Open “DSN=Northwind”
11. selectSQL = “SELECT * FROM Customers”
12. Set RecSet = Connect.Execute (selectSQL)
13. If NOT RecSet.EOF
14. THEN
15. DO UNTIL RecSet.EOF
16. Response.Write RecSet(“Companyname”) & “, ” & RecSet(“Contactname”) &
“<BR><BR>”
17. RecSet.MoveNext
18. Loop
19. End If
20. RecSet.Close
21. Connect.Close
22. Set RecSet = Nothing
23. Set Connect = Nothing
24. %>
25. </BODY></HTML>
26. On the File menu, click Save As.
27. In the Save As dialog box, navigate to C:\Inetpub\wwwroot in the Save in list,
select All Files in the Save as type list, type database.asp in the File name box,
and then click Save.
28. Quit Notepad.

Step 3: Test the ASP Page


1. Click Start, and then click Run.
2. In the Open box, type http://localhost/database.asp, and then click OK. A Web
page that displays the NorthWind sample database customer list is displayed in
the browser window.

3.5 Troubleshooting
If you experience difficulty connecting to a database by using ASP Web pages,
verify that you have sufficient permissions to access the database:
z Verify that the DSN is using an account with sufficient permissions to access
the database.
z If you attempt to connect to a SQL Server over a network, ensure that you use
a domain account as your anonymous IIS account.
z If you attempt to connect to a Microsoft Access database, ensure that the IIS
account has Write permissions to the folder in which the database is stored.
This is to enable the creation of a temporary file when users access the
database.

ASP Cookies
A cookie is often used to identify a user.

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 77

Examples Notes
Welcome cookie
How to create a Welcome cookie?
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user’s computer. Each time the same computer requests a page with a
browser, it will send the cookie too. With ASP, you can both create and retrieve cookie
values.
How to Create a Cookie?
The “Response.Cookies” command is used to create cookies.
Note: The Response.Cookies command must appear BEFORE the <html> tag.
In the example below, we will create a cookie named “firstname” and assign the
value “Alex” to it:
<%
Response.Cookies(“firstname”)=“Alex”
%>
It is also possible to assign properties to a cookie, like setting a date when the
cookie should expire:
<%
Response.Cookies(“firstname”)=“Alex”
Response.Cookies(“firstname”).Expires=#May 10,2012#
%>
How to Retrieve a Cookie Value?
The “Request.Cookies” command is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named “firstname” and
display it on a page:
<%
fname=Request.Cookies(“firstname”)
response.write(“Firstname=” & fname)
%>
Output: Firstname=Alex

A Cookie with Keys


If a cookie contains a collection of multiple values, we say that the cookie has Keys.
In the example below, we will create a cookie collection named “user”. The “user”
cookie has Keys that contains information about a user:
<%
Response.Cookies(“user”)(“firstname”)=“John”
Response.Cookies(“user”)(“lastname”)=“Smith”
Response.Cookies(“user”)(“country”)=“Norway”
Response.Cookies(“user”)(“age”)=“25”
%>

Amity Directorate of Distance and Online Education


78 Web-Enabled Business Processes

Notes Read All Cookies


Look at the following code:
<%
Response.Cookies(“firstname”)=“Alex”
Response.Cookies(“user”)(“firstname”)=“John”
Response.Cookies(“user”)(“lastname”)=“Smith”
Response.Cookies(“user”)(“country”)=“Norway”
Response.Cookies(“user”)(“age”)=“25”
%>
Assume that your server has sent all the cookies above to a user.
Now, we want to read all the cookies sent to a user. The example below shows how
to do it (note that the code below checks if a cookie has Keys with the HasKeys property):
<!DOCTYPE html>
<html>
<body>
<%
dim x,y
for each x in Request.Cookies
response.write(“<p>”)
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & “:” & y & “=” & Request.Cookies(x)(y))
response.write(“<br>”)
next
else
Response.Write(x & “=” & Request.Cookies(x) & “<br>”)
end if
response.write “</p>”
next
%>
</body>
</html>
Output:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:country=Norway
user:age=25

What If a Browser Does NOT Support Cookies?


If your application deals with browsers that do not support cookies, you will have to
use other methods to pass information from one page to another in your application.
There are two ways of doing this:

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 79

1. Add parameters to a URL Notes


You can add parameters to a URL:
<a href=“welcome.asp?fname=John&lname=Smith”>Go to Welcome Page</a>
And retrieve the values in the “welcome.asp” file like this:
<%
fname=Request.querystring(“fname”)
lname=Request.querystring(“lname”)
response.write(“<p>Hello ” & fname & “ ” & lname & “!</p>”)
response.write(“<p>Welcome to my Website!</p>”)
%>

2. Use a Form
You can use a form. The form passes the user input to “welcome.asp” when the
user clicks on the Submit button:
<form method=“post” action=“welcome.asp”>
First Name: <input type=“text” name=“fname” value=“”>
Last Name: <input type=“text” name=“lname” value=“”>
<input type=“submit” value=“Submit”>
</form>
Retrieve the values in the “welcome.asp” file like this:
<%
fname=Request.form(“fname”)
lname=Request.form(“lname”)
response.write(“<p>Hello ” & fname & “ ” & lname & “!</p>”)
response.write(“<p>Welcome to my Website!</p>”)
%>

ASP Session Object


A Session object stores information about, or change settings for a user session.

The Session Object


When you are working with an application on your computer, you open it, do some
changes and then you close it. This is much like a Session. The computer knows who
you are. It knows when you open the application and when you close it. However, on the
internet, there is one problem: the web server does not know who you are and what you
do, because the HTTP address doesn’t maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is
sent to the user’s computer and it contains information that identifies the user. This
interface is called the Session object.
The Session object stores information about, or change settings for a user session.
Variables stored in a Session object hold information about one single user, and are
available to all pages in one application. Common information stored in session variables
are name, ID, and preferences. The server creates a new Session object for each new
user, and destroys the Session object when the session expires.

Amity Directorate of Distance and Online Education


80 Web-Enabled Business Processes

Notes When Does a Session Start?


A session starts when:
z A new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure
z A value is stored in a Session variable
z A user requests an ASP file, and the Global.asa file uses the <object> tag to
instantiate an object with session scope.

When Does a Session End?


A session ends if a user has not requested or refreshed a page in the application for
a specified period. By default, this is 20 minutes.
If you want to set a timeout interval that is shorter or longer than the default, use the
Timeout property.
The example below sets a timeout interval of 5 minutes:
<%
Session.Timeout=5
%>
Use the Abandon method to end a session immediately:
<%
Session.Abandon
%>
Note: The main problem with sessions is WHEN they should end. We do not know if
the user’s last request was the final one or not. So, we do not know how long we should
keep the session “alive”. Waiting too long for an idle session uses up resources on the
server, but if the session is deleted too soon, the user has to start all over again because
the server has deleted all the information. Finding the right timeout interval can be
difficult!
Tip: Only store SMALL amounts of data in session variables!

3.6 Store and Retrieve Session Variables


The most important thing about the Session object is that you can store variables in it.
The example below will set the Session variable username to “Donald Duck” and the
Session variable age to “50”:
<%
Session(“username”)=“Donald Duck”
Session(“age”)=50
%>
When the value is stored in a session variable, it can be reached from ANY page in
the ASP application:
Welcome <%Response.Write(Session(“username”))%>
The line above returns: “Welcome Donald Duck”.
You can also store user preferences in the Session object, and then access that
preference to choose what page to return to the user.

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 81

The example below specifies a text-only version of the page if the user has a low
Notes
screen resolution:
<%If Session(“screenres”)=“low” Then%>
This is the text version of the page.
<%Else%>
This is the multimedia version of the page.
<%End If%>
3.6.1 Remove Session Variables
The Contents collection contains all session variables.
It is possible to remove a session variable with the Remove method.
The example below removes the session variable “sale” if the value of the session
variable “age” is lower than 18:
<%
If Session.Contents(“age”)<18 then
Session.Contents.Remove(“sale”)
End If
%>
To remove all variables in a session, use the RemoveAll method:
<%
Session.Contents.RemoveAll()
%>
Loop Through the Contents Collection
The Contents collection contains all session variables. You can loop through the
Contents collection, to see what’s stored in it:
<%
Session(“username”)=“Donald Duck”
Session(“age”)=50
dim i
For Each i in Session.Contents
Response.Write(i & “<br>”)
Next
%>
Result:
username
age
If you do not know the number of items in the Contents collection, you can use the
Count property:
<%
dim i
dim j
j=Session.Contents.Count
Response.Write(“Session variables: ” & j)
For i=1 to j

Amity Directorate of Distance and Online Education


82 Web-Enabled Business Processes
Response.Write(Session.Contents(i) & “<br>”)
Notes
Next
%>
Result:
Session variables: 2
Donald Duck
50

Loop Through the StaticObjects Collection


You can loop through the StaticObjects collection, to see the values of all objects
stored in the Session object:
<%
dim i
For Each i in Session.StaticObjects
Response.Write(i & “<br>”)
Next
%>

3.7 Summary
An Active Server Page (ASP) is an HTML page that includes one or more scripts
(small embedded programs) that is processed on a Microsoft Web server before the
page is sent to the user. An ASP is somewhat similar to a server-side include or a
common gateway interface (CGI) application in that all involve programs that run on the
server, usually tailoring a page for the user. Typically, the script in the Web page at the
server uses input received as the result of the user’s request for the page to access data
from a database and then builds or customizes the page on the fly before sending it to
the requestor.
ASP is a feature of the Microsoft Internet Information Server (IIS), but, since the
server-side script is just building a regular HTML page, it can be delivered to almost any
browser. You can create an ASP file by including a script written in VBScript or JScript in
an HTML file or by using ActiveX Data Objects (ADOs) program statements in the HTML
file. You name the HTML file with the “.asp” file suffix. Microsoft recommends the use of
the server-side ASP rather than a client-side script, where there is actually a choice,
because the server-side script will result in an easily displayable HTML page. Client-side
scripts (for example, with JavaScript) may not work as intended on older browsers.

3.8 Check Your Progress


I. Fill in the Blanks
1. In the client/server architecture, the component that processes the request and
sends the response is _________.
2. In three-tier client/server applications, the business logic lies at _________.
3. Which among the following are used to create very concurrent, event-driven
server programs _________.
4. _________ is a non-GUI client.
5. In three-tier computing, the request/response protocol between the clients and
web servers is _________.

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 83

II. True or False


Notes
1. The process of advancing E-Commerce technologies will only lead to more
disintermediation.
2. B2B and B2C IT initiatives can use the same E-Commerce platforms.
3. A competitive advantage based on internal cost reduction is much easier to
maintain than one based on price.
4. A well-known brand name is still important to be successful in B2C
e-commerce.
5. There are many advantages to the consumer since the inception of
e-commerce such as power to demand lower prices, higher quality, and better
service.
III. Multiple Choice Questions
1. Multiple object can be sent over a TCP connection between client and server in
__________.
(a) persistent HTTP
(b) non-persistent HTTP
(c) Both (a) and (b)
(d) None of the mentioned
2. HTTP is ________ protocol.
(a) application layer
(b) transport layer
(c) network layer
(d) None of the mentioned
3. In the network, HTTP resources are located by __________.
(a) uniform resource identifier
(b) unique resource locator
(c) unique resource identifier
(d) None of the mentioned
4. HTTP client requests by establishing a __________ connection to a particular
port on the server.
(a) user datagram protocol
(b) transmission control protocol
(c) broader gateway protocol
(d) None of the mentioned
5. In HTTP pipelining, __________.
(a) multiple HTTP requests are sent on a single TCP connection without
waiting for the corresponding responses
(b) multiple HTTP requests can not be sent on a single TCP connection
(c) multiple HTTP requests are sent in a queue on a single TCP connection
(d) None of the mentioned
6. FTP server listens for connection on port number __________.
(a) 20
(b) 21
(c) 22
(d) 23

Amity Directorate of Distance and Online Education


84 Web-Enabled Business Processes
7. In FTP protocol, client contacts server using _______ as the transport protocol.
Notes
(a) transmission control protocol
(b) user datagram protocol
(c) datagram congestion control protocol
(d) stream control transmission protocol
8. In which mode FTP, the client initiates both the control and data connections?
(a) Active mode
(b) Passive mode
(c) Both (a) and (b)
(d) None of the mentioned
9. The file transfer protocol is built on __________.
(a) data-centric architecture
(b) service oriented architecture
(c) client server architecture
(d) None of the mentioned
10. In file transfer protocol, data transfer can be done in __________.
(a) stream mode
(b) block mode
(c) compressed mode
(d) All of the mentioned

3.9 Questions and Exercises


1. What happens to ASP pages?
2. How can you change the primary scripting language for a page?
3. What is Application Object?
4. What is the difference between client-side script and server-side script?
5. What is the command to display characters to the HTML page?
6. Explain the POST and GET Method or Explain the difference between them.
7. How many global.asa files can an Application have?
8. What are Scripting Objects?
9. What is the Order of precedence for LOGICAL Operators?
10. What is an Err Object?
11. What are LOCAL and GLOBAL variables?
12. Which is the default Scripting Language on the client side?
13. What is Active Server Pages?
14. What is dynamic content?
15. Who should use Active Server Pages?
16. Who can create dynamic content with Active Server Pages?
17. What do I need to run Active Server Pages?
18. How much will Active Server Pages cost?

3.10 Key Terms


Ɣ ASP: ASP stands for Active Server Pages.

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 85

Ɣ Virtual directory: Virtual directories are aliases for directory paths on the
Notes
server.
Ɣ Form collection: The Form collection holds the values of the form elements
submitted with the POST method. This is the only way to generate a Form
collection.
Ɣ Variable: Variable is a memory location through which the actual values are
stored/retrieved. Its value can be changed.
Ɣ Client-side script and server-side script: Scripts executed only by the
browser without contacting the server is called client-side script. It is
browser-dependent. The scripting code is visible to the user and hence not
secure. Scripts executed by the web server and processed by the server is
called server-side script.
3.11 Check Your Progress: Answers
I. Fill in the Blanks
1. Network
2. Middle Tier
3. Threads
4. Automatic Teller Machine
5. HTTP
II. True or False
1. False
2. False
3. True
4. True
5. True
III. Multiple Choice Questions
1. (a) persistent HTTP
2. (a) application layer
3. (a) uniform resource identifier
4. (b) transmission control protocol
5. (a) multiple HTTP requests are sent on a single TCP connection without
waiting for the corresponding responses
6. (b) 21
7. (a) transmission control protocol
8. (b) Passive mode
9. (c) client server architecture
10. (d) All of the mentioned

3.12 Case Study


This section explains how to develop an ASP page that delivers services useful in
e-commerce. This section includes the following lessons:
Rotate Ad information. Randomly rotate ads on your Web page.
Redirect users from Ad links. Redirect browsers to advertisers’ sites when users
click on an ad image.
Count page hits. Track the number of times users request a page.

Amity Directorate of Distance and Online Education


86 Web-Enabled Business Processes

Notes Rotate Ad Information


Advertising is big business on the Web. This lesson explains how to take advantage
of the Ad Rotator component installed with ASP by describing how to use this component
to rotate advertisements on your Web pages. The Ad Rotator component selects an
advertisement for your Web page each time the user refreshes or loads the Web page.
Two files are required to set up the Ad Rotator component: An Ad Rotator Include file and
an Ad Images Data file. By setting up these two files, this component can be called by
any ASP page on your site. Changes to the ad parameters are not done on all the sites
containing the ad, but to the ad images data file. This saves lots of time if the ad appears
on numerous pages within your website.
This section explains how to:
Write an Ad Rotator Include File. Creates the ad-image links on any page that
calls this file.
Create an Ad Image Data File. Specifies global ad-display data and information
specific to each ad.
Test the Ad Rotator. Uses an ASP page that calls the Ad Rotator logic Include file
and the image data file to display and rotate ads.

Write an Ad Rotator Include File


Include files are used to store information that will be used by more than one ASP or
HTML file. By creating an Ad Rotator Include file, when changes need to be made to
specific information, you only need to change the information in one location. This lesson
will guide you in creating an Ad Rotator Include file containing a function named getAd().
This function randomly selects ads to display on your ASP pages. You can call this file
from within any ASP page intended to display the rotated ads. When you test calling the
Include file from an ASP page, you will use some images from Microsoft.com for ad
images.
Open a new file in your text editor, paste in the following script, and save the file as
Adrotatorlogic.inc:
<%
Function getAd()
Dim load
‘Create an instance of the AdRotator component
Set load=Server.CreateObject(“MSWC.AdRotator”)
‘Set the target frame, if any. This is the frame
‘where the URL will open up. If the HTML page does
‘not find the target name, the URL will be opened
‘in a new window.
load.TargetFrame = “Target = new”
‘Get a random advertisement from the text file.
getAd = load.GetAdvertisement(“adimagedata.txt”)
End Function
%>

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 87

Create an Ad Images Data File Notes


An ad images data file is created to provide information about the ads to be
displayed. By placing the data in one text file, when changes need to be made, you only
need to change the data in one location. The ASP page (with the logic in the Include file)
sends data in the ad images data file to the Ad Rotator component. The component then
selects an ad for display.
The data file is divided into two sections that are separated by an asterisk (*). The
first section provides information common to all the ads to be displayed. The second
section lists data relevant to each ad.
The following outlines the structure of an ad images data file:
Ɣ REDIRECTION. URL, the path and name of the ASP file that redirects
browsers that select ad images.
Ɣ WIDTH. The width of ad images in pixels. Default is 440.
Ɣ HEIGHT. The height of ad images in pixels. Default is 60.
Ɣ BORDER. The border thickness around ad images. Default is 1.
Ɣ *. Separates the first section from the second section.
Ɣ AdURL. Virtual path and filename of the image file containing the
advertisement.
Ɣ AdHomeURL. URL to jump to when this link is selected. To indicate there is no
link, use a hyphen.
Ɣ Text. Text to display if browser does not support graphics.
Ɣ Impressions. An integer indicating the relative weight, or probability, that this
ad will be selected for display. For example, if two ads were displayed, one with
an impression of 3 and the other with 7, then the one with 3 would have a
30% probability of being selected, while the other would have a 70%
probability.
Open a new file in your text editor, paste in the following script, and save the file as
Adimagedata.txt:
REDIRECT adrotatorredirect.asp
WIDTH 250
HEIGHT 60
BORDER 0
* separates the general data from the image information
images/windows_logo.gif
http://www.microsoft.com/windows
Microsoft Windows
2
images/office_logo.gif
http://www.microsoft.com/office
Office 2000
3

Test the Ad Rotator


To test the system, you will need an ASP page that calls the Ad Rotator Include file
and the Ad Images Data File, and then displays the ads. First, you will need test ad
images stored on your site.
Amity Directorate of Distance and Online Education
88 Web-Enabled Business Processes
Acquire and store the ad images as follows:
Notes
1. Create a directory named Images in the tutorial folder: C:\Inetpub\Wwwroot\
Tutorial\Images.
2. Download the Office logo file, available at http://www.microsoft.com/office/
images/office_logo.gif, from the Microsoft Office Website, and save it as
Office_logo.gif in C:\Inetpub\Wwwroot\Tutorial\Images.
3. Download the Windows logo file, available at http://www.microsoft.com/
windows/images/bnrwinfam.gif(, from the Microsoft Windows Website, and
save it as Windows_logo.gif in C:\Inetpub\Wwwroot\Tutorial\Images.
Open a new file in your text editor, paste in the following script, and save the file as
Displayad.asp:
<%@ Language=“VBScript” %>
<!--Call the Include file, which in turn -->
<!--calls the ad images data text file-->
<!--#include file=”adrotatorlogic.inc”-->
<html>
<head>
<title>Test Ad Display Page</title>
</head>
<body>
<h1>Test Ad Display Page</h1>
<!--Display the ad banner-->
<p><%=getAd()%></p>
<p>The space above should contain an image displaying either the Microsoft
Windows family logo or the Microsoft Office family logo.</p>
<ul>
<li type=“disc”>This indicates that Displayad.asp, Adrotatorlogic.inc and
Adimagedata.txt are working together to correctly display the images.</li>
<li type=“disc”>Repeatedly refreshing the page should result in the Windows and
Office logos displaying in random order.</li>
<li type=“disc”>After you save Adrotatorredirect.asp, clicking on the displayed image
should cause a new window to open, displaying the home page corresponding to the
displayed logo.</li>
<li type=“disc”>After you add the hit counter script to this page, under “Statistics”
you should see the number of page hits since the script was added.</li>
</ul>
<br><br><br><br><br>
<h3>Statistics</h3>
<% Set pageCount = Server.CreateObject(“MSWC.PageCounter”) %>
<!--Increment the counter-->
<% pageCount.PageHit %>
<p>You are visitor number <% =pageCount.Hits %> to this Web page.</p>
</body>
</html>

Amity Directorate of Distance and Online Education


Database Connectivity using ASP 89

Redirect Users from Ad Links Notes


When a user clicks the ad, the browser appends a query string to the request to the
server. Then the server directs the user’s browser to the ad’s URL.
Open a new file in your text editor, paste in the following script, and save the file as
Adrotatorredirect.asp:
<%@Language=VBScript %>
<html>
<head>
<title>Redirection Page</title>
</head>
<body>
<%
Set the response buffer on
Response.Buffer = True
Dim lsURL
Obtain the URL from the query string
lsURL = Request.QueryString(“URL”)
Clear the response and redirect to URL
Response.Clear()
Response.Redirect(lsURL)
%>
</body>
</html>
To check your work, use Displayad.asp. When you click on an ad, you should see a
new window displaying an appropriate ad-related Web page.

Count Page Hits


It is important to know how many hits your Web pages get. This data helps
determine how changes to your Website may affect your customers’ viewing habits. More
importantly, it provides useful insight as to how customers are navigating through your
site and where ads should be placed. Sites with high trafficking have higher
advertisement prices associated with them. The data gathered from a page hit counter
provides you with trafficking information to begin negotiating advertisement prices for
your Web pages.
The Page Counter component uses an internal object to record page hit-count totals
for all pages on the server. At regular intervals, this object saves all information to a text
file so that no counts are lost due to power loss or system failure. The Page Counter
component uses the following three methods:
Ɣ Hits(). This displays the number of hits for a Web page. The default is the
current page.
Ɣ PageHit(). This increments the hit count for the current page.
Ɣ Reset(). This resets the hit count for a page to zero. The default is the current
page.

Amity Directorate of Distance and Online Education


90 Web-Enabled Business Processes
An in-use sample of this script can be seen at the bottom of the Displayad.asp script.
Notes
To place a page hit counter on a Web page, place the following script where you want the
counter displayed on the page:
<% Set pageCount = Server.CreateObject(“MSWC.PageCounter”) %>
<% pageCount.PageHit %>
You are visitor number <% =pageCount.Hits %> to this Website.

3.13 Further Readings


1. Professional Active Server Pages 2.0
2. Active Server Pages 2.0 Programmer’s Reference
3. Using Active Server Pages
4. Enterprise Application Architecture with VB, ASP and MTS
5. Professional ASP Techniques for Webmasters
6. Professional ADO RDS Programming With ASP

Amity Directorate of Distance and Online Education

You might also like