You are on page 1of 266

1

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

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.
2

ASP PROGRAMMERS GUIDE LESSON 1

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.

VBSCRIPT LANGUAGE FUNDAMENTALS

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.

Data Type example


string "hello there"
integer 5
decimal 10.5
numbers 1234
dates 10/15/2002

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.

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.
3

The following example declares a numeric constant and a string constant. Notice strings are
enclosed by double quotes " "

Const Max = 10 Const Name = "Ed"

Keyword Label Value Keyword Label Value

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.

Max 10 Name "Ed"

VBScript has constants already predefined for you. The following chart contains some VB script
predefined constants, that you will be using soon.

Empty indicates an unitialized variable


Nothing indicated a variable does not refer to any object
Null indicates a variable contains invalid data
True value of -1
False a value of 0

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

keyword variable name

You may declare many variables at once using the Dim keyword.

Dim name, address, phoneNumber.

Once you declare your variable you can initialize it to a value.

phoneNumber = "967-1111";

Later you can give your variable a different value.

phoneNumber = "765-8756"

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.
4

A variable or constant value can be assigned to another variable.

Dim x, y
y = Max
x=y

If Max is 10, what is the value of y? What is the value of x?

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

directive at the top of your VBScript program.

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.

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.
5

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

object name dot operator method name

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.

our first VB Script program

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.

<!-- vartest.html -->


<html>
<head>
<title>My first VB Script program</title>
</head>
<body>
<script language="VBScript">
Dim name
name = "hello" ' assign "hello" to variable name name
Document.Write name
</script>
</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.
6

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.

Document.Write name & "<br>"

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 )

Document.Write name & _


"<br>"

ASP LESSON 1 EXERCISE 1

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

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.
7

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.

The syntax for the Input Box function is a little overwhelming.

InputBox (prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])

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:

Constant Value Description


vbCr Chr(13) Carriage return
Chr(13) &
vbCrLf Carriage return–linefeed combination
Chr(10)
vbFormFeed Chr(12) Form feed; not useful in Microsoft Windows
vbLf Chr(10) Line feed
Chr(13) &
Platform-specific newline character; whatever is appropriate for
vbNewLine Chr(10) or
the platform
Chr(10)
vbNullChar Chr(0) Character having the value 0
String having Not the same as a zero-length string (""); used for calling
vbNullString
value 0 external procedures
vbTab Chr(9) Horizontal tab
vbVerticalTab Chr(11) Vertical tab; not useful in Microsoft Windows

Using the Input Box

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

name = InputBox("What is your 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>

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.
9

Here's the input box Here's the VBScript output:

ASP LESSON 1 EXERCISE 2

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.

A Message Box function has the following syntax:

MsgBox(prompt[, buttons] [, title] [, helpfile, context])

Again the optional supplied argument values are in square brackets[ ]. We just use prompt and
title.

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.
10

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 buttons argument settings are:

Constant Value Description


vbOKOnly 0 Display OK button only.
vbOKCancel 1 Display OK and Cancel buttons.
vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.
vbYesNoCancel 3 Display Yes, No, and Cancel buttons.
vbYesNo 4 Display Yes and No buttons.
vbRetryCancel 5 Display Retry and Cancel buttons.
vbCritical 16 Display Critical Message icon.
vbQuestion 32 Display Warning Query icon.
vbExclamation 48 Display Warning Message icon.
vbInformation 64 Display Information Message icon.
vbDefaultButton1 0 First button is default.
vbDefaultButton2 256 Second button is default.
vbDefaultButton3 512 Third button is default.
vbDefaultButton4 768 Fourth button is default.
Application modal; the user must respond to the message
vbApplicationModal 0
box before continuing work in the current application.
System modal; all applications are suspended until the user
vbSystemModal 4096
responds to the message box.
vbMsgBoxHelpButton 16384 Adds Help button to the message box
Specifies the message box window as the foreground
VbMsgBoxSetForeground 65536
window
vbMsgBoxRight 524288 Text is right aligned
Specifies text should appear as right-to-left reading on
vbMsgBoxRtlReading 1048576
Hebrew and Arabic systems

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.
11

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.

Here are the Return Values from the MsgBox

Constant Value Description


vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No

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

Here's our example program using a MsgBox

<html>
<head>
<title>Msg Box Test</title>
<script language="VBScript">
name = MsgBox("Your name is: Tom")
</script>
</head>
<body>
</body>
</html>

ASP LESSON1 EXERCISE 3

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

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.
12

ARRAYS

Arrays represent many variables all accessed by a common name.

variable variable variable variable variable

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

array name index value

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.

ASP LESSON 1 EXERCISE 4

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)

rows variable variable variable


variable variable variable
rows columns

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.
13

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

ASP LESSON 1 EXERCISE 5

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.

functions to check a variable for its data type

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

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.
14

Example using:

A varname represents a variable name where an expression is any value represented by a


constant or variable. We can use the Document.Write method to print out the results of our test.
True
Document.write ( IsArray(a) )

The output on the screen would be True.

The VarType function returns a numeric value identifying what the type of data a variable
represents.

VarType(varname)

The varname argument can be any variable.

Example using:

Dim x
x=5
Document.write ( VarType (x) )

The output on the screen would be 2. 2

(2 is the type for integer see following chart:)

subtypes returned by VarType function:


value subtype
0 empty (unitialized)
1 null (no valid data)
2 integer
3 long integer
4 single precision floating point number
5 double precision floating point number
6 currency
7 date
8 string
9 automation object
10 error
11 boolean
12 variant
13 non automated object
17 byte
8192+type array
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.
15

The TypeName function returns a string describing what data type a variable represents.

TypeName(varname)

The required varname argument can be any variable.


Example using:

Dim x
x=5
Document.write ( TypeName (x) )

Integer
The output on the screen would be "Integer".

(see the following chart for all return string types)

The TypeName function has the following return values:


Value Description
Byte Byte value
Integer Integer value
Long Long integer value
Single Single-precision floating-point value
Double Double-precision floating-point value
Currency Currency value
Decimal Decimal value
Date Date or time value
String Character string value
Boolean Boolean value; True or False
Empty Unitialized
Null No valid data
<object type> Actual type name of an object
Object Generic object
Unknown Unknown object type
Nothing Object variable that doesn't yet refer to an object instance
Error Error

ASP LESSON 1 EXERCISE 6

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

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.
16

FUNCTIONS TO DO OPERATIONS ON ARRAYS:

Here are some function to do operations on arrays.:

Redim [preserve] array_name(subscripts) used to enlarge or reduce an array


preserve save existing data when array is resized
varname name of array to resize
subscripts size you want to change only the last dimension can be changed
Redim preserve a(10)

Erase array_name clears the arrays memory


Erase a

LBound arrayname[.dimension]) returns the lower 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 = LBound(1) ' x is 0
x = LBound(2) ' x is 0

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

ASP LESSON 1 EXERCISE 7

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

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.
17

ASP PROGRAMMERS GUIDE LESSON 2

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

assignment Evaluate expression and assign to variable


operator on left-hand side of assignment 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.
18

ARITHMETIC OPERATORS
11 12 1 (13)

Arithmetic operators are used to do arithmetic


operations on variables. You are already familiar with
arithmetic operators like addition and subtraction etc. 9 3

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)

Unary Operator (-)

This operator negates a variables value. This means if the variable was positive it is now negative

x = - x ' change sign of x

Unary Operator (+)

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

x = + x ' does not change sign of x

ASP LESSON 2 EXERCISE 1

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

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.
19

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 )

( expression1 comparsion_operator expression2 ) Testing values

( x = 5 )

The following table lists all the comparison operators with examples using x and y:

Dim x,y
x=5
y = 10

operator description example result


= equal x =5 true
<> not equal x != 5 false
=> greater than x>y false
>= greater than or equal to x >= y true
< less than y< 5 false
<= less than or equal to x <= y true

You can write out the result of a comparison operator

Document.Write (y < 5)

It will print True or False on the web browser screen.

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.

(condition 1) logical_operator (condition 2)

(x = 5) And ( y = 5) AND (Both)

(x = 5 ) Or (y = 5) OR (Either)

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.
20

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.

operator operation using result


AND both operands are true x =5 And y = 10 True
OR either operands are true x != 5 Or y = 10 False
NOT opposite Not (x > y) False

ASP LESSON 2 EXERCISE 2

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

OTHER LOGICAL OPERATORS

operator operation using result


XOR both operands must be different to be x=5 Xor y=10 False
True but same to be False
EQV both operands must be same to be True x=5 Eqv y=10 True
but different to be False
IMP both operands must be same to be True x=5 Imp y=10 False
If expression 1 is true and expression 2 is
false then the result is False
If expression 1 is false and expression 2 is
true then the result is True

ASP LESSON 2 EXERCISE 3

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.

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.
21

Precedence table:

symbol arithmetic operators level associativity


^ Exponentation 1 left to right
- Negation 2 left to right
*/ Multiplication and Division 3 left to right
\ Integer Division 4 left to right
Mod Modulo arithmetic 5 left to right
+ - () Addition and Subtraction 6 left to right
& string concatenation 7 left to right
= Equality 8 left to right
<> InEquality 8 left to right
< Less than 8 left to right
> Greater than 8 left to right
<= Less than or equal 8 left to right
>= Greater than or equal 8 left to right
Not not 9 left to write
And and 9 left to right
Or or 9 left to right
Xor exclusive or 9 left to right
Eqv equivalence 9 left to right
Imp implication 9 left to right

Examples forcing precedence and using precedence are as follows:

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

What is the value of x ?

x = (a+b) * (c + d) 'Which operations are done first ? a + b then c + d then

What is the value of x ?

ASP LESSON 2 EXERCISE 4

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

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.
22

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

definition one statement more than one


T
statement
If condition Then If x=0 Then y = x If x=0 Then If x = 0 then
y=x
true statement x=x+1
y=x
End If
F

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.
23

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

NESTED IF-ELSE STATEMENTS

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

true statement(s) If x =y then


If (condition) Then y=2 If
true statement Else
else y = x+1 Else
false statement(s) End if
end if Else
else y=x
false statement(s) End If Else
end if

T F
If x=2 then

y=x
T F
If x=y then

y=2 y = x+1

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.
24

ASP LESSON 2 EXERCISE 5

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

ASP LESSON 2 EXERCISE 6

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

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.
25

SELECT CASE STATEMENT

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

Select Case varName Select Case x

Case value 1: Case 0:


statement(s) Document.Write(“ first item is 0”)

Case value 2: Case 1,y:


statement(s) Document.Write(“ got items 1 or 2”)

Case value N: Case Else


statement(s) Document.Write(" I do not know”)

Case Else: End Select


statement(s)

End Select

The _ underscore character is used to join many case values

Case C,Y: _
Case 4,x:

ASP LESSON 2 EXERCISE 7

Convert the If ElseIf statement of previous exercise to a Select Case statement. Call your file
ASPL2Ex7.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.
26

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.

While(condition) const num = 10 F


statement(s) Dim i
Wend i < 10
i=0
' loop while i is less than num T
While(i < num)

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.

Do While(condition) const num = 10 F


statement(s) Dim i
Loop i < 10
i=0
' loop while i is less than num T
Do While(i < num)

i=i+1 i=i+1
Loop
Document.Write("I got:"& i &" items")

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.
27

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.

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.
28

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++

ASP LESSON 2 EXERCISE 8

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 loop variable = startvalue to endvalue step n


statement(s) i = 0; Initialize
next Index Counter

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

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.
29

Loop variables increment by 1. you van change this by using the step keyword

For i=0 To 10 Step 2

x=x+i
y=x

Next

EXIT FOR LOOP


F
The Exit for statement lets you get out of a for loop.
i < 10
' loop till exit
Dim i T
for i=0 to 10

document.write(i & " " ) if i=5 then exit for


if(i=5)then exit for 'exit for loop
i=i+1
next
i++
0 1 2 3 4 5

ASP Lesson 2 Exercise 9

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

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.
30

ASP PROGRAMMERS GUIDE LESSON 3

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.

math function description


Atn(number) Returns a Double specifying the arctangent of a number. The required number
argument is a Double or any valid numeric expression that expresses an angle in
radians.
Cos(number) Returns a Double specifying the cosine of an angle. The required number
argument is a Double or any valid numeric expression that expresses an angle in
radians.
Exp(number) Returns a Double specifying e (the base of natural logarithms) raised to a
power.
Int(number) Returns the integer portion of a number.
Fix(number) Returns the integer portion of a number.
Log(number) Returns a Double specifying the natural logarithm of a number.
Rnd[(number)] Returns a Single containing a random number. The Rnd function returns a value
less than 1 but greater than or equal to zero. The value of number determines
how Rnd generates a random number If number is Rnd generates Less than
zero The same number every time, using number as the seed. Greater than zero
The next random number in the sequence. Equal to zero The most recently
generated number. Not supplied The next random number in the sequence.
Sgn(number) Returns a Variant (Integer) indicating the sign of a number. If number is
Greater than zero Sgn returns 1, Equal to zero returns 0, Less than zero returns
-1
Sin(number) Returns a Double specifying the sine of an angle. The required number
argument is a Double or any valid numeric expression that expresses an angle in
radians.
Sqr(number) Returns a Double specifying the square root of a number
Tan(number) Returns a Double specifying the tangent of an angle. The required number
argument is a Double or any valid numeric expression that expresses an angle in
radians.

ASP LESSON 3 Exercise 1

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

NUMERIC BUILT IN FUNCTIONS

Numeric functions manipulate numbers.

truncates a decimal number

int(1.5) ' returns 1

fix(-1.5) ' returns -2 return lowest value

round a decimal number

round(65434.876554) ' returns 65435

round a decimal number to specified digits

round (65434.876554, 5) ' returns 65434.87655

assign hexadecimal number and octal numbers

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.

Dim num as Integer

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.

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.
32

The following chart shows the numbers 0 to 15 represented by bases binary, octal, decimal and
hexadecimal.

binary octal decimal hexadecimal binary octal decimal hexadecimal


(base 2) (base 8) (base 10) (base 16) (base 2) (base 8) (base 10) (base 16)
0000 0 0 0 1000 10 8 8
0001 1 1 1 1001 11 9 9
0010 2 2 2 1010 12 10 A
0011 3 3 3 1011 13 11 B
0100 4 4 4 1100 14 12 C
0101 5 5 5 1101 15 13 D
0110 6 6 6 1110 16 14 E
0111 7 7 7 1111 17 15 F

Why do we uses letters A to F for hexadecimal numbers?

converting from binary to octal numbers

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

convert binary: 0111001010110110 to octal

converting from binary to hexadecimal numbers

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

convert binary: 0111001010110110 to hexadecimal

converting from octal to binary numbers

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

convert octal: 71266 to binary

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.
33

converting from hexadecimal to binary numbers

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

convert hexadecimal: 72B6 to binary

representing signed numbers

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

sign bit is 1 negative number

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:

-2**(N-1) to 2**(N-1)-1 out range is -2 ** 3 to 2 **3 -1 = -8 to 7

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

ASP LESSON 3 EXERCISE 2

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

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.
34

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"

Joining strings together

You should already know how to join strings together using the '&' catenation operator:

Dim str1 as string "Hello There"


str1= "Hello"
The result is:
str1 = str1 & " There"

Remember to put a space before and after the & operator. You can also use the "+" operator
for joining strings.

str1 = str1 + " There"

getting parts of a string

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

Function Description using result


Left(string, length) extract from the beginning left(str1,5) "Hello"
Mid(string, start, length,) extract from the middle mid(str1,6,1) "T"
Right(string, length) extract from the end right(str1,5) "There"

note:

(1) The Mid function is good for extracting single characters from a string.
(2) String indexes start at zero

Length of a string

The len (string) function returns the length of a string.

len(str1) would be 13

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.
35

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.

Dim str1 as string


str1 = " 1234 "

function using result


LTrim$(string) LTrim$(str1) "1234 "
RTrim$(string) Rtrim$(str1) " 1234"
Trim$(string) Trim(str1) "1234"

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)

ASP LESSON 3 EXERCISE 3

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

GETTING NUMERIC VALUES FROM CHARACTERS

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

Chr$(65) would return the string "A"

GENERATING REPEATED CHARACTERS

The Space$(num) function generates a specified number of spaces

Space$(6) would produce " "

The String(num ,string char) function repeats the specified characters a specified number of
times.

Space(6,"*") would generate "******"

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.
36

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)

StrComp(string1, string2[, compare])

The StrComp function has these named arguments:

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}

The compare argument settings are:

Constant Value Description


