Microsoft®
Active Server Pages (ASP) is a server-side scripting environment that
you can use to create and run dynamic, interactive Web server applications.
With ASP, you can combine HTML pages, script commands, and COM components to
create interactive Web pages or powerful Web-based applications, which are easy
to develop and modify.
If
you are an HTML author, you will find that server-side scripts written in ASP
are an easy way to begin creating more complex, real-world Web applications. If
you have ever wanted to store HTML form information in a database, personalize
Web sites according to visitor preferences, or use different HTML features
based on the browser, you will find that ASP provides a compelling solution.
For example, previously, to process user input on the Web server you would have
had to learn a language such as Perl or C to build a conventional Common
Gateway Interface (CGI) application. With ASP, however, you can collect HTML
form information and pass it to a database using simple server-side scripts
embedded directly in your HTML documents. If you are already familiar with
scripting languages such as Microsoft VBScript or Microsoft® JScript® (JScript
is the Microsoft implementation of the ECMA 262 language specification), you
will have little trouble learning ASP.
If
you want to get started right away with ASP, see the ASP Tutorial. You
can then return to these topics for more detailed information on writing
server-side scripts.
Since
ASP is designed to be language-neutral, if you are skilled at a scripting
language such as VBScript, JScript, or PERL, you already know how to use Active
Server Pages. What more, in your ASP pages you can use any scripting language
for which you have installed a COM compliant scripting engine. ASP comes with
VBScript and JScript scripting engines, but you can also install scripting
engines for PERL, REXX, and Python, which are available through third-party
vendors.
If
you develop back-end Web applications in a programming language, such as Visual
Basic, C++, or Java, you will find ASP a flexible way to quickly create Web applications.
Besides adding scripts to create an engaging HTML interface for your
application, you can build your own COM components. You can encapsulate your
application's business logic into reusable modules that you can call from a
script, from another component, or from another program.
A
server-side script begins to run when a browser requests an .asp file from your
Web server. Your Web server then calls ASP, which processes the requested file
from top to bottom, executes any script commands, and sends a Web page to the
browser.
Because
your scripts run on the server rather than on the client, your Web server does
all the work involved in generating the HTML pages sent to browsers.
Server-side scripts cannot be readily copied because only the result of the
script is returned to the browser. Users cannot view the script commands that
created the page they are viewing.
© 1997-2001 Microsoft
Corporation. All rights reserved.]
ASP Tutorial
In
Module 1, you create ASP pages (.asp files) using HTML and Microsoft® Visual
Basic® Scripting Edition (VBScript). This module includes the following
lessons:
·
Lesson
1: Writing an ASP Page Four examples of how to write and
run ASP pages using HTML and VBScript.
·
Lesson
2: Submitting Information Using Forms Develop a form on an
HTML page so that users can enter their personal data.
·
Lesson
3: Creating a Guest Book Use forms to gather information
from visitors, store their information in a Microsoft Access database, and
display the database contents on a Web page.
·
Lesson
4: Displaying an Excel Spreadsheet Display a Microsoft
Excel spreadsheet on a Web page.
The
best way to learn about ASP is to look at examples; alter integer values,
strings, and statements you are curious about; and determine what changes occur
in the browser.
In
this lesson you perform the following tasks:
·
Example 1 Create, save,
and run an ASP page using HTML and VBScript.
·
Examples 2, 3, and 4 Add
functionality and logic to your ASP page by using built-in functions and
conditional script statements.
VBScript
is the default scripting language for ASP pages; however, the delimiters are
the same for JScript. Use angle brackets as delimiters around HTML tags just as
you would in any .htm page, as follows:
<example></example>
Use
percent signs with brackets as delimiters around script code, as follows:
<% example %>
You
can put many script statements inside one pair of script delimiters, as in
the following example:
<font face="MS Gothic">
<%
'Create a variable.
dim strGreeting
'Set the greeting.
strGreeting = "Hello World!"
'Print out the greeting, using the ASP Response object.
Response.Write strGreeting & "<BR>"
'Also print out the greeting using the <%= method.
%>
<%=strGreeting%>
</font>
This
code displays the following text in the browser:
Hello World!
Hello World!
Here
is the previous example using JScript:
<%@ Language=JScript %>
<font face="MS Gothic">
<%
//Create a variable.
var strGreeting;
//Set the greeting.
strGreeting = "Hello World!";
//Print out the greeting, using the ASP Response object.
Response.Write(strGreeting + "<BR>");
//Also print out the greeting using the <%= method.
%>
<%=strGreeting%>
</font>
To
create ASP pages, use a text editor such as Notepad and save the page with the
.asp extension instead of .htm. The .asp filename extension tells IIS to send
the page through the ASP engine before sending the page to a client. (Note:
In the Notepad Save As dialog box, when Text Documents (*.txt) is
selected in the Save as type box, Notepad automatically appends .txt to
the filename. To prevent this, select All Files in the Save as type
box, type the full filename MyFile.asp in the File Name
field, and then click Save.)
This
example displays a greeting, the date, and the current time. To run this
example, copy and paste the following code into an empty file and save it in
the x:\Inetpub\Wwwroot\Tutorial directory as Example1.asp. View
the example with your browser by typing http://localhost/Tutorial/Example1.asp
in the address bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Example 1</title>
</head>
<body>
<font face="MS Gothic">
<H1>Welcome to my Home Page</H1>
<%
'Create some variables.
dim strDynamicDate
dim strDynamicTime
'Get the date and time.
strDynamicDate = Date()
strDynamicTime = Time()
'Print out a greeting, depending on the time, by comparing the
last 2 characters in strDymamicTime to "PM".
If "PM" = Right(strDynamicTime, 2) Then
Response.Write "<H3>Good Afternoon!</H3>"
Else
Response.Write "<H3>Good
Morning!</H3>"
End If
%>
Today's date is <%=strDynamicDate%> and the time is
<%=strDynamicTime%>
</font>
</body>
</html>
In
the browser, you should see something like the following (depending on the date
and time you perform this exercise):
Today's date is
10/20/2000 and the time is 7:29:50 PM
Note: The Web
server processes Example1.asp in the following sequence:
1.
<%@ Language=VBScript %> tells the
ASP engine to use the VBScript engine to translate the script code.
2.
The ASP engine ignores the HTML code blocks.
3.
The ASP engine executes the code in the <%...%>
blocks and replaces the blocks with placeholders. The results of the Response.Write
strings and <%=...%> strings are saved in memory on the server.
4.
The results of the Response.Write strings and <%=...%>
strings are injected into the HTML code at the matching placeholders before the
page leaves the ASP engine.
5.
The complete page leaves the ASP engine as a file of HTML
code, and the server sends the page to the client.
This
example incorporates a For...Next loop in the ASP page to add a little
dynamic logic. The For...Next loop is one of six conditional statements
available to you. The others are Do...Loop, For Each...Next, If...Then...Else...End
If, Select..Case...End Select, and While...Wend. These
statements are documented at Windows
Script Technologies under VBScript.
Copy
and paste the following code in your text editor, and save the file as Example2.asp.
View the example with your browser by typing http://localhost/Tutorial/Example2.asp
in the address bar.
The
processing order is the same as in Example1.asp.
<%@ Language=VBScript %>
<html>
<head>
<title>Example 2</title>
</head>
<body>
<font face="MS Gothic">
<%
'Create a variable.
dim strTemp
dim font1, font2, font3, font, size
'Set the variable.
strTemp= "BUY MY PRODUCT!"
fontsize = 0
'Print out the string 5 times using the For...Next loop.
For i = 1 to 5
'Close the script delimiters to allow the use of HTML
code and <%=...
%>.
<table align=center><font size= <%=fontsize%>>
<%=strTemp%> </font></table>
<%
fontsize = fontsize + i
Next
%>
<table align=center><font size=6><B> IT ROCKS!
<B></font></table><BR>
</font>
</body>
</html>
In
the browser, you should see something like the following:
|
BUY MY PRODUCT! |
|
BUY MY PRODUCT! |
|
BUY
MY PRODUCT! |
|
BUY MY PRODUCT! |
|
BUY MY PRODUCT! |
|
IT ROCKS! |
Here
is Example 2 using JScript:
<%@ Language=JScript %>
<html>
<head>
<title>Example 2</title>
</head>
<body>
<font face="MS Gothic">
<%
//Create a variable.
var strTemp;
var font1, font2, font3, font, size;
//Set the variable.
strTemp= "BUY MY PRODUCT!";
fontsize = 0;
//Print out the string 5 times using the For...Next loop.
for (i = 1; i < 6; i++) {
//Close
the script delimiters to allow the use of HTML code and <%=...
%>.
<table align=center><font size= <%=fontsize%>>
<%=strTemp%> </font></table>
<%
fontsize = fontsize + i;
}
%>
<table align=center><font size=6><B> IT ROCKS!
<B></font></table><BR>
</font>
</body>
</html>
There
are more multilingual Web sites every day, as businesses see the need to offer
their products around the world. Formatting your date, time, and currency to
match the user's locale is good for diplomacy.
In
Example 3, a predefined function displays the date and currency on your ASP
page. The date and currency are formatted for different locales using the GetLocale
function, the SetLocale function, the FormatCurrency function,
and the FormatDateTime function. Locale identification strings are
listed in the Locale ID Chart on MSDN. (This example doesn't cover
changing the CodePage to display non-European characters on European
operating systems. Please read CodePage topics in your IIS Documentation for
more information.)
Note:
There are more than 90 predefined functions in VBScript, and they are
all well-defined at Windows Script Technologies. To view the documentation,
select VBScript, select Documentation, select Language
Reference, and select Functions.
Copy
and paste the following code in your text editor, and save the file as Example3.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/Example3.asp in the address
bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Example 3</title>
</head>
<body>
<font face="MS Gothic">
<H3>Thank you for your purchase. Please print this page for
your records.</H3>
<%
'Create some variable.
dim saveLocale
dim totalBill
'Set the variables.
saveLocale = GetLocale
totalBill = CCur(85.50)
'For each of the Locales, format the date and the currency
SetLocale("fr")
Response.Write"<B>Formatted for
French:</B><BR>"
Response.Write FormatDateTime(Date, 1) &
"<BR>"
Response.Write FormatCurrency(totalBill) &
"<BR>"
SetLocale("de")
Response.Write"<B>Formatted for
German:</B><BR>"
Response.Write FormatDateTime(Date, 1) &
"<BR>"
Response.Write FormatCurrency(totalBill) &
"<BR>"
SetLocale("en-au")
Response.Write"<B>Formatted for English -
Australia:</B><BR>"
Response.Write FormatDateTime(Date, 1)& "<BR>"
Response.Write FormatCurrency(totalBill) &
"<BR>"
'Restore the original Locale
SetLocale(saveLocale)
%>
</font>
</body>
</html>
In
the browser, you should see the following:
Formatted for
French:
vendredi 20 octobre 2000
85,50 F
Formatted for German:
Freitag, 20. Oktober 2000
85,50 DM
Formatted for English - Australia:
Friday, 20 October 2000
$85.50
The
most common functions used in ASP Scripts are those that manipulate strings.
The most powerful string functions use regular expressions. Because
regular expressions are difficult to adapt to, Example 4 shows you how to
replace characters in a string by using a string expression and a regular
expression. Regular expressions are defined at Windows
Script Technologies. To view the documentation, select VBScript,
select Documentation, and select Regular Expressions Guide.
Copy
and paste the following code in your text editor, and save the file as Example4.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/Example4.asp in the address
bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Example 4</title>
</head>
<body>
<font face="MS Gothic">
<H3>Changing a Customer's Street Address</H3>
<%
'Create some variables.
dim strString
dim strSearchFor ' as a string
dim reSearchFor ' as a regular expression
dim strReplaceWith
'Set the variables.
strString = "Jane Doe<BR>100 Orange
Road<BR>Orangeville,
WA<BR>98100<BR>800.555.1212<BR>"
' Using a string object
strSearchFor = "100 Orange Road<BR>Orangeville,
WA<BR>98100"
' Using a regular expression object
Set reSearchFor = New RegExp
reSearchFor.Pattern = "100 Orange Road<BR>Orangeville,
WA<BR>98100"
reSearchFor.IgnoreCase = False
strReplaceWith = "200 Bluebell Court<BR>Blueville,
WA<BR>98200"
'Verify that strSearchFor exists...
' using a string object.
If Instr(strString, strSearchFor) Then
Response.Write "strSearchFor was found in
strString<BR>"
Else
Response.Write "Fail"
End If
' using a regular expression object.
If reSearchFor.Test(strString) Then
Response.Write "reSearchFor.Pattern was found in
strString<BR>"
Else
Response.Write "Fail"
End If
'Replace the string...
Response.Write "<BR>Original String:<BR>"
& strString & "<BR>"
' using a string object.
Response.Write "String where strSearchFor is
replaced:<BR>"
Response.Write Replace(strString, strSearchFor, strReplaceWith)
& "<BR>"
' using a regular expression object.
Response.Write "String where reSearchFor is
replaced:<BR>"
Response.Write reSearchFor.Replace(strString, strReplaceWith)
& "<BR>"
%>
</font>
</body>
</html>
In
the browser, you should see the following:
strSearchFor was found
in strString
reSearchFor.Pattern was found in strString
Original String:
Jane Doe
100 Orange Road
Orangeville, WA
98100
800.555.1212
String where strSearchFor is replaced:
Jane Doe
200 Bluebell Court
Blueville, WA
98200
800.555.1212
String where reSearchFor is replaced:
Jane Doe
200 Bluebell Court
Blueville, WA
98200
800.555.1212
A
common use of intranet and Internet server applications is to accept user input
by implementing a form in your Web page. ASP includes the following two
collections in the Request object to help process form information: the QueryString
collection and the Form collection.
In
this lesson, you create an HTML page that accepts user input in an HTML form
and sends the user input back to the Web server to the same page. The Web
server then displays the user input. Later in this module, you use this
knowledge about forms to build a guest book application that uses ASP
scripting. To complete this lesson, you perform the following tasks:
·
Example 1 Display a
selection of button elements in a form.
·
Example 2 Display
text box elements in a form, accept the user input from the form, and
display the user input on the Web page.
Forms
can contain many different kinds of elements to help your users enter data. In
this example, there are five input form elements called buttons. There are many
types of buttons including RADIO buttons, SUBMIT buttons, RESET
buttons, CHECKBOX buttons, and TEXT buttons.
After
the user enters information in a form, the information needs to be sent to your
Web application. When a user clicks the button labeled "Submit"
in your Web page, the form data is sent from the client to the Web page that is
listed in the ACTION element of the form tag. This Web page doesn't need
to be the same as the calling page. In this example, the Web page listed in the
ACTION element is the same as the calling page, which eliminates the
need to call another page.
In
this example, METHOD="POST" is used to send data from
the Web client's browser to the Web server. When you use METHOD="POST"
in a form, the user data ends up in the Form collection of the Request
object.
Copy
and paste the following code in your text editor, and save the file as Button.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/Button.asp in the address
bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Button Form</title>
</head>
<body>
<font face="MS Gothic">
<FORM NAME="Button Example" METHOD="POST"
ACTION="button.asp">
<H3>Computer Programming Experience:</H3>
<p>
<INPUT TYPE="RADIO" NAME= "choice"
VALUE="Less than 1"> Less than 1 year.<BR>
<INPUT TYPE="RADIO" NAME= "choice" VALUE="1
to 5"> 1-5 years.<BR>
<INPUT TYPE="RADIO" NAME= "choice"
VALUE="More than 5"> More than 5 years.<BR>
</p>
<p>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET" VALUE="Clear Form">
</p>
</form>
<%
'Check to see if input has already been entered.
dim strChoice
strChoice = Request.Form("choice")
If "" = strChoice Then
Response.Write "<P>(No input
yet.)</P>"
Else
Response.Write "<P>Your last choice was
<B>" & strChoice & "</B></P>"
End If
%>
</font>
</body>
</html>
In
the browser, you should see the following:
(No input yet.)
In
this example, there are three input form elements called text fields and two
input form elements called check boxes. Check boxes differ from option buttons
because you can select more than one. We still need the default Submit
button to send the data back to the server.
In
this example, METHOD=GET is used to send data from the Web client's browser to
the Web server. When you use METHOD=GET in a form, the user data ends up in the
QueryString collection of the Request object.
Look
at the address bar after you click Submit, and you should see the
elements of the QueryString displayed at the end of the URL.
Copy
and paste the following code in your text editor, and save the file as Text.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/Text.asp in the address bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Text and Checkbox Form</title>
</head>
<body>
<font face="MS Gothic">
<FORM NAME="TextCheckbox Example" METHOD="GET"
ACTION="text.asp">
<H3>Please fill out this form to get information on our products:</H3>
<p>
<table>
<tr>
<td><font face="MS Gothic">Name
(required)</td>
<td><INPUT TYPE="TEXT" NAME="name"
VALUE="" SIZE="20" MAXLENGTH="150"></td>
</tr><tr>
<td><font face="MS Gothic">Company</td>
<td><INPUT TYPE="TEXT" NAME="company"
VALUE="" SIZE="25" MAXLENGTH="150"></td>
</tr><tr>
<td><font face="MS Gothic">E-mail
(required)</td>
<td><INPUT TYPE="TEXT" NAME="email"
VALUE="" SIZE="25" MAXLENGTH="150"></td>
</tr>
</table>
</p>
<p>
Requesting information on our:<BR>
<INPUT TYPE="CHECKBOX" NAME= "info"
VALUE="software">Software<BR>
<INPUT TYPE="CHECKBOX" NAME= "info"
VALUE="hardware">Hardware <BR>
</p>
<p>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET" VALUE="Clear Form">
</p>
</form>
<%
'Check to see if input has already been entered.
dim strName, strEmail, strCompany, strInfo
strName = Request.QueryString("name")
strEmail = Request.QueryString("email")
strCompany = Request.QueryString("company")
strInfo = Request.QueryString("info")
'Display what was entered.
If ("" = strName) OR ("" = strEmail) Then
Response.Write "<P>(No required input
entered yet.)</P>"
Else
Response.Write "<P>Your are " &
strName
If Not ("" = strCompany) Then
Response.Write " from " &
strCompany
End If
Response.Write ". <BR>Your email address is
" & strEmail
If Not ("" = strInfo) Then
Response.Write " and you would like
information on " & strInfo & ".</P>"
End If
End If
%>
</font>
</body>
</html>
In
the browser, you should see the following:
(No required input entered yet.)
This
lesson requires that you have Microsoft Access installed on your system and is
not supported on 64-bit platforms until Access is developed for 64-bit
platforms.
Lesson
3 develops a guest book application. Guest books allow your Web site visitors
to leave behind information, such as their names, e-mail addresses, and
comments. In this lesson, you perform the following tasks after creating an
Access database:
·
Example 1 Create an ASP page
to connect to the database using only the ADO Connection object.
·
Example 2 Create an ASP page
to connect to the database using the Connection object and the Command
object together.
·
Example 3 Create an ASP page
to display the guest book information from the database in a browser.
Create
an Access database called GuestBook.mdb, and save it in x:\Inetpub\Wwwroot\Tutorial.
Create a table in the database called GuestBook. Use the Create Table
Using Design View option in Access to add the following fields and
properties:
|
Field Name |
Data Type |
Field General Properties |
|
FID |
AutoNumber |
Field Size=Long Integer, |
|
FTB1 |
Text |
Field Size=255, |
|
FTB2 |
Text |
Field Size=255, |
|
FTB3 |
Text |
Field Size=255, |
|
FTB4 |
Text |
Field Size=255, |
|
FMB1 |
Memo |
Required=No, |
Now
that you have created a database, you can build an ASP page to connect to your
database and read incoming data using Microsoft ActiveX® Data Objects (ADO).
ADO is a collection of objects with methods and properties that can manipulate
data in almost any type of database. (If you plan to use databases frequently,
you should purchase a programmer's reference book for ADO. Only the most basic
ADO code is illustrated in the following examples, enough to open, read in, and
write to a database.)
The
next two examples produce the same results; however, the first example uses
only the Connection object, and the second example gives part of the job
to the Command object, which is much more powerful. Compare both
examples to see how the objects become connected together. After you are
comfortable with the the objects, use an ADO programmer's reference to
experiment with more methods and properties.
To
see an example of an ADO error in your ASP page, try browsing to the page after
renaming your database, after entering a typing mistake in the connection
string, or after making the database Read Only.
Copy
and paste the following code in your text editor, and save the file as GuestBook1.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/GuestBook1.asp in the
address bar.
<%@
Language=VBScript %>
<html>
<head>
<title>Guest Book Using Connection Object Only</title>
</head>
<body>
<font face="MS Gothic">
<h2>Guest Book Using Connection Object Only</h2>
<%
If Not Request.QueryString("Message") = "True"
Then
'No information has been input yet, so provide the
form.
%>
<p>
<FORM NAME="GuestBook1"
METHOD="GET" ACTION="guestbook1.asp">
<table>
<tr>
<td><font face="MS
Gothic">From:</td><td><INPUT TYPE="TEXT"
NAME="From"></td>
</tr><tr>
<td><font face="MS
Gothic">E-mail Address:</td><td><INPUT
TYPE="TEXT" NAME="EmailAdd"></td>
</tr><tr>
<td><font face="MS
Gothic">CC:</td><td><INPUT TYPE="TEXT"
NAME="CC"></td>
</tr><tr>
<td><font face="MS
Gothic">Subject:</td><td><INPUT TYPE="TEXT"
NAME="Subject"></td>
</tr>
</table>
Message:<br><TEXTAREA NAME="Memo"
ROWS=6 COLS=70></TEXTAREA>
</p>
<p>
<INPUT TYPE="HIDDEN"
NAME="Message" VALUE="True">
<INPUT TYPE="SUBMIT" VALUE="Submit
Information">
</FORM>
</p>
<%
Else
'The HIDDEN button above sets the Message variable to
True.
'We know now that form data has been entered.
'Get the data from the form. We will be inserting it
into the database.
'Access doesn't like some characters, such as
single-quotes, so encode the
' data using the HTMLEncode method of the ASP Server
object.
dim strTB1, strTB2, strTB3, strTB4, strMB1, strCommand
strTB1 = Server.HTMLEncode(Request.QueryString("From"))
strTB2 =
Server.HTMLEncode(Request.QueryString("EMailAdd"))
strTB3 =
Server.HTMLEncode(Request.QueryString("CC"))
strTB4 =
Server.HTMLEncode(Request.QueryString("Subject"))
strMB1 = Server.HTMLEncode(Request.QueryString("Memo"))
'This is a connection string. ADO uses it to connect
to a database through the Access driver.
'It needs the provider name of the Access driver and
the name of the Access database.
'Connection strings are slightly different, depending
on the provider being used,
' but they all use semicolons to separate variables.
'If this line causes and error, search in your
registry for
' Microsoft.JET to see if 4.0 is your version.
strProvider = "Provider=Microsoft.JET.OLEDB.4.0;Data
Source=C:\InetPub\Wwwroot\Tutorial\guestbook.mdb;"
'This creates an instance of an ADO Connection object.
'There are 4 other ADO objects available to you, each
with different methods and
'properties that allow you to do almost anything with
database data.
Set objConn =
server.createobject("ADODB.Connection")
'The Open method of the Connection object uses the
connection string to
' create a connection to the database.
objConn.Open strProvider
'Define the query.
'There are many types of queries, allowing you to add,
remove, or get data.
'This query will add your data into the database,
using the INSERT INTO key words.
'Here, GuestBook is the name of the table.
'You need single-quotes around strings here.
strCommand = "INSERT INTO GuestBook
(FTB1,FTB2,FTB3,FTB4,FMB1) VALUES ('"
strCommand = strCommand & strTB1 &
"','" & strTB2 & "','" & strTB3 &
"','" & strTB4 & "','" & strMB1
strCommand = strCommand & "')"
'Execute the query to add the data to the database.
objConn.Execute strCommand
Response.Write("Thank you! Your data has been
added.")
End If
%>
</font>
</body>
</html>
In
the browser, you should see the following:
Copy
and paste the following code in your text editor, and save the file as GuestBook2.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/GuestBook2.asp in the
address bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Guest Book Using Connection Object and Command
Object</title>
</head>
<body>
<font face="MS Gothic">
<h2>Guest Book Using Connection Object and Command
Object</h2>
<%
If Not Request.QueryString("Message") = "True"
Then
'No information has been input yet, so provide the
form.
%>
<p>
<FORM NAME="GuestBook2"
METHOD="GET" ACTION="guestbook2.asp">
<table>
<tr>
<td><font face="MS
Gothic">From:</td><td><INPUT TYPE="TEXT"
NAME="From"></td>
</tr><tr>
<td><font face="MS
Gothic">E-mail Address:</td><td><INPUT
TYPE="TEXT" NAME="EmailAdd"></td>
</tr><tr>
<td><font face="MS
Gothic">CC:</td><td><INPUT TYPE="TEXT"
NAME="CC"></td>
</tr><tr>
<td><font face="MS
Gothic">Subject:</td><td><INPUT TYPE="TEXT"
NAME="Subject"></td>
</tr>
</table>
Message:<br><TEXTAREA NAME="Memo"
ROWS=6 COLS=70></TEXTAREA>
</p>
<p>
<INPUT TYPE="HIDDEN"
NAME="Message" VALUE="True">
<INPUT TYPE="SUBMIT" VALUE="Submit
Information">
</FORM>
</p>
<%
Else
'The HIDDEN button above sets the Message variable to
True.
'We know now that form data has been entered.
'Get the data from the form. We will be inserting it
into the database.
'Access doesn't like some characters, such as
single-quotes, so encode the
' data using the HTMLEncode method of the ASP Server
object.
dim strTB1, strTB2, strTB3, strTB4, strMB1
strTB1 =
Server.HTMLEncode(Request.QueryString("From"))
strTB2 = Server.HTMLEncode(Request.QueryString("EMailAdd"))
strTB3 =
Server.HTMLEncode(Request.QueryString("CC"))
strTB4 =
Server.HTMLEncode(Request.QueryString("Subject"))
strMB1 =
Server.HTMLEncode(Request.QueryString("Memo"))
'The Memo data type in the Access database allows you
to set the field size.
If strMB1 = "" Then
iLenMB1 = 255
Else
iLenMB1 = Len(strMB1)
End If
'This is a connection string. ADO uses it to connect
to a database through the Access driver.
'It needs the provider name of the Access driver and
the name of the Access database.
'Connection strings are slightly different, depending
on the provider being used,
' but they all use semicolons to separate variables.
'If this line causes and error, search in your
registry for
' Microsoft.JET to see if 4.0 is your version.
strProvider =
"Provider=Microsoft.JET.OLEDB.4.0;Data
Source=C:\InetPub\Wwwroot\Tutorial\guestbook.mdb;"
'This creates an instance of an ADO Connection object.
'There are 4 other ADO objects available to you, each
with different methods and
'properties that allow you to do almost anything with
database data.
Set objConn =
server.createobject("ADODB.Connection")
'The Open method of the Connection object uses the
connection string to
' create a connection to the database.
objConn.Open strProvider
'This creates an instance of an ADO Command object.
'Although you could do most of your work with the
Connection object,
' the Command object gives you more control.
Set cm =
Server.CreateObject("ADODB.Command")
'The ActiveConnection property allows you to attach to
an Open connection.
'This is how you link the Connection object above to
the Command object.
cm.ActiveConnection = objConn
'Define the query.
'There are many types of queries, allowing you to add,
remove, or get data.
'This query will add your data into the database,
using the INSERT INTO keywords.
'Because we are using the Command object, we need to
put our query into the
' CommandText property.
'Here, GuestBook is the name of the table.
cm.CommandText = "INSERT INTO GuestBook
(FTB1,FTB2,FTB3,FTB4,FMB1) VALUES (?,?,?,?,?)"
'This is where you see the power of the Command
object.
'By putting ? marks in the string above, we can use
the Parameters collection
' to have ADO fill in the ? with the detailed
parameters below.
'cm.CreateParameter formats the parameter for you.
'cm.Parameters.Append appends the parameter to the
collection.
'Make sure they are in the same order as
(TB1,TB2,TB3,TB4,MB1).
Set objparam = cm.CreateParameter(, 200, , 255,
strTB1)
cm.Parameters.Append objparam
Set objparam = cm.CreateParameter(, 200, , 255,
strTB2)
cm.Parameters.Append objparam
Set objparam = cm.CreateParameter(, 200, , 255,
strTB3)
cm.Parameters.Append objparam
Set objparam = cm.CreateParameter(, 200, , 255,
strTB4)
cm.Parameters.Append objparam
Set objparam = cm.CreateParameter(, 201, , iLenMB1,
strMB1)
cm.Parameters.Append objparam
'Execute the query to add the data to the database.
'Here, the Execute method of the Command object is
called instead of
' the Execute method of the Connection object.
cm.Execute
Response.Write("Thank you! Your data has been
added.")
End If
%>
</font>
</body>
</html>
In
the browser, you should see the same content as GuestBook1.asp, as follows:
After
information is entered in a database, you can use a Web page containing another
script to view and edit the data. Not much changes in the ADO code, except the
way you define your query.
In the last two examples, you used the INSERT INTO query to add records
to a database. In this example, you use the SELECT query to choose
records from a database and display them in the browser. You also use the DELETE
query to remove records from the database. The only query not used in these
examples is the UPDATE query, whose syntax is like that of the INSERT
INTO query. The UPDATE query allows you to change fields in a
database.
Copy
and paste the following code in your text editor, and save the file as ViewGB.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/ViewGB.asp
in the address bar.
<%@ Language=VBScript %>
<html>
<head>
<title>View Guest Book</title>
</head>
<body>
<font face="MS Gothic">
<h2>View Guest Book</h2>
<%
'Read in any user input. Any of these can be empty.
'By doing this first, we can preserve the user input in the form.
dim strTB1, strTB2, strTB3, strTB4, strMB1, strSort, iDelete
strTB1 = Server.HTMLEncode(Request.QueryString("From"))
strTB2 = Server.HTMLEncode(Request.QueryString("EMailAdd"))
strTB3 = Server.HTMLEncode(Request.QueryString("CC"))
strTB4 = Server.HTMLEncode(Request.QueryString("Subject"))
strMB1 = Server.HTMLEncode(Request.QueryString("Memo"))
strSort = Server.HTMLEncode(Request.QueryString("sort"))
iDelete = CInt(Request.QueryString("Delete"))
'Because we use this variable, and it might not be set...
If "" = strSort Then
strSort = "FID"
End If
%>
<p>
<FORM NAME="ViewGuestBook" METHOD="GET"
ACTION="viewgb.asp">
<table>
<tr>
<td><font face="MS Gothic">Sort by
which column:</td>
<td><SELECT NAME="sort"
SIZE="1">
<OPTION VALUE="FID">ID
Number</OPTION>
<OPTION
VALUE="FTB1">Name</OPTION>
<OPTION
VALUE="FTB2">Email</OPTION>
<OPTION
VALUE="FTB3">CC</OPTION>
<OPTION
VALUE="FTB4">Subject</OPTION>
<OPTION VALUE="FMB1">Memo</OPTION>
</SELECT></td>
</tr><tr>
<td><font face="MS Gothic">Name
Contains:</td>
<td><INPUT TYPE="TEXT"
NAME="From" VALUE="<%=strTB1%>"></td>
</tr><tr>
<td><font face="MS Gothic">E-mail
Address Contains:</td>
<td><INPUT TYPE="TEXT"
NAME="EmailAdd" VALUE="<%=strTB2%>"></td>
</tr><tr>
<td><font face="MS Gothic">CC
Contains:</td>
<td><INPUT TYPE="TEXT"
NAME="CC" VALUE="<%=strTB3%>"></td>
</tr><tr>
<td><font face="MS Gothic">Subject
Contains:</td>
<td><INPUT TYPE="TEXT"
NAME="Subject" VALUE="<%=strTB4%>"></td>
</tr><tr>
<td><font face="MS Gothic">Memo
Contains:</td>
<td><INPUT TYPE="TEXT"
NAME="Memo" VALUE="<%=strMB1%>"></td>
</tr>
</table>
<INPUT TYPE="SUBMIT" VALUE="Submit Search
Parameters">
</p>
<%
'Create your connection string, create an instance of the Connection
object,
' and connect to the database.
strProvider = "Provider=Microsoft.JET.OLEDB.4.0;Data
Source=C:\InetPub\Wwwroot\Tutorial\guestbook.mdb;"
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open strProvider
'Define the query.
If iDelete = 0 Then
'If the Delete variable is not set, the query is a SELECT
query.
'* means all fields. ASC means ASCII. % is a wildcard
character.
strQuery = "SELECT * FROM GuestBook"
strQuery = strQuery & " WHERE FTB1 LIKE '%"
& strTB1 & "%'"
strQuery = strQuery & " AND FTB2 LIKE '%"
& strTB2 & "%'"
strQuery = strQuery & " AND FTB3 LIKE '%"
& strTB3 & "%'"
strQuery = strQuery & " AND FTB4 LIKE '%"
& strTB4 & "%'"
strQuery = strQuery & " AND FMB1 LIKE '%"
& strMB1 & "%'"
strQuery = strQuery & " ORDER BY " &
StrSort & " ASC"
Else
'We want to delete a record.
strQuery = "DELETE FROM GuestBook WHERE FID="
& iDelete
End If
'Executing the SELECT query creates an ADO Recordset object.
'This holds the data you get from the database.
Set objRS = objConn.Execute(strQuery)
'Now that you have the database data stored in the Recordset object,
' show it in a table.
%>
<p>
<FORM NAME="EditGuestBook" METHOD="GET"
ACTION="viewgb.asp">
<table border=1 cellpadding=4 >
<%
On Error Resume Next
If objRS.EOF Then
If iDelete = 0 Then
Response.Write
"<tr><td><font face="MS Gothic">There
are no entries in the database.</font></td></tr>"
Else
Response.Write
"<tr><td><font face="MS Gothic">Record
" & iDelete & " was
deleted.</font></td></tr>"
End If
Else
'Print out the field names using some of the
methods and properties
' of the Recordset object.
Response.Write "<tr>"
'For each column in the current row...
For i = 1 to (objRS.Fields.Count - 1)
' write out the
field name.
Response.Write
"<td><font face="MS Gothic"><B>"
& objRS(i).Name & "</B></font></td>"
Next
Response.Write "<td><font
face="MS
Gothic"><B>Delete</B></font></td>"
Response.Write "</tr>"
'Print out the field data, using some other
methods and properties
' of the Recordset object. When you see a
pattern in how they are used,
' you can look up others and experiment.
'While not at the end of the records in the set...
While Not objRS.EOF
Response.Write
"<tr>"
'For each column in the current
row...
For i = 1 to (objRS.Fields.Count -
1)
' write out the
data in the field.
Response.Write
"<td><font face="MS Gothic">" &
objRS(i) & "</font></td>"
Next
'Add a button that will pass in an
ID number to delete a record.
%><td><INPUT
TYPE="SUBMIT" NAME="Delete"
VALUE="<%=objRS(0)%>"></td><%
Response.Write
"</tr>"
'Move to the next row.
objRS.MoveNext
Wend
End If 'objRS.EOF
%>
</table>
</FORM>
<%
'Close the Connection.
objConn.Close
%>
</font>
</body>
</html>
In
the browser, you should see the following:
This
lesson requires that you have Microsoft Excel installed on your system and is
not supported on 64-bit platforms until Excel is developed for 64-bit
platforms.
This
lesson demonstrates how to display a Microsoft Excel spreadsheet in a Web page.
As in the previous lesson, you use ADO. However, in this lesson you connect to
an Excel spreadsheet instead of an Access database.
1.
Using either Excel 98 or Excel 2000, create a spreadsheet
and save it as ASPTOC.xls in x:\Inetpub\Wwwroot\Tutorial. Do not
include any special formatting or column labels when creating the spreadsheet.
2.
Fill in some of the fields with random data. Treat the
first row of cells as column names.
3.
Highlight the rows and columns on the spreadsheet that you
want to display in the Web page. (Click on one of the fields and drag your
mouse diagonally to highlight a block of fields.)
4.
On the Insert menu, select Name, and click Define.
This is where all your workbooks are defined by name and range of cells.
5.
Make sure the cell range you highlighted is displayed
correctly at the bottom. Type the name MYBOOK for your workbook, and
select Add. Whenever you change MYBOOK, make sure the correct cell range
is displayed in the Refers to text box at the bottom of the Define
Name window. Simply selecting MYBOOK after highlighting a new block of
cells does not update the cell range.
6.
If the name shows up in the workbook list, click OK.
Save your spreadsheet.
7.
Close Excel to remove the lock on the file so that your
ASP page can access it.
In
the examples in Lesson 3, you specified a provider name in the connection
string, which maps to a specific ADO DLL. In this example, you use a driver
name, which causes ASP to use the default provider for that driver name.
Copy
and paste the following code in your text editor, and save the file as ViewExcel.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/ViewExcel.asp in the address
bar.
<%@
Language=VBScript %>
<html>
<head>
<title>Display an Excel Spreadsheet in a Web Page</title>
</head>
<body>
<font face="MS Gothic">
<h2>Display an Excel Spreadsheet in a Web Page</h2>
<%
'Create your connection string, create an instance of the
Connection object,
' and connect to the database.
strDriver = "Driver={Microsoft Excel Driver
(*.xls)};DBQ=C:\Inetpub\Wwwroot\Tutorial\MyExcel.xls;"
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open strDriver
'Selects the records from the Excel spreadsheet using the workbook
name you saved.
strSELECT = "SELECT * from `MYBOOK`"
'Create an instance of the ADO Recordset object, and connect it to
objConn.
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open strSELECT, objConn
'Print the cells and rows in the table using the GetString method.
Response.Write "<H4>Get Excel data in one string with
the GetString method</H4>"
Response.Write "<table border=1
><tr><td>"
Response.Write objRS.GetString (, ,
"</td><td><font face="MS
Gothic">",
"</font></td></tr><tr><td>", NBSPACE)
Response.Write "</td></tr></table>"
'Move to the first record.
objRS.MoveFirst
'Print the cells and rows in the table using the ViewGB.asp
method.
Response.Write "<H4>Get Excel data using
MoveNext</H4>"
'Print out the field names using some of the methods and
properties
' of the Recordset object.
Response.Write "<table border=1 ><tr>"
'For each column in the current row...
For i = 0 to (objRS.Fields.Count - 1)
' write out the field name.
Response.Write "<td><font
face="MS Gothic"><B>" & objRS(i).Name &
"</B></font></td>"
Next
'While not at the end of the records in the set...
While Not objRS.EOF
Response.Write "</tr><tr>"
'For each column in the current row...
For i = 0 to (objRS.Fields.Count - 1)
' write out the data in the field.
%><td><font face="MS
Gothic"><%=objRS(i)%></font></td><%
Next
'Move to the next row.
objRS.MoveNext
Wend
Response.Write "</tr></table>"
'Close the Connection.
objConn.Close
%>
</font>
</body>
</html>
In
the browser, you should see the following:
|
A2 |
B2 |
C2 |
|
A3 |
B3 |
C3 |
|
A1 |
B1 |
C1 |
|
A2 |
B2 |
C2 |
|
A3 |
B3 |
C3 |
© 1997-2001 Microsoft
Corporation. All rights reserved.
Using
Microsoft® Component Object Model (COM) components in your ASP pages can
dramatically extend the power that ASP already offers. COM components are
pieces of compiled code that can be called from ASP pages. COM components are
secure, compact, reusable objects that are compiled as DLLs and can be written
in Microsoft Visual C++®, Microsoft Visual Basic®, or any language that supports
COM. For example, Microsoft ActiveX® Data Objects (ADO), which are used in
Module 1 of this tutorial, provides you with methods and properties to
efficiently query databases. By using ADO, you don't have to write your own
complex data access code because ADO objects are built using COM components.
In
this module, you use COM components that are included with ASP, and you also
have a chance to write one of your own. This module shows how to develop an ASP
page that delivers services useful in e-commerce and includes the following
lessons:
·
Lesson
1: Rotating Advertisements Rotate ads on a Web page,
record user data, and redirect users when advertisements are clicked on.
·
Lesson
2: Counting Page Hits Track the number of times users
request a page.
·
Lesson
3: Creating a Visual Basic COM Object Create your own
ActiveX object using Microsoft Visual Basic.
·
Lesson
4: Creating a Java COM Object Create your own Java object
using Microsoft Visual J++®.
Advertising
is big business on the Web. This lesson describes how to use the Ad Rotator
component, installed with IIS, to rotate advertisements on your Web pages. The
Ad Rotator component selects an advertisement for your Web page each time the
user loads or refreshes the Web page. Furthermore, if you want to change an
advertisement, you only need to change it in the redirection and rotation
schedule files, instead of changing all the ASP files that contain the
advertisement. This saves development time if the advertisement appears on
numerous pages within your Web site.
Two
files are required to set up the Ad Rotator component: a redirection file,
which contains URL links to ads, and a rotation schedule file, which contains
display data. By setting up these two files, the Ad Rotator component can be
called by any ASP page on your Web site.
In
this lesson you perform the following tasks:
·
Example 1 Create an Ad Rotator
rotation schedule file that creates ad-image links on any page that calls this
file.
·
Example 2 Create an Ad Rotator
redirection file that specifies global ad-display data and information specific
to each advertisement.
·
Example 3 Create an include
file to hold your Ad Rotator calling code.
·
Example 4 Test the Ad Rotator
by creating an ASP page that calls the Ad Rotator component to display and
rotate ads. This example requires that examples 1, 2, and 3 are completed
first.
A
rotation schedule file is used to catalog information about the ads you want to
display, including redirection information after the advertisement is clicked
on, the size of the displayed advertisement, the image to display, a comment
for the advertisement, and a number that indicates how often a particular advertisement
is chosen. When methods of the Ad Rotator component are called in an ASP page,
the component uses this file to select an advertisement to display.
The
rotation schedule file is divided into two sections that are separated by an
asterisk (*). The first section provides information common to all the ads, and
the second section lists specific data for each ad. To test the rotation
schedule file, you will use some images from Microsoft.com for your ad images.
The following list outlines the structure of the rotation schedule file:
·
Redirection In URL form,
the path and name of the ASP file that can be executed before showing an
advertisement. This file can be used to record information about the user who
clicks on your ad. You can record information such as the client's IP address,
what page the client saw the advertisement on, how often an advertisement was
clicked on, and so forth. This ASP file can also handle the case where there is
no URL associated with any advertisement in Section 2. When charging
advertisers for each hit on their advertisement, it is good practice to prove
to them that all the hits aren't resulting from the same user repeatedly
hitting Refresh.
·
Width The width of
each ad image, in pixels. The default is 440.
·
Height The height of
each ad image, in pixels. The default is 60.
·
Border The border
thickness around each ad image. The default is 1.
·
Asterisk (*) Separates the
first section from the second section. This character must be on a line by
itself.
You
need to complete the following for each advertisement:
·
Image URL The virtual
path and filename of the image file for the advertisement.
·
Advertiser's Home URL The
URL to jump to when this link is selected. If there is no link, use a hyphen
(-).
·
Text The text to
display if the browser does not support graphics.
·
Impressions An integer
indicating the relative weight to give to this ad when the Ad Rotator component
selects an advertisement. For example, if you list two advertisements, an ad
given an impression of 3 has a 30% probability of being selected while an ad
given an impression of 7 has a 70% probability of being selected. In this
example, the Ad Rotator component selects the Microsoft Windows® advertisement
two times out of five and the Microsoft Office advertisement is selected three
times out of five.
Copy
and paste the following code in your text editor, and save the file as MyAdRot.txt
in the x:\Inetpub\Wwwroot\Tutorial directory.
REDIRECT AdRotRedirect.asp
WIDTH 250
HEIGHT 60
BORDER 0
*
http://www.microsoft.com/windows/images/bnrWinfam.gif
http://www.microsoft.com/windows
Microsoft Windows
2
http://www.microsoft.com/office/images/office_logo.gif
http://www.microsoft.com/office
Office 2000
3
When
a user clicks on an advertisement, an Ad Rotator redirection file written in
ASP can capture some information before showing the advertisement and write
that information to a file.
For
this to work, the x:\InetPub\Wwwroot\Tutorial folder must give
Read/Write access to the IUSR_ComputerName and IWAM_ComputerName
accounts. Alternatively, you can write this information to a Microsoft Access
database using the code from Lesson 3 in
Module 1 of this tutorial.
Copy
and paste the following code in your text editor, and save the file as AdRotRedirect.asp
in the x:\Inetpub\Wwwroot\Tutorial directory.
<%@ Language=VBScript %>
<html>
<head>
<title>AdRotRedirect file</title>
</head>
<body>
<%
'Create some variables.
dim strLogFile
'Get the physical path of this Web directory so that we know the
path exists.
'The ASP Server object has many useful methods.
strLogFile = Server.MapPath(".") &
"\AdRotLog.txt"
'Set some constants for working with files.
Const cForAppending = 8
Const cTristateUseDefault = -2
'Create a FileSystemObject object,
' which gives you access to files and folders on the system.
Set fsoObject =
Server.CreateObject("Scripting.FileSystemObject")
'Open a handle to the file.
'True means that the file will be created if it doesn't already
exist.
Set tsObject = fsoObject.OpenTextFile(strLogFile, cForAppending,
True)
'Record the data for the user who has just clicked on an
advertisement.
'We have used the Write method of the ASP Request object.
'The ServerVariables collection of the ASP Request object holds
vast
' amounts of data for each request made to a Web server.
tsObject.WriteLine "--------------------"
tsObject.WriteLine Date & ", " & Time
tsObject.WriteLine Request.ServerVariables("LOGON_USER")
tsObject.WriteLine
Request.ServerVariables("REMOTE_ADDR")
tsObject.WriteLine Request.QueryString("url")
tsObject.WriteLine
Request.ServerVariables("HTTP_REFERER")
tsObject.WriteLine
Request.ServerVariables("HTTP_USER_AGENT")
tsObject.Close
'Redirect to the Advertiser's Web site using the Redirect method
' of the ASP Response object.
'When the AdRotator component calls AdRotRedirect.asp, it
' automatically passes in the advertiser's URL in the QueryString.
Response.Redirect Request.QueryString("url")
%>
</body>
</html>
Include
files are used to store any code that will be used by more than one ASP or HTML
file. It makes sense to put your Ad Rotator code into a simple function in an
include file. With an Ad Rotator include file, you need to make only one
function call from any ASP or HTML file when you want to display an
advertisement. Alternatively, you can put the code from the include file in
every ASP file where you plan to show an advertisement. However, if you want to
change that code, you have to make the change in every ASP file instead of in
one include file.
In
this example, you create an Ad Rotator include file containing a function named
GetAd. This function randomly selects ads to display on your ASP pages.
Copy
and paste the following code in your text editor, and save the file as AdRotatorLogic.inc
in the x:\Inetpub\Wwwroot\Tutorial directory.
<%
Function GetAd()
dim objLoad
'Create an instance of the AdRotator component.
Set objLoad =
Server.CreateObject("MSWC.AdRotator")
'Set the TargetFrame property, if any. If you have a
Web
' page using frames, this is the frame where the URL
opens.
'If the HTML page does not find the TARGET name,
' the URL will be opened in a new window.
objLoad.TargetFrame = "TARGET=new"
'Set one of the other AdRotator properties.
objLoad.Border = 1
'Get a random advertisement from the text file.
GetAd =
objLoad.GetAdvertisement("MyAdRot.txt")
End Function
%>
Example 4: Test the Ad Rotator
To
test the application you have built on the Ad Rotator component, you need an
ASP page that calls the function in the Ad Rotator include file you created.
Copy
and paste the following code in your text editor, and save the file as DisplayAds.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/DisplayAds.asp in the
address bar.
<%@ Language=VBScript %>
<html>
<head>
<title>Display an Advertisement</title>
</head>
<body>
<font face="MS Gothic">
<h2>Display an Advertisement</h2>
<comment>Include the file you created to get an
advertisement.</comment>
<!-- #include File = "AdRotatorLogic.inc" -->
<comment>Call the Function in the include file.</comment>
<%=GetAd()%>
</font>
</body>
</html>
In
the browser, you should see the following:

Click
the Refresh button in your browser about 20 times to watch the
advertisement change. Click the advertisement to see how AdRotRedirect.asp
redirects you to the advertiser's Web site. Open AdRotLog.txt to see what was
recorded when you clicked on an advertisement.
It
may be useful to know how many times someone requests, or hits, your Web
pages. Sites with high traffic may attract more advertising revenue for you.
Some Web sites use this data to charge advertisers a flat fee per hit. Traffic
information also indicates how customers are navigating through your site and
where ads should be placed. And pages that never seem to be hit might indicate
that design changes are needed.
The
PageCounter component uses an internal object to record Web page hits on the
server. At regular intervals, PageCounter saves all information to a text file
so that no counts are lost due to power loss or system failure. The PageCounter
component uses three methods, as follows:
·
Hits This method
displays the number of hits for a Web page. The default is the calling page.
·
PageHit This method
increments the hit count for the current page. If you want hits recorded for an
ASP page, this method must be called inside that page.
·
Reset This method
sets the hit count for a page to zero. The default is the calling page.
Copy
and paste the following code in your text editor, and save the file as PageCounter.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/PageCounter.asp in the
address bar.
<%@
Language=VBScript %>
<html>
<head>
<title>Page Counter Example</title>
</head>
<body>
<font face="MS Gothic">
<H3>Page Counter Example</H3>
<p>
<FORM NAME="PageCounter" METHOD="GET"
ACTION="PageCounter.asp">
<INPUT TYPE="CHECKBOX" NAME="reset"
VALUE="True">Reset the Counter for this page?<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</p>
<%
'Instantiate the PageCounter object.
Set MyPageCounter =
Server.CreateObject("MSWC.PageCounter")
'Increment the counter for this page.
MyPageCounter.PageHit
If Request.QueryString("reset") = "True" Then
'Reset the counter for this page.
MyPageCounter.Reset("/Tutorial/PageCounter.asp")
End If
%>
Hits to this page = <%=MyPageCounter.Hits %><BR>
</font>
</body>
</html>
In
the browser, you should see the following:
Hits to this page = 1
Click
the Refresh button in your browser or the Submit button on the
page to watch the hit count grow. Check the box if you want to reset the
counter.
In
this lesson, you use Visual Basic to create a simple COM object, which you can
call from an ASP page. This example requires Visual Basic with the ActiveX
Wizard, and it is not supported on 64-bit platforms until the Visual Basic
runtime is developed for 64-bit platforms. You create a 32-bit COM object that
runs on a 64-bit platform, but you must call the 32-bit COM object from a
32-bit application. Because IIS is a 64-bit application on 64-bit platforms, it
cannot call 32-bit objects.
Suppose
you want to create a Web application that needs functionality VBScript does not
have. In this case, you must create a custom procedure that is called, as
needed, from any ASP page in your application.
Normally,
this approach is an adequate solution for encapsulating custom functionality.
However, imagine that you are creating a Web application intended to service
thousands of users and that your procedure encapsulates proprietary functions
you do not want other people to see. In this case, encapsulating your
functionality in the form of a COM component is a superior approach. Components
provide better security and performance than scripts because they are compiled
code. Components also allow you to use functionality provided by Visual Basic,
C++, Java, or any of the other COM-compliant languages.
The
ActiveX DLL Wizard of Visual Basic is the easiest way to create a COM
component. You can also use Microsoft Visual C++ to create a COM component,
either by using the Active Template Library (ATL) or by writing all the code
yourself. This example uses Visual Basic.
In
this lesson, you learn how to create and encapsulate a Visual Basic function as
a component. Visual Basic includes many financial functions not available to
VBScript. This example computes the future value of an investment based on a
fixed interest rate and periodic, fixed payments.
1.
Open Visual Basic. If you don't see a window titled New
Project, choose File and then click New Project.
2.
Select ActiveX DLL, and click OK.
3.
A window should open called Project1 - Class1 (Code).
This is where you enter your code.
4.
From the Project menu, click Project1
Properties. In the General property sheet, in the Project
Name box, type ASPTut. Your DLL is called ASPTut.dll. Select
the Unattended Execution check box so that the project runs
without user interaction and has no user interface elements. Make sure the Threading
Model is Apartment Threaded so that more than one user at a time can
use the DLL. Click OK.
5.
In Visual Basic, you define a class to group together
methods and properties. Under the Project - ASPTut window, click the Class1
(Class1) node to list the class properties below. Under Properties -
Class1, click in the text field beside (Name) and change the class
name to Finance. When you call this COM component in an ASP page or
other script, you will reference it with ASPTut.Finance. Click the
drop-down box beside Instancing, and select 5 - MultiUse.
6.
Learn about the Visual Basic function you are about to
use. FV is documented on MSDN
under the Visual Basic library.
7.
The window that was previously titled Project1 - Class1
(Code) should now be titled ASPTut - Finance (Code). Copy and paste
the following text into that window:
Option Explicit
'Declare the global variables that will be set by the Property
functions.
Dim gAnnualIntRate As Double
Dim gNumPayPeriods As Integer
Dim gPayment As Double
Dim gPresentSavings As Variant 'Optional
Dim gWhenDue As Variant 'Optional
Public Function CalcFutureValue() As Double
'The global variables you pass to the FV function are set
'when user sets the properties in the ASP page.
'You could pass variables into the CalcFutureValue() function
'if you wanted to avoid using properties.
'CalcFutureValue becomes a method in your component.
Dim IntRatePerPeriod As Double
Dim FullFutureValue As Double
If (gAnnualIntRate = Null) Or (gNumPayPeriods = Null) Or
(gPayment = Null) Then
CalcFutureValue = 0
Else
IntRatePerPeriod = gAnnualIntRate / 100 / 12
FullFutureValue = FV(IntRatePerPeriod,
gNumPayPeriods, gPayment, gPresentSavings, gWhenDue)
CalcFutureValue = Round(FullFutureValue, 2)
End If
End Function
Public Property Get AnnualIntRate() As Double
'Get functions return the value of the global variables
'as if they were properties.
'In your ASP page, you might say x = oASPTut.Rate.
AnnualIntRate = gAnnualIntRate
End Property
Public Property Let AnnualIntRate(ByVal vAnnualIntRate As Double)
'Let functions set the global variables when your ASP page
'makes a call such as oASPTut.Rate = 5.
gAnnualIntRate = vAnnualIntRate
End Property
Public Property Get NumPayPeriods() As Integer
NumPayPeriods = gNumPayPeriods
End Property
Public Property Let NumPayPeriods(ByVal vNumPayPeriods As Integer)
gNumPayPeriods = vNumPayPeriods
End Property
Public Property Get Payment() As Double
Payment = gPayment
End Property
Public Property Let Payment(ByVal vPayment As Double)
gPayment = -(vPayment)
End Property
Public Property Get PresentSavings() As Variant
PresentSavings = gPresentSavings
End Property
Public Property Let PresentSavings(ByVal vPresentSavings As Variant)
gPresentSavings = -(vPresentSavings)
End Property
Public Property Get WhenDue() As Variant
WhenDue = gWhenDue
End Property
Public Property Let WhenDue(ByVal vWhenDue As Variant)
gWhenDue = vWhenDue
End Property
8.
All server components require an entry (starting) point.
This is the code that will be called when the object is first instantiated with
Server.CreateObject Your ASPTut component does not have to do anything
special when it is first called. For this reason, you can provide an empty Sub
Main procedure. From the Project menu, select Add Module.
In the Add Module window, under the New tab, select the Module
icon and click Open. In the Module 1 code window, type Sub
Main and hit Enter. An empty sub is created for you.
9.
Save your Sub Main module as Main.bas. Save
your class file as Finance.cls. Save your project as ASPTut.vbp.
10.
Click File, and click Make ASPTut.dll. This
compiles and registers the ASPTut.dll. After you have called ASPTut.dll from an
ASP page, you cannot make the DLL in Visual Basic until you unload the
application in which the ASP file is running. One way to do this is to use the IIS snap-in to open
the properties on your default Web site and click the Unload button. If
you want to register your DLL on another Web server, copy ASPTut.dll to the
server, click Start, click Run, and type cmd into the Open
text box. In the same directory as ASPTut.dll, type regsvr32 ASPTut.dll.
11.
Exit Visual Basic.
This
example ASP page uses a form to read in user data, creates an instance of your
object, and calculates the future value of your savings plan.
Copy
and paste the following code in your text editor, and save the file as CalculateFutureValue.asp
in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/CalculateFutureValue.asp in
the address bar.
<%@
Language=VBScript %>
<%
Response.Expires = 0
Payment = Request.Form("Payment")
AnnualIntRate = Request.Form("AnnualIntRate")
NumPayPeriods = Request.Form("NumPayPeriods")
WhenDue = Request.Form("WhenDue")
PresentSavings = Request.Form("PresentSavings")
%>
<HTML>
<HEAD><TITLE>Future Value
Calculation</TITLE></HEAD>
<BODY>
<FONT FACE="MS Gothic">
<H2 align=center>Calculate the Future Value of a Savings
Plan</H2>
<FORM METHOD=POST
ACTION="calculatefuturevalue.asp">
<TABLE cellpadding=4 align=center>
<TR>
<TD>How much do you plan to save each month?</TD>
<TD><INPUT TYPE=TEXT NAME=Payment VALUE=<%=Payment%>>
(Required)</TD>
</TR><TR>
<TD>Enter the annual interest rate.</TD>
<TD><INPUT TYPE=TEXT NAME=AnnualIntRate
VALUE=<%=AnnualIntRate%>> (Required)</TD>
</TR><TR>
<TD>For how many months will you save?</TD>
<TD><INPUT TYPE=TEXT NAME=NumPayPeriods
VALUE=<%=NumPayPeriods%>> (Required)</TD>
</TR><TR>
<TD>When do you make payments in the month? </TD>
<TD><INPUT TYPE=RADIO NAME=WhenDue VALUE=1 <%If 1=WhenDue
Then Response.Write"CHECKED"%>>Beginning
<INPUT TYPE=RADIO NAME=WhenDue VALUE=0 <%If 0=WhenDue Then
Response.Write"CHECKED"%>>End </TD>
</TR><TR>
<TD>How much is in this savings account now?</TD>
<TD><INPUT TYPE=TEXT NAME=PresentSavings
VALUE=<%=PresentSavings%>> </TD>
</TR>
</TABLE>
<P align=center><INPUT TYPE=SUBMIT VALUE=" Calculate
Future Value ">
</FORM>
<%
If ("" = Payment) Or ("" = AnnualIntRate) Or
("" = NumPayPeriods) Then
Response.Write "<H3 align=center>No valid input
entered yet.</H3>"
ElseIf (IsNumeric(Payment)) And (IsNumeric(AnnualIntRate)) And
(IsNumeric(NumPayPeriods)) Then
Dim FutureValue
Set oASPTut =
Server.CreateObject("ASPTut.Finance")
oASPTut.AnnualIntRate = CDbl(AnnualIntRate)
oASPTut.NumPayPeriods = CInt(NumPayPeriods)
oASPTut.Payment = CDbl(Payment)
If Not "" = PresentSavings Then
oASPTut.PresentSavings = CDbl(PresentSavings)
oASPTut.WhenDue = WhenDue
FutureValue = oASPTut.CalcFutureValue
Response.Write "<H3 align=center>Future value =
$" & FutureValue & "</H3>"
Else
Response.Write "<H3 align=center>Some of your
values are not numbers.</H3>"
End If
%>
</FONT>
</BODY>
</HTML>
In
the browser, you should see the following:
In
this lesson, you use Microsoft® Visual J++® to create a COM object which does
the same thing as the Visual Basic component in Lesson 3. This step requires
Visual J++ 6.0 or later.
1.
Open Visual J++. If you don't see a window titled New
Project, click the File menu and click New Project.
2.
Select Visual J++ Projects, and click the Empty
Project icon. In the Name text box, type ASPTut. Click Open.
3.
In the Project menu, click Add Class. In the
Name text box, type ASPTut.java. The class name must be the same
as the project name for a Java server component. Click Open. The
following should appear in a text editing window:
public class ASPTut
{
}
4.
Copy the following code, and paste it between the brackets
{}. Watch capitalization because Java is case-sensitive. The following is a
method in your component:
public double CalcFutureValue(
double dblAnnualIntRate,
double dblNumPayPeriods,
double dblPayment,
double dblPresentSavings,
boolean bWhenDue)
{
double dblRet, dblTemp, dblTemp2, dblTemp3, dblIntRate;
if (dblAnnualIntRate == 0.0)
{
dblRet = -dblPresentSavings - dblPayment *
dblNumPayPeriods;
}
else
{
dblIntRate = dblAnnualIntRate / 100 / 12;
dblPayment = -dblPayment;
dblPresentSavings = -dblPresentSavings;
dblTemp = (bWhenDue ? 1.0 + dblIntRate : 1.0);
dblTemp3 = 1.0 + dblIntRate;
dblTemp2 = Math.pow(dblTemp3,
dblNumPayPeriods);
dblRet = -dblPresentSavings * dblTemp2 - dblPayment
* dblTemp * (dblTemp2 - 1.0) / dblIntRate;
}
return dblRet;
}
5.
From the Build menu, click Build. Look in
the Task List window below the text editing window to see whether any
errors are generated.
6.
The Java class file must be registered on the same machine
as the Web server. In a command window, find the ASPTut.class file that was
built. It is most likely either in %USERPROFILE%\My Documents\Visual Studio
Projects\ASPTut or in x:\Documents and Settings\user name\My
Documents\Visual Studio Projects\ASPTut, where x: is the drive on which you
installed Windows. Copy ASPTut.class to x:\Winnt\Java\Trustlib. Type javareg
/register /class:ASPTut /progid:MS.ASPTut.Java, and press ENTER to
register the Java class.
7.
Close Visual J++.
This
example ASP page uses a form to read in user data, creates an instance of your
object, and calculates the future value of your savings plan. This example uses
JScript, but you can call a Java component from VBScript as well.
Copy
and paste the following code in your text editor, and save the file as CalculateFutureValueJava.asp
in the x:\Inetpub\wwwroot\Tutorial directory. View the example with your
browser by typing http://localhost/Tutorial/CalculateFutureValueJava.asp
in the address bar.
<%@ Language=JScript %>
<%
Response.Expires = 0;
Payment = Request.Form("Payment");
AnnualIntRate = Request.Form("AnnualIntRate");
NumPayPeriods = Request.Form("NumPayPeriods");
WhenDue = Request.Form("WhenDue");
PresentSavings = Request.Form("PresentSavings");
%>
<HTML>
<HEAD><TITLE>Future Value Calculation -
Java</TITLE></HEAD>
<BODY>
<FONT FACE="MS Gothic">
<H2 align=center>Calculate the Future Value of a Savings
Plan</H2>
<FORM METHOD=POST
ACTION="calculatefuturevaluejava.asp">
<TABLE cellpadding=4 align=center>
<TR>
<TD>How much do you plan to save each month?</TD>
<TD><INPUT TYPE=TEXT NAME=Payment
VALUE=<%=Payment%>> (Required)</TD>
</TR><TR>
<TD>Enter the annual interest rate.</TD>
<TD><INPUT TYPE=TEXT NAME=AnnualIntRate
VALUE=<%=AnnualIntRate%>> (Required)</TD>
</TR><TR>
<TD>For how many months will you save?</TD>
<TD><INPUT TYPE=TEXT NAME=NumPayPeriods
VALUE=<%=NumPayPeriods%>> (Required)</TD>
</TR><TR>
<TD>When do you make payments in the month? </TD>
<TD><INPUT TYPE=RADIO NAME=WhenDue VALUE=1 <%if
(1==WhenDue) Response.Write("CHECKED")%>>Beginning
<INPUT TYPE=RADIO NAME=WhenDue VALUE=0 <%if (0==WhenDue)
Response.Write("CHECKED")%>>End </TD>
</TR><TR>
<TD>How much is in this savings account now?</TD>
<TD><INPUT TYPE=TEXT NAME=PresentSavings
VALUE=<%=PresentSavings%>> </TD>
</TR>
</TABLE>
<P align=center><INPUT TYPE=SUBMIT VALUE="
Calculate Future Value ">
</FORM>
<%
if (("" == Payment) || ("" ==
AnnualIntRate) || ("" == NumPayPeriods)) {
Response.Write("<H3 align=center>No valid
input entered yet.</H3>");
} else {
AnnualIntRate = parseFloat(AnnualIntRate)
NumPayPeriods = parseFloat(NumPayPeriods)
Payment = parseFloat(Payment)
if ("" != PresentSavings) PresentSavings =
parseFloat(PresentSavings);
if ((isNaN(Payment)) || (isNaN(AnnualIntRate)) ||
(isNaN(NumPayPeriods))) {
Response.Write("<H3 align=center>Some
of your values are not numbers.</H3>");
} else {
var FutureValue, Cents;
var oASPTut =
Server.CreateObject("MS.ASPTut.Java");
FutureValue =
oASPTut.CalcFutureValue(AnnualIntRate, NumPayPeriods, Payment, PresentSavings,
WhenDue);
Response.Write("<H3
align=center>Future value = $" + parseInt(FutureValue) +
"</H3>");
}
}
%>
</FONT>
</BODY>
</HTML>
In
the browser, you should see the following content, which should be identical to
the display generated using the Visual Basic component in Lesson 3 of this
module:
© 1997-2001 Microsoft
Corporation. All rights reserved.
This
module describes the process of maintaining session state in Active Server Pages
(ASP). Session refers to the time segment that a specific user is actively
viewing the contents of a Web site. A session starts when the user visits the
first page on the site, and it ends a few minutes after the user leaves the
site. The pieces of user-specific information, relevant to a particular
session, are collectively known as session state.
Because
HTTP is a stateless protocol, a problem arises when trying to maintain state
for a user visiting your Web site. The Web server treats each HTTP request as a
unique request, which is unrelated to any previous requests. Thus, the
information a user enters on one page (through a form, for example) is not
automatically available on the next page requested. The Web server must
maintain session state to identify and track users as they browse through pages
on a Web site.
One
solution is through the use of cookies. Cookies record information about
a user on one page and transfer that information to other pages within the
site. However, a few browsers do not recognize cookies, and on other browsers,
users can disable cookies. If you are concerned about reaching this Web
audience, you can maintain session state without using cookies by using HTTP
POST.
This
module includes the following lessons:
·
Maintaining
Session State with Cookies Provides two cookie examples,
one using the ASP Response and Request objects and another using the ASP
Session object.
·
Maintaining
Session State Without Cookies Provides an example of the
alternative to maintaining session state with cookies: HTTP POST.
Cookies
store a set of user specific information, such as a credit card number or a
password. The Web server embeds the cookie into a user's Web browser so that
the user's information becomes available to other pages within the site; users
do not have to reenter their information for every page they visit. Cookies are
a good way to gather customer information for Web-based shopping, for retaining
the personal preferences of the Web user, or for maintaining state about the
user.
There
are two kinds of cookies, as follows:
·
In-memory cookies An
in-memory cookie goes away when the user shuts the browser down.
·
Persistent cookies A
persistent cookie resides on the hard drive of the user and is retrieved when
the user comes back to the Web page.
If
you create a cookie without specifying an expiration date, you are creating an
in-memory cookie, which lives for that browser session only. The following
illustrates the script that would be used for an in-memory cookie:
Response.Cookies("SiteArea")
= "TechNet"
If
you want the cookie information to persist beyond the session, you should
create a persistent cookie by specifying an expiration date. Supplying an
expiration date causes the browser to save the cookie on the client computer.
Until the cookie expiration date is reached, the data in the persistent cookie will
stay on the client machine. Any request to the original Web site will
automatically attach the cookie that was created by that site. Cookies go only
to the sites that created them because part of the Web site name and ASP file
make up the data in the cookie.
The following illustrates the script used to create a persistent cookie:
Response.Cookies("SiteArea")
= "TechNet"
Response.Cookies("SiteArea").Expires = "August
15, 2000"
The
script to create a cookie should be placed at the beginning of the ASP file
because cookies need to be generated before any HTML text is sent to the
browser.
Persistent
cookies are produced using the Response and Request objects,
although these objects may also be used to create an in-memory cookie. The
majority of Web applications employ these objects to maintain session state.
·
Response object Use the Response
object to create and set cookie values.
·
Request object Use the Request
object to retrieve the value of a cookie created during a previous Web session.
In
this lesson you will use the Response and Request objects to
create the following files. Please create them all at once, because some of
them need the others. After you have created all the files, run the application
by typing http://LocalHost/Tutorial/Frame.htm in your browser.
·
Frame.htm A page that
splits the the user's view into two windows. This page requires that Menu.htm
and CustomGreeting.asp.
·
Menu.htm A page
containing links to the samples for this lesson. For the links to work, this
page requires that all the other pages have been created.
·
CustomGreeting.asp An ASP
script that takes the user's name in a form and sets an in-memory cookie.
·
DeleteGreetingCookie.asp An
ASP script that deletes the cookie that contains the user's name. If no cookie
is set, a warning is displayed.
·
SelectColors.asp An ASP
script that sets up the cookies for the user's color choices.
·
DeleteColorCookie.asp An
ASP script that deletes the Web colors previously chosen. If none are chosen, a
warning is displayed.
·
Cookie.asp An ASP script
that sets persistent cookies to hold the current date and time of the user's
visit and record the total number of visits.
·
DeleteCookies.asp This ASP
script deletes the cookies set in Cookie.asp. If no cookies are set, a warning
is displayed.
Open
a new file in your text editor, paste in the following script, and save the
file as C:\Inetpub\Wwwroot\Tutorial\Frame.htm.
<html>
<head>
<title>Customized Greeting and Colors Using In-Memory and
Persistent Cookies</title>
</head>
<frameset cols="40%,60%">
<frame src="menu.htm" name="left"
marginheight="5" marginwidth="5">
<frame src="CustomGreeting.asp"
name="right" marginheight="5" marginwidth="5">
</frameset>
<noframes>
Sorry, your browser does not support frames. Please go to
the <a href="menu.htm">Menu</a>.
</noframes>
</html>
Open
a new file in your text editor, paste in the following script, and save the
file as C:\Inetpub\Wwwroot\Tutorial\Menu.htm.
<html>
<head>
<title>Maintaining Session State With Cookies</title>
</head>
<body>
<font face="MS Gothic">
<h2 align="center">Cookie Examples</h2>
<table align=center border=1 cellpadding=4>
<tr>
<td><a href="CustomGreeting.asp"
target="right"><b>Custom Greeting
Page</b></a></td>
</tr><tr>
<td><a href="DeleteGreetingCookie.asp"
target="right"><b>Delete the Greetings
Cookie</b></a></td>
</tr><tr>
<td><a href="SelectColors.asp"
target="right"><b>Set Page
Colors</b></a></td>
</tr><tr>
<td><a href="DeleteColorCookie.asp"
target="right"><b>Delete Page Colors
Cookies</b></a></td>
</tr><tr>
<td><a href="Cookie.asp"
target="right"><b>Set Cookies for Date, Time and Total
Visits</b></a></td>
</tr><tr>
<td><a href="DeleteCookies.asp"
target="right"><b>Delete Cookies for Date, Time and Total
Visits</b></a></td>
</tr>
</table>
</font>
</body>
</html>
Open
a new file in your text editor, paste in the following script, and save the
file as C:\Inetpub\Wwwroot\Tutorial\CustomGreeting.asp.
<%@ Language="VBScript" %>
<%
'If the user has selected text and background colors,
' cookies are used to remember the values between HTTP sessions.
'Do this first so that your page can use use the values if they
are set.
If Not (Request.QueryString("Text")="") Then
Response.Cookies("TextColor") =
Request.QueryString("Text")
Response.Cookies("BackgroundColor") =
Request.QueryString("Background")
End If
' If the user has typed in a name, a cookie is created.
If Not (Request.QueryString("Name")="") Then
Response.Cookies ("Name") =
Request.QueryString("Name")
' If the user does not give his/her name, a cookie
' is created so that we do not keep asking for the name.
ElseIf (InStr(Request.QueryString,"Name")=1) Then
Response.Cookies ("NoUserInput") =
"TRUE"
End If
%>
<html>
<head>
</head>
<%
'Set colors according to existing previous user input.
If (Request.Cookies ("TextColor")="") Then
%>
<body>
<% Else %>
<body
bgcolor=<%=Request.Cookies("BackgroundColor")%>
text=<%=Request.Cookies("TextColor")%>>
<% End If
%>
<font face="MS Gothic">
<%
'If there is no name cookie set, no name entered by the user,
' and there was no user input at all, get the user's name.
If ( (Request.Cookies("Name")="") And
((Request.QueryString("Name"))="")) And
(Not(Request.Cookies("NoUserInput")="TRUE") ) Then %>
<FORM ACTION="CustomGreeting.asp"
METHOD="GET" NAME="DataForm">
<table align=center><tr><td>
<INPUT TYPE=TEXTBOX NAME="Name"
SIZE=33></td></tr><tr><td>
<INPUT TYPE=Submit VALUE="Please Enter Your Name"></td></tr></table>
</FORM>
<% ElseIf Not(Request.Cookies("Name")="")
Then %>
<H2 align=center>Greetings
<%=Request.Cookies("Name")%></H2>
<% Else %>
<H2>Hello!</H2>
<H3>You did not give us your name so we are not
able to greet you by name.</H3>
<% End If
%>
<H3>In-Memory Cookie Example</H3>
<P>
Once you enter your name:
<UL>
<LI>If you hit <B>Refresh</B> in your browser, you
should still see your name.</LI>
<LI>If you close your browser, the cookie is deleted. When you
re-open your browser to this page, you should be asked for your name
again.</LI>
<LI>If you click on <B>Delete the Greetings
Cookie</B>, and click on <B>Custom Greeting Page</B>, you
should be asked for your name again.</LI>
</P>
</font>
</body>
</html>
Open
a new file in your text editor, paste in the following script, and save the
file as C:\Inetpub\Wwwroot\Tutorial\DeleteGreetingCookie.asp.
<%@ Language="VBScript" %>
<html>
<head>
</head>
<% If (Request.Cookies ("TextColor")="") Then
%>
<body>
<font face="MS Gothic">
<% Else %>
<body
bgcolor=<%=Request.Cookies("BackgroundColor")%>
text=<%=Request.Cookies("TextColor")%>>
<font face="MS Gothic"
color=<%=Request.Cookies("TextColor")%>>
<% End If %>
<%
If Not ("" = Request.Cookies("Name")) Then
Response.Cookies ("Name").Expires =
"January 1, 1992"
Response.Cookies ("NoUserInput").Expires =
"January 1, 1992" %>
<h2 align=center>In-Memory Greeting Cookie
Deleted</h2>
<P>
The cookie used to keep track of your name has been
deleted.<BR>
Please click on <B>Custom Greeting
Page</B> to be asked for your name again.
</P>
<% Else %>
<h2 align=center>No In-Memory Greeting Cookie
Deleted</h2>
<P>
There was no cookie set with your name.<BR>
Please click on <B>Custom Greeting
Page</B> to enter your name.
</P>
<% End If
%>
</font>
</body>
</html>
Open
a new file in your text editor, paste in the following script, and save the
file as C:\Inetpub\Wwwroot\Tutorial\SelectColors.asp.
<%@ Language="VBScript" %>
<%
' If the user has selected text and background colors,
' cookies are used to remember the values between HTTP
sessions.
If Not (Request.QueryString("Text")="")
Then
Response.Cookies ("TextColor") =
Request.QueryString("Text")
Response.Cookies ("BackgroundColor") =
Request.QueryString("Background")
End If
%>
<html>
<head>
</head>
<%
'Set colors according to existing previous user input.
If (Request.Cookies ("TextColor")="")
Then %>
<body>
<% Else %>
<body
bgcolor=<%=Request.Cookies("BackgroundColor")%> text=<%=Request.Cookies("TextColor")%>>
<% End If
%>
<font face="MS Gothic">
<H2 align=center>Select the colors for your Web page</H2>
<P>
In Memory Cookies will be used to store these values.
</P>
<FORM ACTION="SelectColors.asp" METHOD="GET"
NAME="DataForm">
<table border="1" width="450" cellpadding=0>
<tr><td>
<table>
<tr><td BGCOLOR=99FF99>
<B><font color=000000>Please select the
background color</font></B>
</td></tr><tr><td BGCOLOR=FFFFFF>
<input type="RADIO" NAME="Background"
VALUE="FFFFFF" CHECKED><font COLOR=000000> FFFFFF
</font>
</td></tr><tr><td BGCOLOR=D98719>
<input type="RADIO" NAME="Background"
VALUE="D98719"> D98719
</td></tr><tr><td BGCOLOR=D9D919>
<input type="RADIO" NAME="Background"
VALUE="D9D919"> D9D919
</td></tr><tr><td BGCOLOR=00FFFF>
<input type="RADIO" NAME="Background"
VALUE="00FFFF"> 00FFFF
</td></tr><tr><td BGCOLOR=FF00FF>
<input type="RADIO" NAME="Background"
VALUE="FF00FF"> FF00FF
</td></tr><tr><td BGCOLOR=000000>
<input type="RADIO" NAME="Background"
VALUE="000000"> <font COLOR=FFFFFF>000000</font>
</td></tr>
</table>
</td><td>
<table>
<tr><td BGCOLOR=99FF99>
<B><font color=000000>Please select the text
color</font></B>
</td></tr><tr><td BGCOLOR=FFFFFF>
<input type="RADIO" NAME="Text"
VALUE="FFFFFF" CHECKED><font COLOR=000000> FFFFFF
</font>
</td></tr><tr><td BGCOLOR=D98719>
<input type="RADIO" NAME="Text"
VALUE="D98719"> D98719
</td></tr><tr><td BGCOLOR=D9D919>
<input type="RADIO" NAME="Text"
VALUE="D9D919"> D9D919
</td></tr><tr><td BGCOLOR=00FFFF>
<input type="RADIO" NAME="Text"
VALUE="00FFFF"> 00FFFF
</td></tr><tr><td BGCOLOR=FF00FF>
<input type="RADIO" NAME="Text"
VALUE="FF00FF"> FF00FF
</td></tr><tr><td BGCOLOR=000000>
<input type="RADIO" NAME="Text"
VALUE="000000" CHECKED><font COLOR=FFFFFF> 000000
</font>
</td></tr>
</table>
</td></tr>
</table>
<P>
<input type=Submit VALUE="Submit selected colors">
</FORM>
</font>
</body>
</html>
Open
a new file in your text editor, paste in the following script, and save the
file as C:\Inetpub\Wwwroot\Tutorial\DeleteColorCookie.asp.
<%@ Language="VBScript" %>
<html>
<head>
</head>
<body>
<font face="MS Gothic">
<%
If Not ("" = Request.Cookies("TextColor"))
Then
Response.Cookies("TextColor").Expires =
"January 1, 1992"
Response.Cookies("BackgroundColor").Expires
= "January 1, 1992" %>
<h2 align=center>In-Memory Color Cookie
Deleted</h2>
<P>
The cookie used to keep track of your display colors
has been deleted.<BR>
Please click on <B>Set Page Colors</B> to
set your colors again.
</P>
<% Else %>
<h2 align=center>No In-Memory Color Cookie
Deleted</h2>
<P>
There was no cookie set with your color
choices.<BR>
Please click on <B>Set Page Colors</B> to
set display colors.
</P>
<% End If
%>
</font>
</body>
</html>
Open
a new file in your text editor, paste in the following script, and save the
file as C:\Inetpub\Wwwroot\Tutorial\Cookie.asp.
<%@ Language="VBScript" %>
<%
LastAccessTime = Request.Cookies("LastTime")
LastAccessDate = Request.Cookies("LastDate")
'If the NumVisits cookie is empty, set to 0, else increment it.
If (Request.Cookies("NumVisits")="") Then
Response.Cookies("NumVisits") = 0
Else
Response.Cookies("NumVisits") = Request.Cookies("NumVisits")
+ 1
End If
Response.Cookies("LastDate") = Date
Response.Cookies("LastTime") = Time
'Setting an expired date past the present date creates a
persistent cookie.
Response.Cookies("LastDate").Expires = "January 15,
2001"
Response.Cookies("LastTime").Expires = "January 15,
2001"
Response.Cookies("NumVisits").Expires = "January
15, 2001"
%>
<html>
<head>
</head>
<% If (Request.Cookies ("TextColor")="") Then
%>
<body>
<font face="MS Gothic">
<% Else %>
<body
bgcolor=<%=Request.Cookies("BackgroundColor")%>
text=<%=Request.Cookies("TextColor")%>>
<font face="MS Gothic"
color=<%=Request.Cookies("TextColor")%>>
<% End If %>
<H2 align=center>Persistent Client-Side Cookies!</H2>
<P>
Three persistent client-side cookies are created.
<UL>
<LI>A cookie to count the number of times you visited the Web
page.</LI>
<LI>A cookie to determine the date of your visit.</LI>
<LI>A cookie to determine the time of your visit.</LI>
</UL>
</P>
<table border="1" width="300" cellpadding=4
align=center>
<tr><td>
<% If (Request.Cookies ("NumVisits")=0) Then %>
Welcome! This is your first visit to this Web page!
<% Else %>
Thank you for visiting again! You have been to this Web page
a total of <B><%=Request.Cookies("NumVisits")%></B>
time(s).
<% End If %>
</td></tr>
</table>
<P>
<B>The Current time is <%=Time%> on <%=Date%><BR>
<% If (Request.Cookies ("NumVisits")>0) Then %>
You last visited this Web page at
<%=LastAccessTime%> on <%=LastAccessDate%>
<% End If %>
</strong>
</P> s
</font>
</body>
</html>
Open
a new file in your text editor, paste in the following script, and save the
file as DeleteCookies.asp.
<%@ Language="VBScript" %>
<html>
<head>
</head>
<% If (Request.Cookies ("TextColor")="") Then
%>
<body>
<font face="MS Gothic">
<% Else %>
<body
bgcolor=<%=Request.Cookies("BackgroundColor")%>
text=<%=Request.Cookies("TextColor")%>>
<font face="MS Gothic"
color=<%=Request.Cookies("TextColor")%>>
<% End If %>
<%
If Not ("" = Request.Cookies("NumVisits"))
Then
Response.Cookies("NumVisits").Expires =
"January 1, 1993"
Response.Cookies("LastDate").Expires =
"January 1, 1993"
Response.Cookies("LastTime").Expires =
"January 1, 1993" %>
<H2 align=center>Persistent Cookies Are
Deleted</H2>
<P>
The cookies used to keep track of your visits and date
and time of last visit have been deleted.<BR>
Please click on <B>Set Cookies for Date, Time
and Total Visits</B> to set your cookies again.
</P>
<% Else %>
<H2 align=center>No Persistent Cookies Are
Deleted</H2>
<P>
There were no cookies set to keep track of your
visits, and date and time of last visit.<BR>
Please click on <B>Set Cookies for Date, Time
and Total Visits</B> to set your colors again.
</P>
<% End If %>
</font>
</body>
</html>
With
the Session object, you can create only an in-memory cookie. For the Session
object to work correctly, you need to determine when a user's visit to the site
begins and ends. IIS does this by using a cookie that stores an ASP Session ID,
which is used to maintain a set of information about a user. If an ASP Session
ID is not present, the server considers the current request to be the start of
a visit. The visit ends when there have been no user requests for ASP files for
the default time period of 20 minutes.
In
this lesson, you will create the following:
·
Global.asa Global.asa is a
file that allows you to perform generic actions at the beginning of the
application and at the beginning of each user's session. An application starts
the first time the first user ever requests a page and ends when the
application is unloaded or when the server is taken offline. A unique session
starts once for each user and ends 20 minutes after that user has requested
their last page. Generic actions you can perform in Global.asa include setting
application or session variables, authenticating a user, logging the date and
time that a user connected, instantiating COM objects that remain active for an
entire application or session, and so forth.
·
VisitCount.asp This ASP
script uses the Session object to create an in-memory cookie.
When
an application or session begins or ends, it is considered an event. Using the
Global.asa file, you can use the predefined event procedures that run in
response to the event.
Open
a new file in your text editor, paste in the following script, and save the
file in your root directory as C:\Inetpub\Wwwroot\Global.asa.
Important:
Global.asa files must be saved in the root directory of the application for ASP
to find it. If you had a virtual path called Test mapped to
C:\Inetpub\Wwwroot\Test, your URL would be http://LocalHost/Test, and the
Global.asa file would have to go in C:\Inetpub\Wwwroot\Test. We did not create
a virtual path mapped to C:\Inetpub\Wwwroot\Tutorial, so our root directory is
still C:\Inetpub\Wwwroot.
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
'Using application-level variables to track the number of users
' that are currently looking at the site and the number that have
' accessed the site.
Sub Application_OnStart
'Get the physical path to this vdir, and append a filename.
Application("PhysPath") =
Server.MapPath(".") & "\hits.txt"
'Set some Visual Basic constants, and instantiate the
FileSystemObject object.
Const cForReading = 1
Const cTristateUseDefault = -2
Set fsoObject =
Server.CreateObject("Scripting.FileSystemObject")
'Get the last saved value of page hits and the date that it
happened.
If fsoObject.FileExists(Application("PhysPath"))
Then
'If the file hits.txt exists, set the
Application variables.
Set tsObject =
fsoObject.OpenTextFile(Application("PhysPath"), cForReading,
cTristateUseDefault)
Application("HitCounter") =
tsObject.ReadLine
Application("AppStartDate") =
tsObject.ReadLine
tsObject.Close
Else 'No file has been saved, so reset the values.
Application("HitCounter") = 0
Application("AppStartDate") = Date
End If
Application("CurrentUsers") = 0
End Sub
Sub Application_OnEnd
Const cForWriting = 2
Const cTristateUseDefault = -2
Set fsoObject =
Server.CreateObject("Scripting.FileSystemObject")
If fsoObject.FileExists(Application("PhysPath"))
Then
'If the file exists, open it for writing.
set tsObject =
fsoObject.OpenTextFile(Application("PhysPath"), cForWriting,
cTristateUseDefault)
Else
'If the file doesn't exist, create a new one.
set tsObject =
fsoObject.CreateTextFile(Application("PhysPath"))
End If
'Write the total number of site hits and the last day
recorded to the file.
tsObject.WriteLine(Application("HitCounter"))
tsObject.WriteLine(Application("AppStartDate"))
tsObject.Close
End Sub
Sub Session_OnStart
'The Session time-out default is changed to 1 for the
purposes of
' this example.
Session.Timeout = 1
'When you change Application variables, you must lock them
so that other
' sessions cannot change them at the same time.
Application.Lock
'Increment the site hit counter.
Application("HitCounter") =
Application("HitCounter") + 1
Application("CurrentUsers") =
Application("CurrentUsers") + 1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
'Decrement the current user counter.
Application("CurrentUsers") =
Application("CurrentUsers") - 1
Application.UnLock
End Sub
</SCRIPT>
You
can use variables set in Global.asa to measure visits and sessions.
Open
a new file in your text editor, paste in the following script, and save the
file as C:\Inetpub\Wwwroot\Tutorial\VisitCount.asp. View the file in
your browser by typing http://Localhost/Tutorial/VisitCount.asp.
Open
a second instance of the browser to http://Localhost/Tutorial/VisitCount.asp,
and click Refresh on the first browser. Total Visitors and Active
Visitors should increase by one. Close down the second browser, wait over a
minute, and click Refresh on the first browser. Active Visitors should
decrease by one.
<% Response.Buffer = True%>
<html>
<head>
<title>Retrieving Variables Set in Global.asa</title>
</head>
<body>
<font face="MS Gothic">
<H3 align=center>Retrieving Variables Set in Global.asa</H3>
<P>
Total Visitors = <%=Application("HitCounter")%> since
<%=Application("AppStartDate")%><BR>
Active Visitors = <%=Application("CurrentUsers")%>
</P>
</font>
</body>
</html>
Some
browsers do not recognize cookies, and users can choose to disable cookies in
their browsers. The HTTP POST method provides an alternative to cookies to
maintain session state. The HTTP POST method provides the same state
information as would a cookie but has the advantage that it works even when
cookies are not available. This method is not common in practice, but it is a
good example to learn from. The HTTP POST method works similarly to an
in-memory cookie; user information can be maintained only during the visit, and
the session state information is gone when the user turns off the browser.
Open
a new file in your text editor, paste in the following script, and save the
files as C:\Inetpub\Wwwroot\Tutorial\DataEntry.asp. View the file in
your browser by typing http://Localhost/Tutorial/DataEntry.asp.
<%@ Language=VBScript %>
<html>
<head>
<title>Data Entry Without Cookies</title>
</head>
<body>
<font face="MS Gothic">
<!-- In this example, subroutines are listed first.
There's a subroutine for each page of the
order process.
The main calling code is at the bottom.
-->
<% Sub DisplayInitialPage %>
<table border=1 cellpadding=3 cellspacing=0 width=500
bordercolor=#808080 align=center>
<tr><td bgColor=#004080 align=center>
<font color=#ffffff><H2>Order
Form</H2></font>
</td></tr><tr><td bgColor=#e1e1e1
align=left>
<P><B>Step 1 of 4</B></P>
<P align=center>
This form uses the HTTP POST method to pass along hidden
values that contain
your order information. This form does not use cookies.
</P>
<FORM METHOD=POST ACTION="DataEntry.asp"
NAME=DataEntryForm>
<P>Enter your name
<INPUT TYPE="TEXT" NAME=FullName>
<BR>Enter your imaginary credit card number
<INPUT TYPE="TEXT" NAME=CreditCard>
</P>
<!-- Keeps track of the information by using the hidden
HTML form variable Next Page. -->
<INPUT TYPE="HIDDEN" NAME=NextPage VALUE=2>
<INPUT TYPE="SUBMIT" VALUE="Next
->" NAME=NextButton>
</FORM>
</td></tr>
</table>
<% End Sub %>
<% Sub DisplayDogBreed %>
<table border=1 cellpadding=3 cellspacing=0 width=500
align=center>
<tr><td bgColor=#004080 align=center>
<font color=#ffffff><H2>Order
Form</H2></font>
</td></tr><tr><td bgColor=#e1e1e1>
<P><B>Step 2 of 4</B></P>
<P align=center>
Please select the type of dog you want.
</P>
<FORM METHOD=POST ACTION="DataEntry.asp"
NAME=DataEntryForm>
<P>
<INPUT TYPE=RADIO NAME=DogSelected VALUE="Cocker
Spaniel" CHECKED>Cocker Spaniel<BR>
<INPUT TYPE=RADIO NAME=DogSelected
VALUE="Doberman">Doberman<BR>
<INPUT TYPE=RADIO NAME=DogSelected VALUE="Timber
Wolf">Timber Wolf<BR>
<INPUT TYPE=RADIO NAME=DogSelected
VALUE="Mastiff">Mastiff<BR>
</P>
<!--Keeps track of the information by using the hidden
HTML form variable Next Page. -->
<INPUT TYPE="HIDDEN" NAME=NextPage VALUE=3>
<INPUT TYPE="SUBMIT" VALUE="Next
->" NAME=NextButton>
</FORM>
</td></tr>
</table>
<% End Sub %>
<% Sub DisplayCity %>
<table border=1 cellpadding=3 cellspacing=0 width=500
align=center>
<tr><td bgColor=#004080 align=center>
<font color=#ffffff><H2>Order
Form</H2></font>
</td></tr><tr><td bgColor=#e1e1e1>
<P><B>Step 3 of 4</B></P>
<P align=center>
We deliver from the following cities. Please choose the one
closest to you.
</P>
<FORM METHOD=POST ACTION="DataEntry.asp"
NAME=DataEntryForm>
<P>
<INPUT TYPE=RADIO NAME=CitySelected
VALUE="Seattle" CHECKED>Seattle<BR>
<INPUT TYPE=RADIO NAME=CitySelected VALUE="Los
Angeles">Los Angeles<BR>
<INPUT TYPE=RADIO NAME=CitySelected
VALUE="Boston">Boston<BR>
<INPUT TYPE=RADIO NAME=CitySelected VALUE="New
York">New York<BR>
</P>
<!--Keeps track of the information by using the hidden
HTML form variable Next Page. -->
<INPUT TYPE="HIDDEN" NAME=NextPage VALUE=4>
<INPUT TYPE="SUBMIT" VALUE="Next
->" NAME=NextButton>
</FORM>
</td></tr>
</table>
<% End Sub %>
<% Sub DisplaySummary %>
<table border=1 cellpadding=3 cellspacing=0 width=500
align=center>
<tr><td bgColor=#004080 align=center>
<font color=#ffffff><H2>Order Form
Completed</H2></font>
</td></tr><tr><td bgColor=#e1e1e1>
<P><B>Step 4 of 4</B></P>
<P align=center>
The following information was entered.<BR>
A transaction will now be executed to complete your order if
your name and
credit card are valid.
</P>
<table cellpadding=4>
<tr bgcolor=#ffffcc><td>
Name
</td><td>
<%=Session.Value("FullName")%>
</td></tr><tr
bgcolor=Beige><td>
Credit Card
</td><td>
<%=Session.Value("CreditCard")%>
</td></tr><tr
bgcolor=Beige><td>
Dog Ordered
</td><td>
<%=Session.Value("DogSelected")%>
</td></tr><tr
bgcolor=Beige><td>
City Ordered From
</td><td>
<%=Session.Value("CitySelected")%>
</td></tr>
</table>
</td>
</tr>
</table>
<% End Sub %>
<% Sub StoreUserDataInSessionObject %>
<%
Dim FormKey
For Each FormKey in Request.Form
Session(FormKey) = Request.Form.Item(FormKey)
Next
%>
<% End Sub %>
<%
'This is the main code that calls all the subroutines
depending on the
' hidden form elements.
Dim CurrentPage
If Request.Form.Item("NextPage") = ""
Then
CurrentPage = 1
Else
CurrentPage =
Request.Form.Item("NextPage")
End If
'Save all user data so far.
Call StoreUserDataInSessionObject
Select Case CurrentPage
Case 1 : Call DisplayInitialPage
Case 2 : Call DisplayDogBreed
Case 3 : Call DisplayCity
Case 4 : Call DisplaySummary
End Select %>
<BR>
<HR>
<H3 align=center><A HREF="DataEntry.asp">Reset
Order</A></H3>
</font>
</body>
</html>
© 1997-2001 Microsoft
Corporation. All rights reserved.