© Minder Chen, 1998-2002 ASP - 1
Active Server Pages
Minder Chen, Ph.D.
Course Description
Active Server Pages (ASP) are scripting files processed by
Microsoft Internet Information Server. ASP provides
server-side 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
© Minder Chen, 1998-2002 ASP - 3
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
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.
© Minder Chen, 1998-2002 ASP - 5
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>
This page was last refreshed on 9/11/98 4:30:00 PM. </BODY>
</HTML>
This page was last refreshed on
9/11/98 4:30:00 PM.
Interpreted ASP code: An HTML document.
Rendered via a
The Active Server Pages Model
B ro w s er Web Server(IIS)
Web Server(IIS)
Request an ASP file Active Server PageASP
Interpreter: Process ASP Scripting StatementsReturn a processed
ASP file in the forma
t of
an HTML document
• 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 .asp files
© Minder Chen, 1998-2002 ASP - 7
© Minder Chen, 1996 -1998 Web&DB - 35
ActiveX Server Scripting (VBScript, JavaScript, Perl, ...)
Internet Information Server 3.0
Internet/ Intranet
Web Clients
Web Server
HTTP
COM
.ASP Files
ActiveX Server Components
ODBC Databases
Active Server Pages: Server VB Scripting
ASP Architecture
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 Client-Side
© Minder Chen, 1998-2002 ASP - 9
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.
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.
© Minder Chen, 1998-2002 ASP - 11
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
Developing ASP Scripts
Creating/Revising
ASP scripts
Posting ASP scripts on the
web server or saving them
on the local web server
© Minder Chen, 1998-2002 ASP - 13
Hello.asp: Display Information
<HTML> <HEAD>
<TITLE>Hello World Example</TITLE> </HEAD>
<BODY> <%
Response.write "Hello World!"
%>
</BODY> </HTML>
The end of script section
The start of the script section Build-in Object Argument <HTML> <HEAD>
<TITLE>Hello World Example</TITLE>
</HEAD> <BODY>
Hello World! </BODY> </HTML>
Returned HTML Document
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.
© Minder Chen, 1998-2002 ASP - 15
http://www.ipswitch.com/
65.168.115.6
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
© Minder Chen, 1998-2002 ASP - 17
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
<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>
Return HTML Source Code
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 %>
© Minder Chen, 1998-2002 ASP - 19
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
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.
© Minder Chen, 1998-2002 ASP - 21
Hello3.asp
<%
' Define two variables with string values
.
x = "Hello"
y = "World"
%>
<P>My response is to say "<%= y %>
<%= x %>." </P>
<% Color = "Green" %> <%Color="Green"%>
<%
Color = "Green" %>
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>
© Minder Chen, 1998-2002 ASP - 23
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.
Data Types
•
Empty
– Variant is uninitialized. Value is 0 for numeric variables or a zero-length 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
© Minder Chen, 1998-2002 ASP - 25
Data Types
•
Single
– Contains a singleprecision, floatingpoint 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 doubleprecision, floatingpoint 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
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:
© Minder Chen, 1998-2002 ASP - 27
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 C = A(1)
<% Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error.
MyVar = 10 ' Declared variable does not generate error. %>
Dim MyVar, MyCheck
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>" %>
Have to be the first line
© Minder Chen, 1998-2002 ASP - 29
Response Object: Write Method
<HTML><HEAD><TITLE>Hello World</TITLE>
</HEAD>
<BODY>
<% response.write "Hello World" %>
</BODY>
Hello World
<HTML><HEAD><TITLE>Message</TITLE></
HEAD><BODY>
<%
Dim message
message = "Hello World"
Response.Write message
%>
Math Operations
<HTML><HEAD><TITLE>Math Operations</TITLE></HEAD><BODY>
<%
A = 7
B = 3
Response.Write A & " + " & B & " = " & A + B
Response.Write "<BR>"
Response.Write A & " - " & B & " = " & A - B
Response.Write "<BR>"
Response.Write A & " * " & B & " = " & A * B
Response.Write "<BR>"
Response.Write A & " / " & B & " = " & A / B
%>
</BODY></HTML>
7 + 3 = 10
© Minder Chen, 1998-2002 ASP - 31
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
Control Flow
True Block
© Minder Chen, 1998-2002 ASP - 33
• 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
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
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
© Minder Chen, 1998-2002 ASP - 35
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 %>
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.
© Minder Chen, 1998-2002 ASP - 37
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
Loops
<HTML><HEAD><TITLE>Loops</TITLE></HEAD><BODY> <%
Dim iCount
For iCount = 1 to 5
Response.Write iCount Response.Write "<BR>" Next
© Minder Chen, 1998-2002 ASP - 39
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.
Loop: Do While …… Loop
<%
Dim Counter
Counter = 1
Do While Counter < 3
Response.Write "Counter = " & Counter & "<br>"
Counter = Counter + 1
Loop
%>
Counter = 1
Counter = 2
© Minder Chen, 1998-2002 ASP - 41
Do … Loop While
•
Dim Counter
Counter = 1
Do
Response.Write "Counter = " & Counter &
"<br>"
Counter = Counter + 1
Loop While Counter < 3
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:
© Minder Chen, 1998-2002 ASP - 43
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 %>
Exercise: Form Input Data Processing
© Minder Chen, 1998-2002 ASP - 45
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) %>
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")
%>
© Minder Chen, 1998-2002 ASP - 47
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>
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>
© Minder Chen, 1998-2002 ASP - 49
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 %>
<% ElseIf Title = "ms" Then %> Ms. <%= LastName %>
<% Else %>
<%= Request.Form("fname") & " " & LastName %> <% End If %>
</FONT> </BODY> </HTML>
Exercise: Calculator
•
Operator can be: +, -, *, /
•
Check divide-by-zero error
A*B=600
© Minder Chen, 1998-2002 ASP - 51
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>
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
© Minder Chen, 1998-2002 ASP - 53
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
%>
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
© Minder Chen, 1998-2002 ASP - 55
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.
Exercise: sub1.asp
<HTML><HEAD><TITLE>Subroutine</TITLE>
<%
Sub MySub(iNum)
Response.Write iNum * iNum
End Sub
%>
</HEAD><BODY>
<%
Dim a
a = 20
MySub a
%>
<HTML><HEAD><TITLE>Subroutine</TITLE> <%
Sub MySub(iNum, iSquare) iSquare = iNum * iNum End Sub
%>
</HEAD><BODY> <%
Dim a, b a = 20
MySub a, b
Response.write "The square value of " & a & " is " & b %>
© Minder Chen, 1998-2002 ASP - 57
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 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 script-level variable and has script-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.
© Minder Chen, 1998-2002 ASP - 59
Global and Local Variable
<%
SUB X()
DIM A
A=3
End Sub
Dim A
A = 1
X
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 ASP - 61
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
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
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
© Minder Chen, 1998-2002 ASP - 63
Formal and Actual Arguments
Sub ShowProduct (Multiplicand, Multiplier)
Response.Write Multiplicand * Multiplier
End Sub
Dim x1, y1
x1=4
y1=5
Call ShowProduct (x1, y1)
or
-Dim x1, y1
x1=4
y1=5
ShowProduct x1, y1
Actual
arguments
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.
© Minder Chen, 1998-2002 ASP - 65
Functions: temp2.asp
<%
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
Sub ConvertTemp(tempF, tempC) tempC = Celsius(tempF)
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."
%>
Function Celsius(fDegrees)
appears before Sub
ConvertTemp() because the Sub procedure, ConvertTemp, calls the Function procedure,
Celsius.
<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>
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.
© Minder Chen, 1998-2002 ASP - 67
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 theObject 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
© Minder Chen, 1998-2002 ASP - 69
Build-in ASP Objects
C
l
i e
n
t
S
e
r
v
e
r
Request Object • Cookies • Form • QueryString • ServerVariables • ClientCertificate Response Object • Cookies • (Properties) • (Methods) ObjectContext Object • (Properties)• (Methods) Server Object
Build-in ASP Objects
•
Request Object
– Collections: ClientCertificate Cookies Form QueryString ServerVariables – Properties: TotalBytes – Methods: BinaryRead
•
Server Object
– Properties: ScriptTimeout – Methods: CreateObject HTMLEncode MapPath
•
Response Object
© Minder Chen, 1998-2002 ASP - 71
Build-in ASP Objects
•
Application Object
– Collections: Contents StaticObjects – Methods: Lock Unlock – Events: Application_OnEnd Application_OnStart
•
ObjectContext Object
– Methods: SetAbort SetComplete – Events: OnTransactionAbort OnTransactionCommit
•
Session Object
– Collections: Contents StaticObjects – Properties: CodePage LCID SessionID Timeout – Methods: Abandon – Events: Session_OnEnd Session_OnStart
Setting the Content Type
• For example, the following command sets the
content type for channel definitions:
© Minder Chen, 1998-2002 ASP - 73
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
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">
© Minder Chen, 1998-2002 ASP - 75
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
%>
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:
© Minder Chen, 1998-2002 ASP - 77
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>
Food.asp
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
computer.asp
<html><head><title> Apple.asp </title></head> <body>
© Minder Chen, 1998-2002 ASP - 79
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
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
© Minder Chen, 1998-2002 ASP - 81
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
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
© Minder Chen, 1998-2002 ASP - 83
SQL:
Data Manipulation Language (DML)
SELECT
UPDATE
INSERT
DELETE
SELECT
UPDATE
INSERT
DELETE
p_no
name
quantity
price
101
Color TV
24
500
201
B&W TV
10
250
202
PC
5
2000
SELECT p_no, name, price FROM PRODUCT
WHERE PRICE < = 1000 ORDER BY PRICE DESC;
p_no name price ---
---
---101 Color TV 500 201 B&W TV 250 Data
Manipulation Language (DML)
Database Schema - Product Table
Sample Data Base: Access expense.mdb
© Minder Chen, 1998-2002 ASP - 85
Employee Table
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
© Minder Chen, 1998-2002 ASP - 87
Department List
Departments table
Expense
100
ASP Script
100
Record set SQL statement
Format result setresult set
Dynamically generated
Dynamically generated
web page
web page
<form action="xxx.asp" method="post">
<a href="xxx.asp?id=all&y=3">Department List</a>
1
2
© Minder Chen, 1998-2002 ASP - 90
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")%> <%= RSDeptList("name")%> : <%= RSDeptList("description")%> <%
RSDeptList.MoveNext Loop
dbConnection.close
set dbConnection = Nothing %>
© Minder Chen, 1998-2002 ASP - 92
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"
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
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>
© Minder Chen, 1998-2002 ASP - 96
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:aitc@erols.com">Send E-mail to</a>aitc@erols.com</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
Revised Version
<% Do While Not RSEmployeeList.EOF %>
<TR><TD><%= RSEmployeeList("EmployeeID")%> </TD>
<TD><%= RSEmployeeList("FirstName") & " " & RSEmployeeList("LastName") %></TD> <TD><%= RSEmployeeList("Title")%> </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
© Minder Chen, 1998-2002 ASP - 98
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
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')"
© Minder Chen, 1998-2002 ASP - 100
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
Authors.mdb
• The database can be found at http://65.168.115.6/asp/database
or locally at c:\InetPub\IISSamples\asp\database
© Minder Chen, 1998-2002 ASP - 102
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")