Performs a comparison using the setting of the Option Compare
vbUseCompareOption -1
statement. Option Compare {Binary | Text | Database}
vbBinaryCompare 0 Performs a binary comparison. (case sensitive) (exact)
vbTextCompare 1 Performs a textual comparison. (case insensitive) (letters)
Microsoft Access only. Performs a comparison based on
vbDatabaseCompare 2
information in your database.

The StrComp function return values are:

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

Here is an example using StrComp:

Dim str1 as String


Dim str2 as String
Str1 = "hello"
Str2 = "HELLO"

If you specify case insensitive ( vbTextCompare) meaning upper case is same as lower case

If StrComp(str1,str2, vbTextCompare) <>0 Then


Document.Write "str1 not equal to str2" str1 equal to str2"
Else
Document.Write "str1 is equal to str2"
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.
37

If you specify case sensitive (vbBinaryCompare) upper case is different from lower case

If StrComp(str1,str2, vbBinaryCompare) <>0 Then str1 is not equal to str2"


Document.Write "str1 not equal to str2"
Else
Document.Write "str1 is equal to str2"
End If

CONVERTING UPPER CASE TO lower CASE

The UCase$(string) converts a string to upper case.

UCase$("hello") would produce "HELLO"

The LCase$(string) converts a string to lower case.

LCase$("HELLO") would produce "hello"

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"

Dim str1 As String


str1 = "hello there"

using description output


StrConv(str1,vbUpperCase) convert string to upper case HELLO THERE
StrConv(str1,vbLowerCase) convert string to lower case hello there
StrConv(str1,vbProperCase) convert string to proper case Hello There
(First letter is a capital)

ASP LESSON 3 EXERCISE 4

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

CONVERT A STRING TO A NUMERIC VALUE

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")

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.
38

If you cannot convert to the conversion type


then you get a Type MisMatch Error.

Here are all conversion functions with examples you can use. These conversion functions can handle
comma's etc.

conversion function description example using


CBool convert to Boolean b = CBool("1")
CByte convert to Byte b = CByte("1")
CDate convert to Date d = CDate("01/24/03")
CDbl convert to Double d = CDbl(1234)
CInt convert to Integer i = CInt(1234)
CLng convert to Long Integer l = CLng(1234)
CSng convert to Single s = CSng(1234)
CStr convert to String s = CStr(1234)

ASP LESSON 3 EXERCISE 5

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

FINDING STRINGS INSIDE STRINGS

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")

The function would return 5.

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"

Instr(7, str1, "the")

Now it will return 18 because we have started at index 7 and has found the word at index 18

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.
39

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

result = "Tom is smart" Like "i*"

The Like operator has these parts:

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.

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.
40

The following table shows the characters allowed in pattern and what they match:

Characters in pattern Matches in string


? Any single character.
* Zero or more characters.
# Any single digit (0–9).
[charlist] Any single character in charlist.
[!charlist] Any single character not in charlist.

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.

Other important rules for pattern matching include the following:

• 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.

• The character sequence [] is considered a zero-length string ("").

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.
41

A good example using the like operator is to test if an email address is valid

Dim str1

str1= "students@cstutoring.com"

If str1 Like "*[@]*[.]*" then


Document.Write "email is valid"
Else
Document.Write "email is not valid"
End If

ASP LESSON3 EXERCISE 6

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.

replace(source, find, replace, [start], [count], [comparemethod])

This is good for replacing strings with double spaces with a single space.

Dim str1 Double space


"double
The result is now
str1 = "double space" space".
Single space
str1 = replace(str1, " ", " ")

The double space has been replaced by a single space.

REVERSING A STRING

You use the StrReverse function to reverse all the letters in a string..

StrReverse(string) as String

Here is an example reversing the string "Tomorrow is Yesterday"

Dim str1

str1 = StrReverse("Tomorrow is Yesterday")

The reversed string would be:


"yadretseY si worromoT"

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.
42

Some words cannot be reversed like "radar" and are known as a palindrome.

Dim str1

str1 = StrReverse("radar")

The reversed string would be still: "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

EXTRACTING WORDS FROM A STRING

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.

It is a cloudy day it is a cloudy day

delimiters tokens
(spaces) (individual words)

The split function returns a zero-based, one-dimensional array containing a specified number of
substrings.

Split(expression[, delimiter[, count[, compare]]])

Split(str1, " ")

The Split function has these parts:


Part Description
Required. String expression containing substrings and delimiters. If expression is a
expression zero-length string(""), Split returns an empty array, that is, an array with no
elements and no data.
Optional. String character used to identify substring limits. If omitted, the space
delimiter character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a
single-element array containing the entire expression string is returned.
Optional. Number of substrings to be returned; –1 indicates that all substrings are
count
returned.
Optional. Numeric value indicating the kind of comparison to use when evaluating
compare
substrings. See Settings section for values.
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.
43

The compare argument can have the following values:


Constant Value Description
Performs a comparison using the setting of the Option
vbUseCompareOption –1
Compare statement.
vbBinaryCompare 0 Performs a binary comparison.
vbTextCompare 1 Performs a textual comparison.
Microsoft Access only. Performs a comparison based on
vbDatabaseCompare 2
information in your database.

Here is an example using split function we have a string "It is cold today" where a space is the
delimiter.

Dim str1 as String Here is the output:


Dim words() As String

str1 = "It is cold today" It


words = Split(str1, " ") is
cold
For Each word In words today
Document.Write word
Next

REBUILDING STRINGS

The join function receives an array of strings and a delimiter like a space and rebuilds the original
string.

join(string array, delimiter)

We can take the array of words and space delimiter used from the split example and rebuild our
original string

str1 = Join(words, " ")


It is cold today
The output would be:

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.

Filter(InputStrings, Value[, Include[, Compare]])

Filter(words, "i") 'we use words from previous example

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.
44

The Filter function has these parts:

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.

The Compare argument can have the following values:

Constant Value Description


Performs a comparison using the setting of the Option
vbUseCompareOption –1
Compare statement.
vbBinaryCompare 0 Performs a binary comparison.
vbTextCompare 1 Performs a textual comparison.
Microsoft Access only. Performs a comparison based on
vbDatabaseCompare 2
information in your database.

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

We can search for all words with the letter i.


is
words = Filter(words, "i")
The output is:
For Each word In words
Document.Write word
Next

In the next example we set parameter included to True and parameter compare to
vbTextCompare

words = Filter(words, "i", True, vbTextCompare)

For Each word In words 'we use words from previous example
Document.Write word
It
Next The output would be: is
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.
45

ASP LESSON 3 EXERCISE 8

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

SUMMARY OF STRING FUNCTIONS

string function description example using


Left$(string, length) extract from the beginning left$(str1,5)
Mid$(string, length) extract from the middle mid$(str1,6,1)
Right$(string, length) extract from the end right$(str1,5)
len(string) returns length of string len(str1)
LTrim$(string) remove blanks from left side LTrim(str1)
RTrim$(string) remove blanks from right side RTrim$(str1)
Trim$(string) remove blanks from both sides Trim(str1)
Asc(string) return numeric value of first string character Asc("A")
Chr$(integer) convert a number into a string character Chr$(65)
space$(num) function generates a specified number of spaces space$(6)
String(num ,string char) repeats the specified characters number of times String(6 ,"*")

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")

StrConv(string,vbUpperCase) convert string upper case StrConv("hello",vbUpperCase)


StrConv(string,vbLowerCase) convert string lower case StrConv("HELLO",vbUpperCase)
StrConv(string,vbProperCase) convert string lower case StrConv("the end",vbProperCase)

CBool convert string to Boolean CBool("True")


CByte convert string to Byte CByte("34")
CDate convert string to Date CDate("01/02/2002")
CDbl convert string to Double CDbl("45.678")
CInt convert string to Integer CInt("3454")
CLng convert string to Long Integer CLng("65544323")
CSng convert string to Single CSng("54.654")
CStr convert number to String CStr(43);
InStr(first, second); searches for a substring in another string Instr(str1, "the")
and returns the location of the first character
in substring if found
InStr(start,first,second) searches for a substring in another string Instr(7, str1, "the")
and returns the location of the first character
in substring if found starting at a specified
index
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.
46

InStrRev(source,search, search for a substring InStrRev(str1, "the")


[start], [compareMethod]) backward starting from the end
of the string.
string Like pattern str1 Like "*[@]*[.]*"
Replace(source, find, replace, find and replace a string str1 = Replace(str1, " ", " ")
[start], [count],
[comparemethod])
StrReverse(string) reverse a string str1 = StrReverse("radar")
Split(source, [delimiter], extract words from a string words = Split(str1, " ")
[limit],[compare method])
join(string array, delimiter) rebuilds a strings from words str1 = Join(words, " ")
stored in an array
Filter(source, search, words = Filter(words, "i")
[include], [compare method])

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.
47

ASP PROGRAMMERS GUIDE LESSON 4

File: aspGuideL4.doc
Date Started: Mar 20, 2002
Last Update: June 15, 2003
ISBN: 0-9730824-3-7
Version: 0.0

FORMATTING NUMBERS, DATE, TIME AND UTILITY OBJECTS

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.

Function Description Example


FormatNumber returns a string formatted as a decimal number 10.674
FormatPercent returns a string formatted as a percentage 6.25%
Format Currency returns a string formatted as a currency value $1000.00

FORMAT NUMBER

The FormatNumber function Returns an expression formatted as a number. It has the following
syntax:
FormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit
[,UseParensForNegativeNumbers [,GroupDigits]]]])

The FormatNumber function syntax has these parts:


Part Description
Expression Required. Expression to be formatted.
Optional. Numeric value indicating how many places to the right of the
NumDigitsAfterDecimal decimal are displayed. Default value is -1, which indicates that the
computer's regional settings are used.
Optional. Tristate constant that indicates whether or not a leading zero
IncludeLeadingDigit
is displayed for fractional values. See Settings section for values.
UseParensForNegative Optional. Tristate constant that indicates whether or not to place
Numbers negative values within parentheses. See Settings section for values.
Optional. Tristate constant that indicates whether or not numbers are
GroupDigits grouped using the group delimiter specified in the control panel. See
Settings section for values.

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.
48

Tri-state constants have 3 values. The IncludeLeadingDigit,


UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant Value Description


TristateTrue -1 True
TristateFalse 0 False
TristateUseDefault -2 Use the setting from the computer's regional settings.

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]]]])

The FormatPercent function syntax has these parts:


Part Description
Expression Required. Expression to be formatted.
Optional. Numeric value indicating how many places to the right
NumDigitsAfterDecimal of the decimal are displayed. Default value is -1, which indicates
that the computer's regional settings are used.
Optional. Tristate constant that indicates whether or not a
IncludeLeadingDigit leading zero is displayed for fractional values. See Settings
section for values.
Optional. Tristate constant that indicates whether or not to
UseParensForNegative
place negative values within parentheses. See Settings section
Numbers
for values.
Optional. Tristate constant that indicates whether or not
GroupDigits numbers are grouped using the group delimiter specified in the
control panel. See Settings section for values.

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.
49

Tri-state constants have 3 values. The IncludeLeadingDigit,


UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:
Constant Value Description
TristateTrue -1 True
TristateFalse 0 False
Use the setting from the computer's regional
TristateUseDefault -2
settings.

When one or more optional arguments are omitted, the values for the omitted arguments are
provided by the computer's regional settings.

The following example uses the FormatPercent function to format an expression as a


percent:

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]]]])

The FormatCurrency function syntax has these parts:


Part Description
Expression Required. Expression to be formatted.
Optional. Numeric value indicating how many places to the right of
NumDigitsAfterDecimal the decimal are displayed. Default value is -1, which indicates that
the computer's regional settings are used.
Optional. Tristate constant that indicates whether or not a leading
IncludeLeadingDigit
zero is displayed for fractional values. See Settings section for values.
UseParensForNegative Optional. Tristate constant that indicates whether or not to place
Numbers negative values within parentheses. See Settings section for values.
Optional. Tristate constant that indicates whether or not numbers
GroupDigits are grouped using the group delimiter specified in the computer's
regional settings. See Settings section for values.

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.
50

Tri-state constants have 3 values. The IncludeLeadingDigit,


UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:
Constant Value Description
TristateTrue -1 True
TristateFalse 0 False
TristateUseDefault -2 Use the setting from the computer's regional settings.

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)

ASP LESSON 4 EXERCISE 1

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.

DATE AND TIME OBJECTS

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>

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.
51

Making Date Objects

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.

DateSerial(year, month, day)

TimeSerial(hour,minutes,second)

Here is a small program using the DateSerial and TimeSerial functions:

<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>

ASP LESSON 4 EXERCISE 2

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.

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.
52

EXTRACTING DATE AND TIME

The following functions let you extract parts of a date and time's

function description using


DateValue(Date) returns the date portion of a date object Document.Write
DateValue(myDate)
TimeValue(Date) returns the time portion of a date object Document.Write
TimeValue(myDate)
Day(Date) returns the month day (1 to 31) Document.Write
Day(myDate)
Month(Date) return the month (1 to 12) Document.Write
Month(myDate)
Year(Date) returns the year (2002) Document.Write
Year(myDate)
Hour(Date) returns the hour (0 to 23) Document.Write
Hour(myDate)
Minute(Date) returns the minute (0 to 59) Document.Write
Minute(myDate)
Second(Date) returns the second (0 to 59) Document.Write
Second(myDate)
WeekDay(Date) returns the week day (1 to 7) Document.Write
Weekday(Date)

Date myDate = #01/03/1995 5:23:43 PM# 01/03/95 5:23:43 AM


Document.Write DateValue(myDate) 01/03/95
Document.Write TimeValue(myDate) 5:23:43 AM

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(interval, date[,firstdayofweek[, firstweekofyear]])

DatePart("yyyy", Now)

The DatePart function has these named arguments:

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.

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.
53

The interval argument has these settings:


Setting Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second

The firstdayofweek argument has these settings:

Constant Value Description


vbUseSystem 0 Use the NLP API setting.
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

The firstweekofyear argument has these settings:

Constant Value Description


vbUseSystem 0 Use the NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
Start with the first week that has at least four days in
vbFirstFourDays 2
the new year.
vbFirstFullWeek 3 Start with first full week of the year.

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

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.
54

Examples using the DatePart function

<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.

The DataAdd function is used to add two dates:

DateAdd(interval, number, date)

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

Dim mydate 12/27/4004 12:24:33 PM

mydate = DateAdd("yyyy", DatePart("yyyy", Now), Now)

The easiest way to add two date objects is to add them !


12/27/4004 12:24:33 PM
mydate = Now + Now

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)

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.
55

Subtracting dates.

The DateDiff function is used to find the difference between two dates:

DateDiff(interval, startdate, enddate)

DateDiff("YYYY", Now, Date2)

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

Here are some examples using DateAdd and DateDiff:

Dim Date2 6/9/07 2:45:12 PM


DateAdd("yyyy", 5, Now)
5
Print Date2
Print DateDiff("YYYY", Now, Date2)

ASP LESSON 4 EXERCISE 3

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 example note


General Date 6/9/07 2:45:12 PM
Long Date September 10, 1997
Medium Date 10-Sept-97
Short Date 9/10/97 month/day/year
Long Time 10:45:24
Medium Time 10:45 AM
Short Time 10:45 24 hour format
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.
56

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]]])

Format(Now, "mm/dd/yy h:m:s")

The Format function has these parts:

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:

Constant Value Description


vbUseSystem 0 Use NLS API setting.
VbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

The firstweekofyear argument specifies which day is the first of the year and has these settings:

Constant Value Description


vbUseSystem 0 Use NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
vbFirstFourDays 2 Start with the first week that has at least four days in the year.
vbFirstFullWeek 3 Start with the first full week of the year.

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

special character description example output


mmm abbreviated month Aug
mmmm complete month August
d 1 or 2 digit day of month 9
dd 2 digit day of month 09
ddd abbreviated weekday Mon
dddd complete week day Monday
y 1 or 2 digit year 2
yy 2 digit year 02
yyyy 4 digit year 2002
ww week in the year 23
q quarter of year
hh always 2 hour digits
mm always 2 minute digits
ss always 2 second digits
hh:mm:ss 02:23:06
h 1 or 2 hour digit
m 1 or 2 minute digits
s 1 or 2 second digits
h:m:s 2:23:6
AMPM before or after noon 2:23:6 PM

Examples using Format function for dates and times

Document.Write Format (Now, "mm/dd/yy h:m:s")


