Active Server Pages - Vishwa Bharati Public School

Download Report

Transcript Active Server Pages - Vishwa Bharati Public School

Active Server Pages
Minder Chen, Ph.D.
[email protected]
© Minder Chen, 1998-2002
ASP - 1
Course Description
Active Server Pages (ASP) are scripting files processed by
Microsoft Internet Information Server. ASP provides serverside scripting to create interactive Web applications,
including tasks such as gathering information from the client,
updating or retrieving data in a database, or dynamically
creating HTML pages returned to the users. This course will
describe the basics of Visual Basic Scripting (VB Script)
language and how to build ASP using VB Script. Student
will learn how to: describe the HTTP protocol; build
interactive Web applications; use the ASP objects including
Response, Request, Session, and Application objects;
create and use cookies; use an ActiveX server component in
Web applications. Students will also learn how to create
Web pages that access information in a database by using
the ActiveX Data Objects (ADO).
© Minder Chen, 1998-2002
ASP - 2
Outline
•
•
•
•
•
•
•
Introduction and architecture
VB Script for Active Server Page
Form Data Processing
Using Build-in and Installable ASP Components
Using Database Access Component (ADO)
Session Management
More Examples (Optional)
© Minder Chen, 1998-2002
ASP - 3
Resources
•
Web Master Training Web Site:
– http://65.168.116.6/web9/net
•
ASP Documentation from Microsoft:
– http://msdn.microsoft.com/library/
–
–
Personal Web Server (PWS) is one of many new features available through the Windows NT
Option Pack.
http://www.microsoft.com/ntserver/nts/downloads/recommended/NT4OptPk/default.asp
– http://www.microsoft.com/windows/ie/pws/
– http://www.windows.com/windows2000/en/server/iis/htm/asp/iiwauslw.htm
•
Best Web Sites:
– http://www.aspin.com/
– http://www.activeserverpages.com/
– http://www.asp101.com
•
Additional ASP Resources
– http://www.microsoft.com/net
– http://www.aspcode.net/freeasphost/freeasphost.asp (Free ASP hosting)
•
–
–
–
http://www.datareturn.com/developerresources.asp
http://msdn.microsoft.com/scripting/
http://www.chilisoft.com/ ' for porting Asp to other platform
Books:
– Beginning Active Server Pages 3.0, Wrox Press Inc.
– Professional Active Server Pages 2.0, Wrox Press Inc.
– Active Server Pages 3.0, Nicholas Chase, Que, 2000.
– ASP in a Nutshell: A Quick Reference, O'Reilly, 1999
© Minder Chen, 1998-2002
ASP - 4
Creating ASP Page
• ASP uses the delimiters <% and %> to enclose script commands.
• By default, the primary scripting language is VBScript.
test.asp
<HTML>
<BODY>
This page was last refreshed on <% =Now() %>.
</BODY>
</HTML>
• The VBScript function Now returns the current date and time.
<HTML>
<BODY>
Rendered
This page was last refreshed on 9/11/98 4:30:00 PM.
via a
</BODY>
browser
</HTML>
Interpreted ASP code:
An HTML document.
© Minder Chen, 1998-2002
This page was last refreshed on
9/11/98 4:30:00 PM.
ASP - 5
The Active Server Pages Model
Browser
Web Server
(IIS)
.asp files
ASP
Active
Server
Page
Interpreter:
Process
ASP
Scripting
Statements
• An ASP script begins to run when a browser requests a .asp file from
your Web server.
• Your Web server then calls ASP, which reads through the requested
file from top to bottom, executes any ASP statements, and sends an
HTML page to the browser.
© Minder Chen, 1998-2002
ASP - 6
ASP Architecture
(ADO)
© Minder Chen, 1998-2002
ASP - 7
Platforms for VBScript Program
•
When initiating and processing Web data takes place on the client computer,
you can include VBScript code in HTML files to enhance Web pages in Internet
Explorer.
•
When initiating and processing Web data takes place on the server, you can
include VBScript code in HTML files that are used by Internet Information
Server (IIS) Active Server Pages.
•
To run scripts directly on the Windows desktop or command console, use
Windows Scripting Host (WSH) to run VBScript programs.
Server-Side
VBScripting
© Minder Chen, 1998-2002
Client-Side
VBScripting
ASP - 8
Active Server Page
• A .asp file is an ASCII text file that contains
– HTML commands
– text or other content (such as client side scripts)
– server-side script commands
• When a client browser requests a URL with an
.asp file name extension, any script contained
within the <% and %> delimiters and within
<SCRIPT RUNAT=Server
LANGUAGE=VBSCRIPT> and </SCRIPT> tags is
executed on the server. Use the value JSCRIPT
for LANGUAGE for Jscript.
• The resulting HTML and text are sent back to the
client browser.
© Minder Chen, 1998-2002
ASP - 9
Benefits of ASP Applications
• Completely integrated with your HTML files.
• Easy to create, with no manual compiling or linking of
programs required.
• Object-oriented and extensible with ActiveX server
components.
• ASP supplies scripting engines for Microsoft® Visual
Basic® Scripting Edition (VBScript) and JScript.
• You can incorporate sophisticated functionality using
ActiveX server components, formerly known as
Automation servers, to process data and generate useful
information.
• ASP-generated content is compatible with standard Web
browsers.
© Minder Chen, 1998-2002
ASP - 10
ASP Scripting
• The first line in an .asp file specifies the
scripting language for the page. For example,
the following first line in .asp file specifies that
the script is VBScript:
<%@ LANGUAGE=VBScript %>
• Without a language tag, script in the file is
processed as the default language (VBScript by
default.) under the ASP entry in the Web server
registry.
• Active Server Pages can provide a scripting
environment for a number of other scripting
languages, including Jscript (build-in), REXX,
and Perl, and others.
© Minder Chen, 1998-2002
ASP - 11
Developing ASP Scripts
Creating/Revising
ASP scripts
Posting ASP scripts on the
web server or saving them
on the local web server
Testing ASP Scripts
© Minder Chen, 1998-2002
ASP - 12
Hello.asp: Display Information
<HTML>
<HEAD>
Returned HTML Document
<TITLE>Hello World Example</TITLE>
</HEAD>
<BODY>
<%
The start of the
script section
Response.write
%>
<TITLE>Hello World Example</TITLE>
</HEAD>
<BODY>
Hello World!
</BODY>
"Hello World!" </HTML>
method
Build-in
Object
</BODY>
</HTML>
<HTML>
<HEAD>
Argument
The end of
script
section
© Minder Chen, 1998-2002
ASP - 13
Setting Up ASP Files
• An Active Server Pages (ASP) file is a text file
with the extension .asp that contains any
combination of the following:
–
–
–
–
Text
HTML tags
ASP script commands
Call to ActiveX server components
• ASP is server-side scripting.
• ASP files only work with the IIS on NT or PWS
on Windows 95.
• .asp files should be saved on your Web site in a
directory that has Script or Execute permission
enabled.
© Minder Chen, 1998-2002
ASP - 14
http://www.ipswitch.com/
Ws_FTP
65.168.115.6
© Minder Chen, 1998-2002
ASP - 15
Using ftp and Testing ASP applications
• MkDir to create a new subdirectory (e.g., 01)
• Double click a subdirectory to enter to the subdirectory
• Test it by using the URL: http://ft-commerce/asp/01/hello.asp
– For the server at the lab remotely: http://65.168.115.6/asp/01/hello.asp
– For a local server: http://localhost/asp/hello.asp
© Minder Chen, 1998-2002
ASP - 16
Hello2.asp
<HTML><HEAD>
<TITLE>HELLO WORLD</TITLE>
</HEAD><BODY>
<% FOR i = 3 to 7 %>
<FONT SIZE = <% =i %>>
Hello World!<BR>
<% NEXT %>
</BODY></HTML>
http://localhost/asp/hello.asp
Return HTML Source Code
<HTML><HEAD>
<TITLE>HELLO WORLD</TITLE>
</HEAD><BODY>
<FONT SIZE = 3>
Hello World!<BR>
<FONT SIZE = 4>
Hello World!<BR>
<FONT SIZE = 5>
Hello World!<BR>
<FONT SIZE = 6>
Hello World!<BR>
<FONT SIZE = 7>
Hello World!<BR>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 17
Greeting.asp
<%
' This is the greeting script
If Time >= #12:00:00 AM# And Time < #12:00:00 PM# Then
Greeting = "Good Morning!"
Else
Greeting = "Hello!"
End If
%>
<%= Greeting %>
• The <%= Greeting %> command sends the
current value of the variable to the browser.
<% If Time >= #12:00:00 AM# And Time < #12:00:00 PM# Then %>
Good Morning!
<% Else %>
Hello!
<% End If %>
© Minder Chen, 1998-2002
ASP - 18
Alternative Approach
<%
If Time >= #12:00:00 AM# And Time < #12:00:00 PM# Then
Response.Write "Good Morning!"
Else
Response.Write "Hello!"
End If
%>
• Response.Write sends the text that follows it to the
browser. Use Response.Write from within a
statement when you want to dynamically construct
the text returned to the browser.
© Minder Chen, 1998-2002
ASP - 19
Markup
• HTML tags are differentiated from text by
delimiters: The less than (<) and greater than (>)
symbols.
• ASP use delimiters <% and %> to enclose script
commands.
– <% color = "green" %> assigns the value green to the
variable color.
• The ASP output directive <%= expression %>
displays the value of an expression.
– the output expression <% = greeting %> sends the current
value of the variable greeting to the browser.
• The ASP processing directive <%@ keyword %> gives ASP
information it needs to process an .asp file.
– <%@ LANGUAGE=VBScript %>
© Minder Chen, 1998-2002
ASP - 20
Hello3.asp
<%
' Define two variables with string values.
x = "Hello"
y = "World"
%>
<P>My response is to say "<%= y %>&nbsp;
<%= x %>." </P>
<% Color = "Green" %>
<%Color="Green"%>
<%
Same result
Color = "Green"
%>
© Minder Chen, 1998-2002
ASP - 21
Hello4.htm: Sample JavaScript Code
<HTML><HEAD><TITLE>HELLO WORLD</TITLE></HEAD>
<BODY>
<%
Response.write("Hello world! -- From ASP")
%>
<SCRIPT LANGUAGE="JavaScript1.2">
document.write("<P>Hello world! -- From Client-Side Scripting!")
</SCRIPT>
<P>Hello World! -- From HTML </BODY>
</HTML>
© Minder Chen, 1998-2002
ASP - 22
Data Types
• Variables: Simple variables and Array variables
• VBScript subsumes all categories of data under one name
called a Variant.
• At a basic level, Variants contain either string or numeric
data.
• String data is used for text, while numeric data contains
only numbers.
• Variant data can be further classified into subtypes. For
example, you can have numeric data that represents
currency, or a date or time, and the Variant will interpret
the data accordingly.
• You can use the data type conversion function for data
type conversion. For example, CInt function to force
conversion of an expression to the Variant of subtype
Integer.
© Minder Chen, 1998-2002
ASP - 23
Data Types
• Empty
– Variant is uninitialized. Value is 0 for numeric variables or a zerolength string ("") for string variables.
• Null
– Variant intentionally contains no valid data.
• Boolean
– Contains either True or False.
• Byte
– Contains integer in the range 0 to 255.
• Integer
– Contains integer in the range -32,768 to 32,767.
• Currency
– -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
• Long
– Contains integer in the range -2,147,483,648 to 2,147,483,647.
© Minder Chen, 1998-2002
ASP - 24
Data Types
• Single
– Contains a single-precision, floating-point number in the range 3.402823E38 to -1.401298E-45 for negative values and
1.401298E-45 to 3.402823E38 for positive values.
• Double
– Contains a double-precision, floating-point number in the range
-1.79769313486232E308 to -4.94065645841247E-324 for negative
values and 4.94065645841247E-324 to 1.79769313486232E308 for
positive values.
• Date (Time)
– Contains a number that represents a date or time between
January 1, 100 to December 31, 9999.
• String
– Contains a variable-length string that can be up to
approximately two billion characters in length.
• Object
– Contains an object.
• Error
– Contains an error number.
© Minder Chen, 1998-2002
ASP - 25
Declaring Variables
• VBScript implicitly creates a variable the first time that it encounters an
unrecognized string of characters that could be a variable name.
• The Option Explicit statement informs VBScript to generate an error if it
encounters an undeclared variable. The Option Explicit statement should
be the first line of code in a script that uses variables.
• Dim varname[([subscripts])][, varname[([subscripts])]] . . .
– Dim a, x(10), y(2, 5)
• A variable name:
 Must begin with an alphabetic character.
 Cannot contain an embedded period.
 Must not exceed 255 characters.
 Must be unique.
 Is not case-sensitive.
