ASP Ebook
ASP Ebook
ASP Ebook
ASP E-Book
from www.cstutoring.com
Contents
Lesson 1 Introduction to VB Script
Lesson 2 VB Script Operators
Lesson 3 VB Script Built in Functions
Lesson 4 VB Script Formatting and Utility Objects
Lesson 5 Introduction to ASP
Lesson 6 ASP Objects
Lesson 7 Database Access using ASP
Lesson 8 ASP Project 1
Lesson 9 Dictionary and File System Objects
Lesson 10 VB Script Procedures
Lesson 11 VB Script Classes and Objects
Lesson 12 Introduction to XML
Lesson 13 XML and XSL
Lesson 14 XML Applications
Lesson 15 VB, ASP and XML
Lesson 16 SOAP Simple Object Access Protocol
Lesson 17 ASP Project 2
This E-Book was written by the staff at www.cstutoring.com and sold by www.cscourses.com and www.csebooks.com
ISBN 0-9730824-3-7
The E-Book is made up of Individual Lessons that contain many exercises. Two of the Lessons are Projects. Each
Lesson provides a learning unit. You should complete each Lesson in sequence. It is important to do the exercises. Since
understanding will only be possible after you complete the exercises. People who purchase lessons separately may get
each exercise marked and obtain solutions. People who buy the E-Book only, must pay extra for, marking and solution
sets. We hope you enjoy this E-Book. The E-Books are designed to be enable someone to write a program. We use our
own E-books to write programs. Our goal is to have all the information we need in one book to complete a program.
Email any questions or typo's to: courses@cstutoring.com. Email exercises or projects to students@cstutoring.com
File: aspGuideL1.doc
Date Started: Mar 16, 2002
Last Update: June 15, 2003
ISBN: 0-9730824-3-7
Version: 0.0
VB SCRIPT
ASP stands for Active Server Page. ASP allows a Web Browser to interact with a Web server. A
Web browser can request information from an ASP program running on the Web server and the ASP
program can respond back with the required information. A good example is someone is buying
items on the Internet, the ASP program can track the items being bought, display information about
the bought items and display a bill of sale. ASP uses HTML and the VB Script Language. VB Script
is very similar to Visual Basic. If you know Visual Basic than you can learn VB Script very easily.
Before you can learn VB Script you need to know a little bit about HTML. For those who do not know
HTML you can take our HTML course before proceeding with the ASP course.
We will first study the VBScript programming language. A programming language uses data and
code. A programming language needs to use data to represent values where code are the
instructions telling the program what to do. The programming instructions are in the form of
programming statements. VBScript uses different types of data known as data types. There is
numeric data like 10.5 or string data like "hello". Here's a chart with examples of the different
types of data used in VB Script.
Every piece of data will have value and a data type. The value can be stored as a constant or in a
variable. Constants and variables are identified by a label, like Max or x. A label is just a sequence
of letters used for identification. Labels are also known as identifiers. The difference between a
constant and a variable is that the constant value cannot be changed but the variable value can be
changed at any time.
constants
Constants store values, but the value, once set cannot be changed. Constants are defined using the
const keyword. Keywords are VB Script language command words, that state what you want to do.
Constants usual start with an UPPER case letter. You assign a value to the constant using the "="
assignment operator.
Const Max = 10
The value on the right hand side of the assignment operator is assigned to the constant label on the
left hand side of the assignment operator.
The following example declares a numeric constant and a string constant. Notice strings are
enclosed by double quotes " "
Think that a constant value is contained in a box represented by the constant label. If you know the
constant name then you can gets its value.
VBScript has constants already predefined for you. The following chart contains some VB script
predefined constants, that you will be using soon.
Variables
Variables store values and the value can be changed at any time. Before you can use a variable you
have to declare it with the Dim keyword. Variables can hold any kind of data and have a Variant
data type. Variant means represents any data type.
Dim phoneNumber
You may declare many variables at once using the Dim keyword.
phoneNumber = "967-1111";
phoneNumber = "765-8756"
Dim x, y
y = Max
x=y
Again think as variables represented by a box having a name and a value. With a variable the value
in the box can always change.
y 10 x 10
You don't always need to use the keyword Dim to declare a variable, but you should. To make sure
you declare every variable before you use it you need to put the
Option Explicit
Variables do not represent a particular data type. Variables can represent any data type numeric,
string etc. In VBScript variables are variants that represent any data type. When you use a variable
the most appropriate data type is used.
OBJECTS
Many Variables and constants that have something in common may be grouped into an object. An
object will contain many data values. Their data values ate known as properties. Properties are
used to describe an object.
object
Variables
and
Constants
reference variable
(holds location of object)
Every object has a location in computer memory. The location where the object is, is identified by a
variable. A variable that holds the location of an object is known as a reference variable. Objects
are automatically supplied for you or they may be user defined. There are many Objects defined in
VB Script that you can use right away.
methods
An Object also has methods associated with them. A method contains programming statements
that are instructions to tell the computer what to do. Methods can do many things. Methods are
always associated with an object. When you want to use a method you state the object reference
name, the dot operator and the method name.
Document.Write
For example you may want to print out a value of a variable on a web browser screen. To do this
you need a method associated with an object that can print values to a web browser screen. A good
example is the write method of the pre-defined Document object used to print out the value of a
variable on a web browser screen.
Document.Write Max 10
967-1111
Document.Write phoneNumber.
We can now write our first VB script program. The VB script is included within an HTML page. All VB
scripts start with a <script language="VBScript"> tag and end with a </script> tag. VB script
comments start with a single quote like ' vbsript comment. HTML Comments start with a <!--
and end with a --> (notice the double hyphens). HTML comments and VB Script comments are
quite different. Here is an HTML program containing a VBScript.
To run this script just type it into a text editor like Notepad, save as vartest.html and then open up
using Internet Explorer.
9999999
This script runs on the client side. The client side means the Web browser is executing the HTML and
the VBScript. It is not an ASP page rather than just an HTML file with a VBScript. ASP pages run on
the server. ASP pages also use VBScript for its language.
If you want your output to start on a new line then you need to add a <br> tag in your script. You
can use the concatenation operator & to do this.
We have made a string out of the "<br>" tag. The & operator is known as a concatenation
operator that joins two strings. The variable name and the HTML tag string "<br>". The only way to
start a new line is to use the <br> tag. Why ? Because the string would be interpreted by the web
browser as a line break. The web browser only knows what HTML tags mean. The page written in
HTML and VB Script gets translated into HTML.
You can extend VBScript lines onto other lines in your program using the & operator and _ operator
(you must leave a space before and after the & operator )
Write a VB Script that declares 2 constants and 2 variables. Use Document.write method to print
the values to the screen. Assign the constants to the variables then print out the variable values to
the screen using Document.Write . Call you file ASPL1Ex1.html
INPUT BOX
Your VBScript program will need to get data values from the keyboard. A good way to get data from
the keyboard is to use an Input Box.
These look very professionals and impressive. Each Input Box gets a prompt message to tell the
user what to do. Once they enter the data they can click on the OK button or the Cancel button.
The InputBox is a built in VBScript function. Built in functions are pre-defined code that you can
use right away. Functions receive values and return values. Using built in functions let you program
very fast. You need to know how to use built in functions. Every built in function has a syntax that
specifies how to use it. Functions are different from method. Methods are associated with object and
access the variables in the object. Functions are not associated with any objects and can be used
without specifying an object reference.
Every function gets arguments. Arguments are used to pass values to the function. The InputBox
function needs the prompt message argument. The other arguments enclosed in square brackets [ ]
are optional meaning you do not need to supply values for them. Here are the arguments and their
descriptions. Don't be too concerned right now about all the arguments.
Argument Description
Required. String expression displayed as the message in the dialog box. The maximum
length of prompt is approximately 1024 characters, depending on the width of the
prompt characters used. If prompt consists of more than one line, you can separate the lines
using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage
return–linefeed character combination (Chr(13) & Chr(10)) between each line.
Optional. String expression displayed in the title bar of the dialog box. If you omit title,
title
the application name is placed in the title bar.
Optional. String expression displayed in the text box as the default response if no other
default
input is provided. If you omit default, the text box is displayed empty.
Optional. Numeric expression that specifies, in twips, the horizontal distance of the left
xpos edge of the dialog box from the left edge of the screen. If xpos is omitted, the dialog
box is horizontally centered.
Optional. Numeric expression that specifies, in twips, the vertical distance of the upper
ypos edge of the dialog box from the top of the screen. If ypos is omitted, the dialog box is
vertically positioned approximately one-third of the way down the screen.
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
8
Optional. String expression that identifies the Help file to use to provide context-
helpfile sensitive Help for the dialog box. If helpfile is provided, context must also be
provided.
Optional. Numeric expression that is the Help context number assigned to the
context appropriate Help topic by the Help author. If context is provided, helpfile must also be
provided.
The following string constants can be used anywhere in your code in place of actual values:
It's easy to use the InputBox function, all you have to do is assign the function to a variable. The
variable gets the value that the user has entered into the input box
Dim name
Here's a sample program that asks someone for their name and then prints their name to the web
browser screen.
<html>
<head>
<title>Input Box Test</title>
<script language="VBScript">
Dim name
name = InputBox("What is your name?")
Document.Write "Your name is " & name
</script>
</head>
<body>
</body>
</html>
Write a VBScript that uses multiple input boxes to ask someone for their name, address and age,
then print the answers on the web browser screen. Call your HTML file ASPL1Ex2.htm
MSG BOX
A message box lets you display information in a window. The message box is displayed until the OK
button is pressed.
Again the optional supplied argument values are in square brackets[ ]. We just use prompt and
title.
Here are the descriptions of the named arguments for the MsgBox:
Part Description
Required. String expression displayed as the message in the dialog box. The maximum length
of prompt is approximately 1024 characters, depending on the width of the characters
prompt used. If prompt consists of more than one line, you can separate the lines using a
carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return –
linefeed character combination (Chr(13) & Chr(10)) between each line.
Optional. Numeric expression that is the sum of values specifying the number and type of
buttons buttons to display, the icon style to use, the identity of the default button, and the
modality of the message box. If omitted, the default value for buttons is 0.
Optional. String expression displayed in the title bar of the dialog box. If you omit title,
title
the application name is placed in the title bar.
Optional. String expression that identifies the Help file to use to provide context-sensitive
helpfile
Help for the dialog box. If helpfile is provided, context must also be provided.
Optional. Numeric expression that is the Help context number assigned to the appropriate
context
Help topic by the Help author. If context is provided, helpfile must also be provided.
The first group of values (0–5) describes the number and type of buttons displayed in the dialog
box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512)
determines which button is the default; and the fourth group (0, 4096) determines the modality of
the message box. When adding numbers to create a final value for the buttons argument, use only
one number from each group. Note these constants are specified by Visual Basic for Applications. As
a result, the names can be used anywhere in your code in place of the actual values.
When both helpfile and context are provided, the user can press F1 to view the Help topic
corresponding to the context. If the dialog box displays a Cancel button, pressing the ESC key has
the same effect as clicking Cancel. If the dialog box contains a Help button, context-sensitive Help
is provided for the dialog box. However, no value is returned until one of the other buttons is
clicked. Note To specify more than the first named argument, you must use MsgBox in an
expression. To omit some positional arguments, you must include the corresponding comma
delimiter
<html>
<head>
<title>Msg Box Test</title>
<script language="VBScript">
name = MsgBox("Your name is: Tom")
</script>
</head>
<body>
</body>
</html>
Change the previous exercise to use a MsgBox. Ask the user to enter their name, address and age
using the Input Box and then display all three answers in a MsgBox. Use a line feed character
Chr(10) or Vbcrlf to separate lines in the MsgBox. Call your HTML file APSL1Ex3.htm
ARRAYS
Each variable of the array is known as a cell or element. An example of using an array is to record
the temperature of every hour for a certain day.
temperatures 45 89 56 34 23
It's easy to make an array you just declare a variable with the number of columns you want minus
1. The number of columns minus 1 is known as the upper bound. The lower bound is 0.
Dim a(4)
Once you declare your array you can store values in it. You access the array cells by an index. Each
cell is accessed using an index.
a(1) = 5
In VB Script All array start at index 0. Array a will have indexes from 0 to 4. The value 5 will be
located in the array at index 1. Arrays have default value 0.
0 1 2 3 4
a 0 5 0 0 0
Arrays that have only one row, are known as 1 dimensional arrays.
Declare a 1 dimensional array of 5 elements assign to each element the value of its index. Print out
each array element using Document.write. Call you file ASPL1Ex4.html
2 dimensional arrays
An array may have more than 1 row. These arrays are known as 2 dimensional. To declare a two-
dimensional array you must declare the number of rows and columns. Again we use minus 1. These
are the upper bound indexes for the number of rows and columns. The lower bound is 0.
columns
dim b ( 1, 2)
You assign values to the array cells by specifying row and column indexes. Arrays have default value
starting index of 0.
b(1,2) = 5 columns
0 1 2
rows 0 0 0 0
1 0 0 5
row columns
Declare a 2 dimensional array of 3 rows and 3 columns. Assign to each element the value of its row
and column index. For example B(1,2) = 12 Print out each array element using Document.Write
as the array would normally appear. ( 3 rows and 3 columns ). Call you file ASPL1Ex5.html
1 2 3
4 5 6
7 8 9
BUILT IN FUNCTIONS
The VBScript language come with functions that you can use right away to do things. Functions
contain variables and programming statements. Functions differ from methods in that they are not
associated with any objects. "Built in" means that someone has already coded it for you. So you can
use them right away. Functions receive values, do a calculation and return the calculated value.
There are many groups of functions available in VBScript . The first group of functions are used to
check variables to determine what data type they represent.
function description
IsArray(varname) returns true if variable is an array
IsDate(expression) returns true if expression can be converted to a date
IsEmpty(expression) returns true if variable has been initialized
IsNull(expression) returns true if expression returns no valid data
IsNumeric(expression) returns true if expression can be evaluated as a number
IsObject(expression) returns true if expression references an automated object
VarType(varname) returns a value representing the subtype
Example using:
The VarType function returns a numeric value identifying what the type of data a variable
represents.
VarType(varname)
Example using:
Dim x
x=5
Document.write ( VarType (x) )
The TypeName function returns a string describing what data type a variable represents.
TypeName(varname)
Dim x
x=5
Document.write ( TypeName (x) )
Integer
The output on the screen would be "Integer".
Make variables of different data types. Use the variable check functions to test if they are really what
you assign them to be. Finally print out the value type and string name of each variable. Call your
file ASPL1Ex6.htm
UBound arrayname[. dimension]) returns the upper bound of the specified dimension
arrayname name of array
subscripts specifies which dimension you want 1 for first, 2 for second dimension (1 is default)
Dim b(3,4)
x = UBound(1) ' x is 2 remember indexes start at 0
x = UBound(2) ' x is 3 remember indexes start at 0
Declare an array2 by 3 array and fill it values of your choice. Print out the lower and upper bound of
each dimension. Resize the array to 4 columns. Assign new values to this array. Print out the lower
and upper bounds again. Finally erase the array. Call you file ASPL1Ex7.htm
File: aspGuideL2.doc
Date Started: Mar 16, 2002
Last Update: June 15, 2003
ISBN: 0-9730824-3-7
Version: 0.0
OPERATORS
Operators are symbols that to do operations on variables and constants. The operations may be
adding or comparing the values of variable and constants. The variables or constants are called
operands. Operators with operands are known as expressions.
expression
x + 5 operators do operations
on variables and
operand operator operand constants
Assignment operator
Assignment statements use the assignment operator to evaluate and assign expressions to a
variable. The right hand side of the assignment operator is evaluated and assigned to the
variable on the left hand side of the assignment operator. The original value of the left hand
variable is lost, and is replaced by the evaluated value of the expression.
variable = expression;
x = x + 5
ARITHMETIC OPERATORS
11 12 1 (13)
Dim x, y
x=5
y = 10
6
operator description example
+ addition x=x+5 To find the modulus of a number:
- subtraction x=x–5 you multiply the remainder after division
* multiplication x=x*y by the denominator.
/ decimal division x=x/y For example:
\ integer division x=x\y 13 mod 12 is 13/12 = 1.0833333...
Mod modulus x = y MOD 5 Multiply remainder by denominator
(remainder) 0.0833333.. * 12 = 1 (13 mod 12) = 1
^ exponention x=y^5
You can use Document.Write method to print out the value of arithmetic expressions
Document.Write (x + y)
This operator negates a variables value. This means if the variable was positive it is now negative
This operator does not change value. This means if the variable was positive it is still positive
This means if the variable was negative it is still negative
Write an HTML program using VBScript to test out all the arithmetic functions. You can use an
InputBox to get values and a MsgBox to print out the results. Call you file ASPL2Ex1.htm
COMPARISON OPERATORS
Comparison operators (or sometimes called relational operators) evaluate 2 expressions and
evaluate the result as true or false. When you compares two expressions, this is known as a
condition.
( condition )
( x = 5 )
The following table lists all the comparison operators with examples using x and y:
Dim x,y
x=5
y = 10
Document.Write (y < 5)
Logical Operators
Logical operators are used to test if both conditions are True or if either expression is True when
comparing two conditions. The AND logical operator will test if two conditions are both true. The OR
logical operator will test if either two conditions are true. The two conditions will be evaluated as
True or False depending on the logical operator used to test the two conditions.
(x = 5 ) Or (y = 5) OR (Either)
The following table lists all the logical operators with examples using x and y:
Dim x, y
x=5
y = 10
The trick is to evaluate the conditions first and then apply the logical operator.
Draw a truth table for the AND, OR and NOT operators. Write VB Script code to demonstrate the
truth table. Call you file ASPL2Ex2.htm
Draw a truth table for the XOR, EQV AND IMP operators. Write VBScript code to demonstrate the
truth table. Call you file ASPL2Ex3.htm
Precedence
Precedence tells the compiler which operations are to be performed first. Round brackets ( ) are
used to force which expressions to be evaluated first. If round brackets are not used then the
compiler must decide for you. The compiler makes it decision by using a precedence table that
indicates which operators are to be performed first. Associativity is a term that states, which order
the operations are to be evaluated, either from left to right or from right to left. Operators in an
expression having the same level precedence are evaluated to the associativity direction.
Precedence table:
Dim a,b,c,d
a=1, b=2, c=3, d=4
Dim x
x = a + b * c + d ' Which operations are done first ? b * c then + a + b
Design your own mathematical equation using all the arithmetic operators. Assign values to all of
your variables, don't use any round brackets. Print out the results. Put round brackets in your
mathematical equation and print out the results Compare both answers print out if they are the
same or not. Call you file ASPL2Ex4.htm
CONTROL STATEMENTS
Control statements are used to control program execution flow. Control statements are used to test
conditions that decide which programming statements get executed. There are control statements
that direct which programming statements get executed and there are control statements called
loops that cause programming statements to repeat themselves until a condition is false or true.
The following chart lists all the control statements.
control description
If execute programming statements if test condition is true
If Else executes programming statements if a test condition is true and executes a different
group of programming statements if test condition is false.
Else If many test conditions are evaluated and executes the programming statements for the
first test condition that is true.
Select executes compare programming statements associated with a constant that matches
a variable
While continually executes a group of programming statements if test condition is true
Do While continually executes a group of programming statements at least once if test condition
is true
IF STATEMENT
The if statement is used with conditions to make a decision in a program flow. An if expression
contains one or more conditions that are evaluated as True or False. When the if expression is
True then the statements belonging to the if statement is executed. When the if expression is
False then program flow is directed to the next program statement. If an if statement has more
than one statement then the statements belonging to the if expressions must be followed by an
end if. An if statement allows you to make a choice in program execution direction.
Dim x, y
x=5
y = 10
IF ELSE STATEMENT
An if statement may have an optional else statement. The else statement executes the alternative
false condition. You need an end if statement at the end if else statement. The if expression may
contain multiple lines or single lines. The statements following the else may contain multiple lines or
single lines.
F
If(condition)then If x=0 then T
true statement If x=0 then
Else y=x
false statement x=x+1
y=x
End If x=x+y x=1
Else
x=1
end if
If-else statements may be nested. Nested means an if-else statement inside an if-else
statement. In this case the else belongs to the balanced if.
If
If (condition) Then If x =2 Then
T F
If x=2 then
y=x
T F
If x=y then
y=2 y = x+1
Write a VBScript that initializes 3 integer variables with different values between 1 and 10. Print out
the name and value of the largest value variable. Use an InputBox to get values and a MsgBox to
print out the results. Call you file ASPL2Ex5.htm
IF ELSE IF STATEMENTS
The If Else If statements can be sequenced to choose a certain condition. As soon it finds a
condition true it executes the statements associated with that If statement. If the value you are
looking for is not found then program execution is directed to the else statement.
If(condition)then If x = y Then F
T
true statement y=1
y=1
ElseIf(condition) then ElseIf x <y Then x =y
true statement y=2
F
ElseIf (condition) then ElseIf x > y Then
true statement x=3 T
Else Else y=2
x< y
default statement; x=4
End If End If
F
T
x=3
x>y
x=4
Write an If-ElseIf statement that can print out all the number of days in a year from the start of
each month. Call you file ASPL2Ex6.htm
To avoid typing in many If ElseIf statements use the Select Case statement is used. A variable
name is compared to many values in a case statement. The values may be constants or variables. A
case statement may have more than 1 value. This allows you to test for more than 1 value. A case
statement maybe empty to take no action when that value is found.
Dim x, y
x=5
y = 10
End Select
Case C,Y: _
Case 4,x:
Convert the If ElseIf statement of previous exercise to a Select Case statement. Call your file
ASPL2Ex7.htm
WHILE LOOP
The while loop tests a condition at the top of the loop. If the expression is true the statement
inside the while loop is executed. When the while expression is false the program exits the loop.
You must be careful and make sure that the test condition is initialized before entering the loop. You
use the while loop when you do not know how many items you have. If the test condition is false
before entering the loop then the while loop statements will never get executed.
i=i+1 i=i+1
Wend
Document.Write("I got:"& i &" items")
DO WHILE STATEMENT
The while loop tests a condition at the top of the loop. If the expression is true the statement
inside the while loop is executed. When the while expression is false the program exits the loop.
You must be careful and make sure that the test condition is initialized before entering the loop. You
use the while loop when you do not know how many items you have. If the test condition is false
before entering the loop then the while loop statements will never get executed.
i=i+1 i=i+1
Loop
Document.Write("I got:"& i &" items")
DO LOOP WHILE
A do while loop tests the expression at the bottom of the loop and exits if false. The statements
inside the do loop are executed at least once. The repeat statements are executed before the test
condition.
Do const num = 10
repeat statement(s) Dim i
Loop While (condition) i=0 i=i+1
Do
i=i+1
Loop While ( i < num ) T F
Document.Write ("I got:" & i & " items") i < 10
What is the difference between a Do while loop and a While Do loop. When would you use a Do
while loop. When would you use a While Do loop ? A While Do loop executes the loop
statements at least once, where a Do While loop may never execute the loop statements. You use a
While Do loop when you want the loop statements to be executed at least once.
DO LOOP UNTIL
A do until loop tests the expression at the bottom of the loop and exits if true . The statements
inside the do while loop are executed at least once. The repeat statements are executed before the
test condition.
Do Dim i
repeat statement(s) i=0
Loop Until (condition ) Do
i=i+1 i=i+1
Loop Until( i >= num )
Document.Write ("I got:" & i & " items") F T
i < 10
What is the difference between a Do While loop and a do until loop. When would you use a while
loop. When would you use a do until loop ? A do until loop executes the loop statements at least
once, where a while loop may never execute the loop statements. You use a do until loop when you
want the loop statements to be executed at least once.
EXIT DO STATEMENTS
The exit do statement lets you get out of a while or do while, do until statements.
F
' loop till break condition encountered
Dim i
i=0 i < 10
Do While(x < 10)
T
Document.Write(i)
If i=5 then Exit Do 'exit loop if true
if i=5 then exit do
i=i+1
Loop
0 1 2 3 4 5
i++
Write a VBScript that initializes 3 integer variables with different values between 1 and 10. Print out
the name and value of the variable of the largest value and smallest value. Call you file
ASPL2Ex8.htm
FOR/NEXT STATEMENT
The For statement is used to loop when you know how many items you want. For example to read
a known number of items from a file.
For i = 0 to 10 F
x=x+1
Next T
i < 10
A for loop may have more than Test
one statement Condition
For i=0 To 10
x=x+i
x=x+i
y=x
Next
i=i+1 Increment
Loop variables increment by 1. you van change this by using the step keyword
x=x+i
y=x
Next
Write a VBScript that adds all the numbers between 1 and 10 and calculates and print out the sum
and average. Call you file ASPL2Ex9.htm
File: aspGuideL3.doc
Date Started: Mar 20, 2002
Last Update: June 15, 2003
ISBN: 0-9730824-3-7
Version: 0.0
BUILT IN FUNCTIONS
VB Script has lots of built in functions to make your programming life easier.
MATH FUNCTIONS
For those mathematical students here are the built-in math functions.
Write a VBScript that uses a InputBox to ask the user to type in a number. Using a MsgBox tell
them if the number is positive or negative, then square the number and multiply by a random
number and display the square root. Call your html file ASPL3Ex1.htm
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
31
Hexadecimal numbers are a base 16 numbering system where octal numbers are a base 8
numbering system. Base 16 means you count up to 15 before you start the next digit. Since there
are only 10 digits we are forced to use letters 'A' to F' to represent values 10 to 15. Base 8 means
you count up to 7 before you start the next digit.
num = &h1FAE2 ' specify a hexadecimal number (starts with letter 'h')
num = &o43445 ' specify a octal number (starts with small letter 'o' )
BINARY NUMBERS
A memory cell in a computer is called a bit and can have two possible states off or on and is
represented as a 0 or a 1 respectively. Numbers containing 0's and 1's are known as binary
numbers having a number base of 2. Since 0's and 1's are very difficult to work with, four bits are
grouped together to represent the numbers 0 to 15. The 4 bits grouped together are known as a
hexadecimal number having base 16 because 2 4 = 16
0 1 1 0
Hexadecimal numbers use numbers 0 to 9, and letters A to F to represent the decimal numbers
from 0 to 15. Letters are used because we want one character to represent a number. Hexadecimal
numbers are used because they are more convenient to work with than binary numbers.
The following chart shows the numbers 0 to 15 represented by bases binary, octal, decimal and
hexadecimal.
It's easy to convert a binary number to a octal number. All you have to do is group three binary bits
together.
1 1 1 0 0 1 0 1 1 0 1 1 1 0 0 1
1 6 2 6 7 1
It's easy to convert a binary number to a hexadecimal number. All you have to do is group four
binary bits together.
1 1 1 0 0 1 0 1 1 0 1 1 1 0 0 1
E 5 B 9
If you want to convert octal numbers to binary just use the chart ! Look up the octal number and
write down the binary equivalent.
1 6 2 6 7 1
1 1 1 0 0 1 0 1 1 0 1 1 1 0 0 1
If you want to convert hexadecimal numbers to binary just use the chart ! Look up the hexadecimal
number and write down the binary equivalent.
E 5 B 9
1 1 1 0 0 1 0 1 1 0 1 1 1 0 0 1
The most significant bit (MSB) is called the sign bit and determines if a signed number represents a
negative or positive number. When the MSB or most left bit is a 1 then a signed number is
considered negative.
1 0 1 0 1 1 0 0
When the MSB or most left bit is 0 then a signed number is considered positive.
0 0 1 0 1 1 0 0
positive number
sign bit is 0
The following chart lists all the numbers for a signed number using 4 bit resolution. When N is 4 and
we use our signed number range formula the range is:
signed -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
binary 1000 1001 1010 1011 1100 1101 1110 1111 0000 0001 0010 0011 0100 0101 0110 0111
unsigned 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7
Write a VBScript that assigns a hexadecimal number and the same value octal number to variables.
Print out the variables on the screen. Call your html file ASPL3Ex2.htm
STRINGS
Strings are made up of characters like "Hello". Strings may be declared using Dim as follows:
Dim str1
Once you declare your string variable you can give it a string value.
str1 = "Hello"
You should already know how to join strings together using the '&' catenation operator:
Remember to put a space before and after the & operator. You can also use the "+" operator
for joining strings.
The next important thing to do with strings, is to be able get some portion of it. Portions of strings
are known as sub strings. There are three functions that let you get sub strings. Left$, Mid$ and
$Right
note:
(1) The Mid function is good for extracting single characters from a string.
(2) String indexes start at zero
Length of a string
len(str1) would be 13
Trimming a string
Trimming means you remove blank characters on the left or right or both sides of a string, There are
three functions to do this with: LTrim$, RTrim$, Trim$. From the following example code the
result of each trim function is shown in the table.
Note: to make the result permanent you would have to assign the output of the function to the same
variable or another string variable or the same one.
str1 = Trim$(str1)
Make a VBScript that gets a word from the user using an input box. Reverses all the characters in a
string and print on a MsgBox. Call your HTML program ASPL3Ex3.htm
Every string character has a numeric value. The character's value is assigned by the ASCII table. For
example the capital letter 'A' has the numeric value 65. To get the numeric code of a character
you use the Asc(string) function.
Asc("A") would be 65
In situations where the string is more than 1 character then only the first character is converted into
a number.
You can also convert a number into a string character using the Chr$ function
The String(num ,string char) function repeats the specified characters a specified number of
times.
COMPARING STRINGS
You use the StrComp function to test if two strings are equal. The StrComp function returns a
Variant (Integer) indicating the result of a string comparison. (<=-1 less, 0 equal, >=1 greater)
Part Description
string1 Required. Any valid string expression.
string2 Required. Any valid string expression.
Optional. Specifies the type of string comparison. If the compare argument is Null,
compare an error occurs. If compare is omitted, the Option Compare setting determines the
type of comparison. Option Compare {Binary | Text | Database}
If StrComp returns
string1 is less than string2 -1
string1 is equal to string2 0
string1 is greater than string2 1
string1 or string2 is Null Null
If you specify case insensitive ( vbTextCompare) meaning upper case is same as lower case
If you specify case sensitive (vbBinaryCompare) upper case is different from lower case
The strConv(string, convert) function lets you specify to convert to upperCase, lowerCase or
ProperCase. Proper case is when the first letter of every word in the string is upper case and the
rest is lower case, example: "It Is Cold Today"
Make a VB Script that asks the user to enter a message using an Input Box. Display the message
with all the words sorted into ascending order. Write even numbers words as UPPER case and odd
numbers words as lower case. Call your HTML file ASPL3Ex4.htm
In most cases ASP will automatically convert one data type to another data type for you.
Dim x,s
x = 1234
s = "1234"
All variables in VB Script are variant data type this means you may have to convert to a different
types. There may instances when you want to convert the string "1234" to an integer 1234. In this
situation you need to use a conversion function like CInt
Dim x
x = CInt ("1234")
Here are all conversion functions with examples you can use. These conversion functions can handle
comma's etc.
Write an HTML program using VBScript to test out all the conversion functions. Use an InputBox to
allow the user to enter a number and then display all the conversion results in a MsgBox. Call your
file ASPL3Ex5.htm
The Instr$ function Instr(first, second) searches for a substring in another string and if found
returns the index location of the first character. (all string character locations start at index 0). If
it cannot find the substring it returns -1. A substring is part of a string.
Dim str1
str1 = "find the word in the string"
Instr(str1,"the")
You can also specify the starting index substr(start, first, second) where you want to start
searching for the substring
Dim str1
str1 = "find the word in the string"
Now it will return 18 because we have started at index 7 and has found the word at index 18
search backward
You may want to search backward starting from the end of the string. Here we have the
InStrRev(source, search, [start], [compareMethod]) function that starts searching at the end
of the string.
Dim str1
str1 = "find the word in the string"
InStrRev(str1, "the")
would return 18
pattern matching
You use the like operator to find substrings that match a certain pattern, returns True or False.
.
result = string Like pattern True
Part Description
result Required; any numeric variable.
string Required; any string expression. 9
Required; any string expression conforming to the pattern-matching
pattern
conventions described in Remarks.
If string matches pattern, result is True; if there is no match, result is False. If either string or
pattern is Null, result is Null.
The behavior of the Like operator depends on the Option Compare statement. The default string-
comparison method for each module is Option Compare Binary.
Option Compare Binary results in string comparisons based on a sort order derived from the
internal binary representations of the characters. Sort order is determined by the code page. In the
following example, a typical binary sort order is shown:
A<B<E<Z<a<b<e<z<À<Ê<Ø<à<ê<ø
Option Compare Text results in string comparisons based on a case-insensitive, textual sort order
determined by your system's locale. When you sort the same characters using Option Compare
Text, the following text sort order is produced:
(A=a) < (B=b) < (E=e) < (Z=z) < (Ø=ø)
Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching
features allow you to use wildcard characters, character lists, or character ranges, in any
combination, to match strings.
The following table shows the characters allowed in pattern and what they match:
A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any
single character in string and can include almost any character code, including digits.
Note To match the special characters left bracket ([), question mark (?), number sign (#), and
asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match
itself, but it can be used outside a group as an individual character.
By using a hyphen (–) to separate the upper and lower bounds of the range, charlist can specify a
range of characters. For example, [A-Z] results in a match if the corresponding character position in
string contains any uppercase letters in the range A–Z. Multiple ranges are included within the
brackets without delimiters.
The meaning of a specified range depends on the character ordering valid at run time (as
determined by Option Compare and the locale setting of the system the code is running on). Using
the Option Compare Binary example, the range [A–E] matches A, B and E. With Option Compare
Text, [A–E] matches A, a, B, b, E, e.
• An exclamation point (!) at the beginning of charlist means that a match is made if any
character except the characters in charlist is found in string. When used outside brackets, the
exclamation point matches itself.
• A hyphen (–) can appear either at the beginning (after an exclamation point if one is used) or
at the end of charlist to match itself. In any other location, the hyphen is used to identify a
range of characters.
• When a range of characters is specified, they must appear in ascending sort order (from
lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.
A good example using the like operator is to test if an email address is valid
Dim str1
str1= "students@cstutoring.com"
Make a VBScript that allows the user using an input box to enter a string of their favorite words.
Test and print out in a MsgBox if the string "contains all lower case", "contains all upper case".
"contains numbers"," contains all letters", "ends with a number", "begins with a letter" is an E-Mail
address. Call your HTML file ASPL3Ex6.htm
REPLACING SUBSTRINGS
The replace method will find a substring in a string then replace it with another string.
This is good for replacing strings with double spaces with a single space.
REVERSING A STRING
You use the StrReverse function to reverse all the letters in a string..
StrReverse(string) as String
Dim str1
Some words cannot be reversed like "radar" and are known as a palindrome.
Dim str1
str1 = StrReverse("radar")
VB LESSON3 EXERCISE 7
Make a VB Script that allows a user to enter a message of their favorite words, another string that
contains only one of the words in the first sentence, and a another string that has a word not in the
first string using Input Boxes. The word they selected in the second string is to be replaced in the
first string with the word in the third string. Write the results to a MsgBox. Finally reverse the
result string and print to the screen using another MsgBox. Call your HTML file ASPL3Ex7.htm
You will find this function very handy. You always need to extract words from a sentence. The Split
function will do this for you. Each word in the sentence is called a token and the space between
the words is called a delimiter.
delimiters tokens
(spaces) (individual words)
The split function returns a zero-based, one-dimensional array containing a specified number of
substrings.
Here is an example using split function we have a string "It is cold today" where a space is the
delimiter.
REBUILDING STRINGS
The join function receives an array of strings and a delimiter like a space and rebuilds the original
string.
We can take the array of words and space delimiter used from the split example and rebuild our
original string
FILTER
The filter function scans an array searching for a substring and returns another array of all the
items found containing the search substring. You have the option of including words with the search
substring or words not including.
Part Description
InputStrings Required. One-dimensional array of strings to be searched.
Value Required. String to search for.
Optional. Boolean value indicating whether to return substrings that include or
exclude Value. If Include is True, Filter returns the subset of the array that
Include
contains Value as a substring. If Include is False, Filter returns the subset of the
array that does not contain Value as a substring.
Optional. Numeric value indicating the kind of string comparison to use. See
Compare
Settings section for values.
If no matches of Value are found within InputStrings, Filter returns an empty array. An error
occurs if InputStrings is Null or is not a one-dimensional array. For an example we can take out
array of string from last example
It is cold today
In the next example we set parameter included to True and parameter compare to
vbTextCompare
For Each word In words 'we use words from previous example
Document.Write word
It
Next The output would be: is
End Sub
Make A VB Script that asks the user to type in a letter in a InputBox. In s MsgBox display the
words in the sentence that contain the letter. In another MsgBox display all the words that do not
contain the letter. Make sure you use case insensitive. Hint you need to use the split function to put
all the words in an array. Call your HTML file ASPL2Ex8.htm
StrComp(string1, test if two strings are less than, greater than or StrComp("hello",
string2[, compare]) equal for compare use vbTextCompare case "goodbye");
insensitive and vbBinaryCompare for case
sensitive
UCase$(string) converts a string to upper case UCase$("hello")
LCase$(string) converts a string to lower case LCase$("hello")
File: aspGuideL4.doc
Date Started: Mar 20, 2002
Last Update: June 15, 2003
ISBN: 0-9730824-3-7
Version: 0.0
FORMATTING NUMBERS
Formatting is used to print numbers the way we want them. We have the following Formatting
functions, that allows formatting for decimal numbers, currency and percents.
FORMAT NUMBER
The FormatNumber function Returns an expression formatted as a number. It has the following
syntax:
FormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit
[,UseParensForNegativeNumbers [,GroupDigits]]]])
When one or more of the optional arguments are omitted, the values for omitted arguments are
provided by the computer's regional settings.
The following example uses the FormatNumber function to format a number to have four
decimal places:
Dim str
Dim Num
Num = 10.7654345 10.7654
str = FormatNumber(Num,4)
Document.Write(str)
FORMAT PERCENT
The FormatPercent function returns an expression formatted as a percentage (multiplied by 100) with
a trailing % character.
FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
[,UseParensForNegativeNumbers [,GroupDigits]]]])
When one or more optional arguments are omitted, the values for the omitted arguments are
provided by the computer's regional settings.
Dim str
str = FormatPercent(1/16) 6.25%
Doucument.Write(str)
FORMAT CURRENCY
The FormatCurrency function returns an expression formatted as a currency value using the
currency symbol defined in the system control panel.
FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
[,UseParensForNegativeNumbers [,GroupDigits]]]])
When one or more optional arguments are omitted, values for omitted arguments are provided
by the computer's regional settings. The position of the currency symbol relative to the currency
value is determined by the system's regional settings.
The following example uses the FormatCurrency function to format the expression as a
currency:
$1000.00
Dim str
ste = FormatCurrency(1000)
Document.Wite(str)
Make a VBScript using Input Boxes that asks the user for three numbers. Add up all three numbers
and calculate the average. Display the number and total with average as a percent in a MsgBox.
The numbers should be formatted to 2 decimal places. The total should be expressed as a currency
and the average as a formatted percent. Call your HTML file ASPL4Ex1.htm.
A Date object is used to store the Date and Time. To get the date use the Date property to get the
time use Time property. If you want both date and time use the Now property. We can fill a
MsgBox box with the time and date or both:
<html>
<head>
<title>Date and Time</title>
</head>
<body>
<script language="VBScript">
MsgBox "Today is: " & Date & " " & Time
MsgBox "Today is: " & Now
</script>
</body>
</html>
A date string starts with a # and ends with a # example: #01/03/1995 5:23:43 PM#
Dim myDate
5:23:43 AM
myDate = #5:23:43 PM# ' time
01/03/95
myDate = #01/03/1995# ' date 01/03/95 5:23:43 AM
myDate = #01/03/1995 5:23:43 PM# ' both
It is much easier using the DateSerial and TimeSerial functions to build dates and times.
TimeSerial(hour,minutes,second)
<html>
<head>
<title>Date and Time</title>
</head>
<body>
<script language="VBScript">
Dim myDate
myDate = DateSerial(1993, 04,23)
MsgBox mydate
Dim myTime
mytime = TimeSerial(4,45,23)
MsgBox mytime
</script>
</body>
</html>
Make a VBScript using Input Boxes that asks the user for year, month, day, hours, minutes, seconds
Display the date in one MsgBox and the time in another Msgbox. Call your HTML file ASPL4Ex2.htm.
You can use the isDate function to determine if a Input Box contains a valid Date or Time string.
The following functions let you extract parts of a date and time's
Extracting any date and time value using the DatePart function
There is a DatePart function that lets you specify what part of a Date object you want. You can
extract the year, month or what ever. It returns a Variant (Integer) containing the specified part
of a given date.
DatePart("yyyy", Now)
Part Description
interval Required. String expression that is the interval of time you want to return.
date Required. Variant (Date) value that you want to evaluate.
Optional. A constant that specifies the first day of the week. If not specified,
firstdayofweek
Sunday is assumed.
Optional. A constant that specifies the first week of the year. If not specified,
firstweekofyear
the first week is assumed to be the week in which January 1 occurs.
You can use the DatePart function to evaluate a date and return a specific interval of time. For
example, you might use DatePart to calculate the day of the week or the current hour. The
firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols. If date is
a date literal, the specified year becomes a permanent part of that date. However, if date is enclosed
in double quotation marks (" "), and you omit the year, the current year is inserted in your code
each time the date expression is evaluated. This makes it possible to write code that can be used in
different years
<html>
<head>
<title>Date and Time</title> 5/13/03 4:26:25 PM2003
</head> 2
<body> 5
<script language="VBScript"> 133
13
Document.Write Now
3
Document.Write DatePart("yyyy", Now) & "<br>"
20
Document.Write DatePart("q", Now) & "<br>" 16
Document.Write DatePart("m", Now) & "<br>" 26
Document.Write DatePart("y", Now) & "<br>" 25
Document.Write DatePart("d", Now) & "<br>"
Document.Write DatePart("w", Now) & "<br>"
Document.Write DatePart("ww", Now) & "<br>"
Document.Write DatePart("h", Now) & "<br>"
Document.Write DatePart("n", Now) & "<br>"
Document.Write DatePart("s", Now) & "<br>"
</script>
Adding dates.
DateAdd("yyyy", 5, Now)
The DateAdd function is a little awkward to use since the first date is numeric. If you only have two
dates then you need to convert the first one to a numeric value with the DatePart function
You can use the TimeValue function just to add the time part only
12/28/02 12:56:46 AM
mydate = Now + TimeValue(Now)
You can use the DateValue function just to add the Date part only
12/27/4004 2:53:57 AM
mydate = Now + DateValue(Now)
Subtracting dates.
The DateDiff function is used to find the difference between two dates:
The interval in both functions specifies which date or time unit you want to use.
Setting Description
yyyy difference in Years
q difference in Quarters
m difference in Months
y difference in Day of years
d difference in Days
w difference in Weekdays
ww difference in Weeks
h difference in Hours
n difference in Minutes
s difference in Seconds
Make a VBScript that has a Input Box where someone can enter a date and another Input Box to
enter a time and another input box where they can enter fractional hour like 1.5, which means 1
hour 30 minutes. Add the fractional hours to their data and time. In another MsgBox displays the
difference in the time between the original entered time and the changed time. Call your HTML file
ASPL4Ex3.htm
FORMATTING DATES
Dates can have many types of representation as shown in the following table:
Format Function
You can use the Format function to format dates and time. The Format function returns a Variant
(String) containing an expression formatted according to instructions contained in the format
expression.
Format(expression[, format[, firstdayofweek[, firstweekofyear]]])
Part Description
expression Required. Any valid expression.
format Optional. A valid named or user-defined format expression.
firstdayofweek Optional. A constant that specifies the first day of the week.
firstweekofyear Optional. A constant that specifies the first week of the year.
The firstdayofweek argument specifies which day is the start of the week has these settings:
The firstweekofyear argument specifies which day is the first of the year and has these settings:
Summary
To Format Do This
Use predefined named numeric formats or create user-
Numbers
defined numeric formats.
Use predefined named date/time formats or create user-
Dates and times
defined date/time formats.
Date and time serial numbers Use date and time formats or numeric formats.
Strings Create your own user-defined string formats.
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
57
If you try to format a number without specifying the format parameter than, Format provides
functionality similar to the Str function. Positive numbers formatted as strings using Format don’t
include a leading space reserved for the sign of the value. Those converted using the Str function
retain the leading space.
special characters
06/09/02 15:55:43
06/09/2002 15:55:43
Jun/Sun/2002 15:55:43
Jun/Sunday/2002 15:55:43
Sunday June 9, 2002 03:55:43 PM
Sunday June 09, 2002 03:55:43 PM
The FormatDateTime function is just used for formatting data and time.
FormatDateTime(Date[,NamedFormat])
FormatDateTime(Now, vbGeneralDate)
Part Description
Date Required. Date expression to be formatted.
Optional. Numeric value that indicates the date/time format used. If
NamedFormat
omitted, vbGeneralDate is used.
MonthName(month[, abbreviate])
MonthName(1)
Part Description
Required. The numeric designation of the month. For example, January is 1,
month
February is 2, and so on.
Optional. Boolean value that indicates if the month name is to be abbreviated.
abbreviate If omitted, the default is False, which means that the month name is not
abbreviated.
WeekdayName(1)
Part Description
Required. The numeric designation for the day of the week. Numeric value of
weekday
each day depends on setting of the firstdayofweek setting.
Optional. Boolean value that indicates if the weekday name is to be
abbreviate abbreviated. If omitted, the default is False, which means that the weekday
name is not abbreviated.
Optional. Numeric value indicating the first day of the week. See Settings
firstdayofweek
section for values.
Make a VBScript that asks the user for year, month, day of month and day of week using a MsgBox.
If the person enters a leap year, print out the date and time formatted as Monday February 29,
1984. Else tell them to enter a leap year. Use the MonthName and WeekdayName functions. Call
your HTML file ASPL4Ex4.htm
UTILITY FUNCTIONS
Utility functions provide you with everyday things like random numbers and timer functions. Random
number functions gets you random numbers and timer functions let you time program segments.
RANDOM NUMBERS
Random numbers are needed for mathematical computations. Random numbers are produced by a
mathematical equation. To produce a random number you first need to seed the mathematical
equation. The "seed" is basically the value used to calculate the first random number. You set the
seed with the Randomize Sub. In the following example our seed is 1.
Randomize 1
If you do not specify a seed value the value the time of day is used. (Recommended to use this one)
Randomize
When you use the time of day as a seed, you will always get different random numbers every time
you run your program. This is because time is a unique number.
To get the random number you use the Rnd function. This function returns a positive number
between 0 and not quite 1.
Multiplying by 100 would give us a random number of 0 to 99. To get a number between 1 and 100
just add a 1.
num = (rnd * 100) + 1 ' generate a random number between 1 and 100
In a VBScript generate three random number between 1 and 6. In a MsgBox display the three
random numbers. When all three number match display "You Win". If all three numbers do not
match display "You Loose" . Do this 10 times, use a loop. Call your HTML file ASPL4Ex5.htm
In a VBScript have the user enter a number in a Input Box. After they enter the numbers display
how long it takes to count down to zero using a loop. Display the start, finished and elapsed time.
Call your HTML file ASPL4Ex6.htm
File: ASPGuideL5.doc
Date Started: Mar 16, 2002
Last Update: June 16, 2003
ISBN: 0-9730824-3-7
Version: 0.0
INTRODUCTION TO ASP
ASP stands for Active Server Page. An Active Server Page is a program that executes on a Web
server that receives information from a Web page located on a Web browser. The ASP page receives
the information from the Web browser and then sends back a generated Web page to the Web
browser. Pages now on a Web browser can now interact with the user. The Web page may now
display calculated data or data stored in a database. Here is the big picture.
ASP pages are written in VB Script that we have studied in previous lessons. As you found out
VBScript is very similar to Visual Basic. Once you know Visual Basic you can learn VB Script very
easily.
BUILT IN OBJECTS
ASP relies on provided built in objects. An object is a group of variables all having something in
common. Objects have functions written for them so that they can do calculations on the data
stored in the object. A good example to understand objects is an object to read and write data to a
file. To read and write data to a file we would need variables to store the file name, the file mode,
(read or write) and file status to indicate end of file etc. Once we got the variables we need functions
to do things with these variables. An object needs functions so that we can do things with the
variables. Functions used on an object are known as methods. In our File object example we would
need functions to open read, write, and close files.
We only need one set of functions. We could have many File objects, but we only need one set of
functions because we can only access one File object at a time. It would be a waste of code to have
separate functions for every object. The compiler knows which functions can be used for what
objects. Now that we sort of know what an object is, we must know how to use objects.
ASP OBJECTS
ASP has many objects that are already created for you. All you have to do is use them. Here are a
couple of objects used to receive information from a web browser and to send information back to a
Web browser.
REQUEST OBJECT
The Request object stores all the information provided by the Web browser to the Web server. The
information may be provided by input forms, URL parameters, etc. Here is a complete list of Web
browser information sent to the web server. The Web server needs to store all this information
Here is an example to get the Query String information from the URL. QueryString information
follows a ? in a URL and it contains parameter name=value pairs separated by "&". To get the query
string information we use the QueryString method of the Request object. You give it a parameter
name and it returns the parameter value.
Request.QueryString("msg")
http://localhost/ASPLesson5/hello.ASP?msg=hello+world
The QueryString method would return "Hello world". The query string is xxx-urlencoded where a "
" (space) is represented by a "+". The QueryString method has decoded the query string.
RESPONSE OBJECT
The Response object sends information back to the web browser. We can use the Write method of
the Response object to send some HTML text back to the web browser.
Response.Write("<HTML><HEAD><TITLE>Hello Word</TITLE></HEAD>")
<HTML>
Hello World
<HEAD>
<TITLE>Hello World</TITLE>
</HEAD>
You cannot use the Document.Write method because the Document object is only available on Web
browsers not Web servers.
Here's the big picture. The Web browser requests an asp PAGE from the Web Server. The Web
server receives the request and executes the ASP page. The Web server automatically creates the
Request and Response objects. The received information is stored in the Request object. The ASP
page may want to send an HTML page back to the web browser. All the information needed to send
information back from the Web browser is stored in the Response object.
Before you can start writing ASP code you need to run it on a Web server. ASP code does not run on
a Web browser. HTML code runs on a Web browser. Windows 98, 2000 and XP all include a Web
Server that you can use to run your ASP programs on. For Windows98 it is called PWS 4.0
(Personnel Web Server) If you have Windows 98 2nd version the web server is in the extras sub
directory. You must have the CD version 2 PWS. (CD version 1 PWS does not execute ASP files). If
you are running Windows 2000 or XP it is called IIS (Internet Information Server). You must install
it from the Windows installation CD.
After installation just click on the Web server icon and the following screen appears.
You need to set up a virtual directory to run your ASP pages in. This is easy just press the Advanced
button in the above screen snapshot. The following dialog box appears that allows you to choose a
directory where to run your ASP programs. You need to give this directory an alias name so the web
browser can locate it. An alias represents the directory where you store your web pages.
The ASP page run's in the Web server, the HTML page runs on the Web browser. It is customary to
write ASP code and HTML code in the same file. You need to tell the server which parts run on the
Web server and which parts will be sent to the Web browser. You enclose the ASP code starting with
a <% tag and end with a %> tags. If you want a value to be sent to the web browser screen we
then start with a <%= tag and end with a %> tag. You can have an ASP file with all ASP code and
no HTML or a file containing both HTML code and ASP code or all HTML code. The ASP code is
contained in the <% ASPcode %> tags and the untagged portions are considered HTML code that
is directly sent to the Web browser. ASP code is written in VB Script. Type you first ASP program
into as text editor like node pad, call it Hello.asp.
Put your hello.asp ASP page in your virtual directory. Once you got this typed in you need to
execute the ASP file by calling it on your Web browser. Make sure your Web server is running and
make sure you use http://localhost and not the file name. If you use the file name then the web
browsers will just interpret the HTML portion and ignore the ASP script code. Using Internet Explorer
type the following into the location bar substituting your own alias name.
http://localhost/ASPLesson5/hello.ASP?msg=hello%20world
Then press the Enter key. You should have something like this :
The URL request the hello.ASP page from your web server.
http://localhost/ASPLesson3/hello.asp?msg=hello%20world
To get the query string information we use the QueryString method of the Request object.
Request.QueryString("msg")
Usually the query string originates from a Text Box in a form. In the next example we will make an
HTML page that has a Text Box in a form. When a message is entered into the Text Box the
hello.asp page will be called.
You should now have something like this in your location bar.
http://localhost/ASPLesson5/hello.ASP?msg=hello+world
SERVER VARIABLES
You should now know what server variables are. They are very important but a little confusing to
understand. When a web browser make a connection to your Web server, allot of information is
gathered about the connection, and the Web browser. The Web browser connects to your web page
through its ISP Internet service provider. Regardless of which language you use Perl, Java, ASP for
your script code, you will always encounter the HTTP environment variables.
To read a server variable you use the ServerVariables function of the Request object and specify
the server variable name.
Request.ServerVaraiables("variable name")
The following ASP program prints outs all the HTTP SERVER variable name values. The ASP code is
highlighted in yellow. This is a very good example of ASP code mixed with HTML code..
<HTML>
<head>
<title> test </title>
</head>
<body>
<h2>Environment Variables </h2>
<table>
<%
DIM headers
headers=split(Request.ServerVariables("ALL_HTTP"),chr(10))
%>
<tr>
<td>ALL_HTTP</td>
<td><table>
<% for i=0 to ubound(headers) - 1 %>
<tr>
<td><% Response.write left(headers(i),instr(headers(i),":")-1)%>
</td>
<td><% Response.Write mid(headers(i),instr(headers(i),":")+1)%>
</td>
</tr>
<% next %>
</table>
</td>
</tr>
<tr>
<td>AUTH_TYPE</td>
<td></td>
<td> <%=Request.ServerVariables("AUTH_TYPE")%>
</td>
</tr>
<tr>
<td>AUTH_PASSWORD</td>
<td> <%=Request.ServerVariables("AUTH_PASSWORD")%>
</td>
</tr>
<tr>
<td>AUTH_USER</td>
<td> <%=Request.ServerVariables("ALL_USER")%>
</td>
</tr>
<tr>
<td>CONTENT_LENGTH</td>
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
69
<td> <%=Request.ServerVariables("CONTENT_LENGTH")%>
</td>
</tr>
<tr>
<td>CONTENT_TYPE</td>
<td> <%=Request.ServerVariables("CONTENT_TYPE")%>
</td>
</tr>
<tr>
<td>DOCUMENT_NAME</td>
<td> <%=Request.ServerVariables("DOCUMENT_NAME")%>
</td>
</tr>
<tr>
<td>DOCUMENT_URI</td>
<td> <%=Request.ServerVariables("DOCUMENT_URI")%>
</td>
</tr>
<tr>
<td>DATE_GMT</td>
<td> <%=Request.ServerVariables("DATE_GMT")%>
</td>
</tr>
<tr>
<td>DATE_LOCAL</td>
<td> <%=Request.ServerVariables("DATE_LOCAL")%>
</td>
</tr>
<tr>
<td>GATEWAY_INTERFACE</td>
<td> <%=Request.ServerVariables("GATEWAY_INTERFACE")%>
</td>
</tr>
<tr>
<td>LAST_MODIFIED</td>
<td> <%=Request.ServerVariables("LAST_MODIFIED")%>
</td>
</tr>
<tr>
<td>PATH_INFO</td>
<td> <%=Request.ServerVariables("PATH_INFO")%>
</td>
</tr>
<tr>
<td>PATH_TRANSLATED</td>
<td> <%=Request.ServerVariables("PATH_TRANSLATED")%>
</td>
</tr>
<tr>
<td>QUERY_STRING</td>
<td> <%=Request.ServerVariables("qUERY_STRING")%>
</td>
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
70
</tr>
<tr>
<td>QUERY_STRING_UNESCAPED</td>
<td> <%=Request.ServerVariables("QUERY_STRING_UNESCAPED")%>
</td>
</tr>
<tr>
<td>REMOTE_ADDR</td>
<td> <%=Request.ServerVariables("REMOTE_ADDR")%>
</td>
</tr>
<tr>
<td>REMOTE_HOST</td>
<td> <%=Request.ServerVariables("REMOTE_HOST")%>
</td>
</tr>
<tr>
<td>REMOTE_USER</td>
<td> <%=Request.ServerVariables("REMOTE_USER")%>
</td>
</tr>
<tr>
<td>REQUEST_METHOD</td>
<td> <%=Request.ServerVariables("REQUEST_METHOD")%>
</td>
</tr>
<tr>
<td>SCRIPT_NAME</td>
<td> <%=Request.ServerVariables("SCRIPT_NAME")%>
</td>
</tr>
<tr>
<td>SERVER_NAME</td>
<td> <%=Request.ServerVariables("SERVER_NAME")%>
</td>
</tr>
<tr>
<td>SERVER_PORT</td>
<td> <%=Request.ServerVariables("SERVER_PORT")%>
</td>
</tr>
<tr>
<td>SERVER_PORT_SECURE</td>
<td> <%=Request.ServerVariables("SERVER-PORT_SECURE")%>
</td>
</tr>
<tr>
<td>SERVER_PROTOCOL</td>
<td> <%=Request.ServerVariables("SERVER_PROTOCOL")%>
</td>
</tr>
<tr>
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
71
<td>SERVER_SOFTWARE</td>
<td> <%=Request.ServerVariables("SERVER_SOFTWARE")%>
</td>
</tr>
<tr>
<td>URL</td>
<td> <%=Request.ServerVariables("URL")%>
</td>
</tr>
</table>
</body>
</HTML>
The output on the Web browser would be like this: It is different for every web browser connection.
Environment Variables
image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, application/vnd.ms-excel,
HTTP_ACCEPT
application/msword, application/vnd.ms-powerpoint,
*/*
HTTP_ACCEPT_LANGUAGE en-us
ALL_HTTP
HTTP_CONNECTION Keep-Alive
HTTP_HOST localhost
Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;
HTTP_USER_AGENT
DigExt)
HTTP_ACCEPT_ENCODING gzip, deflate
AUTH_TYPE
AUTH_PASSWORD
AUTH_USER
CONTENT_LENGTH 0
CONTENT_TYPE
DOCUMENT_NAME
DOCUMENT_URI
DATE_GMT
DATE_LOCAL
GATEWAY_INTERFACE CGI/1.1
LAST_MODIFIED
PATH_INFO /aspLesson3/env.asp
PATH_TRANSLATED C:\courses\asp\programs\Lesson3\env.asp
QUERY_STRING
QUERY_STRING_UNESCAPED
REMOTE_ADDR 127.0.0.1
REMOTE_HOST 127.0.0.1
REMOTE_USER
REQUEST_METHOD GET
SCRIPT_NAME /aspLesson3/env.asp
SERVER_NAME localhost
SERVER_PORT 80
SERVER_PORT_SECURE
SERVER_PROTOCOL HTTP/1.1
SERVER_SOFTWARE Microsoft-IIS/4.0
URL /aspLesson3/env.asp
Forms allows the user to enter data on a Web browser and send to the Web server. Forms are
written in HTML. The following is a list of available form objects.
Using forms is a good example of a Model - View - Controller architecture. The view is the web
page executing on the web browser. The model is the web server that gets data requests from the
web browser. The controller the web browser that may request an HTML file to be displayed or
send form data to the web server. A form control residing on an HTML file may request data from
the Web server using the ASP file. The ASP file may get the requested data from a file, database or
locally stored in memory.
web browser
webserver
request html page
web page
HTML
Document send html page
stored data
file
database
memory
The only draw back I don't like about this model is that a new Web page must always be generated
(refreshed). What we need is a web page where the form controls individually can communicate with
the Web server. One day this will be possible. but for now the ASP code must send back a
generated Web page.
Data from Form controls are usually sent to the Web server ASP page by the POST method rather
than the GET method. The GET method sends the data as a query string following a "?" after the
requested URL.
http://localhost/ASPLesson5/hello.asp?msg=hello+world
The POST method sends the Data as binary data hidden from the viewer. The POST method is used
because the information is not to be shown on the Web browser URL location bar. Another good
reason is that unlimited data can be sent using POST.
To receive a message using the Post method we use the Form method from the Request object.
LABELS
<html>
<head>
<title> Label.htm </title>
</head>
<body>
<INPUT type="label" value ="I'm a Label">
</body>
</html>
TEXTBOXES
Text boxes allow a user to send information like their name, address to a ASP file.
<html>
<head>
<title> Textbox.html </title>
</head>
<body>
<h2>Enter a message:</h2>
<form action=message.asp method=post>
<table>
<tr>
<td>name:</td>
<td><input type="text" name="message"></td>
</tr>
<tr>
</table>
</form>
</body>
</html>
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
74
Here's some ASP code that will receive the message then send it back to the web browser.
<html>
<head>
<title> Message.asp </title>
</head>
<% = Request.Form("message") %>
<body>
</body>
</html>
Now run your HTML file using localhost on internet explorer. You should get something like this,
Type in the above program and get it going. Once it is working use it to write an HTML page that has
three text boxes labeled Name, Address and Phone. Write as ASP program that receive the
information from the web page and returns a Thankyou page listing their Name, Address and Phone.
Bonus if they forget to enter some data tell them! Call your HTML file ASPEx1.htm and your ASP
page ASPL5Ex1.asp.
BUTTONS
• Submit
• Reset
• Push Button
The Submit button is used to send the values of the form controls to the web server. The Reset
button is used to clear the values of the form controls. The Push button is used to call VBScript
functions to do things like validate data in a TextBox.
We will now add a submit and reset button to our previous HTML example.
<html>
<head>
<title>button.html</title>
</head>
<form method=post action="button.asp">
<table>
<tr><td>
<input type=text name="message">
</td></tr>
<tr><td>
<input type=submit name="submit"
value="Submit">
<input type=reset name="reset"
value="Reset">
<input type=button name="button"
value="Button">
</td></tr>
</body>
</html>
When we type in "Hello World" in the message box and press the Submit button, the Button.ASP file
is called. The Button.asp extracts the information from the form and sends back a message to the
Web browser for display. Notice we only can display the value of the text box and submit button.
<html>
<head>
<title> Button.asp </title>
</head>
<body>
<% = Request.Form("message") %>
<p>
<% = Request.Form("submit") %> <br>
<% = Request.Form("reset") %> <br>
<% = Request.Form("button") %> <br>
</p>
</body>
</html>
Add a Submit and Reset button to the previous exercise. Call your HTML file ASPL5Ex2.htm and
your ASP page ASPL5Ex2.asp.
CLICK EVENTS
PushButtons do not do anything by them selves. You use the ONCLICK event to make them do
something. When the user clicks on the pushbutton an event handler can be called that does
something.
In proceeding lessons you will find lots of uses for the ONCLICK event. All of the controls respond to
events. Here is the complete html file using pushbuttons and ONCLICK events.
end sub
</script>
</head>
<form method=post action="pushbutton.asp" name="form1">
</body>
</html>
RADIO BUTTONS
Radio buttons let you select one option only from many. To group radio buttons together each radio
button needs to have the same name. To identify which radio button was selected, each radio button
needs its own value for identification. Here is our HTML code with the radio buttons. We still need a
Submit button to send the information to the Web server.
<html>
<head>
<title> Radiobutton.html </title>
</head>
<body>
<h2>Select a Color:</h2>
<form action="radiobutton.asp"
method="post">
<table><tr>
<td><input type="radio" name="color"
value="red"></td>
<td>red</td>
<td><input type="radio" name="color"
value="green"></td>
<td>green</td>
<td><input type="radio" name="color"
value="blue"></td>
<td>blue</td></tr>
<tr><td colspan="6">
<input type=submit name="submit"
value="Submit">
<input type=reset name="reset"
value="Reset"></td></tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title> RadioButton.asp </title>
</head>
<body>
<% = Request.Form("color") %>
</body>
</html>
Add a three radio buttons to your previous exercises. Label them "Small", "Medium" or "Large". Call
your HTML file ASPL5Ex3.htm and your ASP page ASPL5Ex3.asp.
CHECKBOXES
Checkboxes are like radio buttons except they are checked and you can select as many as you want.
Again here is our code.
<html>
<head>
<title> checkbox.html </title>
</head>
<body>
<h2>Choose Colors:</h2>
<form action="checkbox.asp"
method="post">
<table>
<tr><td><input type="checkbox"
name="red" value="red"></td>
<td>red</td>
<td><input type="checkbox"
name="green" value="green"></td>
<td>green</td>
<td><input type="checkbox"
name="blue" value="blue"></td>
<td>blue</td></tr>
<tr><td colspan="6">
<input type=submit name="submit"
value="Submit">
<input type=reset name="reset"
value="Reset"></td></tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title> CheckBox.asp </title>
</head>
<body>
<p>
<% = Request.Form("red") %> <br>
<% = Request.Form("green") %> <br>
<% = Request.Form("blue") %> <br>
</p>
</body>
</html>
Add a four or more check boxes to your previous exercises. Label them "tomatoes", "pepperoni",
"green peppers" and "onions". Call your HTML file ASPL5Ex4.htm and your ASP page ASPL5Ex2.asp.
SELECT LISTS
Select lists lets you chose an item from a list of items. A select list may show 1 item or all items. In
the situation where all items are not shown horizontal scroll bars are provided so that the user can
scroll through the choice of items. If the multiple attribute is set then more than one selection can
be selected by holding down the shift key. All selected items are highlighted.
<html>
<head>
<title> select.html </title>
</head>
<body>
<h2>Choose Colors:</h2>
<form action="select.asp" method="post">
<table>
<tr><td>
<select name="colors" size="3" multiple>
<option selected>red
<option>green
<option>blue
</select>
</td>
</tr>
<tr>
<td>
<input type=submit name="submit"
value="Submit">
<input type=reset name="reset"
value="Reset">
</td>
</tr>
</table>
</form>
<html>
<head>
<title> Select.asp </title>
</head>
<body>
<% = Request.Form("colors") %>
</body>
</html>
Add a List box that lets the user select their city area, like "uptown", "east side", "lower side" etc.
Call your HTML file ASPEx5.htm and your ASP page ASPL5Ex4.asp.
Hidden fields are a great way to exchange data between forms and ASP pages. Hidden fields are not
associated with any Form Control. It is just like sending data back to the Web server. In our
example we send back a name "hidden" having the value "secret"
<html>
<head>
<title> hidden.html </title>
</head>
<body>
<h2>Press the Submit Button:</h2>
<form action="hidden.asp" method="post">
<input type=hidden name="hidden"
value="secret">
<input type=submit name="submit"
value="Submit">
<input type=reset name="reset"
value="Reset">
</form>
</body>
</html>
<html>
<head>
<title> Hidden.asp </title>
</head>
<body>
<% = Request.Form("hidden") %>
</body>
</html>
In a hidden field encode the name of your store and the price of the pizza and toppings. From the
information received make a bill of sale, the total cost of the order the additional charge for the
toppings and any applicable taxes and delivery charge. Call your HTML file ASPEx6.htm and your
ASP page ASPL5Ex6.asp.
File: ASPGuideL6.doc
Date Started: Mar 20, 2002
Last Update: June 17, 2003
ISBN: 0-9730824-3-7
Version: 0.0
RESPONSE OBJECT
Information about the WebBrowser connection to the Web Server is stored in the Response object.
Using the Response object you can send generated HTML pages back to the Web browser. We use
the Write method of the Response object to send some generated HTML text back to the Web
browser.
Response.write("<HTML><head><title>Hello</title></head>")
We can continue with many other Response.Write statements to continue the generated Web
page. You have to be careful using the Response.Write statement because HTML uses double
quotes to group text together. Here is an example using many double quotes.
Every thing is okay as long as all the double quotes are balanced. Alternatively you may like to use
single quotes.
Response.Write("<table width=50%>")
It may not be obvious at first but remember those ASP delimiters <% %> ? While it seems hard to
believe but the ASP scanner thinks that the %> in 50%> is one of those ASP delimiter things! Can
you believe it ? In this situation you need to backslash the angle bracket as follows
Response.write("<table width=50%/>")
Convert any simple HTML document to a generated page or just make up your own using
Response.Write. Call your ASP script ASPL6Ex1.asp.
You will find this very handy. The Redirect method will let you send the Web browser to a different
HTML or ASP Web page! It works for both indirect and direct URL addresses.
Response.redirect("date.ASP")
Response.redirect("http://www.cstutoring.com")
Write an HTML page that has a link to an ASP page that redirects the Web browser to another HTML
page ! Call your HTML file ASPL4Ex2.htm and your script ASPL4Ex2.asp.
BUFFERED OUTPUT
Buffering allows you to build up a Web page in memory rather than sending out line by line. Once
the Web page is built up, it is sent out. The Response object has these methods to allow buffering.
method description
Buffer turn on buffering (True) turn off buffering (False)
Clear empties the buffer
Flush send buffered text to Web browser
<%
Response.Clear
Response.Buffer=True
Response.write("<head><title></title></head><body>")
Response.write("<h2>this is a buffer test</h2>")
Response.write("</body></HTML>")
Response.Flush
%>
You first clear the buffer then set the Buffer to True, write out the HTML then flush. Flush means
send every thing out right away. What could be an immediate benefit using buffering ? Do you Give
up ? You can build up your web page and don't have to worry about re-wending header information.
CACHE CONTROL
Caching allows the Web browser to store Web pages to be displayed to the user later. A Web
browser usually stores image files like GIF and JPEG to be displayed again without downloading.
Since images do not change very often we do not have to mark that the image is current. Web
pages are a different story. Web page content is always changing for example like new stories or
weather report. Some Web pages do not change. You can control if you want a Web page to be
cached or not.
Response.CacheControl = "Private"
Response.CacheControl = "Public"
For dynamically generated pages like your ASP page you do not have to worry if it will be cached or
not, because it is always being re-generated.
You can specify the amount of time you allow for your page to be cached:
Response.Expires= 15
This means this page will expire in 15 minutes, and then a new page cab be reloaded.
Response.Expires= -1
The Web page will always be requested from the Web browser.
You can also indicate when a Web page will expire, this page will expire on Jan 3, 2004.
Response.ExpiresAbsolute = #01/03/04#
The Content Type response header tells the Web browser what kind of data you are sending. The
most common one is text/HTML. There may be situations where you need to send the Web
browser other type of data like "text/plain". To do this all you need to do is:
Response.ContentType = "text/plain"
Content-Type description
text/plain text
text/html text and html
application/octet-stream binary code
application/x-www-form-urlencoded name=value pairs
Write an ASP page that uses buffering, expires immediately and sets the content-type as the last
line in the program. Call your ASP program ASPL4Ex3.asp.
COOKIES
Cookies store pieces of information like a customer identifier on a Web browser file. When a user
connects to your server the only information you have is there IP address. The ISP gave it to the
user when they dialed in. It would be difficult to use the IP address to identify a user because they
would obtain a different IP address every time they logged in. A good way to identify a user is to
store a user id on their Web browser. The next time they connect to your site, you just read the id
from the Web browser then you know who they are! For cookies to work the Web browser must
allow cookies enabled. Cookies are small files stored by the Web browser.
creating a cookie
Cookies are easy to make. We use the Cookies method of the Response object .
Response.Cookies("counter") = "1"
We give our cookie a key "counter" and a value "1". The key let us locate the cookie in the user
machine. Cookies do not last forever. If we do not tell the Web browser how long we want the cookie
to last it will delete it right away. You use the Expires property to set the cookies expiry date.
Response.Cookies("counter").Expires=dateadd("d",1,date)
We use the dateadd method to add 1 day to the current day. The cookie will expire at 12 midnight
the next day. We use the Cookies method of the Request object to read the value of a cookie
stored on a users machine.
request.cookies("counter")
We use the key "Counter" to locate the cookie in the users machine. Here is the complete program:
Notice we create the cookie before the HTML header is written, this is because cookies are sent in
the header section. We need to set up the header information before we send out the header. The
header information is located between the <head> tags.
<%
Response.Cookies("counter") = "1"
response.Cookies("counter").expires=dateadd("d",1,date)
%>
<HTML>
<head><title>cookie test </title></head>
<body>
<p>creating cookie <br>
cookie created <br>
getting cookie <br>
<% response.write(request.cookies("counter")) %> <br></p>
</body>
</HTML>
The cookies are located in the Windows directory in the Cookies subdirectory. They will have the
following fields:
name of value of internet size of Expiration Last modified Last last read
cookie cookie address cookie date and date and time accessed date and
time data and time
time
counter
1
localhost/aspLesson4
0
1997670400
29537600
1896753472
29537468
*
Once you got your cookie on the users machine you need to modify it. This is easy to do you just
write to the cookie again. We are incrementing the counter, we first convert to an integer using the
CInt function then add 1.
response.cookies("counter")=cInt(cookie)+1
removing a cookie
We can also remove our cookie. All we have to do is to set the cookie value to an empty string.
response.cookies("counter")=""
Here is our complete ASP code that increments and display the value of the cookie. Notice again we
put the cookie code before the HTML header code.
<%
dim cookie
cookie = request.cookies("counter")
if(cookie="")then
response.cookies("counter")="1"
response.cookies("counter").expires=dateadd("d",1,Date)
elseif(cookie<>""and cint(cookie)=50)then
response.cookies("counter")=""
else
response.cookies("counter")=cint(cookie)+1
response.cookies("counter").expires=dateadd("d",1,Date)
end if
%>
<HTML>
<head>
<title>cookie2 test </title>
</head>
<body>
<p>getting cookie <br>
<% response.write(request.cookies("counter"))%> </p>
</body>
</HTML>
counter
5
localhost/aspLesson4
0
1997670400
29537600
3705388672
29537518
*
Make an ASP page that has a form that asks for a persons name. Store the name in a cookie. Next
time they visit your form greet them by their name and tell them how many times they have visited
your site. Call your script ASPL6Ex4.asp.
APPLICATION OBJECT
Your ASP project may contain many files. All ASP files in your Web server directory are known as an
application. All the Web page ASP files need to exchange data, an Application object solves this
problem. Here is a real world example using an Application object. In an on-line store you will have
many forms to gather information. You will need a shopping cart that contains the items to buy. This
information is needed to be shared between all ASP files.
To store information in an application object all you have to do is to supply some user id, like a
name or key and a value.
Application("Count") = 1
key value
All other ASP files in your directory will be able to access the value of the key "Count"
count = Application("Count")
All non object information like numbers are put into a Collection object of the Application object. A
Collection object is like an expandable array . You write entries by:
Application.Contents("Count") = 1
count = Application.Contents("Count")
Application("Count") = 1
count = Application("Count")
You can print out all the items in the Contents collection using the for each statement. In ASP the
for each statement is only available for objects like the Application.Contents object.
Application.Contents.Remove("Count")
Application.Contents.RemoveAll
When you have many users all accessing your Web pages all at the same time, you need to restrict
access to the Application object one user at a time.
The Lock method restricts only one user to access the application object until the Unlock method is
called. Locking is very important, one user could update the value before another user reads it!
Application.Lock
Application("Count") = 1
Application.UnLock
Make a form that asks for a persons name. and store the name in a Application object. Next time
they write to our form we greet them by their name and will them how many times they have visited
your site. Call your script ASPL6Ex5.asp
SESSION OBJECT
A Session object lets you store information pertaining to a particulars user. A Session object will
let you keep track of the users connection to your Web page. Even if the user goes off page and
comes back the information is kept in the Session object. Each user who connects to the server
gets their own session object. New users get new Session objects, returning users get their
previously assigned Session object. The secret behind Session objects is the user is identified by a
cookie stored in the users Web browser. Users who have cookies disabled will always be assigned a
new Session object.
Session("Count") = 1
All other ASP files in your directory will be able to access the value of "Count" from the session
object.
All non-object information put into the Session object goes into a Collection object. A Collection
object is like an expandable array with key and value pairs. You write entries by:
Session.Contents("Count") = 1
count = Session.Contents("Count")
Session ("Count") = 1
You can print out all the items in the Contents collection using the for each statement. In ASP the
for each statement is only available for collection objects like the Session.Contents object.
Session Contents.Remove("Count")
Session.Contents.RemoveAll
The Timeout property specifies how many minutes of inactivity will ends the life of the session
object. This is desirable because once you finish using a Session object it should disappear.
Session.Timeout = 30
Response.Write Session.Timeout
Session.Abandon
Once you are finished you this session object you should abandon it.
Every session gets an id for identification. The ids are stored as cookies on the user machine. You
use the SessionId method to read the ID.
Response.Write Session.SessionID
Make a form that asks for a person's name. Store the name in a Session object. Next time they visit
your form we greet them by their name and tell them how many times they have currently visited
your site. Call your script ASPL6Ex6.asp
SERVER OBJECT
The server object provides services from the Web server. The ScriptTimeout property set's how
long a page can run before timing out, the default is 90 seconds. The following will set the time out
for 5 minutes.
Server.ScriptTimeout = 300
The Execute method lets you run other ASP files. The results are shown in the current connected
page.
Server.Execute "mypage.ASP"
You can also include a query string so you can send some information to that page.
Server.Execute "mypage.ASP?msg=hello"
The HTMLEncode method is used to print html to the web browse screen.
Server.HTMLEncode("<BR>")
Response.Write Server.HTMLEncode("<BR>")
This means the screen will actually say <BR> rather than start a new line!
<br>
<br><br>
All the special characters like angle brackets < have been encoded.
The MapPath method takes a file name and converts it into its real directory path name located on
the Web server. This one is really handy to have.
Server.MapPath("myprogram.ASP")
The Transfer method redirects you to another page but also transfers all the values of all built in
objects as well as the original query string values to the other page.
Server.Transfer "myfile.ASP"
The URLEncode method translates all the special characters in a URL into their non functional
equivalents
Server.URLEncode("http://www.myWeb.com");
http%3A%2F%2Fwww%2Ecstutoring%2Ecom
Notice: All special characters like ':' have been translated to their ASCII encoding like %3A
Use the Execute and Transfer method to redirect a page. Once you get to the page use the MapPath
method to display the real path of that page. Call your script ASPL6Ex7.asp .
The global.asa file is automatically supplied for you by the web server for your application.
When a page is loaded the OnStart event is called when a page is unloaded the OnEnd event is
called. You can use these events to open and close files, databases etc, RUNAT =Server means the
script will run at the server.
Sub Application_OnStart
End Sub
Sub Application_OnEnd
End Sub
</Script>
The same events also apply to Session objects. When the Session object is created the OnStart
event is triggered. when the session terminates the OnEnd session is triggered.
Sub Session_OnStart
End Sub
Sub Session_OnEnd
End Sub
</Script>
Declaring Objects
The OBJECT tag can be used to create objects to be used in Application or Session objects.
This is known as scope.
Application scope means the object will be available to all applications. Session scope means
available to the current session.
Thus will make the MyTypes.tlb library file available to the ASP application. This has to be used
outside the ASP script tags <% %>
HANDLING ERRORS
When an error occurs in your program it stops. In this situation you want to report the error and
have your program continue. An example of an error is trying to open a file that does not exist. In
ASP we have only one choice to handle errors.
When an error occurs you can use the Err object to get the error code or to check if an error really
occurred. The Err object takes care of finding errors and providing information about them.
property description
Number numeric error code (default property) 0 means no error has occurred
Source states where the error occurred
Description a string that describes the error
Clear clears last error received
Raise causes an error to occur
MsgBox "Error: " & Err.Description ' report the error in a message box
Here is some real live code that opens a file and reports if the file was not successfully opened.
<%
on error resume next
dim filename
filename = Request.QueryString("filename")
pathname = "./downloads/"&filename
dim fso
set fso = Server.createObject("Scripting.FileSystemObject")
dim mapfile
mapfile=Server.MapPath(pathname)
set os = Server.CreateObject("ADODB.stream")
os.open
os.type=1
os.loadFromFile mapfile
Clear Method
Err.Clear
Err.Clear
When you get an error you should always clear it or else it will occur again.
Raise Method
Generates a run-time error. Use this method to generate your own error event.
The Raise method has the following object qualifier and named arguments:
Argument Description
object Required. Always the Err object.
Required. Long integer that identifies the nature of the error. Visual Basic
errors (both Visual Basic-defined and user-defined errors) are in the range 0–
65535. The range 0–512 is reserved for system errors; the range 513–65535 is
number available for user-defined errors. When setting the Number property to your
own error code in a class module, you add your error code number to the
vbObjectError constant. For example, to generate the error number 513,
assign vbObjectError + 513 to the Number property.
Optional. String expression naming the object or application that generated the
error. When setting this property for an object, use the form project.class. If
source
source is not specified, the programmatic ID of the current Visual Basic project
is used.
Optional. String expression describing the error. If unspecified, the value in
Number is examined. If it can be mapped to a Visual Basic run-time error
description code, the string that would be returned by the Error function is used as
Description. If there is no Visual Basic error corresponding to Number, the
"Application-defined or object-defined error" message is used.
Optional. The fully qualified path to the Help file in which help on this error can
helpfile be found. If unspecified, Visual Basic uses the fully qualified drive, path, and
file name of the Visual Basic Help file.
Optional. The context ID identifying a topic within helpfile that provides help
helpcontext for the error. If omitted, the Visual Basic Help file context ID for the error
corresponding to the Number property is used, if it exists.
Dim x
Dim y
x = 10
y=0
Raising an error:
executing code
Err.Raise
no
error Error Object code
Resume Next
Make an ASP script that receives two numbers from a html form have two text boxes and a button
labeled "Divide". When the user enters two numbers and presses the divide button call the asp
script to divide the two numbers. Display the results in a third text box. If the second number is zero
print out a message that says: "cannot divide by zero". You must use an on error resume next
statement and Err object in your ASP page. Don't forget to clear the error. Call your script
ASPL6Ex8.asp and your html form ASPL6Ex8.htm. Alternatively you can include the form inside your
ASP page.
File: aspGuideL7.doc
Date Started: Mar 20, 2002
Last Update: June 17, 2003
ISBN: 0-9730824-3-7
Version: 0.0
DATABASE ACCESS
ADO Active Data Objects are used to access data bases in ASP. ADO uses many other supporting
objects to access the database
Object Description
Connection connect to data base, represents physical connection to data source
Command execute command to the data base
RecordSet represents a set of records from a data base query
Field represents a field of data in a record
Error contains error information resulting from a data base operation
The ADO Objects also use the following Collections to store data
Collection Description
Fields contains all Field objects in a record
Parameters contains all Parameter objects of the Command object
Errors contains error objects resulting from execution using a Connection object
CONNECTION OBJECT
The connection object is responsible to connect to your database. The Connection object has the
following methods
Method Description
BeginTrans begins a new transaction, returns a Long variable indicating the nesting level
of the transaction.
CommitTrans saves any changes and ends the current transaction. It may also start a new
transaction.
RollbackTrans cancels any changes made during the current transaction and ends the
transaction. It may also start a new transaction.
Cancel Cancels execution of a pending, asynchronous Execute or Open method call.
Close Closes an open object and any dependent objects.
Execute Executes the query, SQL statement, or stored procedure in the CommandText
RecordsAffected, the number of records that the operation affected
Parameters, SQL statement
Options how the provider should evaluate the CommandText property
Execute Executes the specified query, SQL statement, stored procedure, or text
CommandText, the SQL statement, table name, stored procedure, or text to execute
RecordsAffected, provider returns the number of records that the operation affected
Options how the provider should evaluate the CommandText argument.
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
99
Property description
CommandTimeout Indicates how long to wait while executing a command before terminating
the attempt and generating an error. The default is 30.
ConnectionString Contains the information used to establish a connection to a data source.
ConnectionTimeout Indicates how long to wait while establishing a connection before
terminating the attempt and generating an error.
CursorLocation Sets or returns the location of the cursor engine
Provider Indicates the name of the provider for a Connection object.
COMMAND OBJECT
A Command object represents a specific command to execute against a Data Source. A Data
Source represents the database you are connected to. A Command object is used to query a
database and return the records in a RecordSet object. Here are the methods of the Command
object.
Method Description
Cancel Cancels execution of a pending, asynchronous Execute or Open
method call.
CreateParameter Creates a new Parameter object with the specified properties.
Name, Optional. A String representing the name of the Parameter object
Type, Optional. specifying the data type of the Parameter object
Direction, Optional. A Long value specifying the type of Parameter object
Size, Optional. specifying the maximum length for the parameter value
Value Optional. A Variant specifying the value for the Parameter object.
Execute (Command) Executes the query, SQL statement, or stored procedure
RecordsAffected, returns the number of records that the operation affected
Parameters, Array of parameter values passed with an SQL statement.
Options indicates how the provider should evaluate the CommandText
Execute (Connection) Executes query, SQL statement, stored procedure, or provider text.
CommandText,
The SQL statement, table name, stored procedure, or provider text
RecordsAffected,
The number of records that the operation affected.
Options How the provider should evaluate the CommandText argument.
Property Description
ActiveConnection Indicates to which Connection object the specified Command or Recordset
object currently belongs.
CommandText Contains the text of a command that you want to issue against a provider.
CommandTimeout Indicates how long to wait while executing a command before terminating
the attempt and generating an error.
CommandType Indicates the type of a Command object.
Prepared Property Indicates whether or not to save a compiled version of a command before
execution.
State Property Describes for all applicable objects whether the state of the object is open
or closed.
Record sets hold the database records that the user wants to see, this is known as a query. The
SQL Language is used to access a database. The following SQL statement is used to query the
database:
This SQL statement would get all the records from the database and put into the record set object. If
you just want to get one particular record only you use the where clause and a condition:
Record sets can be opened for read only or for changing the data base. There are known as
cursor type. A cursor travels to each record on the record set, the current record is where the
cursor is. The following table lists the possibilities. adOpenForwardOnly is the default.
When you have many users accessing the database you need to lock out other users while you a
changing the database. When, if and how you lock is known as a lock type. The following table lists
the possible lock types. adLockReadOnly is the default.
Warning! The constants are not built into ASP you need to include the adovbs.inc file in your ASP
page to be recognized,
C:\ProgramFiles\CommonFiles\System\ADO
else just use the numbers or make your own constants like:
Const adOpenDynamic = 2
A RecordSet object represents the entire set of records from a data base query. At any time, the
Recordset object refers to only a single record within the set as the current record. Here are the
Recordset methods:
Method Description
AddNew
Creates a new record for an updateable Recordset object
FieldList, Optional. A single name or an array of names or ordinal positions of the fields
Values Optional. A single value or an array of values for the fields in the new record.
Cancel Cancels execution of pending, asynchronous Execute or Open method call.
CancelBatch Cancels a pending batch update.Optional. An AffectEnum value that
AffectRecords determines how many records the CancelBatch method will affect.
CancelUpdate Cancels any changes made to the current record or to a new record prior to
calling the Update method.
Clone Creates a duplicate Records object from an existing Recordset object.
Delete Deletes an object from the Fields collection.
Field A Variant designating the Field object to delete.
Delete Deletes an object from the Parameters collection. The name of the object
Index you want to delete, or the object’s ordinal position (index) in the collection.
Delete Deletes the current record or a group of records.
AffectRecords Determines how many records the Delete method will affect.
Find find record if found cursor set to record at EOF or BOF
criteria, specifies the column name, comparison operator, and value to use in search.
SkipRows, Optional specifies the offset from the current row or start bookmark
searchDirection, optional whether the search should begin on current row or next row
start An optional Variant bookmark to use as the starting position for the search.
Move NumRecords, An optional Long value, whose default value is zero, that specifies the offset
Start from the current row or start bookmark to begin the search.
MoveFirst, An optional SearchDirectionEnum value that specifies whether the search
MoveLast, should begin on the current row or the next available row in the direction of
MoveNext, the search. Its value can be adSearchForward or adSearchBackward. The
MovePrevious search stops at the start or end of the RecordSet, depending on the value of
searchDirection.
NextRecordset An optional Variant bookmark to use as the starting position for the search.
Open Opens a connection to a data source.
ConnectionString, A String containing connection information.
UserID, Optional. A String containing a user name
Password, Optional. A String containing a password
OpenOptions Optional. A ConnectOptionEnum value.
Open Opens a cursor. (Recordset)
Source, Command object, SQL statement, table name, stored procedure call, file
ActiveConnection, a valid Connection object , or ConnectionString parameters.
CursorType, type of cursor that the provider should use when opening the Recordset.
LockType, Determines what type of locking (concurrency) the provider should use how
Options the provider should evaluate the Source argument
Requery Updates the data in a Recordset by re-executing the query
Options A bitmask indicating options affecting this operation.
Resync Refreshes the data in the current Recordset object from the database.
AffectRecords, determines how many records the Resync method will affect.
ResyncValues specifies whether underlying values are overwritten.
Save Saves (persists) the Recordset in a file.
FileName, Complete path name of the file where the Recordset is to be saved.
PersistFormat The format in which the Recordset is to be saved.
Supports Determines if Recordset object supports a particular type of functionality.
(CursorOptions ) A Long expression that consists of one or more of the CursorOptionEnum
values
Update Saves any changes you make to the current record of a Recordset object.
Fields, Optional name or array representing names or ordinal positions of the field
Values Optional. Single value or array representing values for the field or fields
UpdateBatch Writes all pending batch updates to disk.
AffectRecords determines how many records the UpdateBatch method will affect.
Property description
AbsolutePage Specifies in which page the current record resides.
AbsolutePosition Specifies the ordinal position of a Recordset object's current record.
ActiveConnection Indicates to which Connection object the specified Command or Recordset object
currently belongs.
BOF, EOF BOF indicates that the current record position is before the first record
EOF indicates that the current record position is after the last record
Bookmark Returns a bookmark that uniquely identifies the current record in a Recordset
object or sets the current record in a Recordset object to the record identified
by a valid bookmark.
CacheSize Indicates the number of records from a Recordset object that are cached
locally in memory.
CursorLocation Sets or returns the location of the cursor engine
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
103
A RecordSet object has a Fields collection made up of Field objects. Each Field object corresponds
to a column in the RecordSet. A Field object represents a column with a common data type. You
use the Value property of Field objects to set or return data for the current record of a specified
column.
rs.fields(1).Value
You use the Name property if the field object to get the name of the column.
rs.fields(1).Name
You can also use the Column name rather than the column number.
rs.fields("price").Value
We will be using the Fields object of the RecordSet quite extensively to access the data base data
stored in the RecordSet.
overall picture
Here's the overall picture. once you can visualize something it is much easier to understand. The
connection object makes the connection to the database. The command object executed commands
to the database. The RecordSet object stores the records in the field's collection. The Errors
collection holds the errors.
Command
Errors Object
Collection
Fields
Connection Collection
Object
RecordSet
Object
Database
Before you can access a data base you should first make one. A Database is made using Microsoft
Access or SQL server. Databases have the mdb extension. Databases usually reside in the dB
directory of your Web Server. The db directory is the directory on your server that allows write
access. If you are using localhost then you can specify any directory you want.
We first need to create a database. We will use Microsoft Access because it is available on every
computer. You can do this in Design view. Just open up a new database and a new table in Design
View, fill in the field names and then select the data type for the field. Most people just select "text"
the default. The Name field must be unique and is known as the Primary Key.
The next step is to put some data in our database so you can use it. You can do this, by just opening
the database in Access and entering the data. Finally name your table Employee and save your
database in a file called aspL7.mdb.
Make a database with 3 tables called Customer, Products and Orders. The Customers table should
have fields: customer_number, name, address, phone and email. The Products table should have
fields: product_number, description, price. The Orders table needs fields order_number,
customer_number, and product_number. Put some products in the product table, using the data
base editor. Call your database aspL7Ex1.mdb. Do not put spaces inside your database field names
or tables. If you do you are asking for big trouble.
(1) reading
(2) updating
Here is the step by step instructions to connect to a data base and print out the contents to a screen
dim cn
A connection string specifies the data base connection provider and the database you want to
connect to. A provides knows how to connect to the database. For windows 98 using Microsoft
access 97 use:
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" _
& "Data Source=c:\courses\students.mdb"
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=c:\courses\students.mdb"
Query a database means to chooses with information you want to read. A record set will hold the
requested rows. The execute method will query the data base with the SQL statement and return a
record set.
dim rs
Records are made up of fields. The record set will have a collection of field objects to represent the
field value and name. Using the Fields collection of Field objects we can write out the column names
stored in each field object to the web browser screen.
A records set may have many records or none. We use the Eof method to indicate when we are at
the end of the record set. Again we use the fields collection count method to indicate how many
fields in each record. We use the short form rs(i) to print out the values of each field in the record
rs(i) really means rs.fields(i).value. Finally we use the moveNext method to get the next record
from the record set.
Response.Write rs(i)
next
rs.Movenext
loop
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
107
[6] after we display all the information we need to close the connection.
rs = nothing
cn.Close
cn = nothing
Here is the complete ASP file. Notice we us a table to align all the data rows and columns evenly.
<%
Dim cn
Dim rs
Dim i
Response.write("<table border=1>")
Response.Write("<th>")
Response.Write rs(i).name
Response.Write("</th>")
next
Response.Write("</tr>")
rs.MoveNext
loop
cn.Close
%>
Make a script that reads your product table and displays them on the screen. Have three text boxes
to display the fields values with first, previous, next and last buttons. Call your script aspL7Ex2.asp
The next thing we need to do is to update the database with different values. Here are the step by
step instructions:
Dim cn
When you are updating a database you need to make your own record set object. The record set
needs to be opened to update a data base record.
Dim rs
Set rs = Server.CreateObject("ADODB.RecordSet")
We open the record set for adOpenKeySet (1) and adLockOptimistic (3)
rs("Phone") = "123-4567"
rs.fields("Phone") = "123-4567"
rs.Update()
rs.close()
cn.Close
<%
Dim cn
cn.Open
Dim rs
Set rs = Server.CreateObject("ADODB.RecordSet")
rs("Phone") = "123-4567"
rs.Update()
rs.close()
cn.Close
%>
Make a form that displays that has a text box for the fields in the product table. Make a button that
they can press called update. The user should be able to scroll through the record set, change the
entries in the textbox and press the update button. Call your script aspL7Ex3.asp
We use the AddNew methods to add records to an existing data base. Here are the step by step
instructions
Dim cn
When you are updating a data base you need to make your own record set object. The record set
needs to be opened to add records and update a data base record.
Dim rs
Set rs = Server.CreateObject("ADODB.RecordSet")
We open the record set for adOpenKeySet (1) and adLockOptimistic (3)
rs.AddNew
rs("Name") = "Bill"
rs("Address") = "57 Ocean Way"
rs("Phone") = "987-6543"
rs.Update()
rs.close()
cn.Close
Add an add button to your script of previous lessons. When the add button is pressed the values in
the text boxes will be added to the record set. Another alternative is the textboxes could go blank
to allow the user to put in the new values then they presses the update button. Call your script
aspL7Ex4.asp
The command object lets you execute commands directly to the database and places the results in a
record set, a command object has the ActiveConnection method to assign a current open connection.
Here are the step by step instructions:
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
use the commandtext method to assign a SQL statement to the command object.
Dim rs
Set rs = cmd.Execute
in the following example we use a Command object to search for a particular record and display the
result.
<%
Dim cn
cn.Open
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = cn
Dim rs
Set rs = cmd.Execute
Dim i
Response.Write("<table border=1>")
Response.Write("<th>")
Response.Write rs(i).name
Response.Write("</th>")
next
Response.Write("</tr>")
rs.MoveNext
loop
Response.Write("</table>")
rs.Close()
cn.Close
%>
HANDLING ERRORS
The Errors collection stores any errors that may have encounter. There definitely is lots of
opportunity for errors.
at the top of your program. This means if an error occurs program execution will go to the next line.
On the next line you will test for errors. if an error occurs you must clear it, it will not go away by
itself.
property description
Number numeric error code (default property) 0 means no error has occurred
Source states where the error occurred
Description a string that describes the error
Clear clears last error received
Raise causes an error to occur
<%
Dim cn
On Error Resume Next
else
Dim rs
Set rs = cn.Execute("SELECT * FROM marks")
End If
%>
Add error capabilities to your script of previous exercise. Put the error in a read only textbox. Call
your script aspL7Ex5.asp
File: aspGuideL8.doc
Date Started: Mar 20, 2002
Last Update: June 17, 2003
ISBN: 0-9730824-3-7
Version: 0.0
ASP PROJECT 1
In this project we will make the classic on-line store. Our first store will be quite simple. You are only
required to sell one item at a time. Later on, our store will get quite complicated, where customers
can select many items for sale. The following is a block diagram of the components to make the on-
line store.
Credit card
processor
cc.asp
thankyou
Home page order items page
order.asp thankyou.asp
store.asp
Select items for
sale
view orders
view.asp
data base
project1.mdb
update products
update.asp
Customers will buy things for sale either on the front page or on other pages. They will clock on the
item they want to buy. They can click on a link, button or an image. They will then go to an order
page showing the item they bought and price. The customer will then presses a pay button to take
them to a credit card form. Here they will enter all the customer information and their credit card
number. The credit card form will validate the credit card and then send all the results of the
transaction to a thank you page. Here the customer will be informed that their credit card
transaction was successful and all order information is displayed as a bill of sale. At this point the
products will be shipped to the customer and or the customer can download the software, video,
audio images what ever. In the real world we just interface to a real credit card processor that
handles all the credit card transactions for us.
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
116
(1) Products
(2) Categories
(3) Customers
(4) Orders
For example if we are selling posters, all we need is the poster name, some description to intice our
customers, the name of the poster image file to send to the customer and the price of the poster.
(You should not store image files in a database only there names)
Here is an example of a product table:
• boats
• flowers
• Streets
If the customer wanted to view by category or if you want to display your products for sale by
category then you need a category table and a category field in your product table. Our Categories
table has only 1 field, category. but you could definitely have more.
category
boats
flowers
cities
Each table will have a unique key known as the primary key. The primary key is used to make sure
each record is unique (no duplicate names) and as an index for sorting the table The primary key
for the product table will be the item field. The primary key for the category table will be the
category field. When a primary key is used in another table then it is known ass a foreign key. The
category table is used to lists all the available categories. The category field found in the product
table would let us list products for sale by category.
Will need to keep track of all customers who have bought at the store. Each customer needs to be
identified some how. We have many choices
We need to choose something that will never change. The best answer is using the customer name.
When the customer is inserted into the data base, each customer will get an automatic auto id.
Although we will still have to search for customer by name. If you think you will have many
customers with the same name then you can also use phone number and email for further
identification. Microsoft Access allows you to have a primary key spanning one field or more than
one field. All you have to do is: in design select more than 1 field using the shift key. right click and
select primary key option from the pop up menu. The customer ID will be used as foreign keys in
other tables.
In our order table we need to know which customer and which item they bought. We use the item
field from the product table and the customerID field from the customers table. Using the
customerID field makes it easier for us to identify the customer. The orders table needs additional
information like payment method, date purchased etc. Every order gets its own orderID for
identification.
The following chart shows the relations between the tables. The orders table identifies the customer
and item bought.
orders
products orderID
categories item item
category category customerID
description payment
imagefile
price
customers
customerID
Name
Address
Phone EMail
It is best to have a separate page for each thing a customers has to do. We have listed the pages
required for the customer actions.
The home pages must attract customers, be easy to use and navigate. Home pages must also
appear as a safe place to buy. On the front page you can just list your categories of items for sale or
list category and items together. You read the database and then list the items for sale. You can use
the WHERE clause in your SQL SELECT statement to group items by category.
The categories can be obtained from a second record set. You may have a separate page for each
item category. Since our first project is a simple online store they only need to buy item from a
choice of many items. Provide an encoded link button or image, once the click on it they go to the
order confirmation page. You can encode the button with the item number as a query string.
"orders.asp?partnumber=1234"
It is here if the customer really want to buy your product. You must be very convincing at this point.
Offer them a full 30-day money back guarantee! Tell them the terms of sale and methods of
payment and when and how they will get their item once they pay for it. Make them pay for the item
by clicking on a link or by pressing a pay by credit card button.
The credit card processor receives the customer id, item bought and amount for goods. The credit
card processor collects all the customer data for you like address and phone numbers. It receives
the credit card number, check if its is good and then tells you every thing is okay. How does it tell
you every thing is okay? What you got to do is to give it a return URL address. After the credit card
processor validate the transaction it calls the page using the return URL address and then sends all
the transaction details to that page. It also sends a receipt to the customer and to you. In the real
world you can use a ready made credit card processor. They are all have SSL encrypted and
communicate directly with the credit card companies and their banks. For this project you need to
write your own unless you have access to one. For now just hard code a few credit card numbers.
Verify using customer name address and telephone number. If a bad credit card number is found
then the customer will be informed and your thankyou page will not be called. Do not use the
Database to store credit card verification information. The credit card processor has its own data
bases not associated with your database. You must use the POST method for all credit card
transactions.
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
121
Put items bought in Verifies credit card number. Receives customer and transaction
databases identified Collects customer information like information and stores in database.
by a orderid. address and phone number. Presents bill of sale and shipping
Send to thankyou page information or a link to download
page
In your thank you page you thank the customer for the order. You check the credit card transaction
details. You put all the customer information in the customer table. You put all the order information
in the order table. If you a shipping the goods to the customer you displays all customer information
for verification. You supply a ship button to confirm the order. As soon as thy press the button you
send an email to, the shipping dept and a confirmation receipt to the customer. For simplicity use
the mailto protocol to send the email. In a form the action attribute will use the mailto protocol. Use
a hidden field or subject and body name to send the data. Make sure the enctype is text.
If they are to download something you supply as download button or a link where they can
download the goods
SUMMARY
Make this is a real ASP Internet application that you could sell to some business in your area. You
should use the Session object when they ere navigating to buy items so that the page remembers
what items they are buying. You may want to use the Application object to remember the item they
bought as they proceed to the check out stage. Some on-line stores save the order information in
the database just before they check out and not rely on the Application object. Thus is probably a
good idea because the Application object is not 100% safe to use. It is very embarrassing to loose a
customer's order once they pay for every thing. You should not use the database to store the order
as they are navigating your page to choose an item to buy. Here you can use Session. Application
and hidden fields. The reason is database access will slow down the navigation, your data base, may
be filled with orders people started but never finish. Allot of people choose items to buy but very few
checkout and make the final purchase.
File: aspGuideL9.doc
Date Started: Mar 20, 2002
Last Update: June 20, 2003
ISBN: 0-9730824-3-7
Version: 0.0
REVIEW OF OBJECTS
What are those object things again? Objects let us store a group of values together that have
something in common. Each value stored in the object is represented by a variable known as a
property. Certain functions are designated to access the variables in the objects. These functions
are called methods. Why do we need objects? We use objects so that our programs are highly
organized. Without objects you would have thousands of variables scattered through out your
program, you would not know which variables belong to what. Objects are used to group variables
together that have something in common. The variables are known as properties. An object has
methods associated with it to access those properties. ASP has many pre-defined objects that you
can use right away.
ASP OBJECTS
Here is a summary of the ASP pre-defined objects that we can use. Some we have used already.
DICTIONARY OBJECTS
A Dictionary object lets you store data as key = value pairs. Each item value is associated with a
key. The key could be a part number and the value could be the name or description of the part.
"1234" toaster.
key value
To create a Dictionary object you use the CreateObject method of the Server object.
Dim dict
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "1234", "Toaster" 'Add some keys and items
dict.Add "5678", "Hammer"
The key must be a string and the values can only be numeric or string. Dictionary objects only last
when the page is loaded. They disappear when the page unloads. This means they cannot be used
between pages.
CompareMode Property
Sets and returns the comparison mode for comparing string keys in a Dictionary object.
object.CompareMode[ = compare]
dict.CompareMode = vbTextCompare
Count Property
Item Property
object.Item(key) [= newitem]
dict.item("1234") = "wrench"
Key Property
Replaces an existing a key in a Dictionary object with a new key
object.Key(key) = newkey
Add Method
Exists Method
Returns True if a specified key exists in the Dictionary object, False if it does not.
object.Exists(key)
dict.Exists("1234")
If dict.Exists("1234") Then
Response.Write("We got that part number")
Else
Response.Write("Wrong part number")
End If
Items method
a = dict.items
KEYS METHOD
Dim a
a = dict.keys
REMOVE Method
Removes a key, item pair from a Dictionary object.
object.Remove(key)
Dim item
The RemoveAll method removes all key, item pairs from a Dictionary object.
object.RemoveAll
Make an ASP page that has two Text Boxes. One to receive somebody's name the another one to
receive a telephone number. Also have a Text Area or List Box to display results and messages.
Make an Add button add. When the Add button is pressed put their name and telephone number in
a Dictionary object. Use the telephone number as the key. Make a Display Button. When the
Display button is pressed display all names and phone numbers in the Text Area. Make a Clear
Button. When the Clear button is pressed clear all Textboxes and Text Area's. Make a Find
Button. If the find button is pressed it will display the name and phone number in the Text Area
corresponding to what is entered in the Text Box. If both entries are filled then it will do verification.
Make a Remove Button. If the Remove button is pressed then the current item is removed from
the dictionary. Make a RemoveAll Button. The RemoveAll button will remove all entries from the
dictionary. When buttons are pressed the ASP page will call functions to initiate the actions using
ONCLICK events. Call your ASP page aspL9Ex1.asp.
When reading and wiring to files on the server you use the FileSystem objects. The FileSystem
object is a little complicated to use and understand but it makes dealing with files easy. The
FileSystem object mainly deals with text files. There are many supporting Objects associated with
the File System Object.
To read or write to a file you first create a FileSystemObject. You then use the CreateTextFile
method to create a TextStream object. Finally we use the WriteLine method to writes a line of
text to the created text file. The Close method flushes the buffer and closes the file. You need to
create the TextStream object from the FileStreamObject to read and write to files.
Const cRead = 2
Set ts = fso.OpenTextFile("c:\testfile.txt", cRead)
Dim s
s = ts.ReadLine
Drives Property
Returns a Drives collection consisting of all Drive objects available on the local machine.
Removable-media drives need not have media inserted for them to appear in the Drives
collection. You can iterate the members of the Drives collection using a For Each...Next
construct as illustrated in the following code:
The File Stream object has many methods that will only look at the important ones.
CreateTextFile method
Creates a specified file name and returns a TextStream object that can be used to read from
or write to the file.
fso.CreateTextFile("c:\testfile.txt", True)
The following code illustrates how to use the CreateTextFile method to create and open a text
file:
Set fso = CreateObject("Scripting.FileSystemObject")
Set a = fso.CreateTextFile("c:\testfile.txt", True)
a.WriteLine("This is a test.")
a.Close
If the overwrite argument is False, or is not provided, for a filename that already exists, an
error occurs.
OpenTextField Method
Opens a specified file and returns a TextStream object that can be used to read from, write
to, or append to the file.
The following code illustrates the use of the OpenTextFile method to open a file for writing text:
fso.DeleteFile("test.txt")
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFile("test.txt")
object.BuildPath(path, name)
CopyFile Copies one or more files from one location to another.
FolderExists
Returns True if a specified folder exists; False if it does not.
object.FolderExists(folderspec)
GetAbsolute
Returns a complete and unambiguous path from a provided path
PathName specification
object.GetAbsolutePathName(pathspec)
GetBaseName Returns a string containing the base name of the file (less any file
extension), or folder in a provided path specification.
object.GetBaseName(path)
GetDrive Returns a Drive object corresponding to the drive in a specified path.
object.GetDrive drivespec
GetDriveName Returns a string containing the name of the drive for a specified path.
object.GetDriveName(path)
GetExtension
Returns a string containing the extension name for the last component in a
Name
path.
object.GetExtensionName(path)
GetFile
Returns a File object corresponding to the file in a specified path.
object.GetFile
GetFileName
Returns the last file name or folder of a specified path that is not part of the
drive specification.
object.GetFileName(pathspec)
GetFolder Returns a Folder object corresponding to the folder in a specified path.
object.GetFolder(folderspec)
GetParentFolder
Returns a string containing the name of the parent folder of the last file or
Name folder in a specified path.
object.GetParentFolderName(path)
GetSpecialFolder
Returns the special folder specified.
object.GetSpecialFolder(folderspec)
FileSystemObject
Returns a randomly generated temporary file or folder name that is useful
. for performing operations that require a temporary file or folder.
object.GetTempName
MoveFile Moves one or more files from one location to another.
object.MoveFile source, destination
MoveFolder Moves one or more folders from one location to another. object.
MoveFolder source, destination
TEXTSTREAM OBJECT
The TextStream OBJECT is used for sequential access to a text file. Sequential access means read
and write each byte in sequence.
AtEndOfLine Property
Returns True if the file pointer immediately precedes the end-of-line marker in a TextStream
file; False if it is not. Read-only property. The AtEndOfLine property applies only to
TextStream files that are open for reading; otherwise, an error occurs.
AtEndOfStream Property
Returns True if the file pointer is at the end of a TextStream file; False if it is not. Read-only
property. The AtEndOfStream property applies only to TextStream files that are open for
reading, otherwise, an error occurs.
Column Property
Read-only property that returns the column number of the current character position in a
TextStream file. After a newline character has been written, but before any other character
is written, Column is equal to 1.
Set f = fso.OpenTextFile("c:\testfile.txt", 1)
s = f.ReadLine
col = f.Column
Response.write(col);
Line Property
Read-only property that returns the current line number in a TextStream file. After a file is
initially opened and before anything is written, Line is equal to 1.
Close Method
Closes an open TextStream file.
Here is an example that opens a stream file, writes to it then closes it.
Dim fso,ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.CreateTextFile("c:\testfile.txt", True)
ts.WriteLine("Jello World");
ts.Close
Read Method
Reads a specified number of characters from a TextStream file and returns the resulting string.
object.Read(characters)
f.Read(1)
The following example issues the Read method to read a character from a file and return the
resulting string:
ReadAll Method
Reads an entire TextStream file and returns the resulting string. For large files, using the
ReadAll method wastes memory resources. Other techniques should be used to input a file,
such as reading a file line by line.
Const cRead = 1, cWrite = 2
Dim fso, ts, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", Write, True)
ts.Write "Jello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", Read)
s = f.ReadAll
Response.Write(s)
Skip Method
Skips a specified number of characters when reading a TextStream file. Skipped characters
are discarded.
object.Skip(characters)
SkipLine Method
Skips the next line when reading a TextStream file. Skipping a line means reading and
discarding all characters in a line up to and including the next newline character. An error
occurs if the file is not open for reading. Example to use of using the SkipLine method:
Write Method
object.Write(string)
WriteLine Method
Writes a specified string and newline character to a TextStream file.
object.WriteLine([string])
object.WriteBlankLines(lines)
f.WriteBlankLines 2
Continuing from Exercise 1. When the page unloads write all the data from the Dictionary to a file.
When the page loads read all the data from the file and store in the Dictionary object. You need to
use the Global asa file fir page loading and unloading. To map the filename to the server directory
you can use the MapPath method takes a file name and converts it into its real directory path
name located on the Web server. Call your ASP page aspL9Ex2.asp.
MAINTAINING STATE
Tracking a customer is known as maintaining state. When a web browser connects to a server it is
known as a stateless connection. Stateless meaning we do not keep track of who is connected to
us. We have many visitors but we have no direct way to identify them. We can use the following
methods to maintain state to identify who is connected to us.
• Session Id's
• Cookies
• Query String
• Authentication
Session ID is very convenient but very risky. It is impossible to use them for a complete customer's
order. Session objects should just be use to collect the items for sale, once a customer is ready to
pay for the items all the items should be stored in as data base or application object. The session ID
can be used for identification. The Session object lets us store all the products selected for one user.
Why do we need Session objects? We need Session objects because we need to keep track of each
user who comes to our web page. If we could not identify each user than we would not know which
item belongs to which user. How do Session objects track each customer? For every users that
connects to our server a cookie with a unique ID is deposited on the users machine. The server
keeps track of the ID for you and is known as a Session ID. To identify who the user is, all the
server has to do is read the cookie on the user machine to identify the user.
Will session object work if the user has cookies disabled? Session objects will not work if the user
has cookies disabled. Every time the uses goes off page and re-enters a new Session ID would be
generated. How are the session ID's generated. Session ID's are made from mathematical formulas
that ensure a unique id.
Session("toaster") = 2
All other ASP files in your directory will be able to access the value of "toaster" from the session
object.
All keys and values go into a Collection object stored in the Session object. You can print out all
the items in the Contents collection using the for each statement.
Session Contents.Remove("toaster")
Session.Contents.RemoveAll
The Timeout property specifies how many minutes of inactivity will ends the life of the Session
object. This is desirable because once you finish using a Session object it should disappear.
Session.Timeout = 30
Session.Abandon
Once you are finished using the session object you should abandon it.
Every Session gets an id for identification. The ID's are stored as cookies on the user machine. You
use the SessionId method to read the ID.
Response.Write Session.SessionID
You don't need to rely on session objects you can store your own information on the users machine
using cookies. Cookies store pieces of information like a customer identification on a Web browser
file. A good way to identify a user is to store a user id on their Web browser. The next time they
connect to your site, you just read the id from the Web browser then you know who they are! For
cookies to work the Web browser must allow cookies enabled. Cookies as you know are small files
stored by the Web browser. The difference between using cookies and Session objects is that
cookies can be a more permanent solution. Session object are cookies that just last for 30 minutes
or so.
Cookies are easy to make. We use the Cookies method of the Response object .
Response.Cookies("userid") = "1234"
We give our cookie a key "userid" and a value like "1234". The key lets us locate the cookie in the
user machine. Cookies do not last forever. If we do not tell the Web browser how long we want the
cookie to last it will delete it right away.
You use the Expires property to set the cookies expiry date.
Response.Cookies("userid").Expires=dateadd("d",1,date)
We use the dateadd method to add 1 day to the current day. The cookie will expire at 12 midnight
the next day. We use the Cookies method of the Request object to read the value of a cookie
stored on a user machine.
request.cookies("userid")
We use the previous key "userid" to locate the cookie in the user machine. Here is the complete
program: Notice we create the cookie before the HTML header is written, this is because cookies are
sent in the header section. We need to set up the header information before we send out the
header located between the <head> tags.
<%
Response.Cookies("userid") = "1234"
response.Cookies("userid").expires=dateadd("d",1,date)
%>
<HTML>
<head>
<title>cookie test </title>
</head>
<body>
<p>creating cookie <br>
cookie created <br>
getting cookie <br>
<% Response.Write(request.cookies("counter")) %> <br>
</p>
</body>
</HTML>
The cookies are located in the Windows directory in the Cookies subdirectory. They will have the
following fields:
name of value of internet size of Expiration Last modified Last last read
cookie cookie address cookie date and date and time accessed date and
time data and time
time
removing a cookie
We can also remove our cookie. all we have to do is to set the cookie value to an empty string.
Response.Cookies("userid")=""
There is a lot of additional work when using cookies rather than Session objects. When using cookies
you still need to store the customers order somewhere. You can store on a database, a file, and an
Application object or on the cookie itself. For the proceeding reasons it will probably better just to
use the Session object, since you can easily store the customer order in it.
If you think your customers are just going to make some quick purchases and the leave then their IP
address is good to use. You can use the IP address as the key to store information about the user
purchases in an Application object. To store information in an application object all you have to do
is to supply some user id, like a name or key and a value. IP address usually represent a base
address where all users is identified by their user id when they log in. Then they are assigned their
IP address which would be different every time thy log in. It might be unlikely that all your users
will have the same IP address at the same time (but possible!). You can get the user IP address
from the "HostAddress" parameter.
Dim userid
userid = request("HostAddress")
Application(userid) = 1234
key value
All other ASP files in your directory will be able to access the value of the key "Count"
count = Application(userid)
All non object information like numbers are put into a Collection object of the Application object. A
Collection object is like an expandable array . You write entries by:
userid = Application.Contents("userid");
Application("userid ") = 1
count = Application("userid")
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
143
You can print out all the items in the Contents collection using the for each statement. In ASP the
for each statement is only available for objects.
Application.Contents.Remove("Count")
Application.Contents.RemoveAll
When you have many users all accessing your Web pages all at the same time, you need to restrict
access to the Application object one user at a time.
The Lock method restricts only one user to access the application object until the Unlock method is
called. Locking is very important, one user could update the value before another user reads it!
Application.Lock
Application("Count") = 1
Application.UnLock
This is a very common approach. You need to generate a user id for every user that connects to
your page. You can use the getTime() method or a counter from a data base, or the session ID it
seems to be unique.
All you got to do is put the user id at the end of a URL that calls a page as a Query String
http://www.mystore.com/?userid=55443344
When they go to that page then you know who they are.
People use this method on the product links and buttons to identify the user and what products they
are purchasing.
The problem here is that the query string is visible in the web browser location bar. That's okay you
don't notice this any ways. Each page must be self generated to include the Query String
information.
The same principle of using query strings can be extended to use hidden fields. Hidden fields are
mostly used with buttons enclosed in a form. when they click on a button then the user id is
included in the form data.
When they click on the button the product they want to buy and user are received by the users ASP
page the orders asp page must get the user id and pass it to the next form.
Dim userid
userid = request.forms("userid");
To receive a bunch of items check boxes can be used rather than buttons.
If you name the checkbox name the same for all items for sale they each check box can be accessed
as an array
This is the safest method to use. To me a database should be used to store the final order not to
keep track of each item as the user purchases. Many ASP online stores use this method. They have a
temporary table for each order when they add and delete ordered items. only when the user checks
out do they transfer the contents to the data base orders table. They use this method because it is
very safe. Objects in ASP have a chance of disappearing for no apparent reason. Session objects can
get lost, Application objects can get lost database can not get lost. The contents of the Session or
Application objects can be transferred to a database when they check out.
Login pages
This method makes each customer login either knowingly or not knowing. This is a bad method to
use because the customer will always forget their user id and password. The safest user ID to use is
the customers email address. The safest password to use is their date of birth The login method
annoys a lot of people. Therefore Online stores only make them login when thy check out their
order. rather then when they first visit their web page.
This is a very drastic method, using authentication log in pop up box. A web page is authenticated
by setting this up in the web server. Only people who have registered can view the site. The web
server has a list of allowable user and passwords. Once the web browser is authenticated the web
page can request the user from the web browser,
Request.Authentication()
The web browser will re-transmit the userid every time that page is accessed. Authentication is
very inconvenient to use, now all your customers will hate your store.
Add a session and Application object to your online store of previous lesson. The Session object will
be used to store the items for sale. The Application object would be used to store all the items for
sale once the user checks out. Bonus use hidden fields so that the user will not loose all his selected
items if their web browser does not support Sessions. Once you reach the checkout or thank you
page you can transfer every thing to permanent storage in your database.
FILE SERVER
Once your customer pays for the items they need to download the items, to download a file you
simply supply a link. Once the customer finds out your link they do not need to pay for any more
purchases. To avoid this situation you need your own file server. A file server will check if the user
is entitled to download. .We make a link so someone can click and download
<a
href="getfile.asp?filename=<%=filename%>&authcode=<%=auth_code%>">
<%=filename%>
</a>
Building file server in ASP is a little difficult because the file objects only support text file's. Most
download files are binary files. Fortunately the ADO Steam object supports binary files.
const adTypeBinary = 1
set os = Server.CreateObject("ADODB.stream")
os.open
os.type=adTypeBinary
os.loadFromFile mapfile
Here's the code that can serve a binary file:
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
146
<%
on error resume next
pathname = "./downloads/"&filename
'dim fso
set fso = Server.createObject("Scripting.FileSystemObject")
dim mapfile
mapfile=Server.MapPath(pathname)
const adTypeBinary = 1
set os = Server.CreateObject("ADODB.stream")
os.open
os.type=adTypeBinary
os.loadFromFile mapfile
Response.ContentType="application/pdf"
Response.AddHeader "Content-Length", os.size
Response.AddHeader "Content-Disposition", "attachment;filename="&filename
dim buf
loop
set os=nothing
end if
end if
%>
File: aspGuideL10.doc
Date Started: Mar 20, 2002
Last Update: June 20, 2003
ISBN: 0-9730824-3-7
Version: 0.0
PROCEDURES
Procedures contain variables and programming statements. There are two kinds of procedures.
Subs and Functions. Both Subs and Functions receive values. If a Procedure returns a value then it
is called a Function. Subs and Functions receive values through parameters. The variables or
constants containing values are passed to the Sub and are known as arguments. You pass values
to a procedure when you call the procedure to execute.
PrintTotal 10.5
A sub gets a modifier list, a name and a parameter list to receive values. Within the Sub's body,
local variables are declared for temporary calculations. Also within the Sub programming
statements are written. The Sub ends with the End Sub statement. Our Sub definition is in
purple and our example Sub is in blue.
local variables
programming statements
End Sub
End Sub
Part Description
Public Indicates that the Sub procedure is accessible to all other procedures in all scripts.
Indicates that the Sub procedure is accessible only to other procedures in the script
Private
where it is declared.
name Name of the Sub.
List of variables representing arguments that are passed to the Sub procedure
parmlist
when it is called. Multiple variables are separated by commas.
statements Any group of statements to be executed within the body of the Sub procedure.
A Parameter list is made up of Parameters that receive values. Parameters are declared with a name
just as you would declare a variable.
Amount
paramater name
A parameter acts like local variables in a procedure. Here is our example Sub that receives a
currency value and prints it to the screen. The parameter Amount acts like a local variable storing
the currency value to print out.
End Sub
When you come to the last programming statement in a Sub, the Sub has finished running and
program execution returns back to the programming statement that called it. You can make a Sub
return early by using the Exit Sub statement.
End Sub
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
149
Functions
Functions are little different then Subs. Functions receive values and return values You must also
assign a return value from your function by assigning a value to the function name.
programming statements
End Function
Part Description
Indicates that the Function procedure is accessible to all other procedures in all
Public
scripts.
Indicates that the Function procedure is accessible only to other procedures in
Private
the script where it is declared.
name Name of the Function.
List of variables representing arguments that are passed to the Function
arglist
procedure when it is called. Multiple variables are separated by commas.
Any group of statements to be executed within the body of the Function
statements
procedure.
expression Return value of the Function.
Here is a function CtoF that receives a temperature in degrees Celsius, and returns the temperature
converted to Fahrenheit degrees.
End Function
If you do not want to return a value then use the Nothing keyword.
CtoF = Nothing
A function ends at the last programming statement. You can exit a function earlier by using the
Exit Function statement.
IsLarge = x
Exit Function
Else
IsLarge = x + 5
End if
End Function
Variables declared in procedures are said to be local and last as long as the procedure is executing
then the values are no longer valid. Local variables are also called dynamic local variables. You
cannot use the modifiers Public and Private on local variables. Do not confuse variables defined in
your ASP program to variables defined in a subroutine or function. They are quite different.
Variables defined in a sub or function can only be used in that function or sub. Variables defined in a
module or form can be used by all subs and procedures defined in that module or form.
Dim Name .
If you want the local variable values to be preserved between function calls then you can make
them static.
Static Count
Sub CountNames()
count = count + 1
End Sub
You can make all your variables to be static by making the procedure static. Here is our sample sub
as static.
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
151
Dim Count
Count = Count + 1
End Sub
When you want to use a function you call it by its name and supply values using variables or
constants. The variables or constants are called arguments. Here we call the CtoF function. Notice
we use round brackets around the arguments. You must us round brackets for functions.
Dim f
f = CtoF(32)
When you call Subs you do not need to enclose the arguments with round brackets. Here we call the
Sub Two that gets two strings.
When you call functions you need to enclose the arguments in round brackets. To call and print out
the return value of the CtoF function we would write:
Document.Write CtoF(36)
Where do you call Subs and Functions ? You call subs and functions from your ASP page or from
other Subs and Functions.
You can also call Subs using the Call statement. When you use the call statements all arguments
must be enclosed in round brackets.
You can only call functions by their name and you must always use round brackets.
F = CtoF(36)
We call the function CtoF. We pass it the value 10 using the variable c. The CtoF function converts
Centigrade degrees to Fahrenheit degrees. The converted value is returned from the sub CtoF and
the return value is assigned to the variable f.
c = 10 send argument c
f =CtoF(c)
End Function
You can pass a value to a procedure by value or by reference. Value means an actual value is
passed where reference refers to a direct address of the location of the passed variable. If a
procedure knows where a variable is, it can get and modify the value. The default is pass by
reference. You specify pass by value using the ByVal keyword and specify pass by reference using
the ByRef keyword. When you use pass by value, the originating variable value cannot be changed.
In the following example a sub gets two arguments one pass by value and the other pass by
reference.
End Sub
We have two string variables one says "Hello" the other says "Goodbye". When the Two Sub is
called and returns notice the Two Sub can change string2 but not string1.
Response.Write (string1)
Response.Write (string2) before: Hello GoodBye
End Sub
Write a function called isNumber that returns True or False if a received number is greater than a
specified number. When they enter a number in a Text box, call the isNumber function from a
validation sub. Inside the validation sub use a Msg Box to print out a message "too low" if a
number is lower, or "two high" if the entered number is greater. Else "You Win" if they guess the
correct number. Call your ASP Program aspL10Ex1.asp
Make an ASP page that has a Form that has two Text Boxes. One is labeled degrees Fahrenheit the
other is labeled Celsius. When a temperature is entered in one Input box the other one automatically
shows the converted temperature. Call your ASP Program aspL10Ex2.asp
The problems with a ASP Program it starts and then goes on forever there is definitely no
organization involved. What you got to do is to modularize your ASP program. Where each module
represents a distinct section in your program, all programs will have the following divisions.
Input Section
Calculating Section
Output Section
Each Section can be a Sub. Each sub will call a function to help it do things. Functions allow you to
avoid code repetition in a program. When an ASP program first starts it looks for a Main Sub. If
there isn't one it just starts at the top of the program executing programming statements line by
line. If there is a Main Sub then it will execute the programming statements in the Main Sub. When
using a Main Sub your ASP program will now look like this.
Sub Input()
End Sub
Sub Calculate()
End Sub
Sub Output ()
End Sub
Sub Main
Call Input()
Call Calculate()
Call Output
End Sub
We first declare all the variables that will be shared between all the subroutines. Shared variables
are known as global variables. Then we write the subroutines. We write the subroutines first so that
the Main sub will know about them. Each subroutine will have it's own local variables for internal
use. Finally the Main sub will call all the subroutines one by one. By organizing your program in
modules represented by subroutines there will be only a few global variables rather than many
variables. The reader of your program will recognize the importance of theses variables only. Also
when you program is divided up into sections its is much easier to debug and maintain. Each
subroutine will have its own variables known as local variables for temporary calculations. Each
subroutine can also be responsible for its own error handling.
Take your online store project organize into the input, calculating and output sections. Group each
into an appropriate Sub. Use a Main function to call each Sub.
File: aspGuideL11.doc
Date Started: Mar 14, 2002
Last Update: June 20, 2003
Version 0.0
ISBN 0-9730824-3-7
You have already been using ASP pre-built Objects, now its time to know how to make your own
Objects. What is an Object? An Object is simply memory reserved for a group of declared variables
that have something in common. Where do you declare these variables? You define these variables
in a class. It is important to understand the difference between a class and an Object. The class
defines which variables you need for your object. The class must be written before you run your
program. When your program runs, memory is set aside for the variables declared in your class. The
memory that contains the variable values declared in the class is known as an Object. Think that an
object is just memory for a group of declared variables. A good analogy to a class is a recipe,
needed to bake a cake. The recipe is the class and the cake is the object. You cannot eat a recipe
but you definitely you can eat a cake!
class object
coding running
A class is used to represents every day things. A good example of a class is a person. What does a
person have? A person has a name, address and an age. How do I make a Person class? You make a
Person class in a class definition module. Why do we need a class? We need a class because we want
to group all variables that have something in common together about a Person in a separate
module. By having different modules that are specialized, makes a program more organized. It's
like having different web page forms to do different things rather than one web page form to do very
thing. By having many specialized web page forms makes your program more manageable. We want
to do the same thing with data. We want to have specialized data modules. The data modules are
called classes.
A class starts with the key word class followed by the name of the class.
class People
The next you need to do is declare all the variables needed for this class
Dim name
Dim address
Dim phone
You must end the class with the end class keyword.
End Class
A class should go into a separate file having the class name and the extension cls. We put the People
class in a file called People.cls. We must enclose the class in ASP <% %> tags. Here is the
complete Person class:
<%
'Person.cls
class Person
Dim name
Dim address
Dim phone
End Class
%>
Now that we got our class how do we make an Object out of it? Before you can have an Object you
need to make a reference variable. A reference variable contains the memory address location of
the object that you are going to make. The difference between a data variable and a reference
variable is this. A data variable contains a data value where a reference variable contains an address
value. You create a reference to your object as follows:
Dim p
When you declare a reference variable it does not yet refer to a Person object, it is undefined. The
next step is to make a Person object. To create an object we use new operator that allocates
memory for our object and specify the class that we will make our object from.
Notice we use the Set keyword to assign the address of the created object to the reference variable
p. When you create an object from a class definition this is known as instantiating. We now have
memory allocated for our people object referenced to by the reference variable p.
Person Object
Name
Address
p
Age
Reference variable p contains the
address of our Person object
Now that we got our object we need to put some values into it. We use the class reference name.
The dot "." operator and a value to assign a value to the variable in the object.
p.Name = "Tom"
reference variable
variable value
dot operator
Our object will now have all the values stored in it. The reference variable refers to which object you
want to access the data from.
Person Object
Name "Tom"
We put all he code that makes the Person object into an ASP file called Person.asp.
<%
Dim p
%>
Notice we have included the class file to be included at the top of the ASP program, or else the ASP
program would not know what a Person was.
Type the Person class in a file called person.cls. Type the ASP program that makes the Person
object in a file called Person.asp. Print to the screen the values inside the Person object.
using objects
Now that we got these object what are we going to do with them? A good example is a Web page
form that has three Text Boxes one for name, address and phone with submit and reset buttons.
Here is the HTML code for the form. Notice we will call the person.asp file when the submit button
is pressed.
<!-- Person.html -->
<html>
<head>
<title>Person.htm</title>
</head>
<body>
<form method="post" action="person.asp">
<input type=text size=20 name=name>
<input type=text size=20 name=address>
<input type=text size=20 name=phone>
<p>
<input type=submit name=submit>
<input type=reset name=reset>
</p>
</form>
</body>
</html>
asp file
When the user enters data and hit's the submit button the data is sent to the web server. The web
server will call the person.asp program file. The person.asp program will then make the object, put
the data obtained from the web page form in the object. Here is our person2.asp file.
We need to use the include directive to include our person class file or else the asp page will not
know what a person is.
We declare a reference variable called p and create a person object from the Person class definition.
<%
dim p
We then read the form parameters and assign the data to the created Person object reference
to by the variable p
p.name = request.form("name")
p.address = request.form("address")
p.phone = request.form("phone")
%>
The Person object referenced to by p now contains the person's information name, address and
phone sent by the Web browser. You should now realize how classes organize and manage your
data. Name, Address and Age all are variables belonging to a Person. When you write your program
you implicitly group variables together. When you write a Class the Class explicitly groups the
variables for you.
Type the Person class in a file called Person.cls. Type the person form in a file called Person2.htm.
Type the ASP page to receive person info from a person form and store in a person object. From the
person object send back a generated web page displaying and thanking them for their information.
PROPERTIES
You constantly always need to access the variables defined in the class. The variables defined in a
class are known as properties. The big deal about Object Oriented Programming is that all the
variables defined in a class should be private, this means only the class module can access its own
variables. We now declare the variables in our Person class as private.
Notice we have put little m's in front of the variable names, the m means members. The property
variables are members of the Person class. So if only the class can access the variables then how
are you suppose to access them out side the class ? The answer is you need property procedures
so that other programs can access the values of the properties. Property procedures are just
procedures with special names like Get to get the value from a property and like Let to assign the
value to a property.
Here are some of the property procedures for our Person class.
The advantage of property procedures is that your data is enclosed in the class. There is a special
word to describe this containment, the word is Encapsulation. Encapsulation means only the class
can access the data directly. This is a good thing, nobody should know how the data is stored they
should just want to be able to access it. The data may be stored in a database, an array or a file.
You use property procedures just like a ordinary variable. You can just give them a value:
p.Name = "Bill"
name = p.Name
VB LESSON 12 EXERCISE 3
Add all the property procedures to the person class of the last exercise and then run your program.
No changes are needed for the web page form. Call your class file Person2.cls and your asp program
Person3.asp.
You can have many Person Objects all created from the Person class. Each person object will have
its own reference variable.
Name
Person class Address
Phone Name
Address person
Phone
p1 Objects
p2
Name
Address
Phone
p3
A class lets you group common data together. A class let you organize your program data. When
your program run's you need to allocate memory for the variables you have defined in your class
module. This allocated memory for the variables is called an object. The benefit of having pre-
defined classes is that you can make many objects all from the same class. Just like you make many
cakes all from the same recipe. You would need many people objects in your program all with
different names. How do you make more than 1 object ? You just need additional reference variables
to represent your objects and then use the new operator to allocate memory for the object. Lastly,
you assign the Object to the reference variable using Set keyword. Here is the step by step
instructions to make more than 1 object:
Dim p1
Dim p2
step [2] allocate memory for objects and assign the objects to your variables
p1.Name = "tom"
p1.Address = "50 Vine Street"
p1.Age = 24
p2.Name = "Mary"
p2.Address = "42 Lamb Street"
p2.Age = 23
On your form add a button called 'Add' and a 'Button' called search. When the add button is pressed
create a person object in the ASP page and add the person object info to a file. The file must be
opened for append and you need to store the person information on one line separated by commas.
When the search button is pressed read the file. For each line of the file make a person object and
store in a Dictionary object. Search the Dictionary object for the person. Generate an HTML page
displaying the data for the name found in the dictionary object. The file is used to store the data
permanently. The Dictionary object is used to look up the information conveniently. Call your web
page aspL11Ex4.htm and your ASP program aspL11Ex4.asp.
METHODS
Classes can also have subs and functions. Subs and functions defined in a class are known as
methods. Functions return values where subs do not. The neat thing about methods is that they
can use all the variables defined in the class. This is one of the major importance of a class is that all
the variables defined in the class can be shared between all the methods. Let's make our first
method. We need a method to return a String of all the information about a person. We want to
return a value so we need a function. We will call out function PrintAll. We still use Subs and
Functions for methods.
PrintAll = Name & " " & Address & " " & Age
End Function
class Methods
The important concept to realize here is that the methods belong to the class but not to the object.
What does this mean? It means this: the same method can access many objects' instantiated from
the same class. When you use a method it can only access one of the object's at a time. When
using the reference variable. dot operator and method name, you are specifying which object the
method is going to access.
p.Age = 24
value
variable
reference
variable
dot operator
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
165
For example in the following program we have two Person objects each referenced by p1 and p2
respectively.
Dim p1 as Person
Dim p2 as Person
p1.Name = "tom";
p1.Address = "50 Vine Street"
p1.age = 24;
p2.Name = "Mary";
p2.Address = "42 Lamb Street"
p2.age = 23;
Response.Write p1.printAll()
We have two references p1 and p2 referring to two different Person objects but we have only one
printAll method.. We only access one object at a time. The printAll method is needed to access an
object and to return a string describing that object. We need to tell the compiler which object we
want to access and which method to use. The reference variable tells the compiler which object to
use and the method name tells the compiler which method to call. I always think of the dot
operator to specify which object to use when calling the printAll method.
p1.printAll()
Person p1
Name: Tom
Person p2 Address: 50 Vine Street
Age: 24
Person Object
Person class
Name: Mary
methods Address: 42 Lamb Street
Age: 23
P1.PrintAll()
There is only one printAll method, it can access any Person object. You need to tell which object
the printAll method should access.
method from
p1.PrintAll() Person class
The reference variable specifies which object to use. The dot operator says use the printAll
method from the Person class
The difference between a method and a property is a property returns or assigns a value where a
method is performing a calculation.
Add the printAll method to your Person class. Use the printAll method in your ASP page to print
out the information about a person. Call your Person class Person3.cls and your ASP program
aspL11Ex5.asp.
INITIALIZING OBJECTS
When you create objects the values of the variables need values. It is more convenient to initialize
objects when they are created. How do you do this ? When you create a object using the new
operator and the set keyword, the class initialize event is called.
Inside the initialize event you can initialize the property values of your object.
m_Name = "tom"
m_Address = "50 Vine St"
m_Age = 24
End Sub
There is also a terminate class event that is called when the object is destroyed. Objects do not
last forever. When the Object is no longer needed the memory is taken away and used somewhere
else. Objects are usually destroyed when the program ends. Objects can be also destroyed when
they are no longer needed. A good example is when you create an object in a function it is only used
inside that function. When you finish using the function the object disappears. The Terminate
function is called just before the object is destroyed.
End Sub
Add an initialize and terminate method to your Person class. In the initialize event set the object
properties to some values. In the terminate event print out a message "I am terminated" using
Response.Write. Run the program from last exercise.
form
Person p1
Person class me
The problem here is that the methods of the class do not have a reference to the object that they
presently being accessed. There may be times when the class code methods themselves need to get
a reference to the object that is being currently accessed. To solve this problem the compiler keeps
a reference to each currently accessed object. The reference is called me and can be used by any
class. me always refers to the object that is being accessed. In ASP me is not used to often but is
available when it is needed.
When you have finished using an object set it to nothing. All memory allocated to the object will be
returned back to the operating system.
p1 = nothing
DATABASE OBJECT
Our first useful object is a database object. What things do we need to do to a database ?
(1) CONNECT
(2) OPEN
(3) READ
(4) UPDATE
What variables would a database need? Connection object, Record set object etc
Code the data base class. The data base class should be able to handle any database name and
table. Make a small ASP program to test your data base class. Call your class DB.cls and your ASP
test file aspL11Ex7.asp. Once you are confidant your data base class is working replace all your
data base code in your on-line store with your data base class.
SHOPPING CART
Our next useful object is a shopping cart for a on-line store. What things do we need for a shopping
cart ?
(1) ADD Item
(2) CLEAR all Items
(3) RETRIEVE Item Info
What would you store in your Shopping Cart ? Item part number, description and price. You don't
need to store too much information because the data base would already have a lot of the
information stored in it about your items already. You just need to store info that is used quite often.
You would probably make an additional class called item. The shopping cart would then store a
collection or array of items.
Shipping
Cart
Items
Code the Shopping Cart class. You should be able to add a part number and quantity. You may want
to make an Item class where you can store more information like description. Make a small asp
program to test your Shopping Cart class. Call your class ShoppingCart.cls and your ASP test file
aspL11Ex8.asp. Once you are confidant your Shopping Cart class is working add your shopping cart
code to your on-line store of previous Lessons.
File: aspGuideL12.doc
Date Started: Jan 27, 2003
Last Update: June 20, 2003
Version 0.0
ISBN 0-9730824-3-7
Introduction
XML stands for Extensible Markup Language. It is a language used for representing and describing
text-based data. XML is used to exchange data between computers connected through the internet.
XML is similar to HTML, they both use tags having the following format: a starting tag <tag> with a
matching end tag </tag>. Text data is placed between the tags. The difference is that the HTML
tags has pre-specified tag names and already mean something. In XML the tag names are not
specified and the user can choose any tag name they want. The tags will now have there own self-
meaning. The following is a XML example:
<employee>
<name> Joe Smith </name>
<address> 23 Nowhere Street </address>
<city> Toronto </city>
</employee>
The first tag <employee> describes what kind of data we are going to provide. Inside this tag we
have tags providing additional information like the employee's name, address and city. The inside
tags are nested tags of a user specified hierarchy of data. The text and corresponding tags are
known as elements. Alternatively tags can have attribute names with values supplying
additional information. This arrangement is known as name value pairs. (name=value)
Which format you use can be your own preference. You may use a combination of both formats. You
can view XML files in the Internet Explorer. Just type the above XML code each separately in a file
called "employee.xml" and "employee2.xml" and open up with IE version 5 or greater.
Every XML tag must have a closing and end tag, this is known as well formed XML. Well formed
XML uses markup tags to represent the different elements of data in a text file. There are programs
to translate XML to HTML. We also have DTD's Document Type Definition's to specify which tags
will be used in a XML document. Let's investigate an XML document in more detail.
XML Tags
An XML document is made up of tags and information text between the tags. A tag is a name
identifier enclosed by < > brackets. The identifier names are case sensitive, meaning
<employee> and <EMPLOYEE> represent two different tag names. The first tag in an XML
document is known as the root tag. The rest of the tags are called element tags. There can only be
one root tag, but many element tags. An XML element starts with < start tag > and ends with a
</ end tag>. Every start tag has a corresponding end tag.
element
Text is place between the start and end tags and is called element content. The element content
is also known as Parsed Character Data or simply PCDATA.
An XML document starts with a prolog and a root start tag. Enclosed in side the root start tags are
element tags. These are also called child elements. The XML document ends with the root end tag.
<employee>
prolog
<name> Joe Smith </name>
<address> 23 Nowhere Street </address>
root start tag <city> Toronto </city>
</employee>
child elements
prolog
This is the first line in a XML file that indicates that this document is a XML document and states the
version and the encoding used. The prolog starts with a <? and ends with a ?>
The version attribute identifies the version of XML being used and the encoding identifies the
character set used to encode the data. "ISO-8859-1" is Latin-1" the western European and English
language character set. The default is compressed Unicode " UTF-8"
This is the start of the XML document. All other tags are placed inside the document root tag. The
XML document ends with a corresponding end root tag. You can give the root tags any name you
want.
<employee> all other tags go in here </employee>
child nodes
These tags belong to the XML document and are placed inside the root tag like:
<employee>
root <name> Joe smith </name>
tags <address> 23 nowhere street </address> child elements
<city> Toronto </city>
</employee>
attributes
Attributes provide additional information as name=value pairs. Attributes are enclosed by a start
and end tags. The value must be enclosed in single quotes or double quotes.
<employee>
<name> Joe smith </name>
<address> 23 nowhere street </address> child elements
<city> Toronto </city>
</employee>
empty elements
Empty tags are used to specify data, they do not have a corresponding start and end tags. They
just start with a start <tag and end with a / >. A tag that does not enclose any content is known
as an empty tag as follows: <tag/> which really means <tag></tag>. Example this employee
has no address:
<address> </address>
<address />
well-formed tags
XML comments
Processing instructions give commands to an application that is processing XML data. Processing
instructions start with a <? and end with a ?> tag and have the folowing format
The target is the name of the applicatiion that is expected to do the processing and the instructions
is the command for the application to process. Our prolog (described above) is a processing
command telling the version being used for the XML dociument.
no space here
DTD
DTD's are used to verify XML documents. DTD's stand for Document Type Definition. DTD specifies
the kind of tags and the valid arrangement that will be included in your XML document. The DTD
can exist as part of the XML document in the prolog or exist as a separate entity. A DTD starts with:
It is here in the body description of the DTD where your elements are described using the !ELEMENT
tag. First we describe the sequence for our root elment. Our root ELEMENT from our Employy XML
document must have three child elements in the folowing order:
Next we describe our content and Parsed Character Data (#PCDATA) The (#PCDATA) means
parsed character data
The DTD for our above XML example may look like this:
<!DOCTYPE employee [
<!ELEMENT employee (name, address, city)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT address (#PCDATA)>
<!ELEMENT city (#PCDATA)>
]>
Add the DTD to your XML file employee.xml and run in Internet Explorer. Make sure you put a
space betwen the element name and content. All tags are case sensitive.
You can uses DTD to describe start tags with attributes like:
You declare a list of alowable atributes for each element. These lists are called ATTLIST
declarations.
attribute types
When the XML document is being parsed, the DTD is used to validate the elements and attributes.
The word parsed means, the XML document is being scanned and all the individual characters and
elements are being identified. You need to parse an XML dicument to identify and extract all the data
from it.
The current API'S for accessing XML documents are SAX and DOM.
SAX
SAX stands for Simple Api for XML and is a serial access protocol for XML. Serial means it start
parsing from the top to the bottom in one direction only. It is the fastest to execute mechanism you
can use to read and write XML data to a server. It works quite different then the DOM parser. When
it parses the XML Document it calls methods from your code. In your code you must implement
the methods it cals so you can obtain the tag names and values. Here are some of the methods you
must implement that it will call.
startDocument
startElement
endElement
endDocument
MicroSoft has inclused a SAX parser in MSXML version 3.0. MSXML version 3.0. is included with
Internet Explores 6.0.
DOM
DOM stands for Document Object Model that is used to convert a XML document file into a
collection of XML-DOM objects in your program. You then can use these objects quite easilly. This is
also known as Random Access Protocol (RAP) becauuse you can access any part of the data at
any time. The objects are built into a tree structure for easy access.
Document Root
child node
data data
The DOM model reads the entire XML structure into memory and stores them as DOM objects.
DOM
XML file DOM objects
Parser
DOM objects
Here is a list of the DOM objects. The terms elements and nodes seem to be interchangeable.
Object name Description
DOMDocument represents the root of the XML file.
XMLDOMElement represents each element in the DOM Document, namely the
root, root element, and each other element.
XMLDOMNode represents a single Node in the document tree and includes
support for data types, namespaces, DTDs, and XML Schemas.
XMLDOMNodeList Use this object to access (by name) and iterate through the
XMLDOMNode collection.
XMLDOMNamedNodeMap Use this object to access and iterate through the attributes in
an element.
XMLDOMCDATASection represents a section in the value of an element that is closed in
the CDATA section brackets, which are characters that cannot
be parsed by the XML.
XMLDOMAttribute represents a single attribute Node for a given element.
XMLDOMDocumentType represents the Document Type (DTD) in an XML file.
XMLDOMEntity represents an entity in the DTD section of the XML file.
XMLDOMProcessingInstruction represents a processing instruction found in the XML file.
XMLDOMParseError returns detailed information about the last error, including the
line number, character position, and a text description.
XMLHTTPRequest enables you to establish a connection to a web server from your
code and send put, get, and other standard HTML requests.
Elements are represented by Nodes in the DOM. The Nodes and NodeLists in a DOM Object would be
aranged like like this:
DomDocument
docElement or docNode
Node List
DOMElement or DOMNode
DOMElement or DOMNode
The DOM is available in the MSXML supplied by Internet Explorer. In all of our examples we will use
MSMXML version 2.0 supplied with Internet Explorer 6.0. The newer versions MSXML 3.0 and
MSXML 4.0 have many new features.
In a XML Database application we have all the following objects to deal with:
We need to exchange data between all the different objects as shown in the following diagram. We
can use two differrent data bases or the same one.
DOM
DB RS RS DB
XML
Dom
Document
Here we build up a DOM node by Node. As we build up the DOM we are attacching nodes to other
nodes. You would only have to do this if you didn't have information allready stored in a database,
or you need data entered by the user.This is a lot of work to do to build your own DOM. (but worth
it).
<employee>
<name> Joe Smith </name>
<address> 23 Nowhere Street </address>
<city> Toronto </city>
</employee>
(1) The first thing you have to do is make the DOM Document object.
Dim dom
set dom = Server.createObject("MSXML.DOMDocument")
(2) You then create the root element and attach to the DOM document object
Dim node
Set node = dom.createElement("Employee")
dom.appendChild node
(3) Next create the children and attach to the root element node
' name
Set child = dom.createElement("name")
child.Text = "john smith"
node.appendChild child
' address
Set child = dom.createElement("address")
child.Text = "23 nowhere st"
node.appendChild child
' city
Set child = dom.createElement("city")
child.Text = "toronto"
node.appendChild child
Type the above lines of code into a ASP file called DOMTest.asp and run it. Don't worry if you don't
see an output on the screen.
DOMDocument
<employee> </employee>
Print dom contents on the web browser screen. We need to set the ContentType to "text/plain". Add
the following to lines to your DOMTest.asp program.
Response.ContentType="text/plain"
Response.write(dom.XML)
john smith
23 nowhere st
toronto
dom.save Server.MapPath("employee5.xml")
This is an easy thing to do we just call the Load method from a DOM object
dom.Load Server.MapPath("employees.xml")
We can read the contents of the DOM document by traversing it. This means we start at the root and
visit all the nodes. We use the folowing objects and methods of the DOM for traversing.
We start at the root node and get a list of all elements. For each element we get a list of all nodes.
For each node we get a list of all attributes. For each arttribute we print our name and values.
<% 'xmltodom.asp
Dim dom
set dom = Server.createObject("MSXML.DOMDocument")
dom.Load Server.MapPath("employee.XML")
' if children
if nodes.length> 0 then
%>
Type the above ASP program into a file called 'xmltodom.asp and run it.
root: Employee:
This is the output: name: john smith
address: 23 nowhere st
city: toronto
This is also an easy thing to do, we just save the contents of a record set as an XML document. We
connect to the database open up a recordset then disconnect from it. We use the save method of
the record set to write the contents of a Recorsdset to a xml file. We use adPersistXML persist
format which is constant 1
<%
' convert database to XML rstoxml.asp
Dim cn
cn.cursorlocation = 3
cn.Open
Dim rsCategories
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
183
cn.close
dim fs
set fs = server.CreateObject("Scripting.FileSystemObject")
if fs.FileExists(Server.MapPath("aspL12.xml")) then
fs.DeleteFile server.MapPath("aspL12.xml")
end if
response.write(server.MapPath("aspL12.xml"))
Our cursor location is adUseClient (constant value 3) this means the client not the data base
provider will be responsible for controlling the cursor movements.
cn.cursorlocation = 3
Type the above ASP program into a file calkled rstoxml.asp and run it. Make sure you made and
have the database file aspL12.asp in the same directory.
rsCategories.Open "employee",cn,1,4,&H0002
A cursor is a pointer to a record in a record set. A cursor has a type and location. Our cursor type is
adOpenKeyset (constant value 1) which means we can change the records in the database using
the recordset.
Cursor Types
Constant value description
adOpenForwardOnly 0 read only recordset that can only scroll forward
adOpenKeySet 1 add,modify,delete records, can't see changes made by others
adOpenDynamic 2 add,modify,delete records, can see changes made by others
adOpenStatic 3 read-only record set, scroll forward, backeward and bookmarking
Lock Types
Constant value description
adLockReadOnly 1 records are read only and cannot be changed
adLockPessimistic 2 records are locked when you start editing them
adLockOptimistic 3 records areonly locked when you call the update method
adLockBatchOptomistic 4 used for batch updates.This means the records will only
change when the batch update function is called.
Notice our Lock type is adLockBatchOptimistic this means the record set will store the changes
interrnally to be updated later. Lastly we disconnect the recordsdet from the data base connection.
Now you see why we use adLockBatchOptimistic! We will later reconnect to the data base and
update it.
Options is a optional Long value that indicates how the provider should evaluate the Source
argument if it represents something other than a Command object, or that the Recordset should
be restored from a file where it was previously saved. We use adCmdTable &H002 because it will
store which tabLe we are using in the record set.
Constant value Description
adCmdText &H0001 Indicates that the provider should evaluate Source as a textual
definition of a command.
adCmdTable &H0002 Indicates that ADO should generate an SQL query to return all
rows from the table named in Source.
adCmdTableDirect &H0200 Indicates that the provider should return all rows from the table
named in Source.
adCmdStoredProc &H0004 Indicates that the provider should evaluate Source as a stored
procedure.
adCmdUnknown &H0008 Indicates that the type of command in the Source argument is
not known.
adCommandFile &H0100 Indicates that the persisted (saved) Recordset should be
restored from the file named in Source.
Our data base is quite small, it has only one table and 1 record in the table.
Here is the contents of the asp12.xml file as read from Internet Explorer. It has included alot of the
data base information (schema) such as fileld names, field data types and lengths.
(1) record set schema which describes the field data types
(schema describes the data base column field names and data types)
(2) row data
(3) data section
(4) each data row
Each section is identified by a unique prefix ":". example "<rs:data>"These prefixes are called
namespaces. The folowing table lists the prefixes and description
prefix description
s marks the beginning of a record set schema
dt marks the beginning of each row's data type
rs marks the beginning of the data section
z marhs the beginning of each data row
[7] read the contents of a XML file and store in a record set
We use the open method of a record set to read the XML file. Note we use the MSPersist Provider.
<%
' xmltors.asp
Dim rs
Set rs = Server.CreateObject("ADODB.RecordSet")
Const adOpenKeyset = 1
Const adLockBatchOptimistic = 4
Const adCmdFile = &H0100
Const adUseClient = 3
rs.CursorLocation = adUseClient
rs.open Server.MapPath("aspL12.XML"), ,adOpenKeyset,adLockBatchOptimistic,adCmdFile
We can read the contents of this RecordSet. This RecordSet is known as a disconnected RecordSet
To store this data you would have to write the contends to another connected RecordSet or re-
connect to a data base. Notice our cursor location is at the client side. the client is responsible to
provide cursor services not the provider (server). Since we are disconnected we have no provider.
Here we write the contents of the record set to a string for display.
Dim str
Dim index
Do Until rs.EOF
for index = 0 to 2
str = str + rs(index).Name + ": " + rs(index).Value + "<BR>"
next
rs.movenext
Loop
Response.write str
%>
Type the above ASP program into a file called xmltors.asp and run it,
records:
You should get something like this: Name: Joe Smith
Address: 23 Nowhere Street
City: Toronto
You can also update, delete and add new records to the recordset. In our example we just change
one of the fields values.
We do not issue an update, this will happen aiutomatically when we re-connect to the data base.
Here we just reconnect the record set to the data base and issue an update batch. The stored data
in the recotrdset is now used to update the data base.
Dim cn
rs.ActiveConnection = cn
rs.UpdateBatch
rs.Close
Set rs = Nothing
Try it on the above xmltors.asp file anfd then open up your data baew liikung forv the chanre.
[10] DOM to RS
dom.save "asp12.xml"
[11] rs to Dom
Const adPersistXML = 1
rs.save Server.MapPath("aspL12.xml"), adPersistXML
With MSMXML Version 3.0 you can do this all in one step.
Make a small ASP program that can demonstrate all 11 XML things to do. Use ONCLICK events on
the buttons to call the approiate function. When your finished you should have something like this:
ACCESSING NODES BY ID
This is a fast way to get a list of all elements having the same nametag. We have the following XML
file "customers.xml" organized by customer, orders and order items.
<customers>
<customer name="Jack Sprat" address="16 Wonderland Rd">
<orders>
<order number="1234" date="1\21\2003">
<items>
<item name="1 kg ice cream" price="6.38" />
<item name="2 kg bacoon" price="3.78" />
</items>
</order>
</orders>
</customer>
<customer name="Humpty Dumpty" address="12 FallDown Street">
<orders>
<order number="5678" date="1\21\2003">
<items>
<item name="paracheut" price="36.24" />
<item name="safety net" price="24.78" />
</items>
</order>
</orders>
</customer>
</customers>
The above XML file demonstrates the power of XML. We have combined 3 tables in one XML file:
customers, orders and ordered items.
We are going to make a web page to display all the customers in a Select Box, list all the orders
by order number for the selected customer in another Select Box than display the items in a Text
Area for that order.
Dim customerList
Set customerlist = docXML.getElementsByTagName("customer")
We now have a list of element for the tag name "customer", which are
Once we get the list of customer elements we can get each element in the list using the
item(index) method
Dim customer
customer = customerList.Item(0)
Once we got an individual item we can get the values of the attributes of that item using the
getAttribute(attribute_name) method and the attribute name.
customer.getAttribute("name")
It is more work to get a list of order elements for a selected customer, since now we are penetrating
deeper inside the DOM.
Dim orderList
Dim str
str = "customer[@name=""" & custsel & """]/orders/order"
Set orderList = docRoot.getElementsByTagName(str)
Note: The attribute values in the query string must have a " (double quote) that's is why we use ""
to specify a ". We need to specify the customer name to get all order tags for that order. The order
tags are in the orders tag. The query string to obtain the orders for jack sprat would be:
customer[@name="Jack Sprat"]/orders/order
It is even more work to get a list of items for an order of a selected customer.
Dim orderItems
str = "customer[@name=""" & custsel & """]/orders/order[@number=""" & ordersel & """]/items/item"
Set orderItems = docRoot.getElementsByTagName(str)
We need to specify the customer name and order number to get all items for that order. The item
tags are in the items tag. The query string to obtain the items for jack sprat and order 1234 would
be:
customer[@name="Jack Sprat"]/orders/order[@number="1234"]/items/item
Here are the step by step instructions to build the example ASP program to select customer and
orders.
[1] obtain and store the selected customer and order number
' Customer.asp
Dim custsel
Dim ordersel
custsel=request.form("customers")
ordersel=request.form("orders")
[2] load our XML file into a DOM and get reference to root documentElement
Dim docXML
Set docXML = Server.CreateObject("MSXML.DOMDocument")
docXML.Load Server.MapPath("customers.xml")
Dim docRoot
Set docRoot = docXML.documentElement
[3] next we need to get a list of all customers and put into an option box. We use the
ONCHANGE event to call the asp program again using the form's submit() method.
dim customerList
set customerlist = docXML.getElementsByTagName("customer")
Dim i
Response.write "<form name='form1' method='post'>"
Response.Write "<SELECT name=customers size=1 "
Response.Write ">
if custsel="" then
custsel= customerList.Item(0).getAttribute("name")
end if
[4] next we need to get a list of all orders for the selected customer and put into an
option box. We use the ONCHANGE event to call the asp program again using the form's
submit() method. We must specify the customer tag and name attribute to get the customer orders
Dim orderList
Dim str
str = "customer[@name=""" & custsel & """]/orders/order"
Set orderList = docRoot.getElementsByTagName(str)
Response.Write "<SELECT name=orders size=1
>
dim found
found = false
For i = 0 To orderList.length - 1
Dim order
Set order = orderList.Item(i)
if ordersel=order.getAttribute("number") then
found = true
Response.Write "<Option SELECTED>" & order.getAttribute("number")
else
Response.Write "<Option>" & order.getAttribute("number")
end if
Next
Response.Write "</SELECT>"
Response.Write "</form>"
[5] we put all the orders for this customer in a Text Area
we must specify the customer tag and name attribute and order tags and number attribute to get
the items
str = "customer[@name=""" & custsel & """]/orders/order[@number=""" & ordersel & """]/items/item"
str = "customer[@name=""" & custsel & """]/orders/order[@number=""" & ordersel & """]/items/item"
Dim orderItems
Set orderItems = docRoot.getElementsByTagName(str)
dim textstr
textstr=""
For i = 0 To orderItems.length - 1
Dim orderItem
Set orderItem = orderItems.Item(i)
Dim name
Dim price
name = orderItem.getAttribute("name")
price = orderItem.getAttribute("price")
Next
Type customes.xml into a file and the above code into a ASP file called customers.asp. Once you
got it working add more orders to each customer and see if you can select individual orders.
File: aspGuideL13.doc
Date Started: Jan 21, 2003
Last Update: June 20, 2003
Version: 0.0
ISBN: 0-9730824-3-7
XML needs to be displayed in a readable format. XSL is used to transform XML to a readable
output. This means we remove the tags and just display the required data. XSL stands for
eXtensible Stylesheet Language. In a web browser HTML is used to display text, images and sound.
XSL is used to convert XML to HTML. XSL just tells XML how to display its data. There are three
ways to display data from a XML file
Each has its own benefits depending on the application. We will concentrate on using XSL to extract
data from XML. Options (1) (using DOM) and option (2) reading XML into a RecordSet have been
discussed in the previous lesson.
XSL is just XML but has tags that describe how to extract data from XML. Each tag has the XSL
namespace xsl: The xsl name space is identified by a URI Uniform Resource Indicator. A URI
indicates a unique location just like a URL. The xsl name space is declared using the xmlns:xsl and
the URI. Interesting xmlns stands for xml name space.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
The XSL transform processor is used to transform XML into meaningful data. Here is a XSL file
"employees.xsl" that will be used to transform the XML file "employees.xml" used in previous
lessons.
(2) Next we need to declare this as a XSL style sheet, you must have this tag completely as written.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
(3) The next line tells the transform processor, where to start transforming
<xsl:template match="/">
The "/" means to start from the root of the XML document
The xsl:for-each tag locates a set of elements in a XML document and traverse through all nodes.
In our example we look for the Employee elements.
(5) Once we are at one of the nodes we have to extract the value from the node using the value-of
tag
The value-of tag will extract the actual value of the select node's name. We will have additional
value-of tags for address and city.
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
To transform a XML file using a XSL file we have to use the transformNode method belonging to
the DOM
dom.transformNode(xslDocument)
This method returns a String of the results of the transformation. Both the XML and XSL file must
be loaded each into a separate DOM. The transformNode method is called from the XML DOM and
receives the XSL DOM. The XSL file is just used to produce the output string. The original XML and
XSL DOM's stay intact.
XML file
Step [1] type in the following XML into a file called "employees.xml" with no leading spaces.
Step [2] type in the following XSL into a file called "employees.xsl" with no leading spaces.
Step [3] In an ASP program declare two DOM objects, one for a XML DOM the other for a XSL
DOM.
Dim domDoc
Set domDoc = Server.CreateObject ("MSXML.DOMDocument")
Dim xslDoc
Set domDoc = Server.CreateObject ("MSXML.DOMDocument")
Step [4] Load the XML file in a XML DOM and the XSL file into a XSL DOM. You can optionally write
out the file contents to prove that the XML and XSL files have been loaded properly (do this
separately)
xslDoc.Load Server.MapPath("employees.xsl")
'Response.Write xslDoc.xml
Step [7] Finally we call the transformNode method from the XML DOM object and feed it the XSL
DOM object then write out the transformation in the str variable.
Dim str
str = domDoc.transformNode(xslDoc.documentElement)
Response.Write str
Step [8] Run your ASP Program, your output should be something like this:
john smith 23 nowhere st toronto mary smith 32 somehere st orangeville bill smith 43 anywhere st tenessee
Your web browser can automatically transform XML using XSL (IE 5.0 or greater). all you got to do is
to reference the XSL as a style sheet in the XML file.
Here is the employees xml file with a reference to the employees xsl style sheet.
Just add the XSL reference and open up the file in Internet Explorer and again you get the same
result:
john smith 23 nowhere st toronto mary smith 32 somehere st orangeville bill smith 43 anywhere st tenessee
The output is very plain. What we need to do is to spice things up using an HTML Table. We now add
the <TABLE> tags <TH><TR> and <TD> to our XSL file.
Now that we got our XSL file to do all the transformation for us we can call the XML file from an
HTML file. We use the IFRAME tag and the XML file as the src. <HTML>
<HEAD>
<TITLE>Employees2.html</TITLE>
</HEAD>
<BODY>
<IFRAME SRC="EMPLOYEES2.XML"></IFRAME>
</BODY>
</HTML>
DATA ISLANDS
We can reference a XML file and a XSL file in an HTML file using the xml tag.
We use a <DIV> tag to display the transformed text. The transformed text will appear at the
location where the <DIV> tag is located.
<div id="xslEmployee"></DIV>
When the page loads we do the transformation and the transformed text appears at the location
where the div tag is located.
Alternatively you can embed the complete XML and XSL files inside the html program
<xml id="source">
<?xml version='1.0' ?>
<Employees>
<Employee>
<name>john smith</name>
<address>23 nowhere st</address>
<city>toronto</city>
</Employee>
<Employee>
<name>mary smith</name>
<address>32 somewhere st</address>
<city>orangeville</city>
</Employee>
<Employee>
<name>bill smith</name>
<address>43 anywhere st</address>
<city>tenessee</city>
</Employee>
</Employees>
</xml>
<xml id="style">
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<TABLE Border="1">
<TR>
<TH>Name</TH><TH>Address</TH><TH>CITY</TH>
</TR>
<xsl:for-each select="Employees/Employee" >
<TR>
<TD><xsl:value-of select="name" /> </TD>
<TD><xsl:value-of select="address" /></TD>
<TD><xsl:value-of select="city" /></TD>
</TR>
</xsl:for-each>
</TABLE>
</xsl:template>
</xsl:stylesheet>
</xml>
Make a file that contains names, addresses and city. In an ASP program, read in the file and
generate a xml data island as in the above example. This is easy to do using Response.Write
statements and For Loops. Also generate a XSL data island using the employes2.xsl file as the src.
Use a Script to do the transformation and the HTML <DIV> tag method to do display
transformation. When you run the ASP program you should get the same result. Call your ASP file
aspL13EX1.asp.
SORTING OUTPUT
You can sort the result in ascending or descending order using the order-by="name" attribute and
value
Add an additional button where they can select ascending or descending order in the previous
exercise. Call your ASP file aspL13Ex2.asp.
<xml id="source">
<?xml version='1.0' ?>
<Employees>
<Employee name="john smith" address="23 nowhere st" city="toronto" />
<Employee name="mary smith" address="32 somehere st" city="orangeville" />
<Employee name="bill smith" address="43 anywhere st" city="tenessee" />
</Employees>
</xml>
Our XSL file to display the XML with attributes would be:
<xml id="style">
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<TABLE Border="1">
<TR>
<TH>Name</TH><TH>Address</TH><TH>CITY</TH>
</TR>
<xsl:for-each select="Employees/Employee" >
<TR>
<TD><xsl:value-of select="@name" /> </TD>
<TD><xsl:value-of select="@address" /></TD>
<TD><xsl:value-of select="@city" /></TD>
</TR>
</xsl:for-each>
</TABLE>
</xsl:template>
</xsl:stylesheet>
The only difference is we use "@attribute_name" to select the value of the attribute. example:
Put the xml file using attributes and the corresponding xsl file to display the xml as a data island in
an html file. Call your ASP file aspL13Ex3.asp.
XSL OPERATORS
"Context" specifies the source of a XSL query. In the example above our context was "all
employee in employees". Our search path started at the root of the XML document and includes
all employee nodes belonging to employees. XSL has the following query operators to aid in
searching nodes in a path.
operator description
/ use root as context (search all nodes)
./ use current context (the node where they are now)
// search across any levels starting from root of document
.// each across any levels starting from the current context
* find all
@ used to specify an attribute
= equal to
end() last node
index() specify node index
We have used some of these already when we were using the DOM getElementsByTagName
method of the previous lesson. Here are some examples using the XSL operator:
find all employee elements in employees that have child name elements
find all the employee elements that are grandchildren of the root
find all employee elements in employees that have child name element equal to
"john smith"
find all employee elements in employees that have child name element index equal to 2
find all employee elements in employees that have name attribute equal to
"john smith"
Try all the above examples easy when you use a data island. You could add a textbox where the
seer could type in the xsl query string. Make some additional ones. Call your asp file aspL13Ex4.asp.
LOGICAL OPERATORS
Logical operators allow you to compare values to include or exclude elements and nodes. We are
now filtering the XML document even more. Here are all the operators.
operator description
and logical and
or logical or
not() negation
= equal
!= nor equal
> greater than
< use < less than
>= greater than or equal
<= use << less than or equal
Find all attributes in the employees/employee context that have name "tom smith"
(notice the single quotes around 'tom smith'):
Find all attributes in the employees/employee context that have cities greater and equal to toronto
Find all attributes in the employees/employee context that have cities less than toronto
Find all attributes in the employees/employee context that have cities not equal to toronto
Find all attributes in the employees/employee context that have cities equal to 'toronto' and name
equal to 'john smith'
Try all the above examples, make some additional ones. Use the Textbox of Exercise4 to type in the
XSL query strings.
File: aspGuideL14.doc
Date Started: Jan 21, 2003
Last Update: June 20, 2003
Version: 0.0
ISBN: 0-9730824-3-7
XML APPLICATIONS
We can take our xml file "employees.xml" from last exercise and bind to a table.
We make another html file called "Employees6.htm" and include the employees.xml file as a data
island.
The "Employees6.htm" html file will contain the table elements where the data to be displayed will
be obtained from our data island. We bind the xml data to the table using the using the datasrc
property and the xml data island id xmlemployees.
<TABLE DATASRC=#xmlEmployees>
We use the <DIV> tag and datafld attribute to map the data from the xml file fields to the table
columns.
Here is the complete HTML file notice the table header is enclosed in <THEAD> tags. If you are
curious why? then remove the <THEAD> tags to find out!
<BODY>
</BODY>
</HTML>
If you wonder if you can bind (display data) to other HTML elements you are correct! The following
table lists elements with their corresponding property attribute. Not all of the elements are
updateable (can be changed) once they are bound.
or TextBox
Here is the complete html file. Only the address and city fields get bound d to textboxes the name
field gets bound to a <div> tag.
<BODY>
</BODY>
</HTML>
We can navigate through the records displayed in our table to go forward or backward and even
add new records. The first thing we have to do is to is give the table an ID and limit the number of
records to be displayed using the table ID and the datapagesize property attributes.
Now we need to add some buttons to display next, previous, first and last records. We use the
<pre> tag to form the button labels as "<<" "<" ">" and ">".
<BUTTON ID=FIRST
>
<BUTTON ID=previous
>
<BUTTON ID=next
>
<BUTTON ID=last
>
To add a new record we must access the record set of the xmlemployees data island and call the
addNew() method.
>New</button>
Once we add the new record we must navigate to the end of the record set so that the use can see
the empty data fields and add the data.
tblEmployees.lastPage()">
<pre>New</pre></button>
Now the use can add a new record. Once the user moves to another record the data is updated in
the record set.
We need to send the new updated file to the server to store in update the xml file. To do this we
have a form that just gets a hidden field.
We make a function called getxml to submit the data stored in the hidden field to the server. Here
is the getxml function it just writes a XML string to the hidden element and calls the submit()
function to send it to the server.
function getxml()
document.form1.updateit.value=xmlEmployees.xml
document.form1.submit()
getxml=true
end function
We call the getxml function from a button so that can update the server database any time we
want.
Or when the page unloads. This way the server data base will always be updated.
<BODY >
The server gets the xml string writes it to the screen and then can save it to a file.
<%
dim xmlstr
xmlstr = Request.Form("xmlUpdate")
response.write xmlstr
%>
<script LANGUAGE="VBSCRIPT">
function getxml()
'msgbox xmlEmployees.xml
document.form1.updateit.value=xmlEmployees.xml
document.form1.submit()
getxml=true
end function
</script>
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
215
<BODY >
<P>
<BUTTON ID=FIRST
>
<BUTTON ID=next
>
<BUTTON ID=last
>
<BUTTON ID=new
> tblEmployees.lastPage()">
<pre>New</pre></button>
</P>
Complete the ASP program to read the xml string and write to a file. Once the XML file is updated
then redirect back to the html page or to the page they wanted to go to. Call your HTML file
aspL1Ex1.htm and your ASP page aspL14Ex1.asp.
The trouble with using XSL is that you always have to have a hard coded file or a data island. Here is
an ASP program that adds nodes to an existing XSL file to transform the XML file to what you want.
When you call the ASP program you give it the XML and XSL file names and a list of parameters. The
XML and XSL files are loaded into a DOM. The ASP program then reads the parameters and adds the
nodes to the XSL Dom and then returns the transformation result HTML string.
XML XML
File DOM
transformNode
XSL XSL
File DOM
you would use the order-by attribute in the XSL for-each element from:
<xsl:for-each select="Employees/Employee">
to:
ASP PROGRAM
The ASP programs must receive the name of the XML and XSL files and load each into a DOM and
add the additional attributes to the for-each node then call the transformNode method to do the
transformation. The XML and XSL file name and additional attributes are sent to the ASP program
by an HTML program as name value pairs.
http://localhost/Lesson14/xmlserver.asp?a:orderby=name&xmlfile=employees.xml&
xslfile=employees2.xsl
Notice we have prefix the parameters that are XSL node attributes with an "a:"
a:orderby=name
<%
'Lesson14p2.asp
response.expires=-1
response.contentType = "text/html"
xmlfile = request("xmlfile")
xslfile = request("xslfile")
xmldom.load server.mappath(xmlfile)
xsldom.load server.mappath(xslfile)
response.write xmldom.transformNode(xsldom)
key=mid(key,3)
end sub
%>
Let's go through the ASP file line by line. We first get the XSL and XML file names from the query
string parameters.
xmlfile = request("xmlfile")
xslfile = request("xslfile")
Next we create two DOM objects and load in the XML and XSL files asynchronously meaning wait till
the whole file is loaded before proceeding.
xmldom.async = false
xsldom.async = false
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
220
xmldom.load server.mappath(xmlfile)
xsldom.load server.mappath(xslfile)
Next we go through all the received parameter one by one and call the updatexsl sub to add the
attributes to the for-each element of the XSL file.
response.write xmldom.transformNode(xsldom)
It is here in the updatexsl sub where we add the attribute to the for-each element. We first check
for the a: prefix
if left(key,2)="a:" then
If find the "a:" prefix we extract the attribute without the "a:" prefix
key=mid(key,3)
We then select the node using the selectsinglenode method with the for-each tag:
If we find the for-each node we then add the attribute key and value to it using the setAttribute
method.
<xsl:for-each select="Employees/Employee">
to this
We have made an HTML test program to send a XML and XSL files and attributes to the ASP
program. We have three buttons to select order by name, address or city and hidden type's to
send over the XML, XSL files names and XSL attribute's.
<html>
<head>
<title> xml server </title>
</head>
<body>
</form>
</body>
</html>
Pressing the name button would give you this. Notice the names are all in sorted order.
Add a textbox that only finds the entered name when the name button is pressed.
Use the xmlHTTP object to talk to the ASP directly so that the button and transformation are
displayed on the same page.
File: aspGuideL15.doc
Date Started: Jan 21, 2003
Last Update: June 20, 2003
Version: 0.0
ISBN: 0-9730824-3-7
We can write a VB program that reads a XML document from an ASP program.
Web Server
request xml document
VB ASP
Program Program
send xml document
XML
Document
We use the open and send methods from the xmlHttpRequest object to request the XML
document and receive the XML document.
End Sub
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
224
<%
' aspLessonL15p1.asp
%>
Type in the above two programs and get them working. Have the VB program specify which xml
document to send in a TextBox. You would need to use the send(message) function of the
xmlHttpRequest object to send the name of the XML document to the ASP program. You then
need to use the BinaryRead(count) method of the Request object to read the XML file name. The
number of bytes received (count) can be obtained from the TotalBytes property of the Request
object. Use an XSL style sheet somehow to display the text of the XML document rather than the
XML tags in the text box. You can put the XSL stylesheet any where you want. Call you VB program
aspL15Project1.vbp and your asp file aspL15Ex1.asp.
We can also have an ASP program receive a XML file from a VB program. The ASP program would
receive the XML file. We just use the send(message) method of the xmlHttpRequest object to
send a XML file to the ASP page.
Web Server
send xml document
ASP VB
Program Program
Here is the form code that sends a XML Document to a ASP page:
End Sub
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
226
Here is the ASP program that receives and stores the XML document:
<%
' aspLessonL15p2.asp
xmlDoc.load Request
%>
If you are using MSXML version 1 you need to open a file and save the XML as a string.
dim fso
dim myfile
myfile.writeline (myxml)
myfile.close.
Get the above example working. Instead of hard coding the name of the XML file extract the name
of the file from the received XML document!. You would need to make a tag for the file name in the
XML document then use the selectSingleNode(tag name) method of the xmlDocument object to
get the node and then use the getAttribute(attribute name) method of the Node to get the XML
file name. Seems like a lot of work to do! Call you VB project aspL15Project2.vbp with a form called
Form2 and your ASP file aspL15Ex2.asp.
In some situations you will be loading a long XML document but your program may want to do other
things while it is loading. You can set up a file ready complete event that will fire when the XML
document is completely loaded. To demonstrate we can write a VB program that reads a XML
document from an ASP program.
We then set the async property of the xmdoc object to true to allow asynchronous loading.
xmlDoc.async = true
When the xml file is completely loaded it will call the onreadystatechange event. You need to code
a function to receive this event. Once this function is called you can send the xml file to the ASP
program
if xmldoc.readystate = 4 then
End If
End Sub
Get the onready change event working. You may want a message box to pop up once you receive
the onready change event. Call you VB program aspL15Project3.vbp and your asp file
aspL15Ex3.asp.
We now need to demonstrate a typical XML application for your complete understanding. An
example XML application ties it all together for you. In our simple example we have a database of
items. The items can be anything like grocery store or hardware store items. We have a XML
database manager module that will handle request and update to the data base. We will have a
VB program where the owner of the store can view and change the database. They may want to
add, delete or change prices of existing items. Next we have a Customer terminal HTML program
where the cashier can enter items the customer wants to buy. We can have many HTML programs
that act like terminals where customers can buy, order and return items. Finally we have the
Business Services module that connects customer terminal and owner terminal requests to the
database. We call it Business Services because these are the operations a business needs to do. By
using many modules the system gets organized into separate programs, each program is dedicated
to a task. The advantages of modular programming is, if we need to add new features we just have
to update a particular module. Our programming model is as follows:
query.htm bs.asp
HTML xmlDBMgr.asp
Terminal Business
Program Services XML
Database
Manager
Project4.vpb
owner entry
Database
We will now discuss each module one by one with sample code.
DATABASE
The database will just store items, records. a item record is designed as follows
Our data base is stored in a file called Lesson15.mdb but you can use any name you want.
XMLDBMGR
We will be interfacing to the database all in XML. The task of the xmldbmgr is to receive queries,
updates and respond in XML. The xmldbmgr will be class module. A class module has many
functions called methods all sharing the same common variables. Our xmldbmgr will have the
following methods.
method purpose
class_initialize open connection to data base
openRS(table) open table, returns all recordsets as XML
update(table,xmlstr) reconnect to data base update all records
openWhere(table,field,where) query a specific record return as XML
class_terminate disconnect connection
<%
' class xml database manager
cn.cursorlocation = adUseClient
cn.Open
end sub
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
231
Set rs = Server.CreateObject("ADODB.RecordSet")
rs.Open "parts",cn,adOpenKeyset,adLockOptimistic,adCmdTable
cn.close
dim fs
if fs.FileExists(Server.MapPath("parts.xml")) then
fs.DeleteFile server.MapPath("parts.xml")
end if
'response.write xmldom.xml
return dom object
set openRS = xmldom
end function
xmldom.loadXML (xmlstr)
if fs.FileExists(Server.MapPath("parts.xml")) then
fs.DeleteFile server.MapPath("parts.xml")
end if
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
232
end sub
' query a record by part number
' return record as xml
public function openWhere(table,field,where)
dim sql
sql = "SELECT * FROM " + table + " where " + field + " = " + where
rs.Open sql,cn,3,1,&H0001
dim xmlstr
else
xmlstr = "<parts>"
xmlstr = xmlstr + "<part PartNum = '" + cstr(rs(0)) + "'"
xmlstr = xmlstr + " Description = '" + rs(1) + "'"
xmlstr = xmlstr + " Qty = '" + cstr(rs(2)) + "'"
xmlstr = xmlstr + " Price = '" + cstr(rs(3)) + "'"
xmlstr = xmlstr + " BackOrder = '" + cstr(rs(4)) + "'"
xmlstr = xmlstr + " DeliveryDate = '" + cstr(rs(5)) + "' />"
xmlstr = xmlstr + "</parts>"
end if
end function
rs.close
cn.close
end sub
end class
%>
The business services module will receive XML commands from the Customer and Owner
terminal's modules. We use XML because we have the flexibility to have any command we want
Every task we need to do will have a corresponding customer task or owner task.
Customer Tasks
Here is a list of customer tasks we may have to accomplish and the corresponding XML commands
to go with them.
Owner Task's
Here is a list of owner's tasks we may have to accomplish and the corresponding XML commands to
go with them.
task purpose
query return a xml record for a part number
request return all records for a table in xml
update update a data base from a record set
To be successful with working with XML you need to be good at extracting nodes and attributes from
the Dom. This can be quite confusing thing to do.(even for us). We find extracting information from
the Dom very confusing and awkward. The first thing you got to do is get a node, we use the
selectSingleNode method of the DomDocument module to do this.
The selectSingleNode method returns a node object. Once you got this node object we use the
getAttribute method of the node object to get the value of a specified attribute.
cmd = action.getAttribute("cmd")
Here's another DOM attraction example for you. The update command has an embedded XML
node in it. We use the action/xml path to find it.
<%
' bs.asp
' business services module
Response.ContentType = "text/xml"
%>
<%
' create DOM
dim xmlDoc
set xmlDoc = Server.CreateObject("MSXML.DOMDocument")
</action>"
dim action
Set action = xmlDoc.selectSingleNode("action")
Dim cmd,table,xmldb,xmlstr,part
cmd = action.getAttribute("cmd")
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
235
'''''''''
' query '
'''''''''
table = action.getAttribute("table")
part = action.getAttribute("part")
response.write xmlstr
'''''''''''
' request '
'''''''''''
table = action.getAttribute("table")]
response.write xmlDoc.xml
''''''''''
' update '
''''''''''
elseif cmd = "update" then
table = action.getAttribute("table")
'response.write table
Set xmlstr = xmlDoc.selectSingleNode("action/xml")
xmldb.update "parts",xmlstr.xml
end if
%>
CUSTOMER TERMINAL
A cashier will enter a part number and get the record from the data base. The cashier will also have
the options to buy, back order or return items Here are the tasks again of the customer module and
the corresponding XML for them.
Here's the code for the customer terminal. we use HTML and VBScript and the xmlHTTP object for
inter module communication. The code will all execute on the web browser. The customer terminal
will send and receive XML to and from the business services module. So far we have been able
the query a part and display the data in text boxes. It will be part of the next exercise to implement
the full customer terminal. Buttons are used to initiate action and call functions written in vbscript.
dim doc,http,xml
' create XML command use part number from text box
xml="<action cmd='query' table='parts' part='" + number.value + "'/>"
End Sub
number.value=""
desc.value=""
qty.value=""
bo.value=""
price.value=""
delivery.value=""
End Sub
</script>
</head>
<body>
<h3>Query</h3>
<table>
<tr>
<th>number</th>
<th>desc </th>
<th>qty</th>
<th>bo</th>
<th>price</th>
<th>delivery</th>
</tr>
<tr>
<td><input type="text" value="" name="number" size="4"></td>
<td><input type="label" value="" name="desc" size = "20"> </td>
<td><input type="label" value="" name="qty" size="4"> </td>
<td><input type="label" value="" name="bo" size="4"> </td>
<td><input type="label" value="" name="price" size="5"> </td>
<td><input type="label" value="" name="delivery" size="10"> </td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Query" name="B1" > </td>
<td><input type="button" value="Clear" name="B2" </td>
</tr>
</table>
</body>
</html>
OWNER TERMINAL
The owner has to monitor sales, add, delete or change process of existing items. We have a form
with a DataGrid control on it. A DataGrid control is good for displaying and updating contends of a
record set. We will also have a Button for adding records. Using a data grid will automatically update
the RecordSet when you make a change. Here are the customer tasks and corresponding XML
commands again.
' get all records from data base and display in DataGrid
Private Sub Form_Load()
xmlDoc.loadXML strxml
End Sub
rs.Update
SUMMARY
We have presented a very simple application all using XML. Even this simple application was very
confusing and awkward to code. One you continue using XML the awkwardness and confusion will
disappear. The only good thing about this is that you become an XML expert. Using the xmlHTTP
object is very dominant. This is a must because we need to preserve the state of the page you are
working on. By not leaving the page you definitely preserve its state.
You know what you have to do now. First step get all the code going. Every thing should work, if it
doesn't then you have to get it going. To the owner terminal add a delete button you may also
want to add additional features: like show all items that have back order, all items with low
inventory levels. Pick one of theses exciting options to add.
The main work to do is in the customer terminal. You need to add buttons to buy, return and
back order items. For every item they buy you need to add the record to a bill of sale. When they
bought all the items calculate totals and applicable taxes for your area. Display the Bill of sale and
totals on the web browser screen. When items are bought, returned or back ordered, the quantities
must be updated in the data base.
Good luck on finishing this XML mini-project. Once you got it all working properly you will be an
XML expert!
File: aspGuideL16.doc
Date Started: Jan 21, 2003
Last Update: June 7, 2003
Version: 0.0
ISBN: 0-9730824-3-7
Sometimes we need to run a program on different computers all at the same time. The programs
running on the individual computers need to talk to each other and to share information. The code
on one computer needs to talk to code on the other computer. When code, on one computer calls a
function from another computer this is known as RPC Remote Procedure Call. RPC needs a protocol
so that all computers know how to talk to each other. There are many protocols available. Some are
language dependent and some are language independent. Some are platform dependent and some
are platform independent. The platform may be Microsoft Windows, UNIX or Macintosh.
All these protocols have some mechanism to send function names and argument values to code
running on another computer. The code would receive the function name and argument values, call
the named function and pass to it the argument values. The called code will then send the result
from the function call to the request program. COM is used extensively in Microsoft windows where
programs can call methods from different program all running on the same machine. DCOM is like
COM but is used to allow two different computers running Microsoft Windows to call functions from
each other. RMI and IIOP are Java based protocols. RMI can only be used by Java programs but
IIOP can be used by both Java and non-Java Programs. CORBA very difficult to implement and
comes from the C++ world but can be used by any language. SOAP is XML based and very easy to
implement by any Language or platform.
A web browser or even another ASP page may want to call methods from an ASP page.
Some
Function
xmlHTTP object
The xmlHTTP object is used to send and receive XML using HTTP protocol. Using the xmlHTTP
object it is very easy for one program to call another program and receive a response. Using the
xmlHTTP object you can access data from a Web server, parse the data using the XML Document
Object Model (DOM), and post XML data through directly to an HTTP server. Here is the xmlHTTP
data sheet. The xmlHTTP object is available from MSMXML2 that comes with Internet Explore
6.0
xmlHTTP Objects
Object Description
IXMLHTTPRequest Provides client-side protocol support for communication with
HTTP servers.
xmlHTTP Properties
Property Description
onreadystatechange Property Specifies the event handler to be called when the readyState
Property changes.
readyState Property Represents the state of the request.
responseBody Property Represents only one of several forms in which the HTTP
response can be returned.
responseStream Property Represents only one of several forms in which the HTTP
response can be returned.
responseText Property Represents the response entity body as a string.
responseXML Property Represents the parsed response entity body.
status Property Represents the HTTP status code returned by a request.
statusText Property Represents the HTTP response line status.
xmlHTTP Methods
Method Description
abort () Cancels the current HTTP request.
getAllResponseHeaders() Retrieves the values of all the HTTP headers.
getResponseHeader Retrieves the value of an HTTP header from the response body.
(bstrHeader) bstrHeader
String containing the case-insensitive header name.
bstrMethod
String HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.
bstrUrl
String. Requested URL. This must be an absolute URL, such as "http://Myserver/Mypath/Myfile.asp".
varAsync [optional]
Boolean Indicator of whether the call is asynchronous. The default is True (the call returns
immediately). If set to True, attach an onreadystatechange property callback so that you can tell
when the send call has completed.
bstrUser[optional]
Name of the user for authentication. If this parameter is Null ("") or missing and the site requires
authentication, the component displays a logon window.
bstrPassword [optional]
Password for authentication. This parameter is ignored if the user parameter is Null ("") or missing.
Method Description
send (varBody) Sends an HTTP request to the server and receives a response.
varBody [optional] Variant.
Case-insensitive name.
setRequestHeader Specifies the name of an HTTP header
(bstrHeader, bstrValue) bstrHeader
String Header name to set for example: "depth". This parameter
should not contain a colon and should be the actual text of the
HTTP header.
bstrValue
String Value of the header; for example, "infinity".
IMPLEMENTING RPC
Our first example demonstrates receiving and displaying XML. We have an ASP program that
converts Centigrade degrees to Fahrenheit and sends back the result as XML.
<%
' aspL16P1.asp
Response.ContentType = "text/xml"
dim temp
temp = Request.QueryString("Temp")
dim c
c = (cdbl(temp) * 9) / 5 + 32
else
response.write "<centegrade>"&c&"</centegrade>"
end if
%>
Although this is a simple program it demonstrates how to send back data using XML.
We can now discuss this ASP Program line by line:
Response.ContentType = "text/xml"
sets the content type to XML. We need to tell the web browser what kind of data we are sending
back to it. In this case it is text and XML.
Next we get the temperature that we are going to convert from the Web browser
Dim temp
temp = Request.Form("Temp")
We need to trap any errors. Trapping errors is a must because the temperature could be missing. or
an improper number, whatever.
Dim c
c = (cdbl(temp) * 9) / 5 + 32
Lastly we check for any errors either report the temperature or report an error. We send back XML.
Else
Response.write "<centegrade>"&c&"</centegrade>"
End If
We now write a small HTML program to enter and send the temperature to the ASP program. It is
just a form with a text box to get the temperature and a button to send the temperature to the ASP
program.
<html>
<head>
<title>temperature.htm</title>
</head>
<body>
<h3>Centigrade to Fahrenheit</h3>
<form method="post" action="aspL16p1.asp">
<p>What temperature is it?</p>
<div align="left"><p><input type="text" name="Temp" size="10"></p>
</div><p><input type="submit" value="Submit" name="B1"><input
type="reset" value="Reset"
name="B2"></p>
</form>
</body>
</html>
Allow the user to convert Centigrade to Fahrenheit or Fahrenheit to Centigrade. You may want to
have two separate buttons or one button but receive two separate answers!. Have the ASP program
call a conversion function or functions to convert temperature. Call your HTML program
aspL16Ex1.htm and your ASP program aspL16Ex1.asp.
Now instead of sending name=value pairs to the ASP program we will send XML to the ASP
program. We need to modify our ASP program to extract the information from the received XML.
Here is the modified ASP program that receives XML.
<%
'aspL16P2.asp
Response.ContentType = "text/xml"
Response.AddHeader "SOAPAction", "fahrenheit"
Dim requestXML
Dim temp
else
temp = requestXML.selectSingleNode("/convert/centigrade").text
dim c
c = (cdbl(temp) * 9) / 5 + 32
if Err.number <> 0 or _
Request.ServerVariables("HTTP_SOAPAction") <> "convert" then
response.write "<centegrade>"&c&"</centegrade>"
end if
end if
%>
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
248
In the first line we send out two headers back to the web browser. The content is set as text/xml
Response.ContentType = "text/xml"
We load the XML document from the Request object. Since we are sending by Post the body of the
received message will obtain all XML.
Dim requestXML
If we can not load a xml object then we send back an error message.
temp = requestXML.selectSingleNode("/convert/centigrade").text
c = (cdbl(temp) * 9) / 5 + 32
response.write "<centegrade>"&c&"</centegrade>"
end if
In the html file we must send a XML document to the ASP program. We use the xmlHTTP object to
do this. Here is the HTML program.
function sendit()
dim doc,http,xml
xml="<convert><centigrade>"+temp.value+"</centigrade></convert>"
http.open "post",surl,False
http.setRequestHeader "SOAPAction","convert"
http.send(doc)
If isoObject(doc) then
msgbox "no response received"'
ElseIf doc.documentElement.nodeName = "Error" then
msgbox "invalid temperature passed"
Else
msgbox doc.selectSingleNode("/convert/temp").text
End if
End Function
</script>
</head>
<body>
<h3>Centigrade to Fahrenheit</h3>
When the send button is clicked then the sendit function is called. The first thing the
function does is create a XML document from a XML string using the DOMDocument object.
xml="<convert><centigrade>"+temp.value+"</centigrade></convert>"
Next we create a xmlHTTP object and send the XML document to the ASP programs using POST.
http.open "post",url,False
http.setRequestHeader "SOAPAction","convert"
http.send(doc)
if not(isobject(doc)) then
document.write "no response received"'
or received an error
or received a temperature
else
document.write doc.selectSingleNode("/centegrade").text
We have used the responseXML property to retrieve the XML document. object. We can also use
responseText property to receive the XML as a text string.
document.write (http.responseText)
We would receive the following XML string (use source view to view )
<centegrade>73.4</centegrade>
If you're interested in what headers are returned to the HTML program we can use the
getAllResponseHeaders method to view the receive headers.
document.write http.getAllResponseHeaders()
Allow the user to convert Centigrade to Fahrenheit or Fahrenheit to Centigrade. You many want to
have two separate buttons or one button but receive two separate answers!. Have the ASP program
call a conversation function or functions to convert temperature. Call your HTML program
aspL16Ex2.htm and your ASP program aspL16Ex2.asp.
Use the onreadystatechange property to call a function when the send method returns a response.
Call your html program aspL16Ex2.htm and your ASP program aspL16Ex3.asp.
SOAP SPECIFICATION
We have not been using SOAP yet all we have been doing is sending and receiving XML. Basically
this what SOAP does, the only difference is that soap uses some additional tag elements as follows.
(1) Envelope
(2) Body
(3) Header
Envelope
The envelope element is the root element of the SOAP XML document. The envelope is also used to
declare any name spaces used.
<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas:xmlsoap.org/soap/envelope/'>
Body
The body element houses the RPC calls. We define the ct namespace and a procedure call called
convertTemperature. Here is our SOAP body we send to the ASP program.
<SOAP-ENV:Body>
<ct:convertTemperatureDetail xmlns:ct='http://localhost/Lesson16/convertTemp/'>
<ct:temperature>temp.value</ct:temperature>
</ct:convertTemperatureDetail>
</SOAP-ENV:Body>
Header
The header is used to store authentication information. In our example we do not use a header
element.
<SOAP-ENV:Envelope xmlns:SOAP-ENV=
'http://schemas:xmlsoap.org/soap/envelope/'>
<SOAP-ENV:Body>
<ct:convertTemperatureDetail "xmlns:ct='http://localhost/Lesson16/convertTemp/'>
<ct:temperature>temp.value</ct:temperature>
</ct:convertTemperatureDetail>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Here is the html program that sends the SOAP envelope to the ASP program.
function sendit()
dim doc,http,xml
http.open "post",url,False
http.setRequestHeader
"SOAPAction","http://localhost/Lesson16/convertTemperature#convertTemperature"
http.send(xml)
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
254
set doc=http.responseXML
if doc.documentElement.firstChild.firstChild.nodeName="fault" then
document.write "invalid temperature"
else
document.write doc.documentElement.firstChild.firstChild.firstChild.text
End if
End Function
</script>
</head>
<body>
<h3>Centigrade to Fahrenheit</h3>
dim doc,http,xml
http.open "post",url,False
http.setRequestHeader
"SOAPAction","http://localhost/Lesson16/convertTemperature#convertTemperature"
http.send(xml)
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
255
The received soap message will be quite different the sent soap message, we have some additional
elements.
FAULT
<SOAP-ENV:Fault>
<faultcode>soap:client</faultcode>
<faultstring>soap:invalid temperature</faultstring>
<faultfactor>http://localhost/Lesson16/aspL16p3.asp</faultfactor>
<detail>
<ct:convertTemperatureDetail "
<xmlns:ct='http>//localhost/Lesson16/convertTemp/'>
<ct:temperature>temperature</ct:temperature>
</ct:convertTemperatureDetail>
</detail>" & vbcrlf
</SOAP-ENV:Fault>
The fault element has additional sub elements: faultcode, faultstring, faultfactor and Error
The faultcode identifies the type of error. Here are the Fault codes:
The faultfactior element contains a URI specifying the cause if the fault occurred.
The detail element is used to contain additional information about the error.
Here is the asp program that receives the soap envelope and returns a soap envelope.
<%
'aspL16P3.asp
Response.ContentType = "text/xml"
Response.AddHeader "SOAPAction",
"http://localhost/Lesson16/convertTemperature#convertTemperatureResult"
Dim requestXML
Set requestXML = Server.CreateObject("MSXML.DOMDocument")
requestXML.load Request
'On Error Resume Next
Dim temperature
temperature = requestXML.documentElement.firstChild.firstChild.firstChild.text
dim c
c = (cdbl(temperature) * 9) / 5 + 32
' success
Else
response.write "<SOAP-ENV:Envelope xmlns:SOAP-ENV="
response.write "'http://schemas:xmlsoap.org/soap/envelope/'>" & vbcrlf
response.write "<SOAP-ENV:Body>" & vbcrlf
response.write "<ct:convertTemperatureResponse "
response.write "xmlns:ct='http://localhost/Lesson16/convertTemp/'>" & vbcrlf
response.write "<response>"&c&"</response>" & vbcrlf
response.write "</ct:convertTemperatureResponse>" & vbcrlf
response.write "</SOAP-ENV:Body>" & vbcrlf
response.write "</SOAP-ENV:Envelope>"
End if
%>
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
257
Dim requestXML
Set requestXML = Server.CreateObject("MSXML.DOMDocument")
requestXML.load Request
Dim temperature
temperature = requestXML.documentElement.firstChild.firstChild.firstChild.text
dim c
c = (cdbl(temperature) * 9) / 5 + 32
We now either report the error or send back the converted temperature. In either case we send back
a SOAP envelope.
<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas:xmlsoap.org/soap/envelope/'>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>soap:client</faultcode>
<faultstring>soap:invalid temperature</faultstring>"
<faultfactor>http://localhost/Lesson16/aspL16p3.asp</faultfactor>
<detail>
<ct:convertTemperatureDetail xmlns:ct='http>//localhost/Lesson16/convertTemp/'>
<ct:temperature>temperature</ct:temperature>
</ct:convertTemperatureDetail>
</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas:xmlsoap.org/soap/envelope/'>
<SOAP-ENV:Body>
<ct:convertTemperatureResponse xmlns:ct='http://localhost/Lesson16/convertTemp/'>
<response>c</response>
</ct:convertTemperatureResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Allow the user to convert Centigrade to Fahrenheit or Fahrenheit to Centigrade. You many want to
have two separate buttons or one button but receive two separate answers! Have the ASP program
call a conversion function or functions to convert temperature scales. Call your HTML program
aspL16Ex4.htm and your ASP program aspL16Ex4.asp.
File: aspGuideL17.doc
Date Started: Mar 20, 2002
Last Update: June 17, 2003
ISBN: 0-9730824-3-7
Version: 0.0
ASP PROJECT 2
We will now convert our on-line store of previous Lessons to a XML on-line store. The following is a
block diagram of the components to make the on-line store of previous lessons.
Credit card
Item ShoppingCart processor
Item.cls ShoppingCart.cls cc.asp
thankyou
Home page order items page
order.asp download.asp
store.asp
Select items for
sale
view orders
view.asp
Data Base Manager
data base
dbmgr.cls
project2.mdb
update products
update.asp
Customers will buy things for sale either on the font page or other pages. Once they want to buy an
item they will click on it. They will then go to an order page where the item they bought and price is
shown. The customer will then presses a pay button to take them to a credit card form. Here they
will enter all the customer information and their credit card number. The credit card form will
validate the credit card and then send all the results of the transaction to a thank you page. Here
the customer will be informed that their credit cards transaction was successful or not. At this point
the products will be shipped to the customer and or the customer can download the software, video,
audio images what ever. In the real world we just interface to the credit card processor that handles
all the credit card transactions for us.
(1) Products
(2) Categories
(3) Customers
(4) Orders
For example if we are selling posters, all we need is the poster name, some description to intice our
customers, the name of the poster image file to send to the customer and the price of the poster.
Here is an example of the product table:
• boats
• flowers
• Streets
If the customer wanted to view by category or if you want to display your products for sale by
category then you need a category table and a category field in your product table. Our Categories
table has only 1 field, category. but you could definitely have more.
category
boats
flowers
cities
Each table will have a unique key known as the primary key. The primary key is used to make sure
each record is unique (no duplicate names) and as an index for sorting the table The primary key
for the product table will be the item field. The primary key for the category table will be the
category field. When a primary key is used in another table then it is known ass a foreign key. The
category table is used to lists all the available categories. The category field found in the product
table would let us list products for sale by category.
Will need to keep track of all customers who have bought at the store. Each customer needs to be
identified some how. We have many choices
We need to choose something that will never change. The best answer is using the customer name.
When the customer is inserted into the data base, each customer will get an automatic auto id.
Although we will still have to search for customer by name. If you think you will have many
customers with the same name then you can also use phone number and email for further
identification. Microsoft Access allows you to have a primary key spanning one field of more than
one field. The custID will be used as foreign keys in other tables. All you have to do is: in design
select more than 1 field using the shift key. right click and select primary key option from the pop up
menu.
In our order table we need to know which customer and which item they bought. We use the item
field from the product table and the custid field from the customers table. Using the custid field
makes it easier for us to identify the customer. The orders table needs additional information like
payment method, date purchased etc.
The following chart shoes the relations between the tables. The orders table identified the customer
and item bought.
orders
products orderid
categories item item
category category custID
description payment
imagefile date
price
customers
custID
Name
Address
Phone
EMail
It is best to have a separate page for each thing a customers has to do. We have listed the pages
required for the customer actions.
The home pages must attract customers, be easy to use and navigate. Home pages must also
appear as a safe place to buy. On the front page you can just list your categories of items for sale or
list category and items together. You may have a separate page for each item category. Since our
first project is a simple online store they only need to buy 1 of each item. Provide an encoded link
button or image, once the click in it they go to the order confirmation page,
It is here if the customer really want to buy your product. You must be very convincing at this point.
Offer them a full 30-day money back guarantee! Tell them the terms of sale and make them pay by
link on the pay by credit card button.
The credit card processor receives the customer id, item bought and amount for goods. The credit
card processor collects all the customer data for you. It receives the credit card number, check if its
is good and then tells you every thing is okay. How does it tell you every thing is okay? What you
got to do is to give it a return URL address. After the credit card processor validate the transaction it
calls the page and then sends all the transaction details to that page. It also sends a receipt to the
customer and to you. In the real world you can use a ready made credit card processor. They are all
have SSL encrypted and communicate directly with the credit card companies and their banks. For
this project you need to write your own unless you have access to one. For now Just hard code a few
credit card numbers. Verify using customer name address and telephone number.
In your thank you page you thank the customer for the order. You check the credit card transaction
details. You put all the customer information in the customer table. You put all the order information
in the order table. If you a shipping the goods to the customer you displays all customer information
for verification. You supply a ship button. As soon as thy press the button you send an email to, the
shipping dept and a confirmation receipt to the customer. For simplicity use the mailto protocol to
send the email. In a form the action attribute will use the mailto protocol. Use a hidden field or body
name to send the data. Make sure the enctype is text
If they are to download something you supply as download button or a link where they can
download the goods
This class will be responsible to connect to the data base and to read and write to the individual
tables on demand. As soon as the data base operation is over the database connection is closed.
The shopping card class must store all the items the customer is buying before they check out. The
item class stores the item information like price and description.
It is desirable that all data exchanged be XML. All data does not need to be stored in XML but XML is
used to exchange data, Here are some of the possibilities:
(1) The product table can be arranged by category and stored as XML. When products are to be
displayed then the ASP program can read the product XML table much faster rather than connect to
the database. XSL can be used to transform the XML for display. Every time the products table
database is updated then the products XML file must be generated.
(2) The items stored in the shopping cart should be converted to XML when the customer checks
out. The XML can be used to save Shopping Cart contents between ASP pages. You can add two
methods to the shopping cart class readxml and writexml.
(3) XML and XSL can also be used to show the items ordered when the customer checks out or after
the customer has paid for their order in the thankyou page.
(4) You may want to store all data in a disconnected Recordset and then reconnect to the data base
later. XML can be used to read and write data to the disconnected Recordset
To sum up things every time you have an string or array of data to store then this data can be easily
stored as XML. XML as the added capability to read and display data as well as store data.
www.cscourses.com E-Learning, E-Books, Computer Programming Lessons and Tutoring
copyright © www.cscourses.com For use of student or purchaser only. Do not make copies.
265
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises, please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on daily bases. We call our lessons the "living lessons". Please let us keep our lessons alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
This lesson is copyright (C) 1998-2003 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only