Document.Write Format (Now, "mm/dd/yyyy hh:mm:ss")
Document.Write Format (Now, "mmm/ddd/yyyy hh:mm:ss")
Document.Write Format (Now, "mmm/dddd/yyyy hh:mm:ss")
Document.Write Format (Now, "dddd mmmm d, yyyy hh:mm:ss AMPM")
Document.Write Format (Now, "dddd mmmm dd, yyyy hh:mm:ss AMPM")

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

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.
58

Just Formatting Date and Time

The FormatDateTime function is just used for formatting data and time.

FormatDateTime(Date[,NamedFormat])

FormatDateTime(Now, vbGeneralDate)

The FormatDateTime function has these parts:

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.

The NamedFormat argument has the following settings:

Constant Value Description


Display a date and/or time. If there is a date part, display it as a
vbGeneralDate 0 short date. If there is a time part, display it as a long time. If
present, both parts are displayed.
Display a date using the long date format specified in your
vbLongDate 1
computer's regional settings.
Display a date using the short date format specified in your
vbShortDate 2
computer's regional settings.
Display a time using the time format specified in your computer's
vbLongTime 3
regional settings.
vbShortTime 4 Display a time using the 24-hour format (hh:mm).

Examples using the FormatDateTime Function

Document.Write FormatDateTime(Now, vbGeneralDate) 6/9/02 4:07:36 PM


Document.Write FormatDateTime(Now, vbLongDate) Sunday, June 09, 2002
Document.Write FormatDateTime(Now, vbLongTime) 4:07:36 PM
Document.Write FormatDateTime(Now, vbShortDate) 6/9/02
Document.Write FormatDateTime(Now, vbShortTime) 16:07

Here are two other easy to use functions:

MonthName returns a string indicating the specified month.

MonthName(month[, abbreviate])

MonthName(1)

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.
59

The MonthName function has these parts:

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 returns a string indicating the specified day of the week

WeekDayName(weekday, abbreviate, firstdayofweek)

WeekdayName(1)

The WeekDayName function has these parts:

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.

The firstdayofweek argument can have the following values:

Constant Value Description


vbUseSystem 0 Use National Language Support (NLS) API setting.
vbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday

Examples using the MonthName and WeekdayName functions:

Document.Write MonthName(1) January


Document.Write MonthName(1, True) Jan
Document.Write WeekdayName(1) Sunday
Document.Write WeekdayName(1, True) Sun

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.
60

ASP LESSON 4 EXERCISE 4

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.

num = rnd * 100 ' generate a random number between 0 and 99

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

ASP LESSON 4 EXERCISE 5

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

ASP LESSON 4 EXERCISE 6

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

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.
61

ASP PROGRAMMERS GUIDE LESSON 5

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 engine Web server Request asp page


Web browswer
executes asp
page.
Respond by
sending back
generated html

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.

file name open file


File Object file mode read File Functions
file status write
close

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.

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.
62

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

source of information Explanation


Server variables the server variables obtain information about the web browser's ISP when
connection is made
Form DATA data from forms are sent to the web server
query string the URL of the requested page provides additional information
Cookies information store on the web browsers are also sent to the web server
Client Certificates user security certificate SSL

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")

where msg is the name parameter in the query string

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>")

The web browser would receive:

<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.

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.
63

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.

web server web browser


Request request ASP page
object html
ASP page
Page
executing
ion web
server

Response send back generated page html


Object page

USING IIS/PWS 4.0 WEB SERVER

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.

Running the Web Server

After installation just click on the Web server icon and the following screen appears.

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.
64

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.

Writing our first ASP page

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.

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.
65

Running our first ASP page

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

(The %20 means space this is xxx-url-encoding)

Then press the Enter key. You should have something like this :

How does it all work ?

The URL request the hello.ASP page from your web server.

http://localhost/ASPLesson3/hello.asp?msg=hello%20world

The URL has a query string attached to the end of it.


%20 means space
?msg=hello%20world

To get the query string information we use the QueryString method of the Request object.

Request.QueryString("msg")

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.
66

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.

Type in the above program then run on


your web browser. Type in the message
Hello World in the text box. As soon as
you press the enter key the hello.asp
program will be called.

You should now have something like this in your location bar.

http://localhost/ASPLesson5/hello.ASP?msg=hello+world

the "+" will get converted to a space

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.
67

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.

Variable Name Definition


ALL_HTTP all HTTP headers beginning with HTTP as follows:

HTTP_ACCEPT type of content that the users browser will accept


HTTP_ACCEPT_LANGUAGE users language
HTTP_CONNECTION type of connection
HTTP_HOST name of machine where ASP page is hosted
HTTP_USER_AGENT name of users browser
HTTP_COOKIE currently used cookie
HTTP_ACCEPT_ENCODING specified method by which data being sent can be compressed

AUTH_TYPE type of authentication used. Usually "Basic"