• Constants:
– Const CorpName = "Volcano Coffee Company"
– Const HousePayment = 1500
© Minder Chen, 1998-2002
ASP - 26
Assigning Value to a Variable
• C=2
• A = C+300
• UserName = "Bob"
• UserName = Bob
• CutOffDate = #11-21-98#
• Dim A(10)
A(0) = 256
A(1) = 324
A(2) = 100
...
A(10) = 55
Dim MyVar, MyCheck
MyCheck = IsEmpty(MyVar)
MyVar = Null
MyCheck = IsEmpty(MyVar)
MyVar = Empty
MyCheck = IsEmpty(MyVar)
' Returns True.
' Assign Null.
' Returns False.
' Assign Empty.
' Returns True.
C = A(1)
<% Option Explicit
Dim MyVar
MyInt = 10
MyVar = 10
%>
© Minder Chen, 1998-2002
' Force explicit variable declaration.
' Declare variable.
' Undeclared variable generates error.
' Declared variable does not generate error.
ASP - 27
Exercise: Variable.asp
<% Option Explicit %>
<html><head><title>Variables</title><head>
<body>
<%
Dim x, y, x1, a, b, c
x=1
y=2
response.write x+y
x1=6
response.write x1 & "<br>"
a =5
b=7
c= a + b
response.write a + b & "<br>"
response.write a & b & "<br>"
%>
</body></html>
© Minder Chen, 1998-2002
Have to be the
first line
Declare a variable
with a data type
is not allowed:
Dim x as Integer
ASP - 28
Response Object: Write Method
<HTML><HEAD><TITLE>Hello World</TITLE>
</HEAD>
<BODY>
<% response.write "Hello World" %>
</BODY>
<HTML><HEAD><TITLE>Message</TITLE></HEAD><BODY
>
<%
Dim message
message = "Hello World"
Hello World
Response.Write message
%>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 29
Math Operations
<HTML><HEAD><TITLE>Math Operations</TITLE></HEAD><BODY>
<%
A = 7
B = 3
Response.Write
Response.Write
Response.Write
Response.Write
Response.Write
Response.Write
Response.Write
%>
</BODY></HTML>
© Minder Chen, 1998-2002
A & " +
"<BR>"
A & " "<BR>"
A & " *
"<BR>"
A & " /
" & B & " = " & A + B
" & B & " = " & A - B
" & B & " = " & A * B
" & B & " = " & A / B
7 + 3 = 10
7-3=4
7 * 3 = 21
7 / 3 = 2.33333333333333
ASP - 30
Decision Making and Branching
• To vary the flow of a script, you use conditional statements (also known as
control structures) to makes decisions during program execution.
• The conditional statements include test expressions that are evaluated as
the program runs and, based upon their results, control the program flow.
• The two control structures that you will learn include
– If…Then…Else
– Select Case.
© Minder Chen, 1998-2002
ASP - 31
Control Flow
True Block
False Block
© Minder Chen, 1998-2002
ASP - 32
• Dim MyDate 'Create a variable, MyDate
MyDate = #2/13/95# 'Assign a date to MyDate
' Test to see if MyDate is less than today's date
' (which is returned by the Now function).
' If it is, then MyDate is assigned today's date
If MyDate < Now Then MyDate = Now
• If value = 0 Then
sForeColor = "Red"
bBold = True
bItalic = True
End If
© Minder Chen, 1998-2002
ASP - 33
If…Then…Else and Nested If
If value = 0 Then
iForeColor = vbRed
bBold = True
bItalic = True
Else
iForecolor = vbBlack
bBold = False
bItalic = False
End If
© Minder Chen, 1998-2002
If value = 0 Then
iForeColor = vbRed
bBold = True
ElseIf value=1 Then
iForecolor = vbBlack
bBold = False
ElseIf value=2 Then
iForecolor = vbGreen
bBold = False
Else
iForecolor = vbBlue
bBold = False
End If
ASP - 34
Nested If
<HTML><HEAD><TITLE>Greeting</TITLE>
</HEAD>
<BODY>
<%
If Hour(Now) < 12 then
Response.Write "Good Morning"
Else
If Hour(Now) < 18 then
Response.Write "Good Afternoon"
Else
Response.Write "Good Night"
End If
End If
%>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 35
Making Decision Using Select Case
• A Select Case structure works with a single test expression that is evaluated
once at the top of the structure.
• The result of the expression is then compared with the values for each Case
in the structure. If there is a match, the block of statements associated with
that Case is executed.
• Use the Case Else statement to handle any condition that did not match a
specified case.
© Minder Chen, 1998-2002
ASP - 36
Example
Dim Color, MyVar
Sub ChangeBackground (Color)
MyVar = lcase (Color)
Select Case MyVar
Case "red" bgColor = "red"
Case "green" bgColor = "green"
Case "blue" bgColor = "blue"
Case Else bgColor = "white"
End Select
End Sub
© Minder Chen, 1998-2002
ASP - 37
Loops
<HTML><HEAD><TITLE>Loops</TITLE></HEAD><BODY>
<%
Dim iCount
For iCount = 1 to 5
1
Response.Write iCount
2
Response.Write "<BR>"
3
Next
4
For iCount = 10 to 0 step -2
5
Response.Write iCount
10
Response.Write "<BR>"
8
Next
6
%>
4
</BODY></HTML>
2
0
© Minder Chen, 1998-2002
ASP - 38
Loops Statements
• VBScript includes the following looping
constructions:
– Do...Loop: repeats statements while or until a test
condition is met.
– For...Next: repeats statements a specified number of
times.
– For Each element In group Next: repeats statements for
each occurrence of a specific item in a specified group.
© Minder Chen, 1998-2002
ASP - 39
Loop: Do While …… Loop
<%
Check condition at the
Dim Counter
beginning of the loop
Counter = 1
Do While Counter < 3
Response.Write "Counter = " & Counter & "<br>"
Counter = Counter + 1
Loop
%>
Counter = 1
Counter = 2
© Minder Chen, 1998-2002
ASP - 40
Do … Loop While
• Dim Counter
Counter = 1
Do
Response.Write "Counter = " & Counter & "<br>"
Counter = Counter + 1
Loop While Counter < 3
Check condition at
the end of the loop
© Minder Chen, 1998-2002
ASP - 41
Do Until
• To check the test condition at the beginning of the
loop, change the following statement:
Do While Counter<3 …. Loop
to the following:
Do Until Counter>=3 … Loop
• To check the condition at the end of the loop,
change the following statement:
Do … Loop While Counter<3
to the following:
Do … Loop Until Counter>=3
© Minder Chen, 1998-2002
ASP - 42
Square Number
• Display the smallest positive integer that, when
squared, is larger than 1037.
<HTML><HEAD><TITLE>Square Number</TITLE>
</HEAD><BODY>
<%
Dim iResult, iTest
iTest = 1
Do Until iResult > 1037
iTest = iTest + 1
iResult = iTest * iTest
Loop
Response.Write iTest
%>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 43
Exercise: Form Input Data Processing
<input type=text name=UserName>
© Minder Chen, 1998-2002
ASP - 44
Array.asp
<html>
<%
DIM x(3)
x(0) = 1
x(1) = 2
x(2) = 3
x(3) = 4
%>
<head><title>New Page 1</title></head><body>
<%
For k = 0 to Ubound(x)
Response.Write( "x(" & k & ")=" & x(k) & "<br>")
Next
' Total = x(0) + x(1) + x(2) + x(3)
Total = 0
For k = 0 to Ubound(x)
Total = Total + x(k)
Next
Response.Write( "The total is=" & Total)
%>
</body></html>
© Minder Chen, 1998-2002
ASP - 45
Form Input Data Processing
form4.htm
<HTML><HEAD><TITLE>Form Input</TITLE></HEAD><BODY>
<FORM METHOD=POST ACTION="answer04.asp">
Name: <INPUT TYPE=TEXT NAME="UserName">
<INPUT TYPE=SUBMIT>
</FORM></BODY></HTML>
answer04.asp
<HTML><HEAD><TITLE>Form Input Processing</TITLE></HEAD><BODY>
<%
Response.Write Request.Form("UserName")
%>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 46
Form.htm
<HTML><HEAD><TITLE>Order</TITLE></HEAD><BODY>
<H2>Sample Order Form</H2>
Please fill out this form, then click Submit:<P>
<FORM METHOD="POST" ACTION="response.asp">
First Name: <INPUT NAME="fname" SIZE="48"><br>
Last Name: <INPUT NAME="lname" SIZE="48"><br>
Title: <INPUT NAME="title" TYPE=RADIO VALUE="mr">Mr.
<INPUT NAME="title" TYPE=RADIO VALUE="ms">Ms.
<P><INPUT TYPE=SUBMIT><INPUT TYPE=RESET>
</FORM></BODY></HTML>
http://127.0.0.1/vbscriptlab/form.htm
© Minder Chen, 1998-2002
ASP - 47
Response.asp
<%@ LANGUAGE = VBScript %>
<HTML>
<HEAD><TITLE>Response.asp File</TITLE></HEAD>
<BODY BGCOLOR="#FFFFFF"><FONT FACE="ARIAL,HELVETICA">
<H2><CENTER>Order Received</CENTER></H2>
<P ALIGN=CENTER>
<%= Request.Form("fname") & " " & Request.Form("lname")%>
</FONT>
</BODY>
</HTML>
© Minder Chen, 1998-2002
ASP - 48
Response2.asp
<%@ LANGUAGE = VBScript %>
<HTML>
<HEAD><TITLE>Response.asp File</TITLE></HEAD>
<BODY BGCOLOR="#FFFFFF"><FONT FACE="ARIAL,HELVETICA">
<H2><CENTER>Order Received</CENTER></H2>
<P ALIGN=CENTER>
<% Title = Request.Form("title") %>
<% LastName = Request.Form("lname") %>
<%If Title = "mr" Then %>
Mr. <%= LastName %>
Change the action attribute
<% ElseIf Title = "ms" Then %>
of form.htm to response2.asp
Ms. <%= LastName %>
and save it as form2.htm
<% Else %>
<%= Request.Form("fname") & " " & LastName %>
<% End If %>
</FONT>
</BODY>
</HTML>
© Minder Chen, 1998-2002
ASP - 49
Exercise: Calculator
• Operator can be: +, -, *, /
• Check divide-by-zero error
Cal.htm
A*B=600
© Minder Chen, 1998-2002
ASP - 50
Cal.htm
<HTML><HEAD><TITLE>Calculator</TITLE></HEAD><BODY>
<form method="post" action="cal.asp">
First Number: <Input type="text" name="x1"><br>
Operator is:
<select name="op">
<option>+
<option><option>*
<option>/
</select><br>
Second Number: <Input type="text" name="x2"><br>
<input type="submit" value="Calculate" >
</form>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 51
Cal.asp
<HTML><HEAD><TITLE>Calculator</TITLE></HEAD><BODY>
<%
If Request.Form("x1")="" Then
Response.Write "The first number is missing <br>"
If Request.Form("x2")="" Then
Response.Write "The 2nd number is missing <br>"
End If
Response.end
Else
If Request.Form("x2")="" Then
Response.Write "The 2nd number is missing <br>"
Response.End
End If
End If
A = CSng(Request.Form("x1")) ' Convert to single precision
B = CSng(Request.Form("x2"))
© Minder Chen, 1998-2002
ASP - 52
Continued...
Select Case Request.Form("op")
Case "+"
C=A+B
Response.write "A+B=" & C
Case "-"
C=A-B
Response.write "A-B=" & C
Case "*"
C=A*B
Response.write "A*B=" & C
Case "/"
If B<>0 Then
Temp=A/B
C=Round(Temp,2) ' Round it to 2 decimal places
Response.Write "A/B=" & C
Else
Response.write "The second number cannot be zero." & "<br>"
Response.write "Use BACK navigation button to change it!" & "<br>"
End If
Case Else
Response.Write "You need to choose an operator"
End Select
%>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 53
Running VBScripts
 Inline. If you add script outside of a procedure, the script runs