AUTH_PASSWORD value entered in clients authentication dialog box
(Basic authentication"
CONTENT_LENGTH number of bytes ASP script will receive from client
CONTENT_TYPE content type of information supplied in body of POST request
DOCUMENT_NAME current file name
DOCUMENT_URI virtual path to current document
DATE_GMT current date in GMT (Greenwich Mean Time)
DATE_LOCAL current date in local time zone
GATEWAY_INTERFACE CGI version used by Web server
LAST_MODIFIED date that the current document was last modified
PATH_INFO additional path information before query string
PATH_TRANSLATED PATH_INFO virtual path expanded into a directory specification
QUERY_STRING information that follows the ? mark in an URL
QUERY_STRING_UNESCAPED version of query sting that is not URL encodes
REMOTE_ADDR IP address of the client that sent the web page request
REMOTE_HOST host name of the client that sent the web page request
REMOTE_USER user name supplied by client and authenticated by server
REQUEST_METHOD http request method GET or POST
SCRIPT_NAME name of script program being executed
SERVER_NAME server host name or IP Address
SERVER_PORT the TCP/IP port which the request was received (usually port 80)
SERVER_PORT_SECURE if the request is being handled on a secure port then value is 1
SERVER_PROTOCOL name and version of retrieval protocol usually HTTP/1.0
SERVER_SOFTWARE name and version of the web server
URL base portion of the URL

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.
68

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

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.
72

WORKING WITH FORMS

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.

Label display a message


TextBox enter a one line message
Checkbox use a check to select
RadioButton choose one of many choices
ListBox choose one on more choices from a list
Combobox select one of many choices from a list
TextArea enter a message on many lines

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

ASP send data to web server


Code form

generated web page

send generated web page form

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.

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.
73

Receiving data from Form controls

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.

<FORM METHOD = "POST" ACTION ="message.ASP">

To receive a message using the Post method we use the Form method from the Request object.

<% = Request.Form("message") %>

LABELS

Labels are just used to display a text message.

<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,

ASP LESSON 5 EXERCISE 1

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

Basically we got three types of buttons

• Submit
• Reset
• Push Button

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.
75

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>

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.
76

ASP LESSON 5 EXERCISE 2

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.

<input type=button name="pushbutton" value="Button" ONCLICK="handler()">

We can request another ASP page:

<input type=button name="pushbutton" value="Button"


ONCLICK="VBSCRIPT:Location.href='pushbutton.asp'">

We can make the form submit it contents and to a another page:

<input type=button name="pushbutton" value="Button"


ONCLICK="VBSCRIPT:form1.submit()">

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.

<!-- pushbutton.html -->


<html>
<head>
<title>pushbutton.html</title>
<script language="vbscript">
sub handler()

msgbox "I have been clicked"

end sub
</script>

</head>
<form method=post action="pushbutton.asp" name="form1">

<input type=button name="pushbutton" value="Button"


ONCLICK="VBSCRIPT:Location.href='pushbutton.asp'">
<input type=button name="pushbutton" value="Button"
ONCLICK="VBSCRIPT:form1.submit()">
<input type=button name="pushbutton" value="Button" ONCLICK="handler()">

</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.
77

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>

ASP LESSON 5 EXERCISE 3

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.

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.
78

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>

ASP LESSON 5 EXERCISE 4

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.

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.
79

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>

The selection items are received and displayed separated by commas.

<html>

<head>
<title> Select.asp </title>
</head>

<body>
<% = Request.Form("colors") %>
</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.
80

ASP LESSON 5 EXERCISE 5

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.

USING HIDDEN FIELDS

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>

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.
81

ASP LESSON 5 EXERCISE 6

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.

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.
82

ASP PROGRAMMERS GUIDE LESSON 6

File: ASPGuideL6.doc
Date Started: Mar 20, 2002
Last Update: June 17, 2003
ISBN: 0-9730824-3-7
Version: 0.0

RESPONSE, APPLICATION, SESSION, SERVER OBJECTS, COOKIES AND ERROR HANDLING

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>")

The Web browser would receive


Web Browser
<HTML> Response Generated
<head> Object Web Page
<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.

Response.Write("<form method="post" action="display.ASP">")

Every thing is okay as long as all the double quotes are balanced. Alternatively you may like to use
single quotes.

Response.Write("<form method='post' action='display.ASP'>")

Here is a tricky situation

Response.Write("<table width=50%>")

What has happened here ?

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%/>")

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.
83

ASP LESSON 6 EXERCISE 1

Convert any simple HTML document to a generated page or just make up your own using
Response.Write. Call your ASP script ASPL6Ex1.asp.

REDIRECTING A WEB BROWSER

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")

ASP LESSON 6 EXERCISE 2

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

Here is a script using buffering:

<%
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.

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.
84

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.

To indicate that this Web page should not be cached:

Response.CacheControl = "Private"

To allow this Web page to be cached:

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.

To indicate a page that will always expires:

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#

SPECIFYING CONTENT TYPE

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"

The type of data you are sending is known as Content-Type as follows:

Content-Type description
text/plain text
text/html text and html
application/octet-stream binary code
application/x-www-form-urlencoded name=value pairs

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.
85

ASP LESSON 6 EXERCISE 3

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>

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.
86

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

Here is our counter cookie file entry:

counter
1
localhost/aspLesson4
0
1997670400
29537600
1896753472
29537468
*

modifying the cookie

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

We have just incremented the cookie counter value.

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.
87

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")=""

complete cookie example

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
*

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.
88

ASP LESSON 6 EXERCISE 4

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

You access entries by:

count = Application.Contents("Count")

It should be now quite obvious that this is the same as saying:

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.

for each item in Application.Contents


Response.write item & ": " & Application.Contents(item) & "<br>"
next

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.
89

To remove an item from the collection use the Remove method:

Application.Contents.Remove("Count")

You can remove all items using the RemoveAll method:

Application.Contents.RemoveAll

Accessing the Application object one at a time

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

ASP LESSON 6 EXERCISE 5

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.

Again you supply a key and a corresponding value.

Session("Count") = 1

All other ASP files in your directory will be able to access the value of "Count" from the session
object.

count = Session ("Count")

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.
90

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

You access entries by:

count = Session.Contents("Count")

It should be now quite obvious that this is the same as saying

Session ("Count") = 1

count = Session ("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 collection objects like the Session.Contents object.

for each item in Session.Contents


Response.write item & ": " & Session Contents(item) & "<br>"
next

To remove an item from the collection use the Remove method:

Session Contents.Remove("Count")

You can remove all items using the RemoveAll method:

Session.Contents.RemoveAll

life time of a session object

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

You can use the Abandon method to terminate a session immediately.

Session.Abandon

Once you are finished you this session object you should abandon it.

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.
91

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

ASP LESSON 6 EXERCISE 6

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 CreateObject method is used to instantiate objects.

Set myObject = Server.CreateObject("some object name");

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>")

You can combine the above statement with a Response.Write statement

Response.Write Server.HTMLEncode("<BR>")

This means the screen will actually say <BR> rather than start a new line!

<br>

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.
92

If you look at the page source you will see this:

&lt;br&gt;<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

ASP LESSON 6 EXERCISE 7

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 .

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.
93

GLOBAL ASA FILE

The global.asa file is used for:

• Holding Application event code

• Holding Session Event Code

• Declaring objects with either Session or Application scope

• Referencing type libraries to be used both the application

The global.asa file is automatically supplied for you by the web server for your application.

Application event code

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.

<Script Lanaguage=VBScript RUNAT=Server>

Sub Application_OnStart

End Sub

Sub Application_OnEnd

End Sub

</Script>

Session event code

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.

<Script Lanaguage=VBScript RUNAT=Server>

Sub Session_OnStart

End Sub

Sub Session_OnEnd

End Sub

</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.
94

Declaring Objects

The OBJECT tag can be used to create objects to be used in Application or Session objects.
This is known as scope.

To create a object in Application scope:

<OBJECT Runat=Server Scope=Application ID=conn PROGID="adodb.Connection">


</OBJECT>

To create a object in Session scope:

<OBJECT Runat=Server Scope=Session ID=conn PROGID="adodb.Connection">


</OBJECT>

Application scope means the object will be available to all applications. Session scope means
available to the current session.

Referencing type Libraries

Your application may need to reference other libraries.

<!-- METADATA TYPE="TypeLib" FILE="MyTypes.TLB" -->

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.

error statement description


On Error Resume Next ignore any error and proceed to next line

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

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.
95

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

if err.number <> 0 then


Response.write("<h2> The File server has failed accessing: & _
"&filename&"</h2>")
Response.write( err.description & "<br>")
end if
%>

Clear Method

Clears all property settings of the Err object.

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.

object.Raise number, source, description, helpfile, helpcontext

if y=0 Err.Raise Err.vbObjectError + 513

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.
96

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.

Here is an example using the Raise method:

Dim x
Dim y

x = 10
y=0

if y=0 Err.Raise vbObjectError + 513

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.
97

Raising an error:

executing code

Err.Raise

no
error Error Object code

Resume Next

next code statement

ASP LESSON 6 EXERCISE 8

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.

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.
98

ASP PROGRAMMERS GUIDE LESSON 7

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

Open Opens a connection to a data source


ConnectionString, A String containing connection information.
UserID, Optional String containing a user name
Password, Optional String containing a password
OpenOptions A ConnectOptionEnum value.
Open Opens a cursor (Recordset)
Source, Command object , SQL statement, table, stored procedure call, or file name
ActiveConnection, Optional. a Connection object, or ConnectionString parameters
CursorType, A CursorTypeEnum value that determines the type of cursor
LockType, Optional. A LockTypeEnum determines type of locking (concurrency)
Options evaluate the Source argument

The Connection object has the following Properties:

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.

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.
100

Here are the properties of the Command object

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 SET OBJECT

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:

SELECT * from table employees

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:

SELECT * FROM employee WHERE Name='Tom'

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.

Constant Value Description


adOpenForwardOnly 0 read only the can only go forward
(default)
adOpenKeyset 1 add, modify, delete records, don't show changes made by other
users
adOpenDynamic 2 add, modify, delete records, show changes made by other users
adOpenStatic 3 read only the can go forward, backward and book marking,
book marking lets you mar a particular record to return too
later.

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.
101

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.

Constant Value Description


adLockReadOnly 1 can only read record, cannot change
(default)
adLockPessimistic 2 records are locked when you stare changing them
adLockOptimistic 3 records are only locked when you update them
adLockBatchOptimistic 4 used for batch updates

Warning! The constants are not built into ASP you need to include the adovbs.inc file in your ASP
page to be recognized,

<!-- #include file="adovbs.inc" -->

You can find the adovbs.inc in this directory:

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.

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.
102

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.

The RecordSet object has the following properties:

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

CursorType Indicates the type of cursor used in a Recordset object.


EditMode Indicates the editing status of the current record.
Filter Indicates a filter for data in a Recordset.
LockType Indicates the type of locks placed on records during editing.
MarshalOptions Indicates which records are to be marshaled back to the server.
MaxRecords Indicates the maximum number of records to return from a query.
PageCount Indicates how many pages of data the Recordset object contains.
PageSize Indicates how many records constitute one page in the Recordset.
RecordCount Indicates the current number of records in a Recordset object.
Sort Specifies one or more field names the Recordset is sorted on, and whether
each field is sorted in ascending or descending order.
Source Indicates the source for the data in a Recordset object (Command object, SQL
statement, table name, or stored procedure).
State Describes whether the state of the RecordSet object is open or closed.
adStateClosed (Default) - Indicates that the object is closed.
adStateOpen - the Recordset object is open.
adStateConnecting - the Recordset object is connecting.
adStateExecuting - the Recordset object is executing a command.
adStateFetching - the rows of the Recordset object are being fetched
Status Indicates the status of the current record

FIELDS and FIELD OBJECTS

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.

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.
104

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

CREATING A DATA BASE

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.

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.
105

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.

ASP LESSON 7 EXERCISE 1

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.

WORKING WITH DATA BASES

When working with databases we are always doing 3 things:

(1) reading

(2) updating

(3) adding new records

(1) READING A DATA BASE

Here is the step by step instructions to connect to a data base and print out the contents to a screen

[1] make a connection to the data base using a connection object.

dim cn

set cn= Server.CreateObject("ADODB.Connection")

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.
106

[2] specify connection string

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"

For windows 2000 and XP using Microsoft access 2000 use:

cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=c:\courses\students.mdb"

[3] query data base fill a recordsets with record rows

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

set rs = cn.Execute("SELECT * FROM marks")

[4] display the column names of the record set

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.

for i=0 to rs.Fields.Count-1


Response.Write rs(i).name
next

[5] display record field values

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.

do while not rs.Eof

for i=0 to rs.Fields.Count

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

Set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" _
& "Data Source=c:\courses\asp\asp.mdb"
cn.Open

Dim rs

Set rs = cn.Execute("SELECT * FROM employee")

Dim i

Response.write("<table border=1>")

for i=0 to rs.Fields.Count-1

Response.Write("<th>")
Response.Write rs(i).name
Response.Write("</th>")
next

do while not rs.Eof


response.write("<tr>")

for i=0 to rs.Fields.Count-1


Response.Write("<td>")
Response.Write rs(i)
Response.Write("</td>")
next

Response.Write("</tr>")
rs.MoveNext
loop

cn.Close
%>

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.
108

Here is the output after running the ASP script:

ASP LESSON 7 EXERCISE 2

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

(2) UPDATING A DATA BASE

The next thing we need to do is to update the database with different values. Here are the step by
step instructions:

[1] open a connection to the data base

Dim cn

Set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" _
& "Data Source=c:\courses\asp\asp.mdb"
cn.Open

[2] instantiate a record set object

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")

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.
109

[3] open record set

We open the record set for adOpenKeySet (1) and adLockOptimistic (3)

rs.Open "SELECT * FROM employee WHERE Name='Tom'",cn,1,3

[4] assign new field value to record set

rs("Phone") = "123-4567"

This is the sane thing as saying:

rs.fields("Phone") = "123-4567"

[5] call update method to update data base

rs.Update()

[6] close record set and connection

rs.close()

cn.Close

Here is the complete code to update a database:

<%
Dim cn

Set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" _
& "Data Source=c:\courses\asp\asp.mdb"

cn.Open

Dim rs

Set rs = Server.CreateObject("ADODB.RecordSet")

rs.Open "SELECT * FROM employee WHERE Name='Tom'",cn,1,3

rs("Phone") = "123-4567"

rs.Update()

rs.close()
cn.Close
%>

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.
110

ASP LESSON 7 EXERCISE 3

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

ADDING NEW RECORDS

We use the AddNew methods to add records to an existing data base. Here are the step by step
instructions

[1] open a connection to the data base

Dim cn

Set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" _
& "Data Source=c:\courses\asp\asp.mdb"
cn.Open

[2] instantiate a record set object

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")

[3] open record set

We open the record set for adOpenKeySet (1) and adLockOptimistic (3)

rs.Open "SELECT * FROM employee",cn,1,3

[4] call addnew method

rs.AddNew

[5] assign values to fields in new record

rs("Name") = "Bill"
rs("Address") = "57 Ocean Way"
rs("Phone") = "987-6543"

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.
111

[6] call update method to update data base

rs.Update()

[7] close record set and connection

rs.close()

cn.Close

ASP LESSON 7 EXERCISE 4

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

USING THE COMMAND OBJECT

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:

[1] create a command object

Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")

[2] Assign a SQL statement to the command object

use the commandtext method to assign a SQL statement to the command object.

cmd.CommandText = "SELECT * FROM employee WHERE Name='Tom'"


and the execute method to execute the command and put the results in a record set

[3] Execute the SQL statement

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

Set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" _
& "Data Source=c:\courses\asp\asp.mdb"
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.
112

cn.Open

Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")

cmd.CommandText = "SELECT * FROM employee WHERE Name='Tom'"

cmd.ActiveConnection = cn

Dim rs

Set rs = cmd.Execute

Dim i

Response.Write("<table border=1>")

for i=0 to rs.Fields.Count-1

Response.Write("<th>")
Response.Write rs(i).name
Response.Write("</th>")
next

do while not rs.Eof


Response.Write("<tr>")

for i=0 to rs.Fields.Count-1


Response.Write("<td>")
Response.Write rs(i)
Response.Write("</td>")
next

Response.Write("</tr>")
rs.MoveNext
loop

Response.Write("</table>")

rs.Close()
cn.Close
%>

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.
113

HANDLING ERRORS

The Errors collection stores any errors that may have encounter. There definitely is lots of
opportunity for errors.

• connection not opened

• provider or data source not found

• command or record set object not created properly

• command or record set not executed properly

To handle errors you need to put a

On Error Resume Next

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.

A Error collection consist of error objects having the following properties:

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

Here is our asp program that reports errors:

<%
Dim cn
On Error Resume Next

set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.3.51;" _
& "Data Source=c:\courses\asp\aspX.mdb"
cn.Open

if(cn.errors.count > 0) then


for i=0 to cn.errors.count-1
response.write cn.errors(i).description
next

else
Dim rs
Set rs = cn.Execute("SELECT * FROM marks")
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.
114

ASP LESSON 7 EXERCISE 5

Add error capabilities to your script of previous exercise. Put the error in a read only textbox. Call
your script aspL7Ex5.asp

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.
115

ASP PROGRAMMERS GUIDE LESSON 8

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

What are the steps to build this project?

(1) Define all data base tables

(2) Define all ASP pages

(3) Draw an operations block diagram

(4) Start coding

(5) debug and test

(1) data base tables

What data base tables are we going to need?

(1) Products

(2) Categories

(3) Customers

(4) Orders

(1) Products table

What product fields do we need?

Number product identification number


Name product name
Description description of product
Price price of product
Quantify number of products sold

Just make a simple table.

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:

name description image file price


boats1 smallest boat in the world boats1.gif 29.95
flower1 bright flower flower1.jpg 15.35
ship2 largest ship in the world ship2.jpg 17.89
street main street of San Francisco street.jpg 33.67

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.
117

From the above table it is quite obvious we have some categories:

• boats
• flowers
• Streets

(2) Categories table (optional)

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

Our product table will now have a category field:

item category description image file price


boats1 boat smallest boat in the world boats1.gif 29.95
flower1 flower bright flower flower1.jpg 15.35
ship2 boat largest ship in the world ship2.jpg 17.89
street city main street of San Francisco street.jpg 33.67

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.

(3) Customer table

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

(1) Customer number


(2) Phone number
(3) Email address
(4) Name

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.

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.
118

Here is the Customer table:

customerID Name Address Phone EMail


1 John Smith 42 Universe Avenue 967-1111 js@world.com
2 Bill Smith 20 Nowhere Street 875-6543 bill@internet.com
3 George Smith 16 Maple Syrup Lane 654-7654 gsmith@turbo.net
4 Mary Smith 35 Watch Blvd 212-7654 msmith@turbo.net

(3) Orders table

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.

orderID item customerID payment date


1 flower1 1 cc Jan 4, 2003
2 boat2 2 cc Jan 4, 2003
3 street1 3 cc Jan 5, 2003
4 ship1 2 cc Jan 6, 2003

TABLE RELATION SHIPS

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

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.
119

(2) DEFINE ALL ASP PAGES

What does a customer have to do ?

• view items for sale


• select items to buy
• purchase items
• download bought items or wait for shipment

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.

page file name purpose


home default.asp display items for sale
order order.asp order confirmation
purchase cc.asp pay for order by credit card
thankyou download.asp acknowledge and download order

(1) home page (default.asp)

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.

SELECT * FROM Products where Category='boats'

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"

Here are parts of our home page

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.
120

(2) Order confirmation page (orders.asp)

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.

(3) Credit card processor (ccprocessor.asp)

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

order page credit card processor thankyou page

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

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.
122

(4) Thankyou page (thankyou.asp)

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.

<form action="mailto:js@internet.net?subject=order confirmation&body=data


enctype=text">
<input type="hidden" name="item" value="<%=item%>">
</form>

If they are to download something you supply as download button or a link where they can
download the goods

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.
123

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.

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.
124

ASP PROGRAMMERS GUIDE LESSON 9

File: aspGuideL9.doc
Date Started: Mar 20, 2002
Last Update: June 20, 2003
ISBN: 0-9730824-3-7
Version: 0.0

DICTIONARY, FILE SYSTEM OBJECTS AND MAINTAINING STATE

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.

ASP object purpose


Request receives values from the web browser during a page request
Response send output to the web browser that connected to our page
Server provides access to methods and properties on the server
Session Use to store information for a user. Each user has its own Session object
Application store information to use between pages for the web application
Dictionary store data as key values
Err error handling, collection of Error objects
Error represents an Error
FileSystemObject access to the server file system
Drive represents a disk or network drive
Folder represents a directory that is part of a drive
File represents a file part of a directory
TextStream represents a connection to a text file
ADO Connection represents a physical connection to a data source (database)
ADO Recordset represents a set of records that is the result of executing a SQL Statement
ADO Command hold definitions of database actions like stored procedures or queries to
execute
ADO Error contains descriptive information regarding errors of operation of ADO object
ADO Field represents a column of data in a record
ADO Parameter represents a parameter or argument associated with a command object
ADO Rotator automates rotation of advertising images on a Web page

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.
125

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.

A dictionary Object has these properties:

CompareMode Property

Sets and returns the comparison mode for comparing string keys in a Dictionary object.
object.CompareMode[ = compare]

dict.CompareMode = vbTextCompare

The CompareMode property has the following parts:


Part Description
object Required. Always the name of a Dictionary object.
Optional. If provided, compare is a value representing the comparison mode used by
compare
functions such as StrComp.

The compare argument has the following settings:


Constant Value Description
vbBinaryCompare 0 Perform a binary comparison. (exact comparison)
vbTextCompare 1 Perform a textual comparison.

Count Property

Returns the number of items in a Dictionary object. Read-only.


object.Count
num = dict.count
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.
126

Item Property

Sets or returns an item for a specified key in a Dictionary object. Read/write.

object.Item(key) [= newitem]

dict.item("1234") = "wrench"

ItemDemo = dict.Item("1234") 'Get the item for specified key

The Item property has the following parts:


Part Description
object Required. Name of Dictionary object.
key Required. Key associated with the item being retrieved or added.
newitem Optional. If provided, newitem is the new value associated with the specified key.
If key is not found when changing an item, a new key is created with the specified newitem. If
key is not found when attempting to return an existing item, a new key is created and its
corresponding item is left empty.

Key Property
Replaces an existing a key in a Dictionary object with a new key

object.Key(key) = newkey

d.Key("1234") = "1234a" 'Set key for "1234" to "1234a".

The Key property has the following parts:


Part Description
object Required. Always the name of a Dictionary object.
key Required. Key value being changed.
newkey Required. New value that replaces the specified key.
If key is not found when changing a key, a run-time error will occur.

The Dictionary object has the following methods:

Add Method

Adds a key and item pair to a Dictionary object.

object.Add key, item

dict.Add "1234", "Toaster"

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.
127

The Add method has the following parts:


Part Description
object Required. Always the name of a Dictionary object.
key Required. The key associated with the item being added.
item Required. The item associated with the key being added.

An error occurs if the key already exists.

Exists Method

Returns True if a specified key exists in the Dictionary object, False if it does not.

object.Exists(key)

dict.Exists("1234")

The Exists method syntax has these parts:


Part Description
object Required. Always the name of a Dictionary object.
key Required. Key value being searched for in the Dictionary object.

If dict.Exists("1234") Then
Response.Write("We got that part number")
Else
Response.Write("Wrong part number")
End If

Items method

Returns an array containing all the items in a Dictionary object.


Dim a
a = d.Items 'Get the items

Reading all items in dictionary using for loop

a = dict.items

' print out dictionary


for i = 0 to dict.count-1

Response.Write a(i) + "<br>"


next

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.
128

KEYS METHOD

Returns an array containing all existing keys in a Dictionary object.

Dim a

a = d.Keys 'Get the keys

Reading all keys in dictionary using for loop

a = dict.keys

' print out dictionary


for i = 0 to dict.count-1

Response.Write a(i) + "<br>"


next

REMOVE Method
Removes a key, item pair from a Dictionary object.

object.Remove(key)

Dim item

item = dict.Remove("1234") 'Remove item at key "1234"

The Remove method syntax has these parts:


Part Description
object Required. Always the name of a Dictionary object.
Required. Key associated with the key, item pair you want to remove from the
key
Dictionary object.

REMOVE ALL Method

The RemoveAll method removes all key, item pairs from a Dictionary object.

object.RemoveAll

d.RemoveAll 'Clear the dictionary

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.
129

ASP LESSON 9 EXERCISE 1

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.

FILE SYSTEM OBJECT'S

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.

FileSystemObject access to the server file system


Drive represents a disk or network drive
Folder represents a directory that is part of a drive
File represents a file part of a directory
TextStream represents a convection to a text file

Using 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.

Set fso = CreateObject("Scripting.FileSystemObject")


Set ts = fso.CreateTextFile("c:\testfile.txt", True)
ts.WriteLine("This is a test.")
ts.Close

We can then reopen the file to read back the line.

Const cRead = 2
Set ts = fso.OpenTextFile("c:\testfile.txt", cRead)
Dim s
s = ts.ReadLine

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.
130

The FileStreamObject has these properties

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:

Dim fso, d, dc, s, n


Set fso = CreateObject("Scripting.FileSystemObject")
Set dc = fso.Drives
For Each d in dc
s = s & d.DriveLetter & " - "
s = s & "<BR>"
Next
Response.Write (s)

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.

object.CreateTextFile(filename[, overwrite[, unicode]])

fso.CreateTextFile("c:\testfile.txt", True)

The CreateTextFile method has these parts:


Part Description
object Required. Always the name of a FileSystemObject or Folder object.
filename Required. String expression that identifies the file to create.
Optional. Boolean value that indicates if an existing file can be overwritten. The value
overwrite is True if the file can be overwritten; False if it can't be overwritten. If omitted,
existing files are not overwritten.
Optional. Boolean value that indicates whether the file is created as a Unicode or
unicode ASCII file. The value is True if the file is created as a Unicode file; False if it's created
as an ASCII file. If omitted, an ASCII file is assumed.

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

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.
131

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.

object.OpenTextFile(filename[, iomode[, create[, format]]])


fso.OpenTextFile("c:\testfile.txt", cRead, True)

The OpenTextFile method has these parts:


Part Description
object Required. Always the name of a FileSystemObject.
filename Required. String expression that identifies the file to open.
Optional. Indicates input/output mode. Can be one of three constants: ForReading,
iomode
ForWriting, or ForAppending.
Optional. Boolean value that indicates whether a new file can be created if the
create specified filename doesn't exist. The value is True if a new file is created; False if it
isn't created. The default is False.
Optional. One of three Tristate values used to indicate the format of the opened
format
file. If omitted, the file is opened as ASCII.

The iomode argument can have either of the following settings:


Constant Value Description
ForReading 1 Open a file for reading only. You can't write to this file.
ForWriting 2 Open a file for writing only. You can't read from this file.
ForAppending 8 Open a file and write to the end of the file.

The format argument can have any of the following settings:


Constant Value Description
TristateUseDefault -2 Opens the file using the system default.
TristateTrue -1 Opens the file as Unicode.
TristateFalse 0 Opens the file as ASCII.

The following code illustrates the use of the OpenTextFile method to open a file for writing text:

Const cRead = 1, cWrite = 2, cAppend = 8


Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", cRead, True)
f.Write "Hello world!"
f.Close

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.
132

Delete File Method

Deletes a specified file.

object.DeleteFile filespec[, force]

fso.DeleteFile("test.txt")

The DeleteFile method syntax has these parts:


Part Description
object Required. Always the name of a FileSystemObject.
Required. The name of the file to delete. The filespec can contain wildcard
filespec
characters in the last path component.
Optional. Boolean value that is True if files with the read-only attribute set are
force
to be deleted; False (default) if they are not.
An error occurs if no matching files are found. The DeleteFile method stops on the first error
it encounters. No attempt is made to roll back or undo any changes that were made before
an error occurred. The following example illustrates use of the DeleteFile method:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFile("test.txt")

Here is a table of the other methods of the FileStreamObject

Name Description and Syntax


BuildPath Appends a name to an existing path

object.BuildPath(path, name)
CopyFile Copies one or more files from one location to another.

object.CopyFile source, destination[, overwrite]


CopyFolder Recursively copies a folder from one location to another.
object.CopyFolder source, destination[, overwrite]
CreateFolder Creates a folder.
object.CreateFolder(foldername)
DeleteFolder Deletes a specified folder and its contents.
object.DeleteFolder folderspec[, force]
DriveExists Returns True if the specified drive exists; False if it does not.
object.DriveExists(drivespec)
FileExists Returns True if a specified file exists; False if it does not.
object.FileExists(filespec)

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.
133

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

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.
134

TEXTSTREAM OBJECT

The TextStream OBJECT is used for sequential access to a text file. Sequential access means read
and write each byte in sequence.

TEXTSTREAM OBJECT PROPERTIES

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.

Example using the AtEndOfLine property:


Const ForReading = 1
Dim fso, ts, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(filespec, 1, False)
Do While ts.AtEndOfLine <> True
s = theFile.Read(1)
Loop
ts.Close

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.

Example using the AtEndOfStream property:

Dim fso, ts, s


Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(filespec, 1, False)
Do While ts.AtEndOfStream <> True
s = ts.ReadLine
Loop
ts.Close

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.

Example using the Column property:

Dim fso, ts, s, col


Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", 2, True)
f.Write "Jello world!"
f.Close

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.
135

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.

Example using the Line property:

Dim fso, ts, s, n


Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", 1, True)
f.Write "Jello world!" & vbCrLf
Set f = fso.OpenTextFile("c:\testfile.txt", 1)
S = f.ReadAll
n = f.Line
Response.write(n);

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 Read method syntax has these parts:


Part Description
object Required. Always the name of a TextStream object.
characters Required. Number of characters you want to read from the 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.
136

The following example issues the Read method to read a character from a file and return the
resulting string:

Dim fso, ts, s


Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", 1, True)
f.Write "Jello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", 2)
s = f.Read(1)

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)

The Skip method syntax has these parts:


Part Description
object Required. Always the name of a TextStream object.
characters Required. Number of characters to skip when reading a file.
The following example uses the Skip method to skip the first six characters before reading from
a text file:
Const cRead = 1, cWrite = 2
Dim fso, ts, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", cWrite, True)
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", cRead)
f.Skip(2)
s = f.ReadLine

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.
137

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:

Const CRead = 1, CWrite = 2


Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", cWrite, True)
f.Write "Jello world!" & vbcrlf & "Last Line"
Set f = fso.OpenTextFile("c:\testfile.txt", cRead)
f.SkipLine
s = f.ReadLine

Write Method

Writes a specified string to a TextStream file.

object.Write(string)

The Write method syntax has these parts:


Part Description
object Required. Always the name of a TextStream object.
string Required. The text you want to write to the file.
The Specified strings are written to the file with no intervening spaces or characters between
each string. Use the WriteLine method to write a newline character or a string that ends with a
newline character.

The example using the Write method:


Const cRead = 1, cWrite = 2
Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", cWrite, True)
f.Write "Jello world!"

WriteLine Method
Writes a specified string and newline character to a TextStream file.

object.WriteLine([string])

f.WriteLine "Last Line"

The WriteLine method syntax has these parts:


Part Description
object Required. Always the name of a TextStream object.
Optional. The text you want to write to the file. If omitted, a newline character is
string
written to the 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.
138

Example using the WriteLine method:

Const CRead = 1, CWrite = 2


Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", cWrite, True)
f.WriteLine "Jello world!"
f.WriteLine "Last Line"

WriteBlank Line Method


Writes a specified number of newline characters to a TextStream file.

object.WriteBlankLines(lines)

f.WriteBlankLines 2

The WriteBlankLines method syntax has these parts:


Part Description
object Required. Always the name of a TextStream object.
lines Required. Number of newline characters you want to write to the file.
Example using the WriteBlankLines method:

Const cRead = 1, cWrite = 2


Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\testfile.txt", cWrite, True)
f.WriteBlankLines 2
f.WriteLine "Jello World!"

ASP LESSON9 EXERCISE 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.

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.
139

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

• IP Address and Application Object

• Query String

• Hidden Form values

• Database tables or files

• Authentication

Maintaining state with Session ID's

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.

How do I use Session objects?

To use a Session object you supply a key and a corresponding value.

Session("toaster") = 2

All other ASP files in your directory will be able to access the value of "toaster" from the session
object.

qty= Session ("toaster")

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.
140

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.

for each item in Session.Contents


Response.write item & ": " & Session Contents(item) & "<br>"
next

To remove an item from the collection use the Remove method:

Session Contents.Remove("toaster")

You can remove all items using the RemoveAll method:

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

You can use the Abandon method to terminate a Session immediately.

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

MAINTAIN STATE WITH COOKIES

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.

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.
141

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

Here is our counter cookie file entry: userid


1234
localhost/aspLesson4
0
1997670400
29537600
1896753472
29537468
*

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.
142

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.

MAINTAINING STATE USING USERS IP ADDRESS AND APPLICATION OBJECT

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:

Application.Contents ("userid ") = 1

you access entries by:

userid = Application.Contents("userid");

It should be now quite obvious that this is the same as saying

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.

for each item in Application.Contents


Response.write item & ": " & Application.Contents(item) & "<br>"
next

To remove an item from the collection use the Remove method:

Application.Contents.Remove("Count")

You can remove all items using the RemoveAll method:

Application.Contents.RemoveAll

Accessing the Application object one at a time

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

MAINTAINING STATE WITH QUERY STRINGS

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.

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.
144

People use this method on the product links and buttons to identify the user and what products they
are purchasing.

<a href= "http://www.mystore.com/?userid=55443344&product=toaster">toaster buy


me </a>

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.

Maintain state with Hidden values

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.

<FORM METHOD=POST ACTION = :ORDERS.ASP">


<INPUT TYPE=SUBMIT VALUE ="toaster" >
<INPUT TYPE=HIDDEN NAME = USER VALUE<%USRID%>
</FORM>

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.

<FORM METHOD=POST ACTION = :ORDERS.ASP">


<INPUT TYPE CHECKBOX NAME="ITEM" VALUE ="TOASTER">
<INPUT TYPE=SUBMIT VALUE ="SUBMIT ORDER" >
<INPUT TYPE=HIDDEN NAME = USER VALUE=<%USRID%>
</FORM>

If you name the checkbox name the same for all items for sale they each check box can be accessed
as an array

MAINTAINING STATE WITH DATA BASE OR FILES

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.

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.
145

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.

Authorized web sites

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.

ASP Lesson9 Exercise 4

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%>&amp;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

do while not os.eos

buf = os.read (4096)


Response.binarywrite buf

loop

set os=nothing

end if
end if
%>

ASP Lesson9 Exercise 4

Add a your file server to your online store .

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.
147

ASP PROGRAMMERS GUIDE LESSON 10

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

sub name argument


value
Subs

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.

[Private|Public][Static] Sub procedurename (paramater list)

local variables

programming statements

End Sub

Private Sub PrintTotal(Amount)

Response.Write("Your Total is: $" & Amount)

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.
148

The Sub statement syntax has these parts:

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.

Private Sub PrintTotal(Amount)

Respone.Write("Your Total is: $" & Amount);

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.

Private Sub PrintTotal(Amount)

If Amount < 100 Then


Response.Write("Your Total is: " & Amount)
Exit Sub;
End If

Respone.Write("You won a $50 bonus!)


Respone.Write("Your Total is: $" & Amount+50)

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.

[Public | Private] Function name [(paramater list])]


local variables

programming statements

function name = expression

End Function

The Function statement syntax has these parts:

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.

Function CtoF(Deg as single) As Single

CtoF = Deg * 9/5 + 32

End Function

Notice we assign the return value to the function name.

CtoF = Deg * 9/5 + 32

or else the function will just return 0.

If you do not want to return a value then use the Nothing keyword.

CtoF = Nothing

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.
150

A function ends at the last programming statement. You can exit a function earlier by using the
Exit Function statement.

Function IsLarge(x As Integer) As Integer

if x > 100 then

IsLarge = x
Exit Function

Else

IsLarge = x + 5

End if

End Function

Variables declared in procedures

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.

You use the Dim keyword to declare variables in a Sub or Function.

Dim Name .

If you want the local variable values to be preserved between function calls then you can make
them static.

Static Count

Here is our sample sub using a static local variable.

Sub CountNames()

Static count As Integer

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

Static Sub CountNames()

Dim Count

Count = Count + 1

End Sub

Calling Sub and Functions

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.

Two string1, string2

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.

Call Two (string1, string2)

or you can just call a sub by its name.

Two (string1, string2)

You can only call functions by their name and you must always use round brackets.

F = CtoF(36)

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.
152

Here is the overall picture:

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.

Call Function CtoF parameter deg receive


Dim c
Dim f value of argument c

c = 10 send argument c

f =CtoF(c)

Function CtoF(ByVal deg As Single)

CtoF = deg * 9/5 + 32

End Function

local variable f receives


value from function
Do Calculation

return value of conversion

Pass by Value - cannot change original value

PASSING VALUES TO PROCEDURES Pass by Reference - can change original value

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.

Private Sub Two(ByVal str1 As String, ByRef str2 As String)

str1 = "By Val"


str2 = "By Ref"

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.
153

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.

Dim string1 = "Hello"


Dim string2 = "GoodBye" string1 string2

Response.Write (string1)
Response.Write (string2) before: Hello GoodBye

Two string1, string2


after: Hello ByRef
Response.Write (string1)
Response.Write (string2)

End Sub

ASP LESSON 10 EXERCISE 1

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

ASP LESSON 10 EXERCISE 2

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

CtoF = degC* 9/5 + 32

FtoC = (degF - 32 ) * 5/9

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.
154

ORGANIZING YOUR ASP PROGRAM USING PROCEDURES.

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.

Declare Common Variables


used between Subs

Sub Input()

End Sub

Sub Calculate()

End Sub

Sub Output ()

End Sub

Sub Main

Call Input()
Call Calculate()
Call Output

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.
155

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.

ASP LESSON 10 EXERCISE 3

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.

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.
156

ASP PROGRAMMERS GUIDE LESSON 11

File: aspGuideL11.doc
Date Started: Mar 14, 2002
Last Update: June 20, 2003
Version 0.0
ISBN 0-9730824-3-7

CLASSES AND OBJECTS

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!

program Web Server

class object

define variables memory for


variables

coding running

Making your first class

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.

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.
157

writing your first class

A class starts with the key word class followed by the name of the class.

class People

class keyword name of class

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
%>

creating a object from our class definition

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

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.
158

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.

Set p = new Person

assign object allocate class


address reference memory name

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

We can assign values to the rest of the members of the class

p.Address = "50 Vine Street"


p.Age = 24

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.
159

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"

Address "50 Vine Street"


p
Age 24
Reference variable p contains the
address of our Person object

We put all he code that makes the Person object into an ASP file called Person.asp.

<!-- #include file="Person.cls" -->

<%

Dim p

set p = new Person


p.Name = "Tom"
p.Address = "50 Vine Street"
p.Age = 24

%>

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.

<!-- #include file="Person.cls" -->

ASP LESSON 11 EXERCISE 1

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.

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.
160

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.

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.
161

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.

<!-- #include file="Person.cls" -->

We declare a reference variable called p and create a person object from the Person class definition.

<%

dim p

Set p = new Person

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.

ASP LESSON 11 EXERCISE 2

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.

Private m_Name As String


Private m_Address As String
Private m_Age As String

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.

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.
162

Here are some of the property procedures for our Person class.

Public Property Get Name() As String


Name = m_Name
End Property

Public Property Let Name(ByVal vNewValue As String)


m_Name = vNewValue
End Property

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.

USING PROPERTY PROCEDURES

You use property procedures just like a ordinary variable. You can just give them a value:

p.Name = "Bill"

or you can get a value from them and assign to a variable

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.

MAKING MORE THAN 1 OBJECT

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

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.
163

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:

step [1] make reference variables to represent your objects

Dim p1
Dim p2

step [2] allocate memory for objects and assign the objects to your variables

Set p1 = new Person


Set p2 = new Person

step [3] fill your objects with data using properties

p1.Name = "tom"
p1.Address = "50 Vine Street"
p1.Age = 24

p2.Name = "Mary"
p2.Address = "42 Lamb Street"
p2.Age = 23

ASP LESSON 11 EXERCISE 4

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.

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.
164

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.

Here is the PrintAll Function:

Public Function PrintAll()

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

Set p1 = new Person


Set p2 = new 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()

which object to access dot


operator which method to call

Here's the big picture:


Person Object
program

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()

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.
166

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.

ASP LESSON 11 EXERCISE 5

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.

Set p = New Person

Inside the initialize event you can initialize the property values of your object.

Private Sub Class_Initialize()

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.

Private Sub Class_Terminate()

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.
167

ASP LESSON 11 EXERCISE 6

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.

OBJECTS REFERRING TO THEM SELVES.

Consider the following code:


Person Object
Dim p1 as Person

Set p1 = new Person

p1.Name = "tom"; Name: Tom


p1.Address = "50 Vine Street" Address: 50 Vine Street
p1.age = 24; Age: 24

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.

Finishing using objects

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

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.
168

ASP LESSON 11 EXERCISE 7

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

ASP LESSON 11 EXERCISE 8

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.

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.
169

ASP PROGRAMMERS GUIDE LESSON 12

File: aspGuideL12.doc
Date Started: Jan 27, 2003
Last Update: June 20, 2003
Version 0.0
ISBN 0-9730824-3-7

XML EXTENSIBLE MARKUP LANGUAGE

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)

<employee name="joe smith" address="23 nowhere street" city="toronto">


</employee>

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.

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.
170

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

<name> Joe smith </name>

start tag PCDATA end tag

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.

XML document structure

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

root end tag

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.
171

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 ?>

<?XML version="1.0" encoding ="ISO-8859-1" ?>

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"

Document root tag

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" address="23 nowhere street" city="toronto"></employee>

Using attributes is like using many nested child elements:

<employee>
<name> Joe smith </name>
<address> 23 nowhere street </address> child elements
<city> Toronto </city>
</employee>

Which format you use is your own choice.

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.
172

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>

Which can be easily written as:

<address />

An empty tag can also contain an attribute.

<employee name="ed" />

Notice the / is at the end of the tag < />

well-formed tags

These tags have start tags and corresponding end tags.

<employee> name= "ed" </employee>

XML comments

XML comments start with <!-- and end with a -->

<!-- I am a comment -->

procesing comand instructions

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

<?target instrutions ?>

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.

<?xml version= "1.0" ?>

no space here

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.
173

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:

<! DOCTYPE name [ body description ] >

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:

<!ELEMENT employee (name, adress, city)>

Next we describe our content and Parsed Character Data (#PCDATA) The (#PCDATA) means
parsed character data

<!ELEMENT name (#PCDATA)>

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)>
]>

Our complete XML document with the DTD will be:

<?xml version= "1.0" ?>