when the browser encounters it as the page downloads. This is
useful if you want to initialize data or objects on the page.
 Procedures. If you add script in a procedure, the script runs
when the procedure is explicitly invoked. Procedures that return
information are called functions; those that do not return
information are called subroutines.
 Event procedures. (Client-side VB Scripting only). If you add
script in an event procedure, the script runs when the event
occurs. For example, if you create an OnClick event procedure
for a button, the script runs when the user clicks the button.
© Minder Chen, 1998-2002
ASP - 54
Use Procedures to Structured Code
• Structured code consists of compact chunks of related
code that are termed procedures.
• Procedures are reusable code that can be called from
anywhere in your script.
• The main benefits of structured coding are as follows:
– Maintenance—when related code is grouped, it is easier to
maintain. When code needs to be updated or modified, you can
make the changes in a single code segment rather than
throughout an entire program.
– Debugging—because the code is modular, you can pinpoint
where an error occurs and conduct your debugging efforts in
the code segment where the error occurred.
– Reusability—you can call the procedures from anywhere in your
script, as well as use the code segments in other programs that
require the same procedures.
© Minder Chen, 1998-2002
ASP - 55
Exercise: sub1.asp
<HTML><HEAD><TITLE>Subroutine</TITLE>
<%
Sub MySub(iNum)
Response.Write iNum * iNum
sub2.asp
End Sub
<HTML><HEAD><TITLE>Subroutine</TITLE>
%>
<%
Sub MySub(iNum, iSquare)
</HEAD><BODY>
iSquare = iNum * iNum
End Sub
<%
%>
Dim a
</HEAD><BODY>
<%
a = 20
Dim a, b
a = 20
MySub a
MySub a, b
Response.write "The square value of " & a & " is " & b
%>
%>
</BODY></HTML>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 56
Scope of a Variable
• If a variable is declared outside of a procedure,
it is visible throughout the program.
• If a variable is declared inside a procedure, it is
only visible inside that procedure.
• The range of a variable’s visibility is called its
scope.
• In VBScript:
–
–
–
–
Scope is either script-level or procedure-level.
A variable is in effect within its scope.
Variable names must be unique within their scope.
Variables should always be defined with the smallest
scope possible.
© Minder Chen, 1998-2002
ASP - 57
Scope and Lifetime of a Variable
• Script-level variables:
– When you declare a variable outside a procedure, it is
recognizable to all the procedures in your script. This is a scriptlevel variable and has script-level scope.
– The names of script-level variables must be unique throughout
the program.
– The lifetime of a script-level variable extends from the time it is
declared until the script finishes running.
• Procedure-level variables:
– When you declare a variable within a procedure, only code
within that procedure can access or change the value of that
variable.
– It has local scope and is called a procedure-level variable.
– At procedure level, a variable exists only as long as you are in
the procedure. When the procedure exits, the variable is
destroyed.
– You can have local variables of the same name in several
different procedures because each is recognized only by the
procedure in which it is declared.
© Minder Chen, 1998-2002
ASP - 58
Global and Local Variable
<%
SUB X()
DIM A
A=3
End Sub
Dim A
A=1
X
Response.write A
%>
© Minder Chen, 1998-2002
ASP - 59
Tempconvert.asp
<%
Sub ConvertTemp(F)
temp = (F-32)/9*5
Response.Write "The temperature " & F & " degree F " & " is " & _
temp & " degrees C."
End Sub
ConvertTemp 12
%>
© Minder Chen, 1998-2002
round(temp, 2)
ASP - 60
Define and Use Procedures in JavaScript
<SCRIPT LANGUAGE=JScript RUNAT=Server>
function PrintDate()
{
var x
x = new Date()
Response.Write(x.toString())
}
</SCRIPT>
<html><head><title>Test</title></head>
<body>
<% PrintDate %>
</body></html>
• Do not include within <SCRIPT> tags any output
expressions or script commands that are not part of
complete procedures.
© Minder Chen, 1998-2002
ASP - 61
Define a Procedure (Subroutine)
• Define a procedure
Sub WriteSquare(inNum)
Dim outNum
outNum = inNum * inNum
Response.Write outNum
End Sub
• Call a procedure
Dim aNumber
aNumber = 5
Call WriteSquare (aNumber)
- or Dim aNumber
aNumber = 5
WriteSquare aNumber
© Minder Chen, 1998-2002
When you use the Call
statement to call a
procedure, enclose the
argument(s) in parentheses.
If there are no arguments,
you must include an empty
set of parentheses.
When you use only the
procedure name to call a
procedure, do not use
parentheses to enclose the
argument(s).
ASP - 62
Formal and Actual Arguments
Sub ShowProduct (Multiplicand, Multiplier)
Response.Write Multiplicand * Multiplier
Formal
arguments
End Sub
Dim x1, y1
x1=4
y1=5
Call ShowProduct (x1, y1)
- or Dim x1, y1
x1=4
y1=5
ShowProduct x1, y1
© Minder Chen, 1998-2002
Actual
arguments
ASP - 63
Functions
Function fName(arg1, arg2, ...)
...
fName = expression
...
End Function
• Create a variable with the same name as the Function.
• Assign the return value to that variable.
• Arguments, including constants, variables, and
expressions, are passed to the Function procedure,
which can then use the arguments.
• Function arguments are placed inside parentheses. If no
arguments are passed, empty parentheses are required.
© Minder Chen, 1998-2002
ASP - 64
Functions: temp2.asp
<%
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
Sub ConvertTemp(tempF, tempC)
tempC = Celsius(tempF)
Function Celsius(fDegrees)
appears before Sub
ConvertTemp() because the
Sub procedure, ConvertTemp,
calls the Function procedure,
Celsius.
End Sub
%>
<html><head><title>Temperature</title></head><body>
<%
Dim tempX
tempX = Request.Form("InTemp")
' Calls the Sub procedure
ConvertTemp tempX, tempY
Response.write tempY
Response.write " degrees C."
%>
© Minder Chen, 1998-2002
Temp2.htm
<HTML><HEAD><TITLE>Tempreture</TITLE></
HEAD>
<BODY>
<H2>Temperature Conversion Form</H2>
<FORM METHOD="POST"
ACTION="temp2.asp">
<P>
What is the temperature in Degree F: <br>
<INPUT NAME="inTemp" SIZE="48"><br>
<P><INPUT TYPE=SUBMIT><INPUT
TYPE=RESET>
</FORM></BODY></HTML>
ASP - 65
What Is an Object?
• An object is simply a collection of functions and data
grouped together. Typically, most of the object’s functionality
(particularly its data structure) is hidden from the programmer,
who uses the object’s interface, or model, to control the object.
The object’s interface consists of a published set of functions
and data. In pure object-oriented systems, data are private and
therefore cannot be accessed by external object directly.
• Methods: The procedures that an object exposes through its
interface are called methods. Methods are typically functions
and return a value.
• Properties: The variables that are part of an object are called
properties:
 Reading a property’s value is called getting the property’s value.
 Writing a value to a property is called setting the property’s value.
 Properties can be read-only or read/write depending on the design