<!DOCTYPE employee [
<!ELEMENT employee (name, address, city)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT address (#PCDATA)>
<!ELEMENT city (#PCDATA)>
]>
<employee>
<name> Joe smith </name>
<address> 23 nowhere street </address>
<city> Toronto </city>
</employee>

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.

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.
174

DTD for attributes

You can uses DTD to describe start tags with attributes like:

<employee name="joe smith" address="23 nowhere street" city="toronto"></employee>

You declare a list of alowable atributes for each element. These lists are called ATTLIST
declarations.

<!ATTLIST tag_name attribute_name attribute_type attribute_value_declaration>

Our ATTList fot out example would be:

<!ATTLIST employee name ID #REQUIRED address CDATA #REQUIRED


city CDATA #REQUIRED >

attribute types

ID means the attribute value uniquely identifies the containing element


CDATA means the attribute value is character data

attribute value declarations

#REQUIRED means the attribute is required


#IMPLIED means attribute is not required
#FIXED means the attribute value cannot change

Our complete example now would be:

<?xml version= "1.0" ?>


<!DOCTYPE employee [
<!ATTLIST employee name ID #REQUIRED address CDATA #REQUIRED city CDATA #REQUIRED >
]>
<employee name="joe smith" address="23 nowhere street" city="toronto"></employee>

Add the attribute DTD to your employee2.xml file.

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.

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.
175

ACCESSING XML DOCUMENTS

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

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.
176

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

Where to get the DOM

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.

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.
177

READING AND WRITING XML DOCUMENTS USING DOM

In a XML Database application we have all the following objects to deal with:

• Database - permanent storage of data


• RecordSet - holds records for a certain query
• DOM Document - stores records in a node structure
• XML File - represents storage using tags

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

DataBase Record Set Record Set DataBase

DB RS RS DB

XML

Here are the things we need to do:

[1] create a dom document by creating and attaching nodes


[2] print out Dom Document as XML tags
[3] save a dom document as an XML file
[4] create a dom document from a XML File
[5] visit each node in a DOM Document
[6] write the contents of a database to a XML file
[7] read the contents of a XML file and store in a disconnected recordset
[8] update a disconnected record set
[9] update a database from a disconnected recordset
[10] create a DOM document from a data base
[11] update a data base from a DOM Document

This is how we do it:

[1] create a XML DOM document by creating and attaching nodes

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).

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.
178

We will use our "employee.xml" xml file as an example:

<employee>
<name> Joe Smith </name>
<address> 23 Nowhere Street </address>
<city> Toronto </city>
</employee>

Here are the step by step instructions

(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.

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.
179

DOMDocument

<employee> </employee>

<name> Joe Smith </name>

<address> 23 Nowhere Street </address>

<city> Toronto </city>

[2] Print the DOM contents as XML

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)

<Employee><name>john smith</name><address>23 nowhere st</address><city>toronto</city></Employee>

If you Remove the Response.ContentType="text/plain" statement and replace with


Response.ContentType="text/xml" then the web browser interprets the XML tags and just prints
out the character data for each element. Notice the address is in italics.

john smith
23 nowhere st
toronto

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.
180

[3] save a dom document as an XML file

To save the DOM to a XML file:

dom.save Server.MapPath("employee5.xml")

The map employee.XML file woild look like this:


<Employee><name>john smith</name><address>23 nowhere st</address><city>toronto</city></Employee>

[4] create DOM document from an XML file

Dom XML File


Document

This is an easy thing to do we just call the Load method from a DOM object

dom.Load Server.MapPath("employees.xml")

[5] visit each node in a DOM Document

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.

object reference description


IXMLDOMNode root node in tree
methods purpose
nodeType type of node
childNodes list all children of this node
baseName base tag name
Attributes attribute list of this node

XMLDOMNodeList childNodes list all children of this node


methods purpose
length numbeer of children in list
XMLDOMAttribute attrib
methods purpose
nodeType type of mnode
baseName tag base name
Text attibute name
Value value of attribute

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.
181

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

' make a DOM Document object.

Dim dom
set dom = Server.createObject("MSXML.DOMDocument")

' load XML file

dom.Load Server.MapPath("employee.XML")

' visit each node in DOM Document

' get and print out root


dim root
set root = dom.documentElement
response.write("<br>root: " & root.nodename & ": " & root.nodevalue)

' get elements of root


dim elements
set elements = root.childnodes

' get and printout each element of elements


dim element
for each element in elements

response.write ("<br>" & element.nodeName & ": " & element.text)

' check if this element has children


if element.hasChildNodes then

' get children


set nodes = element.childNodes

' if children
if nodes.length> 0 then

' get first child


set node = nodes(0)

' test for attributes of this child


if not(node.attributes is nothing) then

if node.attributes.length > 0 then

' get all attribute names


for each attr in node.attributes
response.write (attr.nodename)
next
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.
182

' loop through all children


for each node in nodes

' get all attribute values


for each attr in node.arrtibutes
response.write(attr.nodevalue)
next
next
end if
end if
end if
end if
next

%>

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

[6] write the contents of a data base to a XML file

Data Base XML File

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

Set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & Server.MapPath("aspL12.mdb")

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

Set rsCategories = Server.CreateObject("ADODB.RecordSet")

' get filename


rsCategories.Open "employee",cn,1,4,&H0002

set rsCategories.ActiveConnection = nothing

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"))

rsCategories.save server.MapPath("aspL12.xml"),1 adPersistXML persist format


%>

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.

Recordset open statement

The recorsdset open statement syntax is as follows:

recordset.Open Source, ActiveConnection, CursorType, LockType, Options

this is what we use:

rsCategories.Open "employee",cn,1,4,&H0002

adOpenKeySet adLockBatchOptomistic adCmdTable

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.

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.
184

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.

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.
185

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.

The Database XML file constists of four sections.

(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

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.
186

[7] read the contents of a XML file and store in a record set

RecordSet XML File

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

Response.Write "Records: " + "<BR>"

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

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.
187

[8] edit a Disconnected record set

You can also update, delete and add new records to the recordset. In our example we just change
one of the fields values.

rs("address") = "42 universe crescent"

Try it on the above xmltors.asp file

We do not issue an update, this will happen aiutomatically when we re-connect to the data base.

[9] reconnect a disconnected recordset

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

Set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & Server.MapPath("aspL12.mdb")
cn.open

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.

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.
188

[10] DOM to RS

We have to do this in two steps:

(1) save the Dom as a XML file

We just call the save method from the DOM

dom.save "asp12.xml"

(2) read the XML file into a recordecset

open the recordset specifying the MSPersist provider

rs.open "asp12.xml", "Provider = MSPersist"

[11] rs to Dom

Again this has to be done in 2 steps:

(1) save the recordset as an XML file

Const adPersistXML = 1
rs.save Server.MapPath("aspL12.xml"), adPersistXML

(2) read in the XMLfile to a dom

dom.Load Server.MapPath ("aspL12.xml")

With MSMXML Version 3.0 you can do this all in one step.

rs.save dom, adPersistXML

ASP LESSON 12 EXERCISE 1

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:

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.
189

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.

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.
190

OBTAINING A LIST OF ELEMENTS FROM THE DOM

Getting customer elements

We use the getElementsByTagName(tag_name) method of the DOMDocument object to get a


list of elements for a specified name tag. It will get all the elements of the named tag. For example:

Dim customerList
Set customerlist = docXML.getElementsByTagName("customer")

We now have a list of element for the tag name "customer", which are

<customer name="Jack Sprat" address="16 Wonderland Rd"> </customer>


<customer name="Humpty Dumpty" address="12 FallDown Street"> </customer>

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)

The first element in the list would be:

<customer name="Jack Sprat" address="16 Wonderland Rd"> </customer>

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")

The values of the attribute name is of course : Jack Sprat

getting order elements for a selected customer

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

We would get the following elements

<order number="1234" date="1\21\2003">

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.
191

getting item elements for a selected customer and order number

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

We would get the following item elements

<item name="1 kg ice cream" price="6.38" />


<item name="2 kg bacoon" price="3.78" />

ASP EXAMPLE PROGRAM

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 "ONCHANGE='document.form1.submit()'>"

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.
192

'loop through list


For i = 0 To customerList.length - 1
Dim customer
Set customer = customerList.Item(i)
if custsel=customer.getAttribute("name") then
Response.Write "<Option SELECTED>" & customer.getAttribute("name")
else
Response.Write "<Option>" & customer.getAttribute("name")
end if
Next
Response.Write "</SELECT>"

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

"customer[@name=""" & cust & """]/orders/order"

Here is the code:

Dim orderList
Dim str
str = "customer[@name=""" & custsel & """]/orders/order"
Set orderList = docRoot.getElementsByTagName(str)
Response.Write "<SELECT name=orders size=1
ONCHANGE='document.form1.submit()'>"

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

if not found then


ordersel = orderList.Item(0).getAttribute("number")
end if

Response.Write "</SELECT>"
Response.Write "</form>"

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.
193

[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"

here is the code

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")

textstr = textstr + name + Space(20 - Len(name)) + price + VBCRLF

Next

Response.Write "<TextArea rows=8 cols=40>"+textstr+"</TextArea>"

ASP LESSON 12 EXERCISE 2

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.

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.
194

ASP PROGRAMMERS GUIDE LESSON 13

File: aspGuideL13.doc
Date Started: Jan 21, 2003
Last Update: June 20, 2003
Version: 0.0
ISBN: 0-9730824-3-7

XML and XSL

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

(1) use DOM or SAX parser

(2) read XML into a Record Set

(3) use XSL

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.

What is this XSL ?

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.

<?xml version="1.0" ?>


<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<xsl:for-each select="Employees/Employee" >
<xsl:value-of select="name" />
<xsl:value-of select="address" />
<xsl:value-of select="city" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

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.
195

We will discuss each line for your understanding:

(1) An XSL document begins with the standard XML prolog

<?xml version="1.0" ?>

(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

(4) Now we come to the XSL processing power tag:

<xsl:for-each select="Employees/Employee" >

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

<xsl:value-of select="name" />

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:value-of select="address" />


<xsl:value-of select="city" />

(6) We start closing all the open tags now

close the for-each tag

</xsl:for-each>

close the template

</xsl:template>

close the style sheet

</xsl:stylesheet>

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.
196

HOW DO WE TELL THE DOM TO START TRANSFORMING ?

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.

XSL file XSL DOM XML DOM Transform output


transformNode as String

XML file

XSL - XML Transform Sample Program

Here are the step by step instructions:

Step [1] type in the following XML into a file called "employees.xml" with no leading spaces.

<?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 somehere st</address>
<city>orangeville</city>
</Employee>
<Employee>
<name>bill smith</name>
<address>43 anywhere st</address>
<city>tenessee</city>
</Employee>
</Employees>

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.
197

Step [2] type in the following XSL into a file called "employees.xsl" with no leading spaces.

<?xml version="1.0" ?>


<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<xsl:for-each select="Employees/Employee" >
<xsl:value-of select="name" />
<xsl:value-of select="address" />
<xsl:value-of select="city" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

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)

domDoc.Load Server.MapPath( "employees.xml")


'Response.Write domDoc.xml

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

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.
198

TRANSFORMING XML WITH XSL ON THE WEB BROWSER

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.

<?xml-stylesheet type="text/xsl" href="employees.xsl"?>

Here is the employees xml file with a reference to the employees xsl style sheet.

<?xml version='1.0' ?>


<?xml-stylesheet type="text/xsl" href="employees.xsl"?>
<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>

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

ADDING A HTML TABLE TO OUR XSL FILE

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.

<?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>

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.
199

<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>

CALLING A XML FILE FROM A HTML 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>

Here is the result:

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.
200

DATA ISLANDS

We can reference a XML file and a XSL file in an HTML file using the xml tag.

<xml id="source" src="employees.xml"></xml>

<xml id="style" src="employees2.xsl"></xml>

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.

<script language="vbscript" for="window" event="onload">


xslEmployee.innerHTML = source.transformNode(style.xmlDocument)
</script>

Here is the complete html program:

<!-- employes3.htm -->


<html>
<head>
<title> employee.htm </title>
</head>

<xml id="source" src="employees.xml"></xml>


<xml id="style" src="employees2.xsl"></xml>

<script language="vbscript" for="window" event="onload">


xslEmployee.innerHTML = source.transformNode(style.xmlDocument)
</script>
<body>
<div id="xslEmployee"></DIV>
</BODY>
</HTML>

Here is the output:

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.
201

Alternatively you can embed the complete XML and XSL files inside the html program

<!-- employes4.htm -->


<html>
<head>
<title> employee.htm </title>
</head>

<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>

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.
202

<script language="vbscript" for="window" event="onload">


xslEmployee.innerHTML = source.transformNode(style.xmlDocument)
</script>
<body>
<div id="xslEmployee"></DIV>
</BODY>
</HTML>

we would get the following output:

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

ASP LESSON13 EXERCISE 1

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

<xsl:for-each select="Employees/Employee order-by="name" >

ASP LESSON 13 EXERCISE 2

Add an additional button where they can select ascending or descending order in the previous
exercise. Call your ASP file aspL13Ex2.asp.

USING XSL TO DISPLAY ELEMENTS WITH ATTRIBUTES

Our xml file with attributes would be:

<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>

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.
203

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:

<TD><xsl:value-of select="@address" /></TD>

We get the same output:

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

ASP LESSON 13 EXERCISE 3

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.

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.
204

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

<xsl:for-each select="Employees/Employee" >

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

find all child elements of employees

<xsl:for-each select="Employees/*" >

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

find all employee elements in employees that have child name elements

<xsl:for-each select="Employees/Employee[name]" >

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

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.
205

find the first employee node in employees

<xsl:for-each select="Employees/Employee[0]" >

Name Address CITY


john smith 23 nowhere st toronto

find the last employee node in employees

<xsl:for-each select="Employees/Employee[end()]" >

Name Address CITY


bill smith 43 anywhere st tenessee

find all the employee elements that are grandchildren of the root

<xsl:for-each select="/*/Employee" >

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

find all grandchildren of the current context

<xsl:for-each select="*/*" >

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

find all employee elements in employees that have child name element equal to
"john smith"

<xsl:for-each select="Employees/Employee[name='john smith']" >

Name Address CITY


john smith 23 nowhere st toronto

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.
206

find all employee elements in employees that have child name element index equal to 2

<xsl:for-each select="Employees/Employee[index()=2]" >

Name Address CITY


bill smith 43 anywhere st tenessee

XSL OPERATION FOR ATTRIBUTES

find all employee elements in employees that have "name" attributes

<xsl:for-each select="Employees/Employee[@name]" >

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

find all employee elements in employees that have name attribute equal to
"john smith"

<xsl:for-each select="Employees/Employee[@name='john smith']" >

Name Address CITY


john smith 23 nowhere st toronto

find all attributes in the employees/employee context

<xsl:for-each select="Employees/Employee[@*]" >

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

ASP LESSON 13 EXERCISE 4

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.

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.
207

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 &lt; less than
>= greater than or equal
<= use &lt;< less than or equal

using logical operators

Find all attributes in the employees/employee context that have name "tom smith"
(notice the single quotes around 'tom smith'):

<xsl:for-each select="Employee/Employee[@name='tom smith']" >

Find all attributes in the employees/employee context that have cities greater and equal to toronto

<xsl:for-each select="Employees/Employee[@city>='toronto'] ">

Find all attributes in the employees/employee context that have cities less than toronto

<xsl:for-each select="Employees/Employee[@city &lt; 'toronto'] ">

Find all attributes in the employees/employee context that have cities not equal to toronto

<xsl:for-each select="Employees/Employee[@city !='toronto'] ">

Find all attributes in the employees/employee context that have cities equal to 'toronto' and name
equal to 'john smith'

<xsl:for-each select="Employees/Employee[@city='toronto' and @name='john smith'] ">

ASP LESSON 13 EXERCISE 5

Try all the above examples, make some additional ones. Use the Textbox of Exercise4 to type in the
XSL query strings.

ASP LESSON 13 EXERCISE 6

Use XSL to make a hyperlink! Call your asp file aspL13Ex6.asp.

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.
208

ASP PROGRAMMERS GUIDE LESSON 14

File: aspGuideL14.doc
Date Started: Jan 21, 2003
Last Update: June 20, 2003
Version: 0.0
ISBN: 0-9730824-3-7

XML APPLICATIONS

BINDING A XML FILE TO A TABLE

We can take our xml file "employees.xml" from last exercise and bind to a table.

<!-- Employees.xml -->


<?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 somehere st</address>
<city>orangeville</city>
</Employee>
<Employee>
<name>bill smith</name>
<address>43 anywhere st</address>
<city>tenessee</city>
</Employee>
</Employees>

We make another html file called "Employees6.htm" and include the employees.xml file as a data
island.

<xml id="xmlEmployees" src="employees.xml"></xml>

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>

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.
209

We use the <DIV> tag and datafld attribute to map the data from the xml file fields to the table
columns.

<TD><DIV datafld="name"></DIV> </TD>

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!

<!-- Employees6.htm -->


<HTML>
<HEAD>
<TITLE>Employees6.html</TITLE>
</HEAD>

<xml id="xmlEmployees" src="employees.xml"></xml>

<BODY>

<TABLE Border="1" DATASRC=#xmlEmployees>


<THEAD>
<TR>
<TH>Name</TH><TH>Address</TH><TH>City</TH>
</TR>
</THEAD>
<TR>
<TD><DIV datafld="name"></DIV> </TD>
<TD><DIV datafld="address"></DIV></TD>
<TD><DIV datafld="city" ></DIV></TD>
</TR>
</TABLE>

</BODY>
</HTML>

The output is as follows:

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.
210

BINDING TO OTHER HTML ELEMENTS.

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.

Element Binding attribute updateable


A href no
APPLET param yes
BUTTON innerTEXT, innerHTML no
DIV src no
FRAME src no
IFRAME src no
IMG src no
CHECKBOX checked yes
HIDDEN value yes
LABEL value yes
PASSWORD value yes
RADIO checked yes
TEXT value yes
LABEL innerTEXT, innerHTML no
MARQUEE innerTEXT, innerHTML no
SELECT option yes
SPAN innerTEXT, innerHTML no
TEXTAREA value yes

WE CAN TRY SOME OF THESE

Bind the employees.xml data island to a Label

<INPUT TYPE=LABEL DATASRC=#xmlEmployees DATAFLD=ADDRESS>

or TextBox

<INPUT TYPE=TEXT DATASRC=#xmlEmployees DATAFLD=ADDRESS>

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.
211

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.

<!-- Employees7.htm -->


<HTML>
<HEAD>
<TITLE>Employees7.html</TITLE>
</HEAD>

<xml id="xmlEmployees" src="employees.xml"></xml>

<BODY>

<TABLE Border="1" DATASRC=#xmlEmployees>


<THEAD>
<TR>
<TH>Name</TH><TH>Address</TH><TH>City</TH>
</TR>
</THEAD>
<TR>
<TD><DIV datafld="name"></DIV> </TD>
<TD><INPUT TYPE=text DATAFLD=ADDRESS></TD>
<TD><INPUT TYPE=text DATAFLD=city></TD>
</TR>
</TABLE>

</BODY>
</HTML>

Here is the result:

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.
212

Navigating through records

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.

<TABLE ID="tblEmployees" datapagesize=10 Border="1" DATASRC=#xmlEmployees>

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
ONCLICK="tblEmployees.firstPage()"><pre><<</pre></button>

<BUTTON ID=previous
ONCLICK="tblEmployees.prevoisPage()"><pre><</pre></button>

<BUTTON ID=next
ONCLICK="tblEmployees.nextPage()"><pre>></pre></button>

<BUTTON ID=last
ONCLICK="tblEmployees.lastPage()"><pre>>></pre></button>

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.
213

Adding new records

To add a new record we must access the record set of the xmlemployees data island and call the
addNew() method.

ONCLICK="xmlEmployees.recordset.addNew()" >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.

ONCLICK="xmlEmployees.recordset.addNew(); 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.

sending data back to the server.

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.

<form name="form1" method="POST" action="xmlUpdate.asp">


<input id=updateit type=hidden name=xmlUpdate>
</form>

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.
214

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.

<BUTTON ONCLICK="getxml()"> Update Database </button>

Or when the page unloads. This way the server data base will always be updated.

<BODY ONUNLOAD="getxml()">

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
%>

Here's the complete HTML program

<!-- Employees10.htm -->


<HTML>
<HEAD>
<TITLE>Employees7.html</TITLE>
</HEAD>

<xml id="xmlEmployees" src="employees.xml"></xml>

<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 ONUNLOAD="getxml()">

<TABLE id=tblEmployees DATAPAGESIZE= 2 Border="1"


DATASRC=#xmlEmployees>
<THEAD>
<TR>
<TH>Name</TH><TH>Address</TH><TH>City</TH>
</TR>
</THEAD>
<TR>
<TD><INPUT TYPE=text DATAFLD=NAME></TD>
<TD><INPUT TYPE=text DATAFLD=ADDRESS></TD>
<TD><INPUT TYPE=text DATAFLD=city></TD>
</TR>
</TABLE>

<P>
<BUTTON ID=FIRST
ONCLICK="tblEmployees.firstPage()"><pre><<</pre></button>

<BUTTON ID=previous ONCLICK="tblEmployees.previousPage()">


<pre><</pre></button>

<BUTTON ID=next
ONCLICK="tblEmployees.nextPage()"><pre>></pre></button>

<BUTTON ID=last
ONCLICK="tblEmployees.lastPage()"><pre>>></pre></button>

<BUTTON ID=new
ONCLICK="xmlEmployees.recordset.addNew()
tblEmployees.lastPage()">
<pre>New</pre></button>

</P>

<form name="form1" method="POST" action="xmlUpdate.asp">


<input id=updateit type=hidden name=xmlUpdate>
</form>

<BUTTON ONCLICK="getxml()"> Update Database </button>


</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.
216

ASP LESSON14 EXERCISE 1

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.

XML TRANSFORMATION SERVER

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

paramaters add XSL


nodes
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.
217

Here's the employees.xml file from previous lessons

<!-- Employees.xml -->


<?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 somehere st</address>
<city>orangeville</city>
</Employee>
<Employee>
<name>bill smith</name>
<address>43 anywhere st</address>
<city>tenessee</city>
</Employee>
</Employees>

Here's the employees2.xsl file from previous lessons

<!-- Employees2.xSl -->


<?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>

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.
218

If we apply the transformation we would get the following result:

Name Address CITY


john smith 23 nowhere st toronto
mary smith 32 somehere st orangeville
bill smith 43 anywhere st tenessee

How would you list the names in sorted order ?

you would use the order-by attribute in the XSL for-each element from:

<xsl:for-each select="Employees/Employee">

to:

<xsl:for-each select="Employees/Employee" order-by="name" >

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

Here is the ASP file.

<%
'Lesson14p2.asp

response.expires=-1
response.contentType = "text/html"

' get xml and xsl file names


dim xmlfile, xslfile

xmlfile = request("xmlfile")
xslfile = request("xslfile")

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.
219

' create xml and xsl dom objects


set xmldom = server.createobject("MSXML.DOMDocument")
set xsldom = server.createobject("MSXML.DOMDocument")
' load xml and xsl files into DOM
xmldom.async = false
xsldom.async = false

xmldom.load server.mappath(xmlfile)
xsldom.load server.mappath(xslfile)

' get all param keys


for each key in request.queryString
updatexsl xsldom, key, request(key)
next

response.write xmldom.transformNode(xsldom)

' add key and value as a attribute


sub updatexsl(xsldom, key, value)

' check of xsl attribute


if left(key,2)="a:" then

key=mid(key,3)

' look for existing


set keynode = xsldom.selectsinglenode("//xsl:for-each")

' if found add


if not keynode is nothing then
keynode.setAttribute key,cstr(value)
end if
end if

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.

set xmldom = server.createobject("MSXML.DOMDocument")


set xsldom = server.createobject("MSXML.DOMDocument")

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.

for each key in request.queryString


updatexsl xsldom, key, request(key)
next

Finally we do the transformation by calling the transformNode method of the xmlDOM.

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:

set keynode = xsldom.selectsinglenode("//xsl:for-each")

If we find the for-each node we then add the attribute key and value to it using the setAttribute
method.

if not keynode is nothing then


keynode.setAttribute key,cstr(value)
end if

We have gone from this

<xsl:for-each select="Employees/Employee">

to this

<xsl:for-each select="Employees/Employee" order-by="name">

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.
221

HTML TEST PROGRAM

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.

<!-- xmlserver.htm -->

<html>
<head>
<title> xml server </title>

</head>

<body>

<form method=get action=xmlserver.asp>


<input type=hidden name=a:order-by value=name>
<input type=hidden name=xmlfile value=employees.xml>
<input type=hidden name=xslfile value=employees2.xsl>
<input type=submit value=Name>
</form>

<form method=get action=xmlserver.asp>


<input type=hidden name=a:order-by value=address>
<input type=hidden name=xmlfile value=employees.xml>
<input type=hidden name=xslfile value=employees2.xsl>
<input type=submit value=Address>
</form>

<form method=get action=xmlserver.asp>


<input type=hidden name=a:order-by value=city>
<input type=hidden name=xmlfile value=employees.xml>
<input type=hidden name=xslfile value=employees2.xsl>
<input type=submit value=City>
</form>

</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.
222

The html file looks like this

Pressing the name button would give you this. Notice the names are all in sorted order.

ASP LESSON 14 EXERCISE 2

Add a textbox that only finds the entered name when the name button is pressed.

ASP LESSON 14 EXERCISE 3

Use the xmlHTTP object to talk to the ASP directly so that the button and transformation are
displayed on the same page.

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.
223

ASP PROGRAMMERS GUIDE LESSON 15

File: aspGuideL15.doc
Date Started: Jan 21, 2003
Last Update: June 20, 2003
Version: 0.0
ISBN: 0-9730824-3-7

VB, ASP AND XML

Reading XML Documents from a ASP Program using VB

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.

' VB program reads asp file


Private Sub CommandGet_Click()

' create XMLHTTPRequest object


Dim xmlHttp As New XMLHTTPRequest
Dim xmlDoc As domdocument
Dim request As String

' request URL


request = "http://localhost/Lesson15/employees.xml"

' open connection


xmlHttp.Open "POST", request, False

' send request


xmlHttp.send

' get response as xml documents


Set xmlDoc = xmlHttp.responseXML

' display xml document


TextDisplay.Text = xmlDoc.xml

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

Here is the ASP program to return the XML document:

<%
' aspLessonL15p1.asp

' create DOM


dim xmlDoc

set xmlDoc = Server.CreateObject("MSXML.DOMDocument")

' load XML File


xmlDoc.load Server.MapPath("employees.xml")

' set content type to XML


Response.contentType = "text/xml"

' return XML file


Response.Write xmlDoc.xml

%>

Here is the VB program running:

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.
225

ASP LESSON 15 EXERCISE 1

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.

VB SENDS A XML FILE TO A ASP PROGRAM

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

XML store xml document


Document XML
Document

Here is the form code that sends a XML Document to a ASP page:

' VB program sends asp file


Private Sub CommandGet_Click()

' create XMLHTTPRequest object


Dim xmlHttp As New XMLHTTPRequest
Dim xmlDoc As New DomDocument
Dim request As String

' load xml file


xmlDoc.Load = xmlFile.Text

' request URL


request = "http://localhost/Lesson15/employees.xml"

' open connection


xmlHttp.Open "POST", request, False

' send request


xmlHttp.send(xmlDoc)

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

' create DOM


dim xmlDoc

set xmlDoc = Server.CreateObject("MSXML2.DOMDocument")

' get XML Doc from Request object

xmlDoc.load Request

' write out xml file


xmlDoc.Save "myfile.xml"

%>

If you are using MSXML version 1 you need to open a file and save the XML as a string.

dim fso

set fso = CreateObject("scripting.FileSystemOAbject");

dim myfile

myfile = fso.createtextfile(Server.MapPath("xmlfile.xml"), true)

myfile.writeline (myxml)

myfile.close.

ASP LESSON 15 EXERCISE 2

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.

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.
227

LOADING A FILE ASYNCHRONOUSLY IN VB

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.

receive on ready event


Web Server
send xml document
ASP send XML VB
Program document Program

XML store xml document


Document XML
Document

To do this you have to do the following:

We need to enable events in our document object

Dim with events xmldoc as new domDocument

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

private sub xmldoc_onreadystatechange

' check the ready state

if xmldoc.readystate = 4 then

' create XMLHTTPRequest object


Dim xmlHttp As New XMLHTTPRequest
Dim xmlDoc As New DomDocument
Dim request As String

' load xml file


xmlDoc.Load = xmlFile.Text

' request URL


request = "http://localhost/Lesson15/employees.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.
228

' open connection


xmlHttp.Open "POST", request, False

' send request


xmlHttp.send(xmlDoc)

End If

End Sub

ASP LESSON 15 EXERCISE 3

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.

TYPICAL VB, ASP XML APPLICATION

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

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.
229

Here are the module descriptions:

module program name description


Customer Terminal query.htm customers buys, orders and returns items
HTML Program
Business Services bs.asp handles customer and owner request to the database
manager
XML Database xmlDBMgr.asp handle XML database request and response with XML
Manager
Database Lesson15.mdb stored item records
Owner Entry Terminal Project15.vbp allows owner to add. delete and update item records

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

Field Name Data Type


PartNum Number
Description Text
Qty Number
Price Currency
BackOrder Number
DeliveryDate Date/Time

The data base may look like this:

PartNum Description Qty Price BackOrder DeliveryDate


1234 hammer 5 $29.95 2 4/3/03
5678 wrench 4 $19.95 0

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

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.
230

Here is the xmldbmgr code:

<%
' class xml database manager

'---- CursorTypeEnum Values ----


Const adOpenForwardOnly = 0
Const adOpenKeyset = 1
Const adOpenDynamic = 2
Const adOpenStatic = 3

'---- LockTypeEnum Values ----


Const adLockReadOnly = 1
Const adLockPessimistic = 2
Const adLockOptimistic = 3
Const adLockBatchOptimistic = 4

'---- CursorLocationEnum Values ----


Const adUseServer = 2
Const adUseClient = 3
const adPersistXML=1

'---- CommandTypeEnum Values ----


Const adCmdUnknown = &H0008
Const adCmdText = &H0001
Const adCmdTable = &H0002
Const adCmdStoredProc = &H0004
Const adCmdFile = &H0100
Const adCmdTableDirect = &H0200

' class to handle data base requests and respond in XML


class xmlDBMgr

private cn ' connection


private rs ' record set

' connect to database


private sub class_initialize

Set cn= Server.CreateObject("ADODB.Connection")


cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & Server.MapPath("Lesson15.mdb")

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

' open table, return xml in dom object


public function openRS(table)

Set rs = Server.CreateObject("ADODB.RecordSet")

rs.Open "parts",cn,adOpenKeyset,adLockOptimistic,adCmdTable

set rs.ActiveConnection = nothing ' disconnect

cn.close

dim fs

' delete xml file if exits


set fs = server.CreateObject("Scripting.FileSystemObject")

if fs.FileExists(Server.MapPath("parts.xml")) then
fs.DeleteFile server.MapPath("parts.xml")
end if

' write out record set as xml to file


rs.save server.MapPath("parts.xml"),1

'read in the XMLfile to a dom


' load xml file into DOM
set xmldom = Server.createObject("MSXML.DOMDocument")
xmldom.Load server.MapPath("parts.xml")

'response.write xmldom.xml
return dom object
set openRS = xmldom

end function

' load rs from xml


' reconnect to data base
' update
public sub update(table,xmlstr)

' create and load DOM


set xmldom = Server.createObject("MSXML.DOMDocument")

xmldom.loadXML (xmlstr)

' delete xml file


dim fs
set fs = server.CreateObject("Scripting.FileSystemObject")

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

' save DOM as xml


xmldom.save Server.MapPath("parts.xml")

' create and load record set


Set rs = Server.CreateObject("ADODB.RecordSet")
rs.CursorLocation = adUseClient
rs.LockType = adLockBatchOptimistic
rs.open server.MapPath("parts.xml"), ,adOpenKeyset , ,adCmdFile

rs.ActiveConnection = cn ' reconnect to database

rs.updateBatch ' update data base

end sub
' query a record by part number
' return record as xml
public function openWhere(table,field,where)

' create and open record set


Set rs = Server.CreateObject("ADODB.RecordSet")

dim sql

sql = "SELECT * FROM " + table + " where " + field + " = " + where

rs.Open sql,cn,3,1,&H0001

dim xmlstr

' make xml record string if record found


if rs.recordCount = 0 then
xmlstr = "<error>no such part </error>"

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

rs.close ' close record set

openWhere = xmlstr ' return record as xml string

end function

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.
233

' close connection


private sub class_terminate

rs.close
cn.close

end sub

end class

%>

BUSINESS SERVICES MODULE

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.

A XML command may look like this

<action cmd=quantity part=1234>

Customer Tasks

Here is a list of customer tasks we may have to accomplish and the corresponding XML commands
to go with them.

customers action XML example


tasks
query return item record <action cmd='query' part='1234'>
back order number in back order <action cmd='backorder' part='1234' quantity='4'>
buy decrease number <action cmd='buy' part='1234' quantity='3' >
return item increase number <action cmd='return' part='1234' quantity= '5' >

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.

owner tasks action XML example


request return price <action cmd='request' table='parts' />
update return number of parts <action cmd='update' table='parts'> &
xmlDoc.xml & "</action>

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.
234

Here is a list of methods in the business services module tasks.

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.

Set action = xmlDoc.selectSingleNode("action")

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.

Set xmlstr = xmlDoc.selectSingleNode("action/xml")

Here the code for the business services module:

<%
' bs.asp
' business services module

Response.ContentType = "text/xml"
%>

<!-- #include file=xmlDbMgr.asp -->

<%
' create DOM
dim xmlDoc
set xmlDoc = Server.CreateObject("MSXML.DOMDocument")

' get XML Doc from Request object


xmlDoc.async=False ' wait to load
xmlDoc.load Request

</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 '
'''''''''

if cmd = "query" then

set xmldb = new xmlDbMgr

table = action.getAttribute("table")

part = action.getAttribute("part")

xmlstr = xmldb.openWhere (table,"PartNum",part)

response.write xmlstr

'''''''''''
' request '
'''''''''''

elseif cmd = "request" then

table = action.getAttribute("table")]

set xmldb = new xmlDbMgr

set xmlDoc = xmldb.openRS ("parts")

response.write xmlDoc.xml

''''''''''
' update '
''''''''''
elseif cmd = "update" then

table = action.getAttribute("table")

'response.write table
Set xmlstr = xmlDoc.selectSingleNode("action/xml")

set xmldb = new xmlDbMgr

xmldb.update "parts",xmlstr.xml

response.write "<response> table " + table + "</response>"

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.
236

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.

customers action XML example


tasks
query return item record <action cmd='query' part='1234'>
back order number in back order <action cmd='backorder' part='1234' quantity='4'>
buy decrease number <action cmd='buy' part='1234' quantity='3' >
return item increase number <action cmd='return' part='1234' quantity= '5' >

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.

<!-- query.htm -->


<html>
<head>
<title>query.htm</title>
<script language="VBSCRIPT">

' query part and display data


sub query()

dim doc,http,xml

' create XML command use part number from text box
xml="<action cmd='query' table='parts' part='" + number.value + "'/>"

' create a DOM from XML command string


set doc = CreateObject("MSXML.DOMDocument")
doc.loadXML(xml)

' create xmlhttp object and send dom


set http = CreateObject("MSXML2.XMLHTTP")
dim url
url="http://localhost/Lesson15/bs.asp"
http.open "post",url,False
http.send(doc)

' wait for response


doc.loadXML(http.responseText)

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.
237

' report arror or received item in text boxes


If not(isObject(doc)) then
msgbox "no response received"
ElseIf doc.documentElement.nodeName = "error" then
clear()
msgbox doc.documentElement.text, , "Error"
Else
clear()
dim part
set part = doc.selectSingleNode("parts/part")
number.value=part.getAttribute("PartNum")
desc.value=part.getAttribute("Description")
qty.value=part.getAttribute("Qty")
price.value=part.getAttribute("Price")
bo.value=part.getAttribute("BackOrder")
delivery.value=part.getAttribute("DeliveryDate")
End if

End Sub

' clear text boxes


sub clear()

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>

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.
238

<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" ONCLICK="query()">
</td>
<td><input type="button" value="Clear" name="B2" ONCLICK="clear()"> </td>
</tr>
</table>

</body>
</html>

Operation would look like this:

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.
239

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.

owner tasks action XML example


request return price <action cmd='request' table='parts' />
update return number of parts <action cmd='update' table='parts'> &
xmlDoc.xml & "</action>

Here is the form code for the Customer terminal

' Customer terminal code


Dim rs As New Recordset ' common record set

' add record


Private Sub CommandAdd_Click()
rs.AddNew
End Sub

' update record set at any time


Private Sub CommandUpdate_Click()
rs.Update
End Sub

' get all records from data base and display in DataGrid
Private Sub Form_Load()

' create XMLHTTPRequest object


Dim xmlHttp As New XMLHTTPRequest
Dim xmlDoc As New MSXML.DOMDocument

Dim request As String

' request URL


request = "http://localhost/Lesson15/BS.asp"

' open http connection


xmlHttp.Open "POST", request, False

' send request as xml


xmlHttp.send ("<action cmd='request' table='parts' />")

' get response as xml document string


Dim strxml
strxml = xmlHttp.responseText

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.
240

xmlDoc.loadXML strxml

MsgBox xmlDoc.xml, , "xmldoc object received"


xmlDoc.Save App.Path & "/Lesson15.xml"

' convert xml document to a record set


rs.CursorType = adOpenKeyset
rs.LockType = adLockBatchOptimistic
rs.CursorLocation = adUseClient
rs.Open App.Path & "/Lesson15.xml", "Provider = MSPersist"

' display xml document


Set DataGrid1.DataSource = rs

End Sub

Private Sub Form_Unload(Cancel As Integer)

' create XMLHTTPRequest object


Dim xmlHttp As New XMLHTTPRequest
Dim xmlDoc As New MSXML.DOMDocument

rs.Update

' convert rs to DOM


'save the recordset as an XML file
Kill "Lesson15.xml"

rs.Save "Lesson15.xml", adPersistXML

'read in the XMLfile to a dom


xmlDoc.Load "Lesson15.xml"

Dim request As String

' send request


Dim strmsg As String
strmsg = "<action cmd='update' table='parts'>" & xmlDoc.xml & "</action>"

' request URL


request = "http://localhost/Lesson15/BS.asp"

' open connection


xmlHttp.Open "POST", request, False
xmlHttp.send strmsg

' get response as xml documents


Dim strrsp
strrsp = xmlHttp.responseText

MsgBox strrsp, , "respose from web"


End Su
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.
241

The form would look something like this:

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.

ASP LESSON15 EXERCISE 4

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!

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.
242

ASP PROGRAMMERS GUIDE LESSON 16

File: aspGuideL16.doc
Date Started: Jan 21, 2003
Last Update: June 7, 2003
Version: 0.0
ISBN: 0-9730824-3-7

SOAP SIMPLE OBJECT ACCESS PROTOCOL

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.

protocol Name language platform


COM Component Object Model independent Microsoft Windows
DCOM Distributed COM independent Microsoft Windows
IIOP Internet Inter-ORB Protocol independent independent
CORBA Common Object Request Broker independent independent
RMI Remote Method Invocation Java independent
SOAP Simple Object Access Protocol independent independent

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.

ASP Page WEB or ASP Page


request to call a function
ASP code

send back result from function

Some
Function

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.
243

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.

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.
244

open (bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword)


Initializes an MSXML2.XMLHTTP request and specifies the method, URL, and authentication
information for the request.

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

We will demonstrate RPC 3 different ways

(1) receiving XML

(2) receiving and sending xml

(3) using SOAP envelops

An Envelope is just a fancy term using nested XML tags.

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.
245

RPC Receiving XML

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")

On Error Resume Next

dim c
c = (cdbl(temp) * 9) / 5 + 32

if Err.number <> 0 then

response.write "<error>Invalid temperature</error>"

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:

The first 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.

On Error Resume Next

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.
246

Then we do the conversion, this is the standard Centigrade to Fahrenheit formula

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.

If Err.number <> 0 Then

Response.write "<error>Invalid temperature</error>"

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>

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.
247

ASP LESSON 16 EXERCISE 1

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.

SENDING XML TO ASP PROGRAM

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

Set requestXML = Server.CreateObject("MSXML.DOMDocument")


requestXML.load Request

Dim temp

if not(isobject (requestXML)) then

response.write "<error>no temperature received </error>"

else

On Error Resume Next

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 "<error>Invalid temperature</error>"


else

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"

and we add a header called SOAPAction

Response.AddHeader "SOAPAction", "fahrenheit"

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

Set requestXML = Server.CreateObject("MSXML.DOMDocument")


requestXML.load Request

If we can not load a xml object then we send back an error message.

if not(isobject (requestXML)) then

response.write "<error>no temperature received </error>"

Else we get the temperature from the convert/centigrade node element.

temp = requestXML.selectSingleNode("/convert/centigrade").text

We then calculate the temperature using the Fahrenheit to centigrade formula:

c = (cdbl(temp) * 9) / 5 + 32

If we get an error or if it is not a SOAP header then we report an error

if Err.number <> 0 or Request.ServerVariables("HTTP_SOAPAction") <> "convert" then

response.write "<error>Invalid temperature</error>"

Else we send back the temperature as XML as before.

response.write "<centegrade>"&c&"</centegrade>"

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.
249

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.

<!-- aspL16P2.htm -->


<html>
<head>
<title>temperature.htm</title>
<script language="VBSCRIPT">

function sendit()

dim doc,http,xml

xml="<convert><centigrade>"+temp.value+"</centigrade></convert>"

set doc = CreateObject("MSXML.DOMDocument")


doc.loadXML(xml)

set http = CreateObject("MSXML2.XMLHTTP")


dim url
url="http://localhost/Lesson16/aspL16p2.asp"

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>

<p>What temperature is it? <input type="text" id="temp" name="Temp"


size="10"></p>

<p><input type="button" value="Send" name="B1" ONCLICK="sendit()">


<input type="reset"
value="Reset" name="B2"></p>
</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.
250

This is how the HTML program works.

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>"

set doc = CreateObject("MSXML.DOMDocument")


doc.loadXML(xml)

Next we create a xmlHTTP object and send the XML document to the ASP programs using POST.

set http = CreateObject("MSXML2.XMLHTTP")


dim url
url="http://localhost/Lesson16/aspL16p2.asp"

http.open "post",url,False
http.setRequestHeader "SOAPAction","convert"
http.send(doc)

We then wait for the response from the ASP pogrom.

set doc = http.responseXML

We now check if we have received an HTML document.

if not(isobject(doc)) then
document.write "no response received"'

or received an error

elseif doc.documentElement.nodeName = "error" then


document.write "invalid temperature passed"

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>

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.
251

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()

We would receive something like this

Server: Microsoft-IIS/4.0 Date: Mon, 09 Jun 2003 17:41:00 GMT


SOAPAction: fahrenheit
Content-Type: text/xml
Cache-control: private Transfer-Encoding: chunked

Program Operation would be like this:

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.
252

ASP LESSON16 EXERCISE 2

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.

ASP LESSON16 EXERCISE 3

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.

Soap uses 3 main tag elements:

(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/'>

We have declared the SOAP-ENV name space

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>

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.
253

Header

The header is used to store authentication information. In our example we do not use a header
element.

SOAP Element transmission

Here is our SOAP Envelope we send to the ASP program

<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.

<!-- aspL16p3.htm -->


<html>
<head>
<title>temperature.htm</title>
<script language="VBSCRIPT">

function sendit()

dim doc,http,xml

xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV="


xml = xml & "'http://schemas:xmlsoap.org/soap/envelope/'>" & vbcrlf
xml = xml & "<SOAP-ENV:Body>" & vbcrlf
xml = xml & "<ct:convertTemperatureDetail "
xml = xml & "xmlns:ct='http://localhost/Lesson16/convertTemp/'>" & vbcrlf
xml = xml & "<ct:temperature>"+temp.value+"</ct:temperature>" & vbcrlf
xml = xml & "</ct:convertTemperatureDetail>" & vbcrlf
xml = xml & "</SOAP-ENV:Body>" & vbcrlf
xml = xml & "</SOAP-ENV:Envelope>"

set doc = CreateObject("MSXML.DOMDocument")


doc.loadXML(xml)

set http = CreateObject("MSXML2.XMLHTTP")


dim url
url="http://localhost/Lesson16/aspL16p3.asp"

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>

<p>What temperature is it? <input type="text" id="temp" name="Temp"


size="10"></p>

<p><input type="button" value="Send" name="B1" ONCLICK="sendit()"> <input


type="reset"
value="Reset" name="B2"></p>
</body>
</html>

We make a SOAP Element and send to the ASP Program:

dim doc,http,xml

xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV="


xml = xml & "'http://schemas:xmlsoap.org/soap/envelope/'>" & vbcrlf
xml = xml & "<SOAP-ENV:Body>" & vbcrlf
xml = xml & "<ct:convertTemperatureDetail "
xml = xml & "xmlns:ct='http://localhost/Lesson16/convertTemp/'>" & vbcrlf
xml = xml & "<ct:temperature>"+temp.value+"</ct:temperature>" & vbcrlf
xml = xml & "</ct:convertTemperatureDetail>" & vbcrlf
xml = xml & "</SOAP-ENV:Body>" & vbcrlf
xml = xml & "</SOAP-ENV:Envelope>"

set doc = CreateObject("MSXML.DOMDocument")


doc.loadXML(xml)

set http = CreateObject("MSXML2.XMLHTTP")


dim url
url="http://localhost/Lesson16/aspL16p3.asp"

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

Received soap message

The received soap message will be quite different the sent soap message, we have some additional
elements.

FAULT

A fault element sends back a fault message

<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:

fault code description


VersionMismatch a different SOAP protocol name space has been specified
MustUnderstand the soap message contained a header that was not understood
Client client sent a bad soap envelope
Server server could not process the SOAP message

The faultstring element contains a string describing the error.

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.

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.
256

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

if Err.number <> 0 or Request.ServerVariables("HTTP_SOAPAction") <> _


"http://localhost/Lesson16/convertTemperature#convertTemperature" then
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 "<SOAP-ENV:Fault>" & vbcrlf
response.write "<faultcode>soap:client</faultcode>" & vbcrlf
response.write "<faultstring>" & "soap:invalid temperature" & "</faultstring>" & vbcrlf
response.write "<faultfactor>http://localhost/Lesson16/aspL16p3.asp</faultfactor>"
response.write vbcrlf & "<detail>" & vbcrlf
response.write "<ct:convertTemperatureDetail "
response.write "xmlns:ct='http>//localhost/Lesson16/convertTemp/'>" & vbcrlf
response.write "<ct:temperature>temperature</ct:temperature>" & vbcrlf
response.write "</ct:convertTemperatureDetail>" & vbcrlf
response.write "</detail>" & vbcrlf
response.write "</SOAP-ENV:Fault>" & vbcrlf
response.write "</SOAP-ENV:Body>" & vbcrlf
response.write "</SOAP-ENV:Envelope>" & vbcrlf

' 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

Operation would be something like this:

Here is the operation:

We first create a xmlDocument from the received XML object.

Dim requestXML
Set requestXML = Server.CreateObject("MSXML.DOMDocument")
requestXML.load Request

We extract the temperature travelling into the dom document.

Dim temperature
temperature = requestXML.documentElement.firstChild.firstChild.firstChild.text

and then attempt the temperature conversion.

dim c
c = (cdbl(temperature) * 9) / 5 + 32

We check for conversion error or no SOAPAction header received.

if Err.number <> 0 or Request.ServerVariables("HTTP_SOAPAction") <> _


"http://localhost/Lesson16/convertTemperature#convertTemperature" then

We now either report the error or send back the converted temperature. In either case we send back
a SOAP envelope.

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.
258

Error SOAP envelope sent

<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>

non-error soap envelope sent

<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>

ASP LESSON 16 EXERCISE 4

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.

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.
259

ASP PROGRAMMERS GUIDE LESSON 17

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.

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.
260

What are the steps to build this project?

[1] Define all data base tables

[2] Define all ASP pages

[3] Define all Classes

[4] designate XML areas

[5] Draw an operations block diagram

[6] Start coding

[7] debug and test

[1] data base tables

What data base tables are we going to need?

(1) Products

(2) Categories

(3) Customers

(4) Orders

(1) Products table

What do product fields do we need?

Number product identification number


Name product name
Description description of product
Price price of product
Quantify number of products sold

Just make a simple table.

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:

name description image file price


boats1 smallest boat in the world boats1.gif 29.95
flower1 bright flower flowr1.jpg 15.35
ship2 largest ship in the world shiop2.jpg 17.89
street main street of San Francisco street.jpg 33.67

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.
261

From the above table it is quite obvious we have some categories:

• boats
• flowers
• Streets

(2) Categories table

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

Our product table will now have a category field:

item category description image file price


boats1 boat smallest boat in the world boats1.gif 29.95
flower1 flower bright flower flowr1.jpg 15.35
ship2 boat largest ship in the world shiop2.jpg 17.89
street city main street of San Francisco street.jpg 33.67

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.

(3) Customer table

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

(1) Customer number


(2) Phone number
(3) Email address
(4) Name

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.

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.
262

Here is the Customer table:

custID Name Address Phone EMail


1 John Smith 42 Universe Avenue 967-1111 js@world.com
2 Bill Smith 20 Nowhere Street 875-6543 bill@internet.com
3 George Smith 16 Maple Syrup Lane 654-7654 gsmith@turbo.net
4 Mary Smith 35 Watch Blvd 212-7654 msmith@turbo.net

(3) Orders table

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.

item custID payment date


flower1 1 cc Jan 4, 2003
boat2 2 cc Jan 4, 2003
street1 3 cc Jan 5, 2003
ship1 2 cc Jan 6, 2003

TABLE RELATION SHIPS

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

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.
263

[2] DEFINE ALL ASP PAGES

What does a customer have to do ?

• view items for sale


• select items to buy
• purchase items
• download item or wait for shipment

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.

page file name purpose


home default.asp display items for sale
order order.asp order confirmation
purchase cc.asp pay for order by credit card
thankyou download.asp acknowledge and download order

(1) home page

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,

(2) 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.

(3) Credit card processor

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.

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.
264

(4) Thankyou 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. 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

<form action="mailto:js@internet.net?subject=order confirmation&body=data


enctype=text">
<input type="hidden" name="item" value="<%=item%>">
</form>

If they are to download something you supply as download button or a link where they can
download the goods

[3] Define all Classes

(1) Data Manager class

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.

(2) Shopping Cart and Item class

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.

[4] Designate XML areas

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

E-Mail all attached files of your completed exercises to:

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

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.
266

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.

You might also like