of the object.
© Minder Chen, 1998-2002
ASP - 66
Declaring Objects
• Before you can use an object, you must declare it.
• In Active Server Pages (ASP), you use the CreateObject
method of the Server object to declare an instance of an object.
The Server object is a built-in object in IIS.
• The following code adds the ActiveX Tracer object to a page:
<%
Set objTrace = Server.CreateObject("IISSample.Tracer")
%>
• This code creates a copy, called an instance, of the object for the script to
work with. The instance of this ActiveX object has been named objTrace.
The programmer who wrote the object itself created the object's full name,
IISSample.Tracer.
• The IISSample.Trace object must be installed on the computer and registered
by using the Regsvr32.exe application. This is often done as part of the
object's setup program.
© Minder Chen, 1998-2002
ASP - 67
Object Property and Method
• You can create an instance of an object by using the
Server.CreateObject statement.
• An object can contain callable program code called methods and data
called properties.
• Dot notation
objectName.propertyName
objectname.methodName
objectname.methodName(arg1, arg2, …)
• For example, you create an instance of an object and name it objBanner. It
has properties named Text and Size and a method named Show.
• Read the value of the Text property into a variable named SLabel:
SLabel = objBanner.Text
• Set the Size property to 12:
objBanner.Size = 12
• Call the Show method of the objBanner object:
objBanner.Show
© Minder Chen, 1998-2002
ASP - 68
Build-in ASP Objects
Request Object
Cookies
Form
QueryString
ServerVariables
ClientCertificate
• Cookies
• (Properties)
• (Methods)
ObjectContext Object
• (Properties)
• (Methods)
MTS
Server Object
• (Properties)
• (Methods)
Server
Client
Response Object
•
•
•
•
•
Application Object
Session Object
• (Properties)
• (Methods)
• (Properties)
• (Methods)
© Minder Chen, 1998-2002
ASP - 69
Build-in ASP Objects
• Request Object
– Collections:





ClientCertificate
Cookies
Form
QueryString
ServerVariables
– Properties:
 TotalBytes
– Methods:
 BinaryRead
• Server Object
– Properties:
 ScriptTimeout
– Methods:




CreateObject
HTMLEncode
MapPath
URLEncode
© Minder Chen, 1998-2002
• Response Object
– Collections:
 Cookies
– Properties:









Buffer
CacheControl
Charset
ContentType
Expires
ExpiresAsolute
IsClientConnected
PICS
Status
– Methods:








AddHeader
AppendToLog
BinaryWrite
Clear
End
Flush
Redirect
Write
ASP - 70
Build-in ASP Objects
• Application Object
– Collections:
 Contents
 StaticObjects
– Methods:
 Lock
 Unlock
– Events:
 Application_OnEnd
 Application_OnStart
• ObjectContext Object
– Methods:
 SetAbort
 SetComplete
• Session Object
– Collections:
 Contents
 StaticObjects
– Properties:




CodePage
LCID
SessionID
Timeout
– Methods:
 Abandon
– Events:
 Session_OnEnd
 Session_OnStart
– Events:
 OnTransactionAbort
 OnTransactionCommit
ObjectContext Object is used when you are running
Microsoft Transaction Server (MTS)
© Minder Chen, 1998-2002
ASP - 71
Setting the Content Type
• For example, the following command sets the
content type for channel definitions:
<% Response.ContentType = "application/x-cdf" %>
© Minder Chen, 1998-2002
ASP - 72
Redirecting the Browser
<%
If Session("CustomerID") = 0 Then
response.Redirect "Homepage.asp"
End If
%>
•
•
Unless your have buffer turned on, you must redirect the browser before any
content or header are returned to the browser.
Place the Response.Redirect statement at the top of the page, before any text
or <HTML> tags, to ensure that nothing has been returned to the browser. If
you use Response.Redirect after content or headers have been returned to
the browser, you will see an error message such as the following one:
Response object error 'ASP 0156 : 80004005'
Header Error
/students/asptutor/page2.asp, line 4
The HTTP headers are already written to the client browser. Any HTTP header
modifications must be made before writing page content.
© Minder Chen, 1998-2002
ASP - 73
QueryString Collection
• The QueryString collection retrieves form values
passed to your Web server using HTTP GET method
or retrieves variable-value pairs set as text followed a
question mark in the request URL.
• Example:
<FORM METHOD="GET" ACTION="profile.asp">
<INPUT TYPE="text" NAME="firstname">
<INPUT TYPE="text" NAME="lastname">
<INPUT TYPE="text" NAME="age">
<INPUT TYPE="hidden" NAME="userstatus" VALUE= "new">
<INPUT TYPE="submit" VALUE="Enter">
</FORM>
© Minder Chen, 1998-2002
ASP - 74
Process Input Data from the QueryString
• If the user typed Jeff, Smith, and 30, then the following URL
request would be sent to the server:
• http://scripts/profile.asp?firstname=Jeff&lastname=Smith&age=30
&userstatus=new
• profile.asp:
Hello, <%= Request.QueryString("firstname") %>
<%= Request.QueryString("lastname") %>.
You are <%= Request.QueryString("age") %> years old.
<%
If Request.QueryString("userstatus") = "new user" then
Response.Write "This is your first visit to this Web site!"
End if
%>
• Hello, Jeff Smith. You are 30 years
old. This is your first visit to this
Web site!
© Minder Chen, 1998-2002
ASP - 75
Multiple Values of a Variable
• The QueryString collection has an optional parameter
Counter that you can to count the number of times that a
specific variable appears.
• A request of a form containing a list box with multiple items:
http://scripts/list.asp?food=apples&food=olives&food=bread
• Command to count multiple values:
Request.QueryString("food").Count
• To display the multiple values types, List.asp could contain the
following script:
<%Total = Request.QueryString("food").Count%>
<%For i = 1 to Total%>
<%= Request.QueryString("food")(i) %> <BR>
<%Next%>
• The preceding script would display:
apples
olives
bread
© Minder Chen, 1998-2002
ASP - 76
Exercise: foodform.asp, food.asp, computer.asp
<html><head><title>Food</title></head>
<body>
<form method="GET" action="food.asp">
<p><select size="3" name="food" multiple>
<option>Apple</option>
<option>Bread</option>
<option>Pineapple</option>
<option>Orange</option>
<option>Rice</option>
</select></p>
<p>
<input type="submit" value="Submit" name="B1">
<input type="reset" value="Reset" name="B2"></p>
</form>
<a href="computer.asp?id=<%=Server.URLEncode("apple computer")%>">
I like apple computer </a><br>
<a href="computer.asp?id=Intel computer">I like Intel computer </a>
</body></html>
© Minder Chen, 1998-2002
ASP - 77
Food.asp
<html><head><title>Food selection</title></head>
<body>
Food items selected in the list: <% = Request.QueryString("food") %>
<% response.write "<hr>" %>
Individual food items selected:
<%Total = Request.QueryString("food").Count%>
<%For i = 1 to Total%>
<%= Request.QueryString("food")(i) %> <BR>
<%Next%>
</body></html>
computer.asp
<html><head><title> Apple.asp </title></head>
<body>
<% = "The food you like: " & Request.querystring("ID") %>
</body></html>
© Minder Chen, 1998-2002
ASP - 78
Using Installable Components
• There are a number of components that are installed with IIS
that your application can call upon to perform a wide variety of
tasks.










Ad Rotator: Demonstrates how to use the Ad Rotator component in an ASP script.
File Access: Illustrates techniques that you can use in scripts to get the most out of the
File Access component.
Browser Capabilities: Illustrates how you can maximize the potential of your Web
application by using the Browser Capabilities component in an ASP script.
Collaboration Data Objects: Illustrates ways for you to use the Collaboration Data
Objects (CDO).
Content Rotator: Demonstrates how you can use the Content Rotator component to
create dynamic, informative applications.
Permission Checker: Illustrates techniques you can use to incorporate authentication
and access control into your ASP script with the Permission Checker component.
Counters: Demonstrates how you can use the Counters component.
Tools: Illustrates techniques you can use to easily add sophisticated functionality to you
Web pages with the Tools component.
Index: Demonstrates how you can access some of the features of Index Server that are
exposed to ASP scripts
Page Counter: Illustrates how you can configure and query the Page Counter component
using ASP scripts .
© Minder Chen, 1998-2002
ASP - 79
Counter.asp: The Page Counter Component
• Page Counter component provides a simple page counter
that you can use on any Web page. The following Web
page demonstrates the simplest way to use the counter:
<HTML><HEAD><TITLE>Page Counter Example</TITLE>
</HEAD><BODY>
<%
Set MyPageCounter = Server.CreateObject("MSWC.PageCounter")
MyPageCounter.PageHit ()
%>
This Web page has been viewed
<%= MyPageCounter.Hits %> times.
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 80
Using IsObject() To Verify Object Creation
• When you use the Server method CreateObject, it is often difficult to tell
when an object creation has failed, particularly when you are using an On
Error Resume Next error trapping routine. You can use the IsObject
function to test for the existence of your object before trying to use a
property or method.
• Testing your objects before using them can save embarrassing Web page
errors.
• In the following code, we have used the IsObject function to make sure our
CDONTS.NewMail object has been successfully created:
<%
SET objMail = CreateObject("CDONTS.NewMail")
IF IsObject(objMail) THEN
objMail.Send Request.Form("From"), Request.Form ("To"), _
Request.Form ("Subject"), Request.Form("Body")
SET objMail = NOTHING
ELSE
Response.write("Mail has not been sent")
END IF
%>
© Minder Chen, 1998-2002
ASP - 81
Use ADO
• The Database Access component uses Active Data
Objects (ADO) to provide easy access to
information stored in a database that complies with
the Open Database Connectivity (ODBC) standard.
• You will learn how to extract data using the SQL
SELECT statement and create an HTML table to
display the results.
© Minder Chen, 1998-2002
ASP - 82
SQL: Data Manipulation Language (DML)
Data Definition Language (DDL)
Data
Manipulation
Language
(DML)
SELECT
UPDATE
INSERT
DELETE
Database Schema - Product Table
p_no
name
quantity
price
101
201
202
Color TV
B&W TV
PC
24
10
5
500
250
2000
SELECT p_no, name, price
FROM PRODUCT
WHERE PRICE < = 1000
ORDER BY PRICE DESC;
© Minder Chen, 1998-2002
p_no
------101
201
name
--------------Color TV
B&W TV
price
---------500
250
ASP - 83
Sample Data Base: Access expense.mdb
EmailAddress
© Minder Chen, 1998-2002
ASP - 84
Employee Table
EmailAddress
© Minder Chen, 1998-2002
Text
ASP - 85
Identify the Database
• Before using a database with the Database Access component, you must
identify the database in the ODBC application in Control Panel. In this
example, you will use a Microsoft® Access database that is provided with
the ASP sample Web site.
• At the computer running your Web server, open Control Panel.
• Double-click the ODBC icon, and then click System DSN.
• There are two types of data sources: User, which is available only to you,
and System, which is available to anyone using the computer. Data
sources for use with the Web server need to be of the System type.
• Click Add, choose the Microsoft Access Driver, and then click Finish.
In the Data Source Name box, type ASP Tutorial DB, and then click
Select. Select the c:\Webshare\asp\AdvWorks.mdb file and click OK.
• Click OK to close the dialog boxes.
Database security for Access using ASP
http://www.aspemporium.com/aspEmporium/forum/display_message.asp?mid=1981&fid=11
http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q253604&
© Minder Chen, 1998-2002
ASP - 86
Set Up ODBC Data Source
© Minder Chen, 1998-2002
ASP - 87
Department List
<form action="xxx.asp" method="post">
<a href="xxx.asp?id=all&y=3">Department List</a>
1
Dynamically generated
web page
5
Expense
2
SQL statement
ASP
Script
Format result set
cursor
Departments
table
Record set
100
100
4
© Minder Chen, 1998-2002
3
ASP - 89
Deptlist.asp
<HTML><HEAD><TITLE>Department Listing</TITLE></HEAD><BODY>
<H1>Department List</H1>
<%
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery ="SELECT * FROM Departments"
Set RSDeptList = dbConnection.Execute(SQLQuery)
%>
<UL>
<% Do While Not RSDeptList.EOF %>
<LI>
<%= RSDeptList("ID")%> &nbsp;
<%= RSDeptList("name")%> :&nbsp;
<%= RSDeptList("description")%>
<%
RSDeptList.MoveNext
Loop
dbConnection.close
set dbConnection = Nothing
%>
</UL></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 90
Using Table
© Minder Chen, 1998-2002
ASP - 91
ASP Code
<%@ LANGUAGE = VBScript %>
<HTML><HEAD>
<TITLE>Department Listing</TITLE></HEAD><BODY>
<H1>Department List</H1>
<!-- ADO Connection -->
<%
Set dbConnection=Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery = "SELECT * FROM Departments"
Set RSDeptList = dbConnection.Execute(SQLQuery)
%>
© Minder Chen, 1998-2002
ASP - 92
ASP Code
<TABLE COLSPAN=8 CELLPADDING=5 BORDER=1>
<!-- BEGIN column header row -->
<TR>
<TD>ID</TD>
<TD>Name</TD>
<TD>Description</TD>
</TR>
<!-- Tutorial Lesson - Display ADO Data -->
<% Do While Not RSDeptList.EOF %>
<TR>
<TD> <%= RSDeptList("ID")%> </TD>
<TD> <%= RSDeptList("name")%></TD>
<TD> <%= RSDeptList("description")%> </TD>
</TR>
<!-- Next Row -->
<%
RSDeptList.MoveNext
Loop
dbConnection.close
set dbConnection = Nothing
%>
</TABLE></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 93
Generate an Employee List Web Page Dynamically
© Minder Chen, 1998-2002
ASP - 94
ASP Code: emp_mail.asp
<%@ LANGUAGE = VBScript %>
<HTML><HEAD>
<TITLE>Customer Listing</TITLE></HEAD><BODY>
<H1>Employee List</H1>
<!-- ADO Connection -->
<%
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery = "SELECT * FROM Employees"
Set RSEmployeeList = dbConnection.Execute(SQLQuery)
%>
<TABLE COLSPAN=8 CELLPADDING=5 BORDER=1>
<!-- BEGIN column header row -->
<TR>
<TD>Employee ID</TD>
<TD>Employee Name</TD>
<TD>Title</TD>
<TD>Department ID</TD>
<TD>E-Mail Address</TD>
</TR>
© Minder Chen, 1998-2002
ASP - 95
Creating Hypertext Link
<% Do While Not RSEmployeeList.EOF %>
<TR>
<TD><%= RSEmployeeList("EmployeeID")%> </TD>
<TD><%= RSEmployeeList("FirstName") & " " & RSEmployeeList("LastName") %></TD>
<TD><%= RSEmployeeList("Title")%> </TD>
<TD><%= RSEmployeeList("DepartmentID")%> </TD>
<!--<a href="mailto:[email protected]">Send E-mail to</a>[email protected]</a> -->
<TD> <a
href="mailto:<%= RSEmployeeList("EmailAddress")%>">
Send E-mail to </a>
<%= RSEmployeeList("EmailAddress")%></TD>
</TR>
<!-- Next Row -->
<%
RSEmployeeList.MoveNext
Loop
dbConnection.close
set dbConnection = Nothing
%></TABLE></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 96
Revised Version
<% Do While Not RSEmployeeList.EOF %>
<TR><TD><%= RSEmployeeList("EmployeeID")%> </TD>
<TD><%= RSEmployeeList("FirstName") & " " & RSEmployeeList("LastName") %></TD>
<TD><%= RSEmployeeList("Title")%> &nbsp; </TD>
<TD><%= RSEmployeeList("DepartmentID")%> </TD>
<% if NOT ISNull(RSEmployeeList("EmailAddress"))THEN %>
<TD> <a href="mailto:<%= RSEmployeeList("EmailAddress")%>">
Send E-mail to </a>
<%= RSEmployeeList("EmailAddress") %></TD>
<% else %>
<td>No email</td></td>
<% end if %>
</TR>
<!-- Next Row -->
<%
RSEmployeeList.MoveNext
Loop
dbConnection.close
set dbConnection = Nothing
%>
</TABLE></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 97
OLE DB Connection String
• Microsoft Access
– Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=physical path to database file
• Microsoft SQL Server
– Provider=SQLOLEDB.1;Data Source=path to
server
• Oracle
– Provider=MSDAORA.1;Data Source=path to
server
• Microsoft Indexing Service
– Provider=MSIDXS.1;Data Source=path to index
file
© Minder Chen, 1998-2002
ASP - 98
Insert
<%
'Define the OLE DB connection string.
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb"
'Instantiate the Connection object and open a database connection.
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open strConnectionString
'Define SQL SELECT statement.
strSQL = "INSERT INTO Customers (FirstName, LastName) VALUES ('Jose','Lugo')"
'Use the Execute method to issue a SQL query to database.
cnn.Execute strSQL, ,adCmdText + adExecuteNoRecords
%>
© Minder Chen, 1998-2002
ASP - 99
Update and Delete
<%
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb"
cnn.Execute _
"UPDATE Customers SET FirstName ='Jeff' WHERE LastName = 'Smith' " _
, ,adCmdText + adExecuteNoRecords
%>
<%
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb"
cnn.Execute _
"DELETE FROM Customers WHERE LastName = 'Smith'" _
,,adCmdText + adExecuteNoRecords
%>
© Minder Chen, 1998-2002
ASP - 100
Authors.mdb
• The database can be found at
http://65.168.115.6/asp/database
or locally at c:\InetPub\IISSamples\asp\database
• Need to give Everyone Group
Read Write access to the database
© Minder Chen, 1998-2002
ASP - 101
SimpleQuery.asp
<%@ LANGUAGE = VBScript %>
<% Option Explicit
%>
<HTML><HEAD><TITLE>Simple ADO Query</TITLE></HEAD>
<BODY BGCOLOR="White" topmargin="10" leftmargin="10">
<!-- Display Header --><font size="4" face="Arial, Helvetica">
<b>Simple ADO Query with ASP</b></font><br><hr size="1" color="#000000">
Contacts within the Authors Database:<br><br>
<%
Dim oConn
Dim oRs
Dim filePath
Dim Index
' Map authors database to physical path
filePath = Server.MapPath("../authors.mdb")
' Create ADO Connection Component to connect with sample database
Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath
© Minder Chen, 1998-2002
ASP - 102
Continued…
' Execute a SQL query and store the results within record set
Set oRs = oConn.Execute("SELECT * From authors")
%>
<TABLE border = 1>
<%
Do while (Not oRs.eof) %>
<tr>
<% For Index=0 to (oRs.fields.count-1) %>
<TD VAlign=top><% = oRs(Index) %></TD>
<% Next %>
</tr>
<% oRs.MoveNext
Loop
%>
</TABLE>
<%
oRs.close
oConn.close
%></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 103
InsertDelete.asp
<% Option Explicit %>
<% Response.Expires= -1 %>
<HTML><HEAD><TITLE>Add/Delete Database Sample</TITLE></HEAD>
<BODY BGCOLOR="White" topmargin="10" leftmargin="10">
<font size="4" face="Arial, Helvetica"><b>Add/Delete Database
Sample</b></font><br><hr size="1" color="#000000">
<%
Dim oConn
Dim oRs
Dim filePath
' Map authors database to physical path
filePath = Server.MapPath("../Authors.mdb")
' Create ADO Connection Component to connect with sample database
Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath
' To add, delete and update recordset, it is recommended to use
' direct SQL statement instead of ADO methods.
oConn.Execute "insert into authors (author, YearBorn) values ('Paul Enfield', 1967)"
© Minder Chen, 1998-2002
ASP - 104
Continued…
' Output Result
Set oRs = oConn.Execute (" select * from authors where Author= 'Paul Enfield' and YearBorn =1967 " )
Response.Write("<p>Inserted Author: " & oRs("Author") & "," & oRs("YearBorn"))
' Close Recordset
oRs.Close
Set oRs= Nothing
' Delete the inserted record
oConn.Execute "Delete From authors where author='Paul Enfield' and YearBorn = 1967 "
' Output Status Result
Response.Write("<p>Deleted Author: Paul Enfield, 1967")
%>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 105
Insert.asp?name=Justin&year=1988
oConn.Execute _
2
4
"insert into authors (author, YearBorn) values ('Paul Enfield', 1967)"
1
strSQL =
5
3
_
"insert into authors (author, YearBorn) values ('"
&
&
&
&
_
request.QueryString("name") _
"'," _
request.QueryString("year") _
")"
oConn.Execute strSQL
© Minder Chen, 1998-2002
ASP - 106
Insert.asp?name=Justin&year=1988
<% Option Explicit %>
<% Response.Expires= -1 %>
<HTML><HEAD><TITLE>Add/Delete Database Sample</TITLE></HEAD>
<BODY BGCOLOR="White" topmargin="10" leftmargin="10">
<font size="4" face="Arial, Helvetica"><b>Add/Delete Database Sample</b></font><br><hr size="1"
color="#000000">
<%
Dim oConn
Dim oRs
Dim filePath
filePath = Server.MapPath("../database/Authors.mdb")
Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath
DIM strSQL
strSQL = _
"insert into authors (author, YearBorn) values ('" _
& request.QueryString("name") _
& "'," _
& request.QueryString("year") _
& ")"
Response.write strSQL & "<br>"
oConn.Execute strSQL
Response.write "Inserted successfully"
%>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 107
Exercise
Emplist.asp
Empmenu.htm
Emplistget.asp
© Minder Chen, 1998-2002
ASP - 108
Empmenu.htm
<HTML><HEAD><TITLE>Employee Data Maintenance</TITLE></HEAD>
<BODY><font size=+1><p align="center">
<b>Employee Data Maintenance</b></font>
<center><big><b>
<form action="emplist.asp">
<input type="submit" value=" List employee data "></form>
<form action="empupdateselect.htm">
<input type="submit" value=" Update employee data "></form>
<form action="empinsert.htm">
<input type="submit" value=" Insert new employees "></form>
<form action="empdeleteselect.htm">
<input type="submit" value=" Delete employee record "></form>
<form action="empteamselect.htm">
<input type="submit" value=" Select team members "></form>
</big></b></center></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 109
Emplist.asp
<%
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery = "SELECT * FROM Departments"
Set RSDeptList = dbConnection.Execute(SQLQuery) %>
<HTML><HEAD><TITLE>List Employee Data </TITLE></HEAD><BODY>
<big><b>List Employee Data </b><br>
Select one or all departments to list employees:<br>
<form action="emplistget.asp" method=POST>
<select name="dept">
<option value="all">- -All the departments- <% Do While Not RSDeptList.EOF %>
<option value = " <%= RSDeptList("ID")%> " >
<%= RSDeptList("name")%>:<%= RSDeptList("description")%>
<% RSDeptList.MoveNext
Loop %>
</select><br><br>
<input type="submit" value="Retrieve employees ">
</form></big></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 110
Emplistget.asp
<%@ LANGUAGE = VBScript %>
<%
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
If Request.Form("dept") = "all" Then
SQLQuery = "SELECT * FROM Employees"
Else
SQLQuery = "SELECT * FROM Employees WHERE DepartmentID =" & _
Request.Form("dept")
End If
Set RSEmpList = dbConnection.Execute(SQLQuery)
%>
© Minder Chen, 1998-2002
ASP - 111
<HTML><HEAD><TITLE>List Employee Data </TITLE></HEAD><BODY>
<% If Request.Form("dept") = "all" Then
Response.Write "<big>Employees from all the departments</big><p>"
else
SQLQuery2 = "SELECT * From Departments Where ID = " & Request.Form("dept")
Set RSDeptList = dbConnection.Execute(SQLQuery2)
Response.Write "<big>Employees from <br>" & RSDeptList("name") & " : " & _
RSDeptList("description") & "</big><p>"
End If
%>
<Table border=2>
<tr><th>ID</th><th>Name</th></tr>
<% Do While Not RSEmpList.EOF %>
<tr><td><%= RSEmpList("EmployeeID") %></td>
<td><%= RSEmpList("LastName")%>,<%= RSEmpList("FirstName")%></td></tr>
<%
RSEmpList.MoveNext
Loop %>
</table>
<a href="empmenu.htm">Back to Main Menu</a>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 112
Add a New Employee
Empinsert.htm
Empinsert.asp
© Minder Chen, 1998-2002
ASP - 113
Emplist2.asp (for Testing Purpose)
<% Set dbConnection=Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery="Select * From Employees"
Set RSEmpList=dbConnection.Execute(SQLQuery) %>
<html><head><title>List Employee Data</title></head><body>
<%
Response.Write "<big>Employees from all the departments</big><p>" %>
<table colspan=8 cellpadding=5 border=1>
<tr><th>ID</th><th>Name</th></tr>
<% Do While Not RSEmpList.EOF %>
<tr>
<td><%=RSEmpList("EmployeeID")%></td>
<td><%=RSEmpList("LastName") & ", " & RSEmpList("FirstName")%></td>
</tr>
<% RSEmpList.MoveNext
Loop%>
<%
dbConnection.Close
Set dbConnection=Nothing %>
</table><p>
<a href="empmenu.htm">Back to Main Menu</a>
</body></html>
© Minder Chen, 1998-2002
ASP - 114
Empinsert.htm
<HTML><HEAD><TITLE>Add a New Employee</TITLE></HEAD><BODY>
<font size=+1><b>Add a New Employee</font>
<big><b>
<form action="empinsert.asp" method=POST>
<table>
<tr><td align=right>Employee Last name: </td>
<td><Input type=text name="LastName"> </td></tr>
<tr><td align=right>Employee First Name: </td>
<td><Input type=text name="FirstName"> </td></tr>
<tr><td align=right>Employee Department ID: </td>
<td><Input type=text name="DepartmentID"> </td></tr>
</table>
<input type="submit" value="Insert a new employees "></form>
</big></b>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 115
Empinsert.asp
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
FUNCTION CheckString (s, endchar)
pos = InStr(s, "'")
While pos > 0
s = Mid(s, 1, pos) & "'" & Mid(s, pos + 1)
pos = InStr(pos + 2, s, "'")
Wend
CheckString="'" & s & "'" & endchar
END FUNCTION
Change O'mer to O''mer
</SCRIPT>
CheckString ("O'mer", ",")
<%
msg=""
returns 'O''mer',
' Do Some form validation
If Request.Form("FirstName") = "" OR _
Request.Form("LastName") = "" OR _
Request.Form("DepartmentID") = "" Then
msg="<P><B><I>All fields must have a valid non-empty response.</I></B>"
End If
© Minder Chen, 1998-2002
ASP - 116
insert into Employees (FirstName, LastName, DepartmentID) VALUES ( 'Smith','Jack',200)
If msg = "" Then
sql = "insert into Employees (FirstName, LastName, DepartmentID) VALUES ( "
sql = sql & CheckString(Request.Form("FirstName"),",")
sql = sql & CheckString(Request.Form("LastName"),",")
sql = sql & Request.Form("DepartmentID") & ")"
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open "expense"
Conn.Execute(sql)
End IF %>
<HTML><HEAD><TITLE>Insert New Employee Data</TITLE></HEAD><BODY>
<font size=+1><b>Insert New Employees Data</b></font>
<% =msg %>
<% If msg = "" Then
SET RSEmp = Conn.Execute("SELECT * FROM Employees WHERE " & _
" EmployeeID = (SELECT MAX(EmployeeID) FROM Employees)")
Response.Write("<p>New employee created successfully! <P>" & _
"Employee ID: " & RSEmp("EmployeeID") & "<p>")
Response.write("<a href=" & "empmenu.htm" & _
">Back to Employee Maintenance Menu</a>")
Conn.close
Else
%>
ASP - 117
© Minder Chen, 1998-2002
<form action="empinsert.asp" method=POST>
<table>
<tr><td align=right>Employee Last name: </td>
<td><Input type=text name="LastName"
value = "<% =Request.Form("LastName") %>"> </td></tr>
<tr><td align=right>Employee First Name: </td>
<td><Input type=text name="FirstName"
value = "<% =Request.Form("FirstName") %>"> </td></tr>
<tr><td align=right>Employee Department ID: </td>
<td><Input type=text name="DepartmentID"
value = "<% =Request.Form("DepartmentID") %>"> </td></tr>
</table>
<input type="submit" value="Insert a new employees "></form>
<% End If %>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 118
Delete Employees
Empdeleteselect.htm
Query Form
Empdeleteget.asp
Empdelete.asp
© Minder Chen, 1998-2002
ASP - 119
Empdeleteselect.htm
<HTML><HEAD><TITLE>Search Employee Data for
Deleting</TITLE></HEAD><BODY>
<font size=+1><b>Select Employees for Deletion</font>
<big><b>
<form action="empdeleteget.asp" method=POST>
<table>
<tr><td align=right>Employee ID: </td>
<td><Input type=text name="EmployeeID"> </td></tr>
<tr><td align=right>Employee Last name: </td>
<td><Input type=text name="LastName"> </td></tr>
<tr><td align=right>Employee First Name: </td>
<td><Input type=text name="FirstName"> </td></tr>
<tr><td align=right>Employee Department ID: </td>
<td><Input type=text name="DepartmentID"> </td></tr>
</table>
<input type="submit" value="Select employees for deletion"></form>
</big></b>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 120
Empdeleteget.asp
SELECT * FROM Employees WHERE 0=0 AND LastName LIKE 'CH%'
<% Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery = "SELECT * FROM Employees WHERE 0=0 "
If Request.Form("EmployeeID") <> "" Then
SQLQuery = SQLQuery & " AND EmployeeID = " & _
Request.Form("EmployeeID")
End IF
If Request.Form("LastName") <> "" Then
SQLQuery = SQLQuery & " AND LastName LIKE '" & _
Request.Form("LastName") & "%'"
End IF
If Request.Form("FirstName") <> "" Then
SQLQuery = SQLQuery & " AND FirstName LIKE '" & _
Request.Form("FirstName") & "%'"
End IF
If Request.Form("DepartmentID") <> "" Then
SQLQuery = SQLQuery & " AND DepartmentID = " & _
Request.Form("DepartmentID")
End IF
Set RSEmp = dbConnection.Execute(SQLQuery) %>
© Minder Chen, 1998-2002
ASP - 121
Dynamic SQL
• Embedding SQL queries that use dynamic parameters is a powerful
mechanism for linking variable inputs to database queries. However,
in more sophisticated applications, you will often want user inputs to
determine not only the content of queries but also the structure of
queries.
• Dynamic SQL allows you to dynamically determine (based on runtime
parameters) which parts of a SQL statement are sent to the database.
So if a user leaves a search field empty, for example, you could
simply omit the part of the WHERE clause that refers to that field. Or,
if a user does not specify a sort order, the entire ORDER BY clause
could be omitted.
• Dynamic SQL is implemented in ASP by using if statements to control
how the SQL statement is constructed.
• The WHERE 0=0 clause has no impact on the query submitted to the
database.
• But if none of the conditions is true, it ensures that the WHERE
clause does not result in a SQL syntax error.
© Minder Chen, 1998-2002
ASP - 122
<HTML><HEAD><TITLE>Delete Employee Data
</TITLE></HEAD><BODY>
<font size=+1><b>Delete Employee Data </b></font>
<p>
Check the checked box(es) to remove the employees to be deleted:
<Form Method=Post Action="empdelete.asp">
<% Do While Not RSEmp.EOF %>
<input type=checkbox name="employeeID" value=
" <% =RSEmp("EMployeeID") %>" > <%= RSEmp("EmployeeID")%> :
<% = RSEmp("FirstName")%> &nbsp; <%= RSEmp("LastName")%>
<br>
<%
RSEmp.MoveNext
Loop
%>
<p><input type="submit" value="Delete all the checked employees ">
</form></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 123
Empdelete.asp
DELETE FROM Employees WHERE EmployeeID IN (20, 63)
<%@ LANGUAGE = VBScript %>
<%
EmpID = Request.Form("EmployeeID")
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
sql="DELETE FROM Employees WHERE EmployeeID IN (" & EmpID & ")"
Set RSEmp = dbConnection.Execute(sql)
%>
<HTML><HEAD><TITLE>Delete Employee Data </TITLE></HEAD><BODY>
<big><b>
Employee data have been deleted successfully. </b> </big> <p>
Employee ID: <% =EmpID %>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 124
Empdeleteselect.asp
<HTML><HEAD><TITLE>Search Employee Data for Deleting</TITLE></HEAD><BODY>
<font size=+1><b>Select Employees for Deletion</font>
<big><b>
<form action="empdeleteget.asp" method=POST>
<table>
<tr><td align=right>Employee ID: </td>
<td><Input type=text name="EmployeeID"> </td></tr>
<tr><td align=right>Employee Last name: </td>
<td><Input type=text name="LastName"> </td></tr>
<tr><td align=right>Employee First Name: </td>
<td><Input type=text name="FirstName"> </td></tr>
<tr><td align=right>Employee Department ID: </td>
<td>
<select name="DepartmentID">
<!-- #include file ="deptoption.inc" -->
</select>
</td></tr>
</table>
<input type="submit" value="Select employees for deletion"></form>
</big></b>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 125
deptoption.inc
<%
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery = "SELECT * FROM Departments"
Set RSDeptList = dbConnection.Execute(SQLQuery)
%>
<% Do While Not RSDeptList.EOF %>
<option value = "<%= RSDeptList("ID")%> " >
<%= RSDeptList("name")%>:
<%= RSDeptList("description")%>
<% RSDeptList.MoveNext
Loop %>
© Minder Chen, 1998-2002
ASP - 126
Screen Snapshots
© Minder Chen, 1998-2002
ASP - 127
Empupdateselect.htm
<HTML><HEAD><TITLE>Search Employee for
Updating</TITLE></HEAD><BODY>
<font size=+1><b>Search Employees for Updating</font><big><b>
<form action="empupdateGet.asp" method=POST>
<table>
<tr><td align=right>Employee ID:
<td><Input type=text name="EmployeeID"></td></tr>
<tr><td align=right>Employee Last name:
<td><Input type=text name="LastName"> </td></tr>
<tr><td align=right>Employee First Name:
<td><Input type=text name="FirstName"> </td></tr>
<tr><td align=right>Employee Department ID:
<td><Input type=text name="DepartmentID"> </td></tr>
</table>
<input type="submit" value="Find employees for updating "></form>
</b></big></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 128
Empupdateget.asp
<%@ LANGUAGE = VBScript %>
<%
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery = "SELECT * FROM Employees WHERE 0=0 "
If Request.Form("EmployeeID") <> "" Then
SQLQuery = SQLQuery & " AND EmployeeID = " & Request.Form("EmployeeID")
End IF
If Request.Form("LastName") <> "" Then
SQLQuery = SQLQuery & " AND LastName LIKE '" & Request.Form("LastName") & "%'"
End IF
If Request.Form("FirstName") <> "" Then
SQLQuery = SQLQuery & " AND FirstName LIKE '" & Request.Form("FirstName") & "%'"
End IF
If Request.Form("DepartmentID") <> "" Then
SQLQuery = SQLQuery & " AND DepartmentID = " & Request.Form("DepartmentID")
End IF
Set RSEmp = dbConnection.Execute(SQLQuery)
%>
© Minder Chen, 1998-2002
ASP - 129
<HTML><HEAD><TITLE>List Employee Data </TITLE></HEAD><BODY>
<font size=+1><p align="center"><b>List Employee Data </b></font>
<big><b>
Select employees to be updated:
<UL>
<% Do While Not RSEmp.EOF %>
<LI>
[<a href="empupdate.asp?EmployeeID=<% =RSEmp("EmployeeID") %>">
Update</a>]
<%= RSEmp("EmployeeID")%> : <%= RSEmp("FirstName")%> &nbsp;
<%= RSEmp("LastName")%>
<%
RSEmp.MoveNext
Loop
%>
<p>
</big></b>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 130
Empupdate.asp
<%
EmpID = Request.QueryString("EmployeeID")
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery = "SELECT * FROM Employees WHERE EmployeeID = " & EmpID
Set RSEmp = dbConnection.Execute(SQLQuery)
%>
<HTML><HEAD><TITLE>Update Employee Data
</TITLE></HEAD><BODY>
<font size=+1><p align="center"><b>List Employee Data </b></font>
<center><big><b>
© Minder Chen, 1998-2002
ASP - 131
Update the employee:
<form action="empupdateconfirm.asp" method=POST>
<table>
<tr><td align=right>Employee ID: </td><td><% =RSEmp("EmployeeID")
%></td></tr>
<Input type=hidden name="EmployeeID" value=
<% =RSEmp("EmployeeID") %>>
<tr><td align=right>Employee Last name: <td><Input type=text
name="LastName" value=<% =RSEmp("LastName") %>> </td></tr>
<tr><td align=right>Employee First Name: <td><Input type=text
name="FirstName" value=<% =RSEmp("FirstName") %>> </td></tr>
<tr><td align=right>Employee Department ID: <td><Input type=text
name="DepartmentID" value=<% =RSEmp("DepartmentID") %>>
</td></tr>
</table>
<input type="submit" value="Update employee data">
</form>
</b></big>
</center>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 132
Empupdateconfirm.asp
UPDATE Employees Set LastName='Chen', FirstName='Minder', DepartmentID=200
WHERE EmployeeID=7
<%
Set dbConnection =Server.CreateObject("ADODB.Connection")
dbConnection.Open "expense"
SQLQuery = "UPDATE Employees SET LastName = " & "'" & _
Request.Form("LastName")& "'," & _
" FirstName = " & "'" & Request.Form("FirstName") & "'," &_
" DepartmentID = " & Request.Form("DepartmentID") & _
" WHERE EmployeeID = " & Request.Form("EmployeeID")
dbConnection.Execute(SQLQuery)
%>
<HTML><HEAD><TITLE>Confirm Employee Data Update </TITLE></HEAD><BODY>
Employee Data Updated! <br>
<a href="empmenu.htm">
Go back to Employee Data Maintenance Page</a>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 133
ASP Applications and Sessions
IIS
ASP
Application
Object 1
Session
Object
1
Session
Object
2
Session
Object 3
© Minder Chen, 1998-2002
Application
Object 2
Session
Object
1
Session
Object
2
Session
Object 3
Application
Object 3
Session
Object
1
Session
Object
2
Session
Object 3
ASP - 134
Application Object
• global.asa is the ASP file for each application
resides in the root directory of the application.
© Minder Chen, 1998-2002
ASP - 135
ASP and Session Management
• Hypertext Transfer Protocol (HTTP) is a stateless protocol. Each
browser request to a Web server is independent, and the server
retains no memory of a browser's past requests.
• The Session object, one of the intrinsic objects supported by ASP,
provides a developer with a complete Web session management
solution.
• The Session object supports a dynamic associative array that a
script can use to store information. Scalar variables and object
references can be stored in the session object.
• For each ASP page requested by a user, the Session object will
preserve the information stored for the user's session. This
session information is stored in memory on the server. The user is
provided with a unique session ID that ASP uses to match user
requests with the information specific to that user's session.
A session is terminated
when you close the browser.
© Minder Chen, 1998-2002
ASP - 136
ASP Sessions Are Cookie-Based
• ASP uses HTTP cookies to send users their unique
session IDs.
• For example, an ASP application that is using sessions
would respond to a user's request with an HTTP header
such as:
Set-Cookie: ASPSESSIONID=PUYQGHUMEAAJPUYL; path=/Webapp
• Each subsequent request by this browser to this server,
in the virtual directory /Webapp, would include the HTTP
cookie header:
Cookie: ASPSESSIONID=PUYQGHUMEAAJPUYL
• ASP automatically processes this cookie and uses it to
restore the values saved in the Session object.
• The cookie that is sent by ASP as a session ID does not
provide an expiration time. Cookies with no expiration
specified are only valid until the browser is closed.
© Minder Chen, 1998-2002
ASP - 137
When Are Session Cookies Sent by ASP?
• ASP will send a different Session ID cookie for each and
every ASP file that is requested until Session state is
used.
• Once a script begins a session, by storing a value in the
Session object, the Session ID is fixed for that user for the
life of the session and no new session ID cookies will be
sent.
• If you don't plan to use session management for any
applications on the server, you may use the Registry to
turn it off for all applications.
• You can also turn on ASP buffering to prevent
unnecessary cookies. When buffered in memory, ASP can
determine whether a session cookie is required before the
completed response is sent, and a session cookie header
will only be included when it is required.
© Minder Chen, 1998-2002
ASP - 138
Session Object Collection
• A script simply assigns a value to a named entry in the array,
as follows:
Session ("UserName") = "John"
• This will store the string "John" in the Session object and
give it the name "UserName." This value can be retrieved
from the Session object by referencing the Session object by
name, as in the following:
Welcome back <% = Session("UserName") %>
• Object references are stored using the SET keyword of
VBScript, for example:
Set Session("MyAd") = Server.CreateObject("MSWC.Adrotator")
© Minder Chen, 1998-2002
ASP - 139
Using Session Objects
• You can use the Session object to store information
needed for a particular user-session.
• Variables stored in the Session object are not
discarded when the user jumps between pages in the
application; instead, these variables persist for the
entire user-session.
• The Web server automatically creates a Session
object when a Web page from the application is
requested by a user who does not already have a
session.
• The server destroys the Session object when the
session expires or is abandoned.
• One common use for the Session object is to store
user preferences.
• Session state is only maintained for browsers that
support cookies.
© Minder Chen, 1998-2002
ASP - 140
Storing Session Information
<%
Session("username") = "Janine"
Session("age") = 24
%>
• If you store an object in the Session object and use
VBScript, you must use the Set keyword.
<% Set Session("Obj1") =
Server.CreateObject("MyComponent.class1") %>
<% Session("Obj1").MyMethod %>
© Minder Chen, 1998-2002
ASP - 141
Sample Code Using Session Object
---file1.asp--<%'Creating and initializing the array
Dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"
'Storing the array in the Session object
Session("StoredArray") = MyArray
Response.Redirect("file2.asp")%>
---file2.asp--<%
'Retrieving the array from the Session Object
'and modifying its second element
LocalArray = Session("StoredArray")
LocalArray(1) = " there" 'printing out the string "hello there"
Response.Write (LocalArray(0)&LocalArray(1))
'Re-storing the array in the Session object
'This overwrites the values in StoredArray with the new values
Session("StoredArray") = LocalArray %>
© Minder Chen, 1998-2002
ASP - 142
Exercise
© Minder Chen, 1998-2002
ASP - 143
global.asa
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
SUB Application_OnStart
Application("visitors") = 0
END SUB
</SCRIPT>
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
SUB Session_OnStart
Application.lock
Application("visitors")= application("visitors") + 1
Application.unlock
END SUB
</SCRIPT>
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
SUB Session_OnEnd
END SUB
</SCRIPT>
© Minder Chen, 1998-2002
ASP - 144
Page.asp
<HTML><HEAD><TITLE>Default Page </TITLE></HEAD>
<BODY>
You are visitor number <% = Application("visitors") %>
<form action="page1.asp" method=Post>
Tell us what background color do you like to use: <br>
<select size = 3 name=bgcolor>
<option>Green
<option>Red
<option>Silver
</select><br>
<input type=submit value="submit my preference">
</form>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 145
Setting and Using Session Variables
Page1.asp
<HTML><HEAD><TITLE>Page One </TITLE></HEAD>
<BODY bgcolor = <% = request.form("bgcolor") %>>
<%
Response.write "You like the color " & request.form("bgcolor") & "."
Session("bgcolor") = request.form("bgcolor")
%>
<br><a href="page2.asp">Go to page 2</a>
</BODY></HTML>
Page2.asp (version 1)
<HTML><HEAD><TITLE>Page Two </TITLE></HEAD>
<BODY bgcolor = <% = Session("bgcolor") %>>
<%
Response.write "You like the color " & Session("bgcolor") & "."
%>
</BODY></HTML>
© Minder Chen, 1998-2002
ASP - 146
Page2.asp (Version 2)
' You have to turn on the Buffer of the Response Object because of
' the Redirect method used in the following
<% Response.Buffer = True %>
<HTML><HEAD><TITLE>Page Two </TITLE></HEAD>
<%
If Session("bgcolor")="" Then
Response.Redirect "Page.asp"
Else
Response.Write "<BODY bgcolor='" & Session("bgcolor") & "'>"
Response.write "You like the color " & Session("bgcolor") & "."
End IF
%>
</BODY></HTML>
Note:
The visitor who visit Page2.asp first but does not set his color
preference will be redirected to Default.asp
© Minder Chen, 1998-2002
ASP - 147
Err.asp
<HTML><HEAD><TITLE>The Err Object</TITLE></HEAD><BODY>
<%
On Error Resume Next
Response.Write "10 / 0 =" & 10/0
IF Err.Number <> 0 THen
Response.Write "<BR>Err.Description =" & Err.Description
Response.Write "<BR>Err.Number=" & Err.Number
Response.Write "<BR>Err.Source=" & Err.Source
Response.Write "<BR>Err.HelpFile=" & Err.HelpFile
Response.Write "<BR>Err.HelpContext =" & Err.HelpContext
Response.write "<p>Stop"
Response.End
Err.Description =Division by zero
Else
Err.Number=11
Err.Source=Microsoft VBScript runtime error
Response.Write "<p>OK"
Err.HelpFile=
End If
Err.HelpContext =0
%> </BODY></HTML>
© Minder Chen, 1998-2002
ASP - 148
Error Handling Subroutine
If Err.Number <> 0 Then
CheckError
' Call CheckError()
Response.End
Else
Response.write "No Error"
End If
Sub CheckError()
Select Case Err.Number
Case 11
response.Write ”Help, help, panic, Division by zero.”
Case 6
response.Write ”No panic. Just an overflow error.”
Case Else
response.write Err.description
End Select
End Sub
© Minder Chen, 1998-2002
ASP - 149
Collaboration Data Objects: CDONTS
•
•
•
•
CDONTS: Collaboration Data Objects for Windows NT Server
Install SMTP when you install IIS 4.0 to install CDONTS.DLL
MS Exchange or SMTP must be installed .
Without a mail server, CDONTS works with SMTP to route all
messaging to a mail server on the network or Internet.
Collaboration Data Object
AddressEntry
Attachment
Folder
Message
ProgramID
CDONTS.AddressEntry
CDONTS.Attach
CDONTS.Folder
CDONTS.Message
NewMail
CDONTS.NewMail
Receipt
Session
CDONTS.Receipts
CDONTS.Session
© Minder Chen, 1998-2002
ASP - 150
Mail.htm and Mail.asp
Mail.htm
Send and receive
email from within
server-only application
through web forms.
Mail.asp
Send out email
Return a page
Mail has been sent
© Minder Chen, 1998-2002
ASP - 151
<HTML><HEAD><TITLE>E-MAIL</TITLE><BODY>
<form method="POST" action="mail.asp">
Mail.htm
To: <input type="TEXT" name="To"><br>
From: <input type="TEXT" name="From"><br>
Subject: <input type="TEXT" name="Subject"><br>
Body: <textarea name="Body" rows="3" cols="44"></textarea><br>
<input type="SUBMIT"></form></BODY></HTML>
Mail.asp
<HTML><HEAD><TITLE>E-MAIL</TITLE><BODY>
<%
SET objMail = Server.CreateObject("CDONTS.NewMail")
IF IsObject(objMail) THEN
objMail.Send Request.Form("From"), _
Request.Form ("To"), _
Request.Form ("Subject"), _
Request.Form("Body")
SET objMail = NOTHING
Response.write("Mail has been sent")
ELSE
Response.write("Mail has not been sent! <br>")
Response.Write("Call us at 703-999-8888 or try to submit your request again.")
END IF
%></BODY></HTML>
© Minder Chen, 1998-2002
ASP - 152
Send Method of NewMail
objNewMail.Send (strFrom, [, strTo] [, strSubject] [, strBody] [, intImportant])
•
Send the current message to its recipients
Parameters:
•
strFrom: Email address of the message's sender
•
strTo: Message's primary recipients (one or more email addresses).
– "[email protected]"
– "[email protected]; [email protected]"
•
strBody: Content of the message
•
intImportant: Priority of the message
–
cdoLow (0)
–
cdoNormal (1)
–
cdoHigh (2)
Set objNewMail = Server.CreateObject("CDONTS.NewMail")
objNewMail.Body = "This is the body of the message"
objNewMail.AttachFile "c:\temp\test.dat", "test.dat", cdoEncodingBase64
objNewMail.Send("[email protected]", "[email protected]", "Subject Line", , cdoHigh)
© Minder Chen, 1998-2002
ASP - 153
Request.htm
Request.asp
© Minder Chen, 1998-2002
ASP - 154
Request.htm
<html><head><title>Course Outline Request Form</title></head><body>
<h1>Course Outline Request Form</h1>
<form method="POST" action="request.asp">
<p>Please check the course outlines that you would like to receive:</p>
<p><input type="checkbox" name="asp" value="ON">ASP Courses <br>
<input type="checkbox" name="DHTML" value="ON">Dynamic HTML Course<br>
<input type="checkbox" name="WEBFAST" value="ON">Web Master Fast Track Program</p>
<p>Your name: <input type="text" name="NAME" size="20"><br>
Your E-mail Address: <input type="text" name="EMAIL" size="20"><br>
Your comment:<br>
<textarea rows="3" name="COMMENT" cols="44" ></textarea>
<p><input type="submit" value="Submit Your Request" name="B1">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="Reset" name="B2"></p>
</form></body></html>
© Minder Chen, 1998-2002
ASP - 155
Request.asp
<HTML><HEAD><TITLE>E-MAIL</TITLE><BODY>
<%
SET objMail = Server.CreateObject("CDONTS.NewMail")
BR = Chr(10) & Chr(13)
EBody = NULL
IF Request.Form("ASP") = "" and Request.Form("DHTML") = "" and Request.Form("WEBFAST") = ""
THEN
EBody = "No course has been requested!" & BR
ELSE
EBody = EBody & "Courses requested: " & BR
IF Request.Form("ASP") = "ON" THEN
EBody = EBody & "Active Server Page" & BR
END IF
IF Request.Form("DHTML") = "ON" THEN
EBody = EBody & "Dynamic HTML" & BR
END IF
IF Request.Form("WEBFAST") = "ON" THEN
EBody = EBody & "Web Fast Track Program" & BR
END IF
END IF
EBody = EBody & "Name: " & Request.Form("NAME") & BR
EBody = EBody & "Email: " & Request.Form("EMAIL") & BR
Ebody = EBody & "Comment: " & BR & Request.Form("COMMENT") & BR
EBody = EBody & "Time received: " & Now()
© Minder Chen, 1998-2002
ASP - 156
Response.write "This is what has been sent to us: " & _
"Name: " & Request.Form("NAME") & "<BR>" & _
"Email: " & Request.Form("EMAIL") & "<BR>" & _
"Comment: " & "<BR>" & Request.Form("COMMENT") & "<BR>"
IF IsObject(objMail) THEN
objMail.Send Request.Form("EMAIL"), _
Request.asp
"[email protected]", _
(continued…)
"Course Outlines reqest", _
EBody, _
cdoHigh ' Importance: cdoLow, cdoNormal, cdoHigh (0, 1, 2)
SET objMail = NOTHING
Response.write("Mail has been sent. <a href='http://www.erols.com/aitc/'>Go
back to AITC Home page</a>")
ELSE
Response.write("Mail has not been sent! <br>")
Response.Write("Call us at 703-999-8888 or try to submit your request again.")
END IF
%>
<!-- METADATA TYPE="TypeLibrary"
</BODY></HTML>
Declare CDO type library in
global.asa to use CDO constants
FILE="CDONTS.DLL"
VERSION="1.2"
-->
Excerpt from Global.asa
© Minder Chen, 1998-2002
ASP - 157