Академический Документы
Профессиональный Документы
Культура Документы
C
h
Introduction to ASP
ASP stands for Active Server Pages. ASP is primarily a scripting environment. You can integrate
scripts created with both JScript and VBScipt into your ASP. ASP in itself isnt a language actually;
instead it uses Vbscript or JavaScript to display dynamic content. ASP is more of a technology
used by vbscript / JScript on the server side.
p
t
Active Server Pages makes it possible for Web developers to write scripts that execute on the
server in variety of scripting languages. In fact, several scripting languages can be used within a
single .asp file. In addition, because scripts are read and processed on the server-side, the browser
that requests the .asp file does not need to support scripting.
Client Side Scripting Languages
Client Side Scripting Languages are included within the HTML for a web page using the <script>
tag. Essentially a Client Side Script functions as a small program (in source code form) that is
interpreted (run) by the web browser once the page has loaded. Client side scripts can be very
powerful because they can allow HTML code to include real programming constructs such as
repetition and selection.
Process
Request
Response
Client Side (Browser)
Display only HTML Tags
Web Server
There are three significant Client Side scripting languages. VBScript, JavaScript and JScript.
2
Process
Response
Client Side (Browser)
Display only HTML Tags
Web Server
Execute Server Side Script
We will assume here that you are not familiar with vbscript, the language of choice for creating.asp
pages. So we will also give you a little insight into vbscript too.
If you are running windows then you can download Personal Web Server (for Win95 & Win98) or
Internet Information Server (for WinNT) from www.microsoft.com. If you are running Windows
2000 then you have got IIS 5 already, you just need to install it. Just go to the control panel and
click the Add/Remove Programs icon. Then on the left click the Add/Remove Windows
Components button, a window will appear offering you a lot of choices. Just check where Internet
Information Services is written and click Next, your IIS 5 will be installed.
For those who are using other operating systems please take a look at www.chilisoft.com. They
offer ASP solution for those who are not running Microsoft Windows. Please note that chilisoft
products are not free but you can download PWS or IIS free of cost from Microsofts web site
above.
Softwares
NT - Server (v4)
NT - Workstation (v4)
Windows 95/98
Windows 2000
System Requirements
Microsoft Windows NT Server 4.0
Computer/Processor
Memory
16 MB of memory (RAM)
Hard Disk
Drive
CD-ROM drive
Display
Computer/Processor
Memory
Hard Disk
Drive
Display
Peripherals
Miscellaneous
Minimum Requirements
Computer/Processor
Memory
Hard Disk
CPU Support
Advantage of ASP
1. Dynamically edit, change or add any content of a Web page.
2. Respond to user queries on data submission from HTML forms.
3. Access any data or databases and return the results to a browser
4. Customize a Web page to make it more useful for individual users.
5.The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed.
6. Provides security since your ASP code cannot be viewed from the browser.
7. Since ASP files are returned as plain HTML, they can be viewed in any browser.
8. Clever ASP programming can minimize the network traffic.
It is advisable you to accept the defaults when it comes to giving the location as to where the
inetpub and wwwroot directories should be installed.
5
While Selecting components you will see the following desktop image.
After the installation of PWS, you will find a PWS icon on your desktop and probably a PWS
small icon in the tray on the right lower corner of your desktop too. Double click any of them to
bring up the PWS control window.
If the PWS is already running then you will see an option Stop PWS. But if PWS has been
stopped and is not running then you will see the option to Start PWS.
Since we want to check that PWS has installed successfully and everything is running optimally,
you should start the PWS if it is not already running. If it has started on its own then you will see
the Stop Button
Ok, now we want to check if PWS is running correctly and Active Server Pages are running or
can be run.Open your Internet browser e.g. Microsoft Internet Explorer. In the URL address type
http://127.0.0.1 and press enter. If all is well then you will see a default page generated by PWS.
If you can see some page then PWS is running correctly and we are done. But if PWS is running
and you cannot see any page by entering the above URL then you need to restart your computer
,start PWS again and then open your browser and Write the URL as explained above.
Note that to see .asp pages you have to open them in browser with the http protocol. You have
to append the url as http://127.0.0.1/ or http://localhost before the page name and address to see
it running on your own local computer.
Installation of IIS
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
We can edit and view Web site property by right clicking the we site name (Default Web Site) and
clicking properties. On Clicking the properties you will see tab with different properties
Language Supported
Setting the Primary Scripting Language
The ASP primary scripting language is the language used to process commands inside the <% and
%> delimiters. By default, the primary scripting language is VBScript. You can use any scripting
language for which you have a script engine as the primary scripting language. You can set the
primary scripting language on a page-by-page basis, or for all pages in an ASP application.
10
11
response.write
Meaning
Start ASP
End ASP
Comment tag
Print to the browser
Note: All ASP pages must be named .asp (or .ASP) by default. If not, the web server will not
parse the file to find the ASP coding.
Now that youve created this ASP script, and we will see in the browser. something like this:
If you right click and view the source of the page displayed, you will note that the browser never
receives any of the comments, nor the ASP code. The browser will only receive the content it is
told to print to the browser using the response.write command.
<% @ Language=VBScript %>
This line tells the ASP code parser that we will be using VBScript to write code in this .asp page.
If you want to use JScript or PerlScript then you might add JScript or PerlScript as the case may
be in place of VBScript (provided that you have script engine for them)
Including Comments
Because the processing of all scripts in ASP is done on the server side, there is no need to include
HTML comment tags to hide the scripts from browsers that do not support scripting, as is often
done with client-side scripts. All ASP commands are processed before content is sent to the
browser. You can use HTML comments to add remarks to an HTML page; comments are returned
to the browser and are visible if the user views the source HTML.
VBScript Comments
Apostrophe-style comments are supported in VBScript. Unlike HTML comments, these are
removed when the script is processed and are not sent to the browser.
<%
These two lines are comments.
The Staement below writes to the browser
Respose.Write(This is the Line Which comes to your
Browser)
%>
13
You cannot include a comment in an output expression. For example, the first line that follows will
work, but the second line will not, because it begins with <%=.
<% i = i +1 This statement increments i. (This script will work.) %>
<%= name This statement prints the variable name. (This script will fail.) %>
JScript Comments
The // comment characters are supported in JScript. These characters should be used on each
comment line.
<%
var x
x = new Date()
// This line sends the current date to the browser,
// translated to a string.
Response.Write(x.toString())
%>
Case Sensitivity
VBScript is not case sensitive. For example, you can use either Request or request to refer to the
ASP Request object. One consequence of case-insensitivity is that you cannot distinguish variable
names by case. For example, you cannot create two separate variables named Color and color.
JScript is case sensitive. When you use JScript keywords in scripts, you must type the keyword
exactly as shown in the reference page for that keyword. For example, using date instead of Date
will cause an error.
<HTML>
<BODY>
<%
response.Write(This is areallllllllllyy _
BigggggggggggStateement!!!!!!!)
%>
</BODY>
</HTML>
:
:
:
:
:
When a browser requests a HTML file to a server specifying the file it wants
The Asp.dll does some initial Processing on the requested page.
The Scripting engine executes the instruction in the script .
Server translates the executed Script code into HTML pages
The HTML is sent back to the web browser which displays the page
H T T P R eq u est
S crip tin g E n g in e
E x ecu tio n
A sp .d ll
P re p ro c essin g
T ra n slatio n to
HTM L
H T T P R esp o n se
You cannot view server side scripts in a browser; you can view only plain HTML. This is because
the scripts are executed on the server before the result is sent to the browser
15
ASP Variables
-
16
ASP Variables
A variable is a place keeper for a piece of text, or binary code. The data contained in a variable
is called the variables value. Variables give you a way to store, retrieve, and manipulate values
using names that help you understand what it does within the script.
Description
Empty
Variant is uninitialized. Value is either 0 for numeric variables or a zerolength string () for string variables.
Null
Boolean
17
Byte
Integer
Currency
-922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long
Single
Contains a single-precision, floating-point number in the range 3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to
3.402823E38 for positive values.
Double
Contains a double-precision, floating-point number in the range 1.79769313486232E308 to -4.94065645841247E-324 for negative
values; 4.94065645841247E-324 to 1.79769313486232E308 for
positive values.
Date (Time)
String
Object
Contains an object.
Error
VBScript
To declare a variable in VBScript, use the Dim, Public, or Private statement. Variables declared
with Dim at the script level are available to all procedures within the script. At the procedure
level, variables are available only within the procedure. You can also use the Dim statement with
empty parentheses to declare a dynamic array. You declare multiple variables by separating each
variable name with a comma. For example:
Dim Length,Width,Height
Public statement variables are available to all procedures in all scripts. A variable that refers to an
object must be assigned an existing object using the Set statement before it can be used. Until it is
assigned an object, the declared object variable is initialized as Empty.
Public MyNumber
Public Variant variable.
Public MyArray(9) Public array variable.
Private statement variables are available only to the script in which they are declared
18
Private Length
Private Variant variable.
Private Students(9)
Private array variable.
We will discuss about ReDim statement in the arrays section
Option Explicit
The Option Explicit statement must appear after any ASP directives and before any HTML text or
script commands. This statement only affects ASP commands that are written in VBScript; it has
no effect on JScript commands. When you use the Option Explicit statement, you must explicitly
declare all variables using the Dim, Private, Public, or ReDim statements. If you attempt to use
an undeclared variable name, an error occurs.
<% Option Explicit %>
<HTML>
<%
Dim MyVar
Declare variable.
MyInt = 10 Undeclared variable generates error.
MyVar = 10 Declared variable does not generate error.
%>
For more information on these commands, see the VBScript Language Reference, which can be
found at the Microsoft Windows Script Technologies Web site, located at http://
msdn.microsoft.com/scripting/.
Variable in JScript
<% var UserName %>
Typically, you will only need to declare a variable in JScript when you need to distinguish a variable
inside a function from a global variable used outside the function. In this case, if you do not
distinguish between the two variables, JScript will assume that that you referring exclusively to the
global variable. For more information on the var statement, see the JScript Language Reference.
You can find this reference at the Microsoft Windows Script Technologies Web site, located at
http://msdn.microsoft.com/scripting/.
Variable Scope
The scope, or lifetime, of a variable determines which script commands can access a variable. A
variable declared inside a procedure has local scope; the variable is created and destroyed every
time the procedure is executed. It cannot be accessed by anything outside the procedure. A variable
declared outside a procedure has global scope; its value is accessible and modifiable by any
script command on an ASP page.A variable declared outside a procedure, could be accessed and
changed by any script in the ASP page where it is declared.
A variable declared inside a procedure, is created and destroyed every time the procedure is
executed. No scripts outside that specific procedure can access or change that variable.
Note Limiting variable scope to a procedure will enhance performance.
19
If you declare variables, a local variable and a global variable can have the same name. Modifying
the value of one will not modify the value of the other. If you do not declare variables, however,
you might inadvertently modify the value of a global variable. For example, the following script
commands return the value 1 even though there are two variables named Y:
<%
Option Explicit
Dim Y
Y = 1
SetLocalVariable
Response.Write Y
Sub SetLocalVariable
Dim Y
Y = 2
End Sub
%>
The following script commands, on the other hand, return the value 2 because the variables are
not explicitly declared. When the procedure call sets Y to 2, the scripting engine assumes the
procedure intended to modify the global variable:
<%
Y = 1
Set Local Variable
Response.Write Y
Sub SetLocalVariable
Y = 2
End Sub
%>
To avoid problems, develop the habit of explicitly declaring all variables. This is particularly
important if you use the #include statement to include files into your .asp file. The included script
is contained in a separate file but is treated as though it were part of the including file. It is easy to
forget that you must use different names for variables used in the main script and in the included
script unless you declare the variables.
Prefix
Integer
Single
sng
Double
dbl
String
str
Date
dt
Boolean
bol
Currency
cur
Object
obj
Constants
Constants are used to assign a value, which cannot be changed. It is suggested that use all capital
letters to refer to constants to help distinguish them from your variables.
VBScript Constant
VBScript has several constant build into it. These constants could be classified as :
Color Constant
Since these constants are built into VBScript, you dont have to define them before using them.
Use them anywhere in your code to represent the values shown for each.
Constant
Value
Description
vbBlack
&h00
Black
vbRed
&hFF
Red
vbGreen
&hFF00
Green
vbYellow
&hFFFF
Yellow
vbBlue
&hFF0000
Blue
vbMagenta &hFF00FF
Magenta
vbCyan
&hFFFF00
Cyan
vbWhite
&hFFFFFF
White
21
Comparison Contants
Constant
Value
Description
vbBinaryCompare
vbTextCompare
Value
Description
vbSunday
Sunday
vbMonday
Monday
vbTuesday
Tuesday
vbWednesday
Wednesday
vbThursday
Thursday
vbFriday
Friday
vbSaturday
Saturday
vbUseSystem
vbUseSystemDayOfWeek
vbFirstJan1
vbFirstFourDays
vbFirstFullWeek
Value
Description
vbGeneralDate
vbLongDate
22
vbShortDate
vbLongTime
vbShortTime
String Constant
Constant
Value
Description
vbCr
Chr(13)
Carriage return.
vbCrLf
Chr(13)
& Chr(10)
vbFormFeed
Chr(12)
vbLf
Chr(10)
Line feed.
vbNewLine
vbNullChar
Chr(0)
vbNullString
vbTab
Chr(9)
Horizontal tab.
vbVerticalTab
Chr(11)
Constant
Value
Description
vbUseDefault
-2
vbTrue
-1
True
vbFalse
False
TriState Constant
23
VarType constants
Constant
Value
Description
vbEmpty
Uninitialized (default)
vbNull
vbInteger
Integer subtype
vbLong
Long subtype
vbSingle
Single subtype
vbDouble
Double subtype
vbCurrency
Currency subtype
vbDate
Date subtype
vbString
String subtype
vbObject
Object
vbError
10
Error subtype
vbBoolean
11
Boolean subtype
vbVariant
vbDataObject
12
13
vbDecimal
14
Decimal subtype
vbByte
17
Byte subtype
vbArray
8192
Array
Arrays
Array is used to store a series of related items. To declare an array we use DIM keywords as we
use in Variables. Difference between a simple variable and array is that we have to specify the size
of an array. It is like that
<%
Dim ArrayName(5)
%>
The above Statement will declare an array of 6 elements, which can store 6 values. To retrieve the
value of each element we use index No. Index Number is always start with 0 known as Lower
bound and ends with one less the size of arrays known as upper bound.
24
25
VBScript Operator
Types of Operators
- Assignment Operator
- Arithmatic Operator
- Comparison Operator
- Logical Operator
- Concation Operator
26
VBScript Operator
WHAT is OPERATOR
Operators are some of the mostly used symbols like *,+ etc which help us to combine, modify or
replace our data types:
TYPES OF OPERATOR
Assignment Operators
Arithmatic Operator
Comparison
Logical
Assignment Operators
= Operator
Assigns a value to a variable or property
Syntax
variable = value
The = operator syntax has these parts:
Part
Variable
Value
Description
Any variable or any writable property.
Any numeric or string literal, constant , or expression .
The name on the left side of the equal sign can be a simple scalar variable or an element of an
array. Properties on the left side of the equal sign can only be those properties that are writable at
run time.
Arithmatic Operators
+ Operator
Sums two numbers.
Syntax
result = expression1 + expression2
27
Description
Any numeric variable.
Any expression .
Any expression.
Although you can also use the + operator to concatenate two character strings, you should use the
& operator (discussed later) for concatenation to eliminate ambiguity and provide self-documenting
code.
When you use the + operator, you may not be able to determine whether addition or string
concatenation will occur.
The underlying subtype of the expressions determines the behavior of the + operator in the following
way:
If
Both expressions are numeric
Both expressions are strings
One expression is numeric and the other is a string
Then
Add.
Concatenate.
Add.
If one or both expressions are Null expressions, result is Null. If both expressions are Empty,
result is an Integer subtype. However, if only one expression is Empty, the other expression is
returned unchanged as result.
- Operator
Finds the difference between two numbers or indicates the negative value of a numeric expression.
Syntax 1
result = number1-number2
Syntax 2
- number
The - operator syntax has these parts:
Part
Result
Number
Number1
Number2
Description
Any numeric variable.
Any numeric expression .
Any numeric expression.
Any numeric expression.
Remarks
In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between
two numbers. In Syntax 2, the - operator is used as the unary negation operator to indicate the
negative value of an expression.
28
If one or both expressions are Null expressions, result is Null. If an expression is Empty , it is
treated as if it were 0.
^ Operator
Raises a number to the power of an exponent.
Syntax
result = number^exponent
The ^ operator syntax has these parts:
Part
Result
Number
Exponent
Description
Any numeric variable.
Any numeric expression .
Any numeric expression.
Remarks
Number can be negative only if exponent is an integer value. When more than one exponentiation is performed
in a single expression, the ^ operator is evaluated as it is encountered from left to right.
If either number or exponent is a Null expression, result is also Null.
* Operator
Remarks
If one or both expressions are Null expressions, result is Null. Any expression that is Empty is
treated as 0.Multiplies two numbers.
Syntax
result = number1*number2
The * operator syntax has these parts:
Part
Result
Number1
Number2
Description
Any numeric variable.
Any numeric expression.
Any numeric expression.
/ Operator
Divides two numbers and returns a floating-point result.
Syntax
result = number1/number2
The / operator syntax has these parts:
29
Part
Result
Number1
Number2
Description
Any numeric variable.
Any numeric expression .
Any numeric expression.
Remarks
If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is
treated as if it were 0.
MOD Operator
Divides two numbers and returns only the remainder.
Syntax
result = number1 Mod number2
The Mod operator syntax has these parts:
Part
Result
Number1
Number2
Description
Any numeric variable.
Any numeric expression
Any numeric expression.
Remarks
The modulus, or remainder, operator divides number1 by number2 (rounding floating-point
numbers to integers) and returns only the remainder as result. For example, in the following
expression, A (which is result) equals 2.
A = 17 Mod 5
If any expression is Null result is also Null. Any expression that is Empty is treated as 0.
Comparison Operator
Is Operator
Used to compare expressions.
Syntax
result = expression1 comparisonoperator expression2
result = object1 Is object2
Comparison operators have these parts:
Part
Result
Description
Any numeric variable.
30
Expression
Comparison operator
Object
Any expression.
Any comparison operator.
Any object name.
Remarks
The Is operator has specific comparison functionality that differs from the operators in the following
table. The following table contains a list of the comparison operators and the conditions that
determine whether result is True, False, or Null :
Operator Description
<
<=
>
>=
=
<>
Less than
Less than or equal
Greater than
Greater than or equal
Equal
Not equal
True if
False if
Null if
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
e1
< e2
<= e2
> e2
>= e2
= e2
<> e2
>= e2
> e2
<= e2
< e2
<> e2
= e2
or e2
or e2
or e2
or e2
or e2
or e2
= Null
= Null
= Null
= Null
= Null
= Null
When comparing two expressions, you may not be able to easily determine whether the expressions
are being compared as numbers or as strings. The following table shows how expressions are
compared or what results from the comparison, depending on the underlying subtype:
If
Then
Logical Operator
AND Operator
Performs a logical conjunction on two expressions.
Syntax
result = expression1 And expression2
The And operat or syntax has these parts:
Part
Result
Description
Any numeric variable.
31
Expression1
Expression2
Any expression.
Any expression.
Remarks
If, and only if, both expressions evaluate to True, result is True. If either expression evaluates to
False, result is False. The following table illustrates how result is determined:
If expression1 is
True
True
True
False
False
False
Null
Null
Null
And expression2 is
True
False
Null
True
False
Null
True
False
Null
The result is
True
False
Null
False
False
False
Null
False
Null
The And operator also performs a bitwise comparison of identically positioned bits in two numeric
expressions and sets the corresponding bit in result according to the following table:
If bit in expression1 is
0
0
1
1
NOT Operator
Performs logical negation on an expression.
Syntax
result = Not expression
The Not operator syntax has these parts:
Part
Result
expression
Description
Any numeric variable.
Any expression.
Remarks
The following table illustrates how result is determined:
If expression is
True
Then result is
False
32
False
Null
True
Null
In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit
in result according to the following table:
Bit in expression
0
1
Bit in result
1
0
In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit
in result according to the following table:
Bit in expression
0
1
Bit in result
1
0
OR Operator
Performs a logical disjunction on two expressions.
Syntax
result = expression1 Or expression2
The Or operator syntax has these parts:
Part
Result
expression1
expression2
Description
Any numeric variable.
Any expression.
Any expression.
Remarks
If either or both expressions evaluate to True, result is True. The following table illustrates how
result is determined:
If expression1
True
True
True
False
False
False
Null
Null
Null
isAnd expression2
True
False
Null
True
False
Null
True
False
Null
isThen result is
True
True
True
True
False
Null
True
Null
Null
The Or operator also performs a bitwise comparison of identically positioned bits in two numeric
33
expressions and sets the corresponding bit in result according to the following table:
If bit in expression1 is
0
0
1
1
Then result is
0
1
1
1
XOR Operator
Performs a logical exclusion on two expressions.
Syntax
result = expression1 Xor expression2
The Xor operator syntax has these parts:
Part
Result
expression1
expression2
Description
Any numeric variable.
Any expression.
Any expression.
Remarks
If one, and only one, of the expressions evaluates to True, result is True. However, if either
expression is Null , result is also Null. When neither expression is Null, result is determined
according to the following table:
If expression1
True
True
False
False
isAnd expression2 is
True
False
True
False
Then result is
False
True
True
False
The Xor operator also performs a bitwise comparison of identically positioned bits in two numeric
expressions and sets the corresponding bit in result according to the following table:
If bit in expression1 is
0
0
1
1
0
1
0
1
Concatenation Operator
& Operator
34
0
1
1
0
Description
Any variable.
Any expression.
Any expression.
Remarks
Whenever an expression is not a string, it is converted to a String subtype. If both expressions
are Null, result is also Null. However, if only one expression is Null, that expression is treated as
a zero-length string () when concatenated with the other expression. Any expression that is
Empty is also treated as a zero-length string.
Eg. Hello & World becomes HelloWorld
35
Control Structure
- Condition Logic
- Looping Logic
- Braching Logic
Typecasting of Variables
- Math Function
- Date Time Function
- String Function
Sub Procedures & Function Procedures
36
Control Structure
A control Structure is a programming structure that allows your program to make decisions
based on he information it is given. A Control Structure primarily is decision-making block given
with set of statements
Using control structures, you can control the flow of your programs execution. If left unchecked
by controlflow statements, a programs logic will flow through statements from left to right, and
from top to bottom. Although you can write very simple programs with only this unidirectional
flow, and although you can control a certain amount of flow by using operators to regulate
precedence of operations, most of the power and utility of any programming language comes from
its ability to change statement order with structures and loops.
Conditional Logic
This type of structure is used when you have to check a particular condition occurs from a set of
conditions such type of structure uses IF..ThenELSE ,Selct Case kind of syntaxes
Looping Logic
This type of structure is used when you have to check for the given condition no of times (iteratively)
within a programming block such type of structure uses Do WHILE.LOOP,FOR ..NEXT kind
of syntaxes.
Branching Logic
This type of structure is used when you have to use function and subroutines. It is useful when
particular section of code has to used several l times ,then these blocks of code can be written in
function or subroutines which increases readability and helps in maintainence.
Control Statement
If.... Then...Else
If.... Then...Else instructions sequence is very similar to the one we may find in different kind of
scripting languages. Lets check an example.
37
<%
AA=coffee
If AA=water Then
response.write (I want to drink coffee )
Else
response.write (I want to drink tea)
End If
%>
We may use it this way:
<%AA=water
If AA=water Then %>
I want to drink water
<% Else %>
I want to drink milk
<% End If %>
In both cases we have checked a condition (AA=water),and we have get a positive instruction
(to write the sentence I want to drink water). We are allowed to execute any kind of instructions
(including If.... then.... Else) and as many instructions as we want.
Iteration
For....Next
This instruction is also similar in different programming languages. Lets see a typical example.
I want to say Hello 10 times
<BR> <% for mynumber = 1 to 10 %>
<% =mynumber %> Hello<BR>
<% Next %>
In this case we have defined a variable (mynumber) and using for...Next instruction we have
repeated 10 times . The For...Next instruction allows defining the value of the increment.
<% For mynumber = 1 to 20 STEP 2
response.write(Hello<BR>)
Next %>
<% For mynumber = 20 to 1 STEP -2
response.write(Hello<BR>)
Next %>
In both cases we will get the same response (Hello 10 times). The increment may be positive or
negative as shown in the example.
38
Do While...Loop
Again, we will define a condition and one or more instructions:
<%
mynumber=0
Do While mynumber<10
response.write(Hello<HR>)
mynumber=mynumber+1
Loop
%>
In this example the condition is mynumber<10 and the instructions defines a response text and
an increment of the variable mynumber. In the example, mynumber will be increased until it gets
a value of 10. Then the loop will be abandon. Several instruction may be used within the loop.
Do Until.... Loop
Quite similar to the previous one, it also includes a condition and one or more instructions:
<%
mynumber=0
Do Until mynumber=10
response.write(Hello<HR>)
mynumber=mynumber+1
Loop
%>
The Exit Do can only be used within a Do...Loop control structure to provide an alternate way to
exit a Do...Loop. Any number of Exit Do statements may be placed anywhere in the Do...Loop.
Often used with the evaluation of some condition (for example, If...Then), Exit Do transfers
control to the statement immediately following the Loop.
When used within nested Do...Loop statements, Exit Do transfers control to the loop that is
nested one level above the loop where it occurs.
Response.write (Number 3)
Case 4
Response.write (Number 4)
Case 5
Response.write (Number 5)
Case Else
Response write (Mynumber is higher than 5)
End Select
%>
In this example above, we have defined mynumber as 3, in this case 3 instructions will be executed,
but they may be several instructions. Case Else is not necessary.
Lets try a second example:
<%
username=Rakesh
Select Case username
Case Rakesh
Response.Write
Case Ramesh
Response.Write
Case Jignesh
Response.Write
Case Else
Response write
End Select
%>
(Hello, Rakesh)
(Hello, Ramesh)
(Hi, Jignesh)
(I do not know you)
Math Function
Abs()
Syntax: Abs(Number)
The Abs function returns the absolute value for a number. Negative numbers become positive.
Positive numbers remain positive.
Code:
<% =Abs(-127.89) %>
Output:
127.89
40
Code:
<% =Abs(127.89) %>
Output:
127.89
Atn()
The Atn function returns the arctangent for a number.
Code:
<%=Atn(45.0)%>
Output:
1.54857776146818
You can also use a negative number.
Code:
<% =Atn(-45.0) %>
Output:
-1.54857776146818
Cos(Number)
The Cos function returns the cosine for a number (angle).
Code:
<% =Cos(45.0) %>
Output: 0.52532198881773
You can also use a negative number (angle).
Code:
<% =Cos(-45.0) %>
Output:
0.52532198881773
Exp(Number )
The Exp function raises e to the power of a number. There is a companion function Log for the
reverse operation.
Code:
<% =Exp(3.269) %>
Output:
26.2850411552082
You can also use a negative number.
41
Code:
<% =Exp(-3.269) %>
Output:
0.038044452511799
Fix(Number)
The Fix function converts a decimal number (floating-point) to an integer number (fix-point). There
is a companion function Int that also converts to integers. There is one major difference between
Int and Fix. Int rounds negative numbers down. Fix rounds negative numbers up.
Code:
<% =Fix(123.456) %>
Output:
123
Positive numbers are not rounded up. The decimal point and all digits to the right are effectively
choppedoff.
Code:
<% =Fix(123.899) %>
Output: 123
Negative numbers can also be converted. Negative numbers are rounded up (towards more positive).
The decimal point and all digits to the right are effectively chopped off.
Code:
<% =Fix(-123.899) %>
Output:
-123
Hex(Number)
Code:
<% =Hex(123) %>
Output:
7B
You can also use a negative integer number.
Code:
<% =Hex(-123) %>
Output:
FF85
For a number with a decimal point (floating-point), the digits to the right of the decimal point are
ignored.
42
Code:
<% =Hex(123.456) %>
Output:
7B
Int(Number)
The Int function converts a decimal number (floating-point) to an integer number (fix-point).
Code:
<% =Int(123.456) %>
Output:
123
Positive numbers are not rounded up. The decimal point and all digits to the right are effectively
chopped off.
Code:
<% =Int(123.899) %>
Output:
123
Negative numbers are rounded down (towards more negative).
Code:
<% =Int(-123.456) %>
Output:
-124
Log(Number)
The Log function returns the natural logarithm of a number. You can not use a negative number.
Code:
<% =Log(26.2850411552082) %>
Output:
3.269
CBool( expression )
Returns an expression that has been converted to a Variant of subtype Boolean.
Remarks
If expression is zero, False is returned; otherwise, True is returned. If expression cant be
interpreted as a numeric value, a run-time error occurs. The following example uses the CBool
function to convert an expression to a Boolean. If the expression evaluates to a nonzero value,
CBool returns True; otherwise, it returns False.
Dim A, B, Check
A = 5
B = 5
Initialize variables.
43
Check = CBool(A = B)
A = 0
Check = CBool(A)
CByte( expression )
Returns an expression that has been converted to a Variant of subtype Byte.
Remarks
Use the CByte function to provide internationally aware conversions from any other data type to
a Byte subtype. For example, different decimal separators are properly recognized depending on
the locale setting of your system, as are different thousand separators.
If expression lies outside the acceptable range for the Byte subtype, an error occurs. The following
example uses the CByte function to convert an expression to a byte:
Dim MyDouble, MyByte
MyDouble = 125.5678
MyByte = CByte(MyDouble)
MyDouble is a Double.
MyByte contains 126.
CCur( expression )
Returns an expression that has been converted to a Variant of subtype Currency.
The expression argument is any valid expression.
Remarks
In general, you can document your code using the subtype conversion functions to show that the
result of some operation should be expressed as a particular data type rather than the default data
type. For example, use CCur to force currency arithmetic in cases where integer arithmetic normally
would occur. You should use the CCur function to provide internationally aware conversions from
any other data type to a Currency subtype. The following example uses the CCur function to
convert an expression to a Currency:
Dim MyDouble, MyCurr
MyDouble = 543.214588
MyCurr = CCur(MyDouble * 2)
MyDouble is a Double.
Convert result of
MyDouble * 2 (1086.429176)
to a Currency (1086.4292).
CDate( date )
Returns an expression that has been converted to a Variant of subtype Date.The date argument
is any valid date expression
Remarks
Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes
date literals and time literals as well as some numbers that fall within the range of acceptable
44
dates. When converting a number to a date, the whole number portion is converted to a date. Any
fractional part of the number is converted to a time of day, starting at midnight.
The correct order of day, month, and year may not be determined if it is provided in a format
other than one of the recognized date settings. In addition, a long date format is not recognized if
it also contains the day-of-the-week string.
The following example uses the CDate function to convert a string to a date. In general, hard
coding dates and times as strings (as shown in this example) is not recommended. Use date and
time literals (such as #10/19/1962#, #4:45:23 PM#) instead.
MyDate = October 19, 1962 Define date.
MyShortDate = CDate(MyDate)
Convert to Date data type.
MyTime = 4:35:47 PM
Define time.
MyShortTime = CDate(MyTime)
Convert to Date data type.
CDbl( expression )
Returns an expression that has been converted to a Variant of subtype Double.
Remarks
Use CDbl or CSng to force double-precision or single-precision arithmetic in cases where currency
or integer arithmetic normally would occur. Use the CDbl function to provide internationally aware
conversions from any other data type to a Double subtype.
This example uses the CDbl function to convert an expression to a Double.
Dim MyCurr, MyDouble
MyCurr = CCur(234.456784) MyCurr is Currency (234.4567)
MyDouble = CDbl(MyCurr * 8.2 * 0.01)
Convert result to Double (19.2254576)
CInt( expression )
Returns an expression that has been converted to a Variant of subtype Integer.
Remarks
Use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or doubleprecision arithmetic normally would occur. Use the CInt function to provide internationally aware
conversions from any other data type to an Integer subtype.
If expression lies outside the acceptable range for the Integer subtype, an error occurs.
The following example uses the CInt function to convert a value to an Integer:
Dim MyDouble, MyInt
45
MyDouble = 2345.5678
MyDouble is a Double.
MyInt = CInt(MyDouble)
MyInt contains 2346.
Note CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional
part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the
nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.
CLng( expression )
Returns an expression that has been converted to a Variant of subtype Long.
Remarks
In general, you can document your code using the subtype conversion functions to show that the
result of some operation should be expressed as a particular data type rather than the default data
type. For example, use CInt or CLng to force integer arithmetic in cases where currency, singleprecision, or double-precision arithmetic normally would occur.
Use the CLng function to provide internationally aware conversions from any other data type to a
Long subtype.
If expression lies outside the acceptable range for the Long subtype, an error occurs.
The following example uses the CLng function to convert a value to a Long:
Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45: MyVal2 = 25427.55
MyVal1, MyVal2
are
Doubles.
MyLong1 = CLng(MyVal1) MyLong1 contains
2527.
MyLong2 = CLng(MyVal2) MyLong2 contains
25428
CSng( expression )
Returns an expression that has been converted to a Variant of subtype Single.
Remarks
In general, you can document your code using the data type conversion functions to show that the
result of some operation should be expressed as a particular data type rather than the default data
type. For example, use CDbl or CSng to force double-precision or single-precision arithmetic in
cases where currency or integer arithmetic normally would occur.
Use the CSng function to provide internationally aware conversions from any other data type to a
Single subtype..
If expression lies outside the acceptable range for the Single subtype, an error occurs.
The following example uses the CSng function to convert a value to a Single:
Dim MyDouble1, MyDouble2, MySingle1, MySingle2
MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
46
CStr( expression )
Returns an expression that has been converted to a Variant of subtype String.
Remarks
For example, use CStr to force the result to be expressed as a String. You should use the CStr
function instead of Str to provide internationally aware conversions from any other data type to a
String subtype. The data in expression determines what is returned according to the following
table:
If expression is
CStr returns
Boolean
Date
Null
Empty
Error
Other numeric
The following example uses the CStr function to convert a numeric value to a String:
Dim MyDouble, MyString
MyDouble = 437.324
MyString = CStr(MyDouble)
MyDouble is a Double.
MyString contains 437.324
Remarks
The following example uses the Date function to return the current system date:
Dim MyDate
MyDate = Date
MyDate contains the current system date.
Month( date )
Returns a whole number between 1 and 12, inclusive, representing the month of the year.
Remarks
The following example uses the Month function to return the current month:
Dim MyVar
MyVar = Month(Now)
MyVar contains the number corresponding to
the current month.
String function
Asc( string )
Returns the ANSI character code corresponding to the first letter in a string.
The string argument is any valid string expression. If the string contains no characters, a run-time
error occurs.
Remarks
In the following example, Asc returns the ANSI character code of the first letter of each string:
Dim MyNumber
MyNumber = Asc(A)
MyNumber = Asc(a)
MyNumber = Asc(Apple)
Returns 65.
Returns 97.
Returns 65.
Note The AscB function is used with byte data contained in a string. Instead of returning the
character code for the first character, AscB returns the first byte. AscW is provided for 32-bit
platforms that use Unicode characters. It returns the Unicode (wide) character code, thereby
avoiding the conversion from Unicode to ANSI.
49
Chr( charcode )
The charcode argument is a number that identifies a character
Remarks
Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10)
returns a linefeed character.
The following example uses the Chr function to return the character associated with the specified
character code:
Dim MyChar
MyChar = Chr(65)
MyChar = Chr(97)
MyChar = Chr(62)
MyChar = Chr(37)
Returns
Returns
Returns
Returns
A.
a.
>.
%.
Note The ChrB function is used with byte data contained in a string. Instead of returning a
character, which may be one or two bytes, ChrB always returns a single byte.
Value
Description
vbBinaryCompare
vbTextCompare
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.
The array returned by the Filter function contains only enough elements to contain the number of
matched items.
The following example uses the Filter function to return the array containing the search criteria Mon:
Dim MyIndex
Dim MyArray (3)
MyArray(0) = Sunday
50
MyArray(1) = Monday
MyArray(2) = Tuesday
MyIndex = Filter(MyArray, Mon)
MyIndex contains Monday.
Compare Settings
The compare argument can have the following values:
Constant
Value
vbBinaryCompare
0
vbTextCompare
1
Description
Perform a binary comparison.
Perform a textual comparison.
Return Values
InStrRev returns the following values:
If
string1 is
string1 is
string2 is
string2 is
string2 is
string2 is
start >
InStrRev
zero-length
Null
zero-length
Null
not found
found within string1
Len(string2) 0
returns
0
Null
Start
Null
0
Position at which match is found
Join(array)
Returns a string created by joining a number of substrings contained in an array .
The Join function syntax has these parts:
listRequired. One-dimensional array containing substrings to be joined. delimiterOptional. String
character used to separate the substrings in the returned string. If omitted, the space character (
) is used. If delimiter is a zero-length string, all items in the list are concatenated with no delimiters.
The following example uses the Join function to join the substrings of MyArray:
Dim MyString
Dim MyArray(4)
MyArray(0) = Mr.
MyArray(1) = John
MyArray(2) = Doe
MyArray(3) = III
MyString = Join(MyArray)
MyString contains Mr.John Doe III.
LCase( string )
Returns a string that has been converted to lowercase.
The string argument is any valid string expression. If string contains Null, Null is returned.
Remarks
Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters
remain unchanged.
The following example uses the LCase function to convert uppercase letters to lowercase
Dim MyString
Dim LCaseString
MyString = VBSCript
LCaseString = LCase(MyString)
LCaseString contains vbscript.
UCase( string )
Returns a string that has been converted to uppercase.
The string argument is any valid string expression. If string contains Null Null is returned.
Remarks
52
Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters
remain unchanged.
The following example uses the UCase function to return an uppercase version of a string:
Dim MyWord
MyWord = UCase(Hello World) Returns HELLO WORLD.
Remarks
To determine the number of characters in string, use the Len function.
The following example uses the Mid function to return six characters, beginning with the fourth
character, in a string:
Dim MyVar
MyVar = Mid(VB Script is fun!, 4, 6)
MyVar contains Script.
Note The MidB function is used with byte data contained in a string. Instead of specifying the
number of characters, the arguments specify numbers of bytes.
Right
Returns a specified number of characters from the right side of a string.
Syntax
Define string.
53
MyStr = Right(AnyString, 1)
MyStr = Right(AnyString, 6)
MyStr = Right(AnyString, 20)
Returns d.
Returns World.
Returns Hello World.
Note The RightB function is used with byte data contained in a string. Instead of specifying the
number of characters to return, length specifies the number of bytes.
Replace
Returns a string in which a specified substring has been replaced with another substring a specified
number of times.
Required.
Required.
Required.
Optional.
count
Optional.
compare
Optional.
Description
String expression containing substring to replace.
Substring being searched for.
Replacement substring.
Position within expression where substring search is to
begin. If omitted, 1 is assumed. Must be used in conjunction
with count.
Number of substring substitutions to perform. If omitted,
the default value is -1, which means make all possible
substitutions. Must be used in conjunction with start.
Numeric value indicating the kind of comparison to use
when evaluating substrings. See Settings section for values.
If omitted, the default value is 0, which means perform a
binary comparison.
Settings
The compare argument can have the following values:
Constant
Value
vbBinaryCompare
vbTextCompare
Description
0
1
Return Values
Replace returns the following values:
If
expression is
expression is
find is
Replace
zero-length
Null
zero-length
returns
Zero-length string ().
An error.
Copy of expression.
54
replacewith is
zero-length
start >
count is
Len(expression)
0
The return value of the Replace function is a string, with substitutions made, that begins at the
position specified by start and and concludes at the end of the expression string. It is not a copy
of the original string from start to finish.
The following example uses the Replace function to return a string:
Dim MyString
MyString = Replace(XXpXXPXXp, p, Y)
A binary comparison starting at the beginning of the
string
Returns XXYXXPXXY.
MyString = Replace(XXpXXPXXp, p, Y, 3, -1, 1)
A textual comparison starting at position 3.
Returns YXXYXXY.
Value
Description
vbBinaryCompare
Perform a binarycomparison.
vbTextCompare
The following example uses the Split function to return an array from a string. The function performs
a textual comparison of the delimiter, and returns all of the substrings.
Dim MyString, MyArray, Msg
MyString = VBScriptXisXfun!
MyArray = Split(MyString, x, -1, 1)
MyArray(0) contains VBScript.
55
StrReverse( string1 )
Returns a string in which the character order of a specified string is reversed.
The string1 argument is the string whose characters are to be reversed. If string1 is a zero-length
string (), a zero-length string is returned. If string1 is Null, an error occurs.
Remarks
The following example uses the StrReverse function to return a string in reverse order:
Dim MyStr
MyStr = StrReverse(VBScript)
MyStr contains tpircSBV.
Remarks
The following example uses the LTrim, RTrim, and Trim functions to trim leading spaces, trailing
spaces, and both leading and trailing spaces, respectively:
Dim MyVar
MyVar = LTrim(
vbscript )
MyVar contains vbscript.
MyVar = RTrim(vbscript
)
MyVar contains vbscript.
MyVar = Trim( vbscript )
MyVar contains vbscript.
Procedures
In VBScript there are two kinds of procedures; the Sub procedure and the Function procedure.
56
Sub Procedures
A Sub procedure is a series of VBScript statements, enclosed by Sub and End Sub statements,
that perform actions but dont return a value. A Sub procedure can take arguments (constants,
variables, or expressions that are passed by a calling procedure). If a Sub procedure has no
arguments, its Sub statement must include an empty set of parentheses ().
The following Sub procedure uses two intrinsic, or built-in, VBScript functions, MsgBox and
InputBox, to prompt a user for some information. It then displays the results of a calculation
based on that information. The calculation is performed in a Function procedure created using
VBScript. The Function procedure is shown after the following discussion.
Sub ConvertTemp()
temp = InputBox(Please enter the temperature in _
degrees F., 1)
Response.write The temperature is & Celsius(temp) & _
degrees C.
End Sub
Function Procedures
A Function procedure is a series of VBScript statements enclosed by the Function and End
Function statements. A Function procedure is similar to a Sub procedure, but can also return a
value. A Function procedure can take arguments (constants, variables, or expressions that are
passed to it by a calling procedure). If a Function procedure has no arguments, its Function
statement must include an empty set of parentheses. A Function returns a value by assigning a
value to its name in one or more statements of the procedure. The return type of a Function is
always a Variant.
In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit.
When the function is called from the ConvertTemp Sub procedure, a variable containing the
argument value is passed to the function. The result of the calculation is returned to the calling
procedure and displayed in a message box.
Sub ConvertTemp()
temp = InputBox(Please enter the temperature in _
degrees F., 1)
Response.write The temperature is & Celsius(temp) & _
degrees C.
End Sub
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
57
placeholders for the data you want to pass into your procedure. You can name your arguments
anything that is valid as a variable name. When you create a procedure using either the Sub statement
or the Function statement, parentheses must be included after the name of the procedure. Any
arguments are placed inside these parentheses, separated by commas. For example, in the following
example, fDegrees is a placeholder for the value being passed into the Celsius function for
conversion:
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
To get data out of a procedure, you must use a Function. Remember, a Function procedure can
return a value; a Sub procedure cant.
Sub ResponseToUnknown()
response.write (Hi. How are you?)
End Sub
%>
In order to call a subroutine, we will use this kind of code:
DOSomething()
Where DOSomething is the name of the subroutine (it is recommended to use a very descriptive
name of the task we want to perform within the subroutine to make it easier to understand the
script). We may also provide information to the subroutine in order to perform the specified task.
The data will be provided this way:
whatever(data1, data2 ... dataN)
In the following example we will provide different data to a unique subroutine depending on the
Name of the person provided
<%
Dim
AA,BB,CC
TheName=Manish
if TheName=Abhay then
ResponseToVisitor 24, 44 ,51
else
if TheName=Manish then
ResponseToVisitor 25,45,50
else
response.write(Who are you?)
end if
end if
Sub ResponseToVisitor(AA, BB, CC)
Response.write (I know your are & AA & years
old, & <BR> )
Respone.write (your Mother is & BB & years
old, & <BR>)
Response.write (your Father is & CC & years
old, & <BR>)
End Sub
In Subroutine declaration AA is the first variable to be get, BB the second one, and CC the third
one. The values for the three variables are provided in the same order in calling the Subroutine.
The script below illustrates how to create three functions that manipulate strings appearence.The
first function, named bigBlue, returns text formatted as big and blue. The second function, named
smallRed, returns text formatted as small and the last function named brownBold returns the text
59
60
ASP Object
Properties,Methods,Events & Collection
ASP in built Objects
- Request
- Response
- Application
- Server
- Session
- ObjectContext
- ASP Error Object
- Component
61
ASP Object
Before we start with ASP Object we should know. What is an object? An object s an instance of
a Component, which has methods and properties. They are compiled piece of code built in any
programming language, which offer you the ability to just create an instance of them (create an
object) and start using their methods. ASP is so much powerful that not only it uses these six builtin Objects but can also call other applications or components like ADO to access databases and
CDO for messaging applications. You can even build your own custom COM components and
then call their methods from within ASP. This is ASP COM integration which gives ASP is so
much power that no other server side scripting language can match.
Following are the Objects which are available to you without needing to create an instance of
them and thats why they are called built-in Objects:
Application
Asp Error
Request
Response
ObjectContext
Server
Session
Collection
Most of the ASP built-in objects provide collections. Collections are data structures similar to
arrays that store strings, numbers, objects and other values. Unlike arrays, collections expand
and contract automatically as items are retrieved or stored. The position of an item will also move
as the collection is modified. You can access an item in a collection by its unique string key, by its
index (position) in the collection, or by iterating through all the items in the collection.
Accessing an Item by Name or Index
You can access a specific item in a collection by referencing its unique string key, or name. For
example, the Contents collection holds any variables stored in the Session object. It can also hold
any objects instantiated by calling Server.CreateObject. Suppose you have stored the following
user information in the Session object:
<%
Session.Contents("FirstName") = "Somil"
Session.Contents("LastName") = "Patel"
Session.Contents("Age") = 29
%>
You can access an item by using the string key you associated with the item when you stored it in
the collection. For example, the following expression returns the string "Somil":
<%= Session.Contents("FirstName") %>
You could also access an item by using the index, or number, associated with an item.
ASP collections are numbered starting with 1. The index associated with an item might change as
items are added to or removed from the collection. You should not depend on an items index
remaining the same. Indexed access is generally used to iterate through a collection, as described
in the following topics, or to access an item in a read-only collection.
You can also use a shorthand notation to access items by name. ASP searches the collections
associated with an object in a particular order. If an item with a particular name appears only once
in an object's collections, you can eliminate the collection name (although doing so may affect
performance):
<%= Session("FirstName") %>
Eliminating the collection name is generally safe when you are accessing items stored in the
Application or Session object. For the Request object, however, it is safer to specify the collection
name because the collections could easily contain items with duplicate names.
Iterating through a Collection
You can iterate through all the items in a collection to see what is stored in the collection or to
modify the items. You must supply the collection name when you iterate through a collection. For
example, you can use the VBScript For...Each statement to access the items you stored in the
Session object:
63
<%
'Declare a counter variable.
Dim strItem
'For each item in the collection, display its value.
For Each strItem In Session.Contents
Response.Write Session.Contents(strItem) & "<BR>"
Next
%>
You can also iterate through a collection by using the VBScript For...Next statement. For example,
to list the three items stored in Session by the previous example, use the following statements:
<%
'Declare a counter variable.
Dim intItem
'Repeat the loop until the value of counter is equal to
3.
For intItem = 1 To 3
Response.Write Session.Contents(intItem) & "<BR>"
Next
%>
Because you do not usually know how many items are stored in a collection, ASP supports the
Count property for a collection, which returns the number of items in the collection. You use the
Count property to specify the end value of the counter.
Response Object
The Response object is your key to sending information to the user. You can write to the screen,
redirect to another page, and create cookies using the Response object.
Application Object
The running Web server is an application. Using the Application object, you can control features
related to starting and stopping the application, as well as store information that should be accessed
by the application as a whole.
64
Server Object
The Server object lets you perform routine functions, such as mapping a virtual path to a physical
one and creating an instance of a component.
Session Object
Using the Session object, you can store information related to each user who is visiting your site.
ObjectContext Object
The ObjectContext object helps you to develop applications out of components. It does this by allowing
you to handle transactions from within an ASP page. A transaction is a single unit of work, that must
either succeed in its entirety or if it fails, then must be undone completely returning the system to the state
it was before the transaction was started.
Components
ASP components, are ActiveX controls that interface with ASP to simplify common procedures.
Some commonly used objects and components are defined below. If some code has been already
been written then it can be reused when it is incorporated in package.
Third-Party Components
There are numerous third-party componentsboth free and fee-basedavailable for ASP.
Registering a .dll is often the extent of the installation, so a component can be a real time-saver.
Instead of spending hours re-creating the wheel, check to see if a component exists to handle the
task at hand:
If your site is hosted by an ISP, you may not be able to install your own components or even have
them installed, so check with your ISPs support team.
65
66
Response Object
Response Object is used to display the output in browser according to client request. As we
know whatever output in browser is only HTML tags because ASP script always execute on
server and the output is send in HTML forms. So we cannot see any ASP script in Browser.
Syntax for Response object
Response.method
Response.property
Response.collection
Methods
Response.clear
Clears the buffered output..Buffered Output is not sent until the script is finished or until some
special command is sent. Without Buffering the request is sent immediately. Use this method to
handle errors. If the Response.Buffer is not set to true, this method will cause a run-time error. In
IIS 5.0 the buffering turned on by default.While in previous version it was off.
<%
Response.Buffer=true
%>
<html>
<body>
<p>This is some text I want to send to the user.</p>
<p>No, I changed my mind. I want to clear the text.</p>
<%
Response.Clear
%>
</body>
</html>
The above block of code will display nothing. Response.Buffer Property stores all the output
data in buffer. Response.clear erase all the data from buffer.
67
Response.End
Stops processing the script, and return the current result.
<Html>
<body>
<p>Is it possible to print second line? <br>
<%
Response.End
%>
No, You cannot print it</p>
</body>
</html>
The above block of code will display only Is it possible to print second line? in browse. This is
because of Response.end. Response.end will stop the execution of Script.
Response.flush
Sends buffered output immediately. If the Response.Buffer is not set to true, this method will
cause a run-time error.
Response.redirect(URL)
Redirects the user to the specify URL.A browser redirection is simply another HTTP header with
its value set to a URL. When the Web browser encounters this header, it moves to the specified
URL automatically without any user intervention.To use redirection, use Response.Redirect in the
following manner:
Response.Redirect(URL)
Where URL is either relative or full path.
Note: You may not use a redirect if you already have sent some data to the HTTP output stream.
For example:
<%
Response.write(my name is shailendra Sharma)
Response.Redirect(name.asp)
%>
It will raise an error. This error happens because the redirect instruction is an HTTP header that is
placed in the HTTP response, and anything sent via a Response.write is placed in the content area
of the response (after the headers).
In the example given below form.asp contains a simple HTML form that contains two form fields.
If the form is submitted, and either of the form fields are empty, then the user is automatically
redirected back to the form.asp page. Notice the statement:
68
Response.Buffer = TRUE
at the top of result.asp. You must include this statement if you use the Redirect method after
sending content to the browser. Otherwise, you will receive an error. You should also notice that
you can use a query string with the Redirect method. In the sample pages below, the querystring is
used to indicate that the user has not completed all the form fields.
Be aware that you cannot reliably use the Target attribute with Redirects. This means that you
cannot redirect to a particular frame.
Form.asp
<html>
<head><title>form.asp</title></head>
<body>
<%
backagain = TRIM( Request( backagain ) )
IF backagain <> THEN
Response.Write <big>You did not complete all the
fields!</big>
END IF
%>
<form method=post action=result.asp>
All of the following fields are required:
<p>
<b>Please enter your name:</b>
<br><input name=yourname type=text>
<p><b>Please enter your favorite color:</b>
<br><input name=color type=text>
<p>
<input type=submit value=Next>
</form>
</body>
</html>
69
Result.asp
<% Response.Buffer = TRUE %>
<html>
<head><title>result.asp</title></head>
<body>
<%
yourname = Trim( Request( yourname ) )
color = Trim( Request( color ) )
IF yourname = or color = THEN
Response.Redirect form.asp?backagain=1
END IF
%>
Thank you for completing the form.
<br>The favorite color of <%=yourname%> is <%=color%>!
</body>
</html>
If you skip any of the textfields and directly press submit then you will be directed to the same
page again with additional message that you did not complete all the fields
70
Cookies
By design, HTTP is a stateless environment. The client browser requests individual documents
from the Web server, which in turn receives the request, processes it, returns a document, and
discards the request. HTTP does not provide any mechanism to associate a particular request
with any previous one. With Active Server Pages (ASP), state can be maintained using session
variables. Unfortunately, as their name implies, session variables are available only within the session or Web application in which they were created. By using cookies, you can maintain application state across multiple Web applications
Cookies are a general mechanism that server-side connections can use to both store and retrieve
information on the client side of the connection. The server-side code can create chunks of state
information (cookies), which are returned to the browser in the documents header. The browser
then stores the cookies on the client computer. Each cookie includes a range of URLs for which
that cookie is valid. Any future requests made by the browser that fall within that range of URLs
will include the cookie data as part of the request.
There is a limit to the amount of data that can be stored in cookies. All of the cookie data is
transmitted in the header of the document. The exact format of the header is not important, since
ASP hides the implementation from the programmer. The maximum amount of data that can be
sent is approximately 5KB.
You can add two types of cookies to a users browser. If you want to create a cookie that lasts
only during the period of time that someone is visiting your Web site, then you can create a session
cookie. Heres how you create a session cookie:
Response.Cookies( myCookie ) = some value
If you want to create a cookie that lasts longer than a session cookie, then you must specify a date
when you want the cookie to expire. You do this with the Expires attribute like this:
Response.Cookies( myCookie) = some value
Response.Cookies(myCookie).Expires = 1/1/2005
Since adding a cookie involves sending a special header to the users browser, you must create
any cookies before you output any content in a page (Alternatively, you can enable page buffering
for the page).
To read a cookie after it has been created, you use the Cookies collection of the Request object
like this:
Response.Write Request.Cookies( myCookie )
The sample Active Server Page below creates a persistent cookie on your browser that lasts until
January 1, 2005. The cookie is assigned the current date and time as a value.
Cookies .asp
<%
If Request.Cookies( firstVisit ) = THEN
Response.Cookies( firstVisit ) = NOW()
71
support or refuse to accept cookies. The Cookie Munger filter intercepts server requests before they
are screened by the ASP filter. Once a request is captured, the filter processes it to determine if the
browser is accepting cookies.
Response.write(String)
Writes a text to the browser. We have all ready seen lot of example for Response.write. We can
use syntax <%= %> for the same.
<html>
<%
dim Username
Username=Brijesh
%>
<html>
Welcome, <%=Username%>
</html>
Above example will print Welcome, Manish in browser.
Properties
Buffer
Whether to buffer output or not. When the output is buffered, the server will hold back the response until all of the server scripts have been processed, or until the script calls the Flush or End
method. If this property is set, it should be before the <html> tag in the .asp file
<%
Response.Buffer=true
%>
<html>
<body>
<p>I write some text, but I will control when the text
will be sent to the browser.</p>
<p>The text is not sent yet. I hold it back!</p>
<p>OK, let it go!</p>
<%
Response.Flush
%>
</body>
</html>
This example demonstrates the Buffer property.When this property is set to true, the server will
hold back the response until all of the scripts have been processed, or we can control manually
when to send the output back to the browser. This example also demonstrates the use of the
Flush method. When Response.Flush is called, ASP sends the buffered output to the client
immediately. This happens whether the output is buffered or not.
74
Content Type
Sets the HTTP content type. Some common content types are text/html, image/gif, image/
jpeg, text/plain. The default is text/html
<%
Response.ContentType=text/html
%>
<html>
<body>
<p>this is some text</p>
</body>
</html>
Expires
Sets how long a page will be cached on a browser before it expires
<%Response.Expires=0%>
<html>
<body>
<p>This page will be refreshed with each access!</p>
</body>
</html>
This example demonstrates the Expires property. This property sets how long a page will be
cached in a browser before it expires. If the user returns to the same page before the specified
number of minutes have elapsed, the cached version is displayed. If you set minutes to 0, the page
will never be cached on a browser
ExpiresAbsolute
Set the date and time when a page cached on a browser will be expire.
<%
Response.ExpiresAbsolute=#May 05,2000 05:30:30#
%>
<html>
<body>
<p>This page will expire on May 05, 2000 05:30:30!</p>
</body>
</html>
This example demonstrates the ExpiresAbsolute property. This property sets a date/time when a
page cached in a browser will expire. If the user returns to the same page before the specified
date/time, the cached version is displayed.
75
Caching
If your application sends pages to the client via a proxy server, the proxy server may cache pages
to return them more quickly to the client. This reduces the load on the network and the Web
server.To prevent a browser from caching pages, set Response.Expires to some negative number. This will force the cached pages to expire immediately. If you set Response.Expires to 0,
and if your browser clock is behind by a few minutes, the page wont expire immediately. If your
Web site contains objects that do not expire often, such as images, set the expiration to some time
in the future. This will greatly increase the speed at which a page is refreshed or downloaded.
Description
HTTP_ACCEPT
HTTP_ACCEPT_LANGUAGE
HTTP_CONNECTION
HTTP_HOST
HTTP_USER_AGENT
HTTP_COOKIE
HTTP_REFER
The HTTP_REFERER header contains the name of the page used to link to the current page. We
can can use this header to determine the source of the traffic to your Web site. The example below
use the HTTP_REFERER header to report the name of the previous page.
page1.asp
<html>
<head><title>page1.asp</title></head>
<body>
The previous page was <b><%=Request.ServerVariables(
HTTP_REFERER )%></b>
<p>
<a href=page2.asp><b>Next Page</b></a>
</body>
</html>
page2.asp
<html>
<head><title>page2.asp</title></head>
76
<body>
The previous page was <b><%=Request.ServerVariables(
HTTP_REFERER )%></b>
<p>
<a href=page3.asp><b>Next Page</b></a>
</body>
</html>
page3.asp
<html>
<head><title>page3.asp</title></head>
<body>
The previous page was <b><%=Request.ServerVariables(
HTTP_REFERER )%></b>
<p>
<a href=page1.asp><b>Next Page</b></a>
</body>
</html>
plus sign (+), fields are separated by an ampersand (&), and any non-alphanumeric character is
replaced by a %xx code(where xx is a hexadecimal representation of the character).
78
An optional parameter that enables you to retrieve one of multiple values for variable. It can be
any integer value in the range 1 to Request.QueryString(variable).Count.
The QueryString collection is a parsed version of the QUERY_STRING variable in the
ServerVariables collection. It enables you to retrieve the QUERY_STRING variables by name.
The value of Request.QueryString(parameter) is an array of all of the values of parameter that
occur in QUERY_STRING. You can determine the number of values of a parameter by calling
Request.QueryString(parameter).Count. If a variable does not have multiple data sets associated
with it, the count is 1. If the variable is not found, the count is 0.
To reference a QueryString variable in one of multiple data sets, you specify a value for index.
The index parameter may be any value between 1 and Request.QueryString(variable).Count.
If you reference one of multiple QueryString variables without specifying a value for index, the
data is returned as a comma-delimited string.
When you use parameters with Request.QueryString, the server parses the parameters sent to
the request and returns the specified data. If your application requires unparsed QueryString
data, you can retrieve it by calling Request.QueryString without any parameters.
You can use an iterator to loop through all the data values in a query string. For example, if the
following request is sent
http://NAMES.ASP?Q=Fred&Q=Sally
and Names.asp contained the following script,
NAMES.ASP<%
For Each item In Request.QueryString(Q)
Response.Write item & <BR>
Next
%>
Names.asp would display the following.
Fred
Sally
The preceding script could also have been written using
Count.
<%
For I = 1 To Request.QueryString(Q).Count
Response.Write Request.QueryString(Q)(I) & <BR>
Next
%>
Example
The client request
/scripts/directory-lookup.asp?name=fred&age=22
Results in the following QUERY_STRING value.
80
name=fred&age=22.
The QueryString collection would then contain two members, name and age. You can then use
the following script.
Welcome, <%= Request.QueryString(name) %>.
Your age is <%= Request.QueryString(age) %>.
The output would be
Welcome, Fred. Your age is 22.
If the following script is used
The unparsed query string is: <%=Request.QueryString %>
The output would be
The unparsed query string is: name=fred&age=22
Form
The Form collection retrieves the values of form elements posted to the HTTP request body, with
a form using the POST method.
Syntax
Request.Form(element)[(index)|.Count]
Parameters
element
The name of the form element from which the collection is to retrieve values.
index
An optional parameter that enables you to access one of multiple values for a parameter. It can be
any integer in the range 1 to
Request.Form(parameter).Count.
Remarks
The Form collection is indexed by the names of the parameters in the request body. The value of
Request.Form(element) is an array of all the values of element that occur in the request body.
You can determine the number of values of a parameter by calling Request.Form(element).Count.
If a parameter does not have multiple values associated with it, the count is 1. If the parameter is
not found, the count is 0.
To reference a single value of a form element that has multiple values, you must specify a value for
index. The index parameter may be any number between 1 and Request.Form(element).Count.
If you reference one of multiple form parameters without specifying a value for index, the data is
returned as a comma-delimited string.
81
When you use parameters with Request.Form, the Web server parses the HTTP request body
and returns the specified data. If your application requires unparsed data from the form, you can
access it by calling Request.Form without any parameters.
Note When using ASP and posting large amounts of data beyond 100 kilobytes, Request.Form
cannot be used. If your application requires posting data greater than this limit, a component can
be written which uses the Request.BinaryRead method.
You can iterate through all the data values in a form request. For example, if a user filled out a
form by specifying two values - Chocolate and Butterscotch - for the FavoriteFlavor element, you
could retrieve those values by using the following script.
<%
For i = 1 To Request.Form(FavoriteFlavor).Count
Response.Write Request.Form(FavoriteFlavor)(i) &
<BR>
Next
%>
The preceding script would display the following.
Chocolate
Butterscotch
You can use this technique to display the parameter name,
as shown in the following script:
<%
For i = 1 to Request.Form(FavoriteFlavor).count
%>
Request.Form(FavoriteFlavor) =
<%= Request.Form(FavoriteFlavor)(i)_
%> <BR>
<% Next %>
This script displays the following in the browser.
Request.Form(FavoriteFlavor) = Chocolate
Request.Form(FavoriteFlavor) = Butterscotch
Example
Consider the following form:
<FORM ACTION = /submit.asp METHOD = post>
<P>Your first name: <INPUT NAME = firstname SIZE = 48>
<P>What is your favorite ice cream flavor: <SELECT NAME =
flavor>
<OPTION>Vanilla
<OPTION>Strawberry
82
<OPTION>Chocolate
<OPTION>Rocky Road</SELECT>
<P><INPUT TYPE = SUBMIT>
</FORM>
From that form, the following request body might be sent:
firstname=James&flavor=Rocky+Road
The following script can then be used in Submit.Asp page:
Welcome,
<%= Request.Form(firstname) %>.
Your favorite flavor is <%= Request.Form(flavor) %>.
he following output is the result:
Welcome, James. Your favorite flavor is Rocky Road.
If the following script is used:
The unparsed form data is: <%= Request.Form %>
the output would be:
The unparsed form data is:
firstname=James&flavor=Rocky+Road
Note If your form includes multiple objects with the same name (for example, HTML SELECT
tags), the item in the form collection will be a comma-delimited list of all the selected values.
Backgroundform.html
<html>
<head><title>Chose background color</title></head>
<form action=backgroundresponse.asp method=post>
Which color do you prefer to use as your background?
<BR>
<input type=radio name=kindofcolor value=defined
checked>
Defined color
<select name=definedcolor>
<option value=#FFFFFF>White</option>
<option value=#FF0000">Red</option>
<option value=#00FF00">Green</option>
<option value=#0000FF>Blue</option>
</select>
<BR>
<input type=radio name=kindofcolor value=custom>
Custom color
<input type=text size=8" name=mycolor></input>
83
backgroundresponse.asp
<%
kindofcolor=Request.form(kindofcolor)
Select Case kindofcolor
case defined
colorofbackground=Request.form(definedcolor)
Select Case colorofbackground
case #FFFFFF
texttoshow=White
case #FF0000
texttoshow=Red
case #00FF00
texttoshow=Green
case #0000FF
texttoshow=Blue
End select
case custom
84
colorofbackground=Request.form(mycolor)
texttoshow=Custon color
End select
%>
<html>
<head><title>Chose background color</title></head>
<body bgcolor=<% =colorofbackground %>>
<center>
<H1><% =texttoshow %></H1>
</center>
</form>
</body>
</html>
If you selected the option for the colour as Blue then your browser output will be something like
this.
85
86
Session Object
You can use the Session object to store information needed for a particular user-session. Variables stored in the Session object are not discarded when the user jumps between pages in the
application; instead, these variables persist for the entire user-session.
The Web server automatically creates a Session object when a user who does not already have a
session requests a Web page from the application. The server destroys the Session object when
the session expires or is abandoned.
One common use for the Session object is to store user preferences. For example, if a user
indicates that they prefer not to view graphics, you could store that information in the Session
object
Note Session state is only maintained for browsers that support cookies.
Syntax
Session.collection
Session.property
Session.method
Properties
SessionId
SessionId returns a unique Session of each user.
<html>
<body>
<%
Response.Write(Session.SessionID)
%>
</body>
</html>
This example demonstrates the SessionID property. This property returns the session id number for
each user (it is a read-only property). The server generates the session id number.
87
TimeOut
TimeOut property sets the time out for the session.
<html>
<body>
<p>
The timeout for this session is
<%
Response.Write(Session.Timeout)
%>
minutes.
</p>
</body>
</html>
This example demonstrates the Timeout property. This example retrieves the timeout (in minutes) for
the session. The default value for the Timeout property is 20 minutes
Methods
Abandon
Abandon method Remove all the Session variable.
Events
Scripts for the following events are declared in the global.asa file.
Session_onStart
Session_onEnd
Session_onstart
Onstart event is fired when user visited the web site for the first time. If user visited the web site from
three different places then onstart event will be fired three times. Onstart event is used when we want to
perform some action when user session starts.
Session_onend
Onend event is fired when user close the web site. Onend event is used when we want to perform some
action when user session ends like: close all the database object, File object.
Remarks
You can store values in the Session object. Information stored in the Session object is available
throughout the session and has session scope. The following script demonstrates storage of two types of
variables.
88
<%
Session(username) = Janine
Session(age) = 24
%>
However, if you store an object in the Session object and use VBScript as your primary scripting
language, you must use the Set keyword. This is illustrated in the following script.
<% Set Session(Obj1) =
Server.CreateObject(MyComponent.class1) %>
You can then call the methods and properties exposed by MyComponent.class1 on subsequent Web
pages, by using the following.
<% Session(Obj1).MyMethod %>
Or by extracting a local copy of the object and using the
following.
<%
Set MyLocalObj1 = session (Obj1)
MyLocalObj1.MyObjMethod
%>
Another way to create objects with session scope is to use the <OBJECT> tags in the global.asa file.
You cannot, however, store a built-in object in a Session object. For example, each of the following
lines would return an error.
<%
Set
Set
Set
Set
Set
%>
Session(var1)
Session(var2)
Session(var3)
Session(var4)
Session(var5)
=
=
=
=
=
Session
Request
Response
Server
Application
If you store an array in a Session object, you should not attempt to alter the elements of the stored array
directly. For example, the following script will not work.
<% Session(StoredArray)(3) = new value %>
This is because the Session object is implemented as a collection.The array element StoredArray(3)
does not receive the new value. Instead, the value is indexed into the collection, overwriting any information
stored at that location.
It is strongly recommended that if you store an array in the Session object, you retrieve a copy of the
array before retrieving or changing any of the elements of the array. When you are done with the array,
you should store the array in the Session object all over again so that any changes you made are saved.
89
Application Object
The Application object is used to store variables and access variables from any page.All users share
ONE Application object. Application object declaration is same as Session object.
Application(Numberofhit)=1
Now this application(Numberofhit) variable will be share by all the user visiting the web site. Difference
between session and application variables is that application variable is share by all the user and session
variable is unique for each visiting session.
The Application object should hold information that will be used by many pages in the application (like
database connection information). This means that you can access the information from any page. It also
means that you can change the information in one place and the new information will automatically be
reflected on all pages.
Application.collection
Application.method
Method
Lock/Unlock
The Application object helps keep the values of application variables orderly by supplying two methods
to control when application variable can be modified. The Lock method will protect all appliation variables
from being modified until Unlock is called.
<html>
<body>
<H1> Welcome to my Home Page! </H1>
<%
Application.lock
Application(Numberofhit)=Application(Numberofhit)+1
%>
The Application currently has
<%=Application(Numberofhit)%>
Visitors.
<%Applicatoin.Unlock%>
When we called the Lock method, we did not specify any particular variable to lock. In fact, when we
call the Lock method, we are locking all application variables. Therefore always remember to call the
Application.Unlock method after you have finished modifying application variables in your script. If you
dont, then other processes executing the script will not be able to modify the variable.
Events
Application object has two events
90
OnStart
Event is fired before the Application Object is first referenced.This event will execute a script in the
Global.asa file, if the script exists. This event fired only once in the entire life of the web site or when the
web server is restarted.
OnEnd
Event fired when web server is shut down or application end. This event will execute a script in
the Global.asa file, if the script exists.
Sub Application_OnEnd
... some vbscript code
End sub
Sub Session_OnStart
......some vbscript code
End sub
sub Session_OnEnd
.....some vbscript code
end sub
</script>
Note: We do not use the ASP script delimiters, <% and %>, to insert scripts in the Global.asa file, we
have to put the subroutines inside the HTML <script> element.
Restrictions
Restrictions on what you can include in the Global.asa file:
You cant display text that is written in the Global.asa file. This file cant display information
You can only use Server and Application objects in the Application_OnStart and Application_OnEnd
subroutines. In the Session_OnEnd subroutine, you can use Server, Application, and Session objects.
In the Session_OnStart subroutine you can use any built-in object
Include/virtual
Server-side include directives give you a way to insert the content of another file into a file before the
Web server processes it. ASP implements only the #include directive of this mechanism. To insert a file
into an .asp file, use the following syntax:<! #include virtual | file =filename >
The virtual and file keywords indicate the type of path you are using to include the file, and filename is
the path and file name of the file you want to include.
Included files do not require a special file name extension; however, it is considered good programming
practice to give included files an .inc extension to distinguish them from other types of files.
93
secret information:<BR>
John.<BR>
is Smith.<BR>
secret information.
In this case it is convenient to save secret_info.txt file in the cgi-bin directory (the .txt file is not accessible
by visitors from this directory, but it will be accessible from our top directory
You can use either the VIRTUAL attribute or the FILE attribute with the #INCLUDE directive to
include a file. When you use the VIRTUAL attribute, you can include a file located in any directory on
your Web server. Typically, youll use the VIRTUAL attribute when including files since it can be used
with a file located anywhere at your Web site.
The FILE attribute can also be used to include a file. When you use the FILE attribute you supply a path
relative to the current directory (the directory containing the page with the #INCLUDE directive). You
can include a file located in the current directory, or a file located in a subdirectory of the current
directory.
With the version of ASP included with Windows 2000 (ASP 3.0) you can dynamically include files with
the Execute() method of the Server object. This wont work with earlier versions of ASP. To dynamically
include files, you need to include all the files in the page and then conditionally display one of the files.
The e xample below shows how to detect the exact time a visitor first arrives at your Web site. The
time is stored in a Session variable named started, and the value of that variable can be accessed from
any ASP page in the application:
<script language=vbscript runat=server>
sub Session_OnStart
Session(started)=now()
end sub
</script>
The Global.asa file can also be used to control page access.
The example below shows how to redirect every new visitor to another page, in this case to a page
called newpage.asp:
<script language=vbscript runat=server>
sub Session_OnStart
Response.Redirect(newpage.asp)
end sub
</script>
And you can include functions in the Global.asa file.
In the example below the Application_OnStart subroutine occurs when the Web server starts.Then the
Application_OnStart subroutine calls another subroutine named getcustomers.The getcustomers
subroutine opens a database and retrieves a set of records from the customers table. The recordset is
assigned to an array, where it can be accessed from any ASP page without querying the database:
<script language=vbscript runat=server>
sub Application_OnStart
getcustomers
End sub
Sub getcustomers
Set conn=Server.CreateObject(ADODB.Connection)
conn.Provider=Microsoft.Jet.OLEDB.4.0"
conn.Open c:/webdata/northwind.mdb
set rs=conn.execute(select name from customers)
Application(customers)=rs.GetRows
rs.Close
conn.Close
End sub
</script>
95
Global.asa Example
In this example we will create a Global.asa file that counts the number of current visitors.
The Application_OnStart sets the Application variable visitors to 0 when the server starts
The Session_OnStart subroutine adds one to the variable visitors every time a new visitor
arrives
The Session_OnEnd subroutine subtracts one from visitors each time this subroutine is triggered
<head></head>
<body>
<p>
There are <%=Application(visitors)%>
online now!
</p>
</body>
</html>
Set the amount of time a script can run before an error occurs
Take a user-supplied string and encode it into HTML format
Convert a virtual path to a physical path on the server
Take a user-supplied string and encode it into the proper format for a Uniform Resource Locator
(URL) string
Create an instance of an ActiveX component.
Change the course of execution by jumping to another page using the Transfer and Execute
properties.
These methods and properties are provided as utility functions for you to use in your pages.They
are not directly used to affect the display of the page, but they still provide valuable support in
creating Active Server Pages.
Method
CreateObject(type_of_object)
Creates an instance of an object
Execute(path)
Executes an .asp file from inside another .asp file. After executing the called .asp file, the procedural
control is returned to the the original .asp file
GetLastError()
Returns an ASPError object that will describe the error that occurred
HTMLEncode( string )
Sometimes, it is necessary when producing HTML output that special (typically non-ASCII) characters
be represented using a special notation. HTMLEncode method is used to convert a value in HTML
format.
97
MapPath(path)
Maps a relative or virtual path to a physical path
Transfer(path)
Sends all of the state information to another .asp file for processing. After the transfer, procedural
control is not returned to the original .asp page
URLEncode(string)
URLEncode method will convert a string so that we can use that string as a value of a QueryString
<%
dim Name, sURL
Name=This is abhy shah
sURL=form.asp?name= & server.URLEncode(name)
Response.Redirect(sURL)
%>
When we run this program following The output in the addressbar will be in the form of querystring
displaying
In the browser addressbar will contain name=This+is+abhy+shah
Description
ASPCode
ASPDescription
Category
Column
Description
File
Line
Number
Source
ASP Transactions
Introduction
Transactions are important to maintain data integrity, among other things, and have been used with
databases for quite a long time . Luckily, transactions arent restricted to databases - you can use them
in Active Server Pages as well, and without having to create custom components using Microsoft
Transaction Server (MTS).
you have deducted the money from account A (and before you add it to account B), you notice a
problem (perhaps account B has restrictions, or is not available for some reason). If the application just
quits here with some error message, then account A will be in an incorrect state, meaning it has funds
missing. These funds are not in account B. With transactions, should you encounter this error, the process
will roll back to a previous state, and the money will automatically go back to where it started. If there
are no problems, however, the transaction will commit, and everything will go through.. As you develop
more and more complex web applications, the need for strong state protection will become increasingly
necessary.
What is MTS?
MTS is Microsofts answer to transactions. MTS is the engine that keeps track of object states, and
rolls them back or commits them when necessary. Even though it wont be apparent in your ASPs, MTS
is working busily behind the scenes to keep track of what youre doing.MTS requires all objects that
use transactions to be registered in MTS. IIS itself has many different components that process web
applications that are all registered with MTS, which is why ASPs can run transactionally through MTS,
invisible to the user.
NOTE: Though MTS is installed with Windows NT, it usually is not set up to run automatically. Therefore,
before running any of the examples below, make sure the MTS service (MSDTC) is running (in the
services control panel).
The Basics
The transaction ASP code looks like regular ASP code. We must simply add a one line directive to the
beginning code to get it to behave properly:
<%@ TRANSACTION = value %>
Where value can be any one of the following:
Requires_New
Required
Supported
Not_Supported
Typically, each ASP page will be its own transaction, however, it is possible to continue transactions
across more than one page by using the Server.Transfer and Server.Execute methods (new to IIS 5). If
the calling page is transacted, and the current page uses Transaction = Required or Transaction =
Supported then the current page will continue the existing transaction, which makes some very complex
applications possible.
End Sub
sub OnTransactionAbort()
Response.write(Operation was unsuccessful)
End Sub
%>
In this scenario, weve moved the commit and abort functions out of the inline code to separate
procedures.Our script runs normally in the first script block. In the second script block, we create the
sub procedures OnTransactionCommit and OnTransactionAbort. These two procedures tell the application
what to do if the transaction is successful or unsuccessful.
Note that the only way to let the application know the transaction is unsuccessful is by calling the
ObjectContext.SetAbort method as outlined above. Unless you explicitly call this method somewhere in
the code, MTS will always think the transaction is successful, and therefore execute the code in
OnTransactionCommit. For example, if your code completes its execution, and no SetAbort method
has been called, OnTransactionCommit will run.On the other hand, as soon as you call SetAbort, the
code execution stops, the process rolls back, and then OnTransactionAbort runs.
In the following code, even though the application should prompt out when the variable strText is empty,
MTS thinks this is successful, and will always execute OnTransactionCommit, which can be highly
probelmatic so dont forget to tell the application where to stop in case of an error!
<%@ TRANSACTION = value %>
<%
strText = Request.form(Textbox)
if strText = then
Response.write(You did not enter the text.<p>)
else
Response.write(Processing transaction...<p>)
end if
%>
<%
commit and rollback code
sub OnTransactionCommit()
Response.write(Operation was successful)
End Sub
sub OnTransactionAbort()
Response.write(Operation was unsuccessful)
End Sub
%>
It is simple even to modify existing code to take part in transactions simply by adding the @Transactions
directive and making sure to properly use SetAbort and build the transaction events OnTransactionCommit
and OnTransactionAbort.
102
Conclusion
By using transactions in ASP, you are opening up a whole new world of professional functionality.
Transactions make your applications stronger, and can ease development pains. The best part is that
they are simple to use once youve learned the basics.
103
ASP Components
ASP Components
Adrotator include file
Image data file
Redirecting users from AD Links
Counting Page Hits
Browser Capabilities
Opening and Reading ,Writing Textfiles
104
Components
Components are reusable code blocks. The code block performs a common task (like deleting a record
in a database). Other pages and other applications can access components. This is very powerful; you
do not have to write the same code over and over again on different pages or in different applications.
Components can be created in C, C++, Java, VB, etc.
Component
Ad Rotator
Creates an Ad Rotator object that displays a different advertisement each time a user enters or refreshes
a page
Browser Capabilities
Creates a BrowserType object that gives you a description of the capabilities of the clients browser
Content Rotator
Creates a ContentRotator object that displays a different HTML content string each time a user enters
or refreshes a page
Content Linking
Creates a Nextlink object that holds a list of urls, which is used to treat web pages like a book
Counter
Creates a Counters object that can create, hold, increment, and get any number of individual counters
Database Access
Create ActiveX Data Objects (ADO) to access information stored in a database
File Access
Creates a FileSystemObject which provides the methods, properties and collections you use to access
the file system
105
MyInfo
Creates a MyInfo object that keeps track of personal information
Page Counter
Creates a PageCounter object that counts and displays the number of times a Web page has been
opened
Permission Checker
Creates a PermissionChecker object that uses the password authentication protocols provided in
Microsoft Internet Information Services (IIS) to determine whether a Web user has been granted
permissions to read a file
Tools
Creates a Tools object that provides utilities that enable you to easily add sophisticated functionality to
your Web pages
Status
Creates a Status object that has properties that contain server status information. This server status is
only available on Personal Web Server for Macintosh
Rotate Ad Information
Advertising is big business on the Web. This following eg. explains how to take advantage of the Ad
Rotator component installed with ASP by describing how to use this component to rotate advertisements
on your Web pages. The Ad Rotator component selects an advertisement for your Web page each time
the user refreshes or loads the Web page. Two files are required to set up the Ad Rotator component: an
Ad Rotator Include file and an ad images data file. By setting up these two files, this component can be
called by any ASP page on your site. Changes to the ad parameters are not done on all the sites
containing the ad, but to the ad images data file. This saves lots of time if the ad appears on numerous
pages within your Web site.
This is done in the following way.
Write an Ad Rotator Include File. Creates the ad-image links on any page that calls this file.
Create an Ad Image Data File. Specifies global ad-display data and information specific to each ad.
Test the Ad Rotator. Uses an ASP page that calls the Ad Rotator logic Include file and the image data
file to display and rotate ads.
on your ASP pages. You can call this file from within any ASP page intended to display the rotated ads.
Adrotatorlogic.inc:
<%
Function getAd()
Dim load
Create an instance of the AdRotator component
Set load=Server.CreateObject(MSWC.AdRotator)
Set the target frame, if any. This is the frame
where the URL will open up. If the HTML page does
not find the target name, the URL will be opened
in a new window.
load.TargetFrame = Target = new
Get a random advertisement from the text file.
getAd = load.GetAdvertisement(adimagedata.txt)
End Function
%>
107
display. For example, if two ads were displayed, one with an impression of 3 and the other with 7, then
the one with 3 would have a 30 percent probability of being selected, while the other would have a 70
percent probability.
Adimagedata.txt:
REDIRECT adrotatorredirect.asp
WIDTH 250
HEIGHT 60
BORDER 0
*
separates the general data from the image information
images/windows_logo.gif
http://www.microsoft.com/windows
Microsoft Windows
2
images/office_logo.gif
http://www.microsoft.com/office
Office 2000
3
<%@Language=VBScript %>
<html>
<head>
<title>Redirection Page</title>
</head>
<body>
<%
Set the response buffer on
Response.Buffer = True
Dim lsURL
Obtain the URL from the query string
lsURL = Request.QueryString(URL)
Clear the response and redirect to URL
Response.Clear()
Response.Redirect(lsURL)
%>
</body>
</html>
To check your work, use Displayad.asp. When you click on an ad, you should see a new window
displaying an appropriate ad-related Web page.
Browser Capabilities
The Browser Capabilities component creates a BrowserType object that determines the type, capabilities
and version of each browser that visits your site.An HTTP User Agent Header is sent to the server when
a browser connects to it. This header identifies the browser and the browser version. The BrowserType
object compares the header to entries in the Browscap.ini file. If it finds a match, the BrowserType
object assumes the properties of the browser listing that matched the User Agent header. If the object
does not find a match for the header in the Browscap.ini file, it sets every property to UNKNOWN.The
file Browscap.ini is a text file on the server that maps browser capabilities to the HTTP User Agent
header.
Syntax
<%
Set Browser = Server.CreateObject(MSWC.BrowserType)
%>
Eg.
<html>
<body>
<%
Set Browser=Server.CreateObject(MSWC.BrowserType)
%>
<table border=1" width=65%>
<tr>
<td width=52%>Client OS</td>
<td width=48%><%=Browser.platform%></td>
</tr>
<tr>
<td >Web Browser</td>
<td ><%=Browser.browser%></td>
</tr>
<tr>
<td>Browser version</td>
<td><%=Browser.version%></td>
</tr>
<tr>
<td>Frame support</td>
<td><%=Browser.frames%></td>
</tr>
<tr>
<td>Table support</td>
<td><%=Browser.tables%></td>
</tr>
111
<tr>
<td>Sound support</td>
<td><%=Browser.backgroundsounds%></td>
</tr>
<tr>
<td>Cookies support</td>
<td><%=Browser.cookies%></td>
</tr>
<tr>
<td>VBScript support</td>
<td><%=Browser.vbscript%></td>
</tr>
<tr>
<td>JavaScript support</td>
<td><%=Browser.javascript%></td>
</tr>
</table>
</body>
</html>
The output will be something like this depending upon your
browser.
112
Line 2 will create the appropriate environment to hold an instance of the FileSystemObject,which allows
performing the operations involving files in the server. We have defined a variable named fs to do it
(we may change the name of this variable).
In line 4 we have create a new variable named wfile and we have apply the method OpenTextFile to
variable fs. We have also defined which is the exact location of the file we want to open in this line (the
complete path is necessary).
OpenTextFile method has the following syntax:
Objectname.OpenTextFile (filename, mode, create, format)
The last three arguments are optional. If you want to use one of them, you must use all the preceding
ones, too.
Filename is the name of the file to be opened. It should be a physical path.
Mode has three possible values:
ForReading
ForWriting
ForAppending
1
2
8
113
These values indicate to open the file for Reading, Writing and Appending text to the end of the file.
If the file specified by filename is found, there are two options: OpenTextFile can either create a new,
empty file with the name, or it can return an error message. Create indicates which of these it should do.
If create is true, a new file is created. If it is False, an error is displayed. The default for create is Fales.
Format indicates whether to open the file as ASCII or Unicode.
In line 5 we have read all the content of the file to a variable named filecontent using the instruction
ReadAll.
Lines 7 to 9 are use to let the server know we have finished all operations involving files. In line 11 we
have response to the client with the content in the variable filecontent.
Lets suppose we have a file with different kind of information in each line (a name in the first line, the last
name in the second one, and the age in the third one), and we want to use them separately. This one will
be the script we may use:
This example is very similar to the previous one, but in this case each line we have read from myfile.txt
has been saved to a different variable (lines 5 to 7), and they have been used in lines 15 to 17 to respond
to the client.
This example will read all lines in the file, and the response page will include the content of each line with
its line number.
In line 6 we will define the variable counter, and in line 7 to 11 we will repeated instructions within the
Do_While _Loop until the file does not reach the end of the file (the condition is not
wfile.AtEndOfStream).
114
Lets suppose we have a file with a number in line 1 and a second number in line 2.
In the previous examples we were able to save the value in a line to a variable, but that variable was a
string class variable. In this example we have saved the content of line 1 and line 2 to variables number1
and number2" by using the function Clng. This function has allow us to add both numbers in line 10
and send the result to the client (line 11).
The differences to instructions when opening a file are line 6 and line 7:
The method used in line 5 is CreateTextFile; it is necessary to indicate the complete path to the file we
want to create; we may use the instruction True (to allow over-writing an existing file) or False (if the file
exits, it is not over-written).
115
<% forappending=8
VisitorsIP=Request.ServerVariables (REMOTE_ADDR)
Set fs = CreateObject(Scripting.FileSystemObject)
Set wfile = fs.OpenTextFile(c:\Mydir\mylog.txt,forappending)
wfile.WriteLine (VisitorsIP)
wfile.close
Set wfile=nothing
Set fs=nothing
response.write(IP registered)
%>
In line 2 to we are storing visitor IP through ServerVariables REMOTE_ADDR in line 4 we are using
forappending mode for changing our log file
116
117
Browser
Server
COM Objects
Step 5: COM Objects
Do their Thing
ASP Engine
Step 4: ASP Engine calls
COM Objects (if any)
ActiveX Data Objects (ADO) are an easy-to-use yet extensible technology for adding database access
to your Web pages. You can use ADO to write compact and scalable scripts for connecting to OLE DB
compliant data sources, such as databases, spreadsheets, sequential data files, or e-mail directories.OLE
DB is a system-level programming interface that provides standard set of COM interfaces for exposing
database management system functionality. With ADOs object model you can easily access these
interfaces (using scripting languages, such as VBScript or JScript) to add database functionality to your
Web applications. In addition, you can also use ADO to access Open Database Connectivity (ODBC)
compliant databases.
There are 3 top-level ADO objects that you need to be concerned with: The Command, Connection,
and RecordSet objects.
Command Object
When you do something with a Database, you must send a Command to that database. The Command
Object is a sort of container for a command. Since a command can take many forms, the Command
Object is designed to accommodate those many forms, and enable you to work with the elements of the
Command easily. In most cases, your command is going to be a SQL Statement, but it may contain
parameters to be passed to a Stored Procedure, or other similar qualities. But most of the time, you
wont need to specifically invoke the Command Object.
119
Connection Object
The Connection Object is the link between your ASP application and the database itself. The link must
be opened initially, it must be closed when youre done, and it may have varying qualities, according to
your needs. These qualities are the properties of the Connection Object. And there are a few methods
as well. But there are also default properties for a Connection Object.Most of the time, you wont
specifically need to invoke the Connection Object.
RecordSet Object
A RecordSet object is a container for what is called a Cursor. A cursor is a temporary table, which is
constructed by performing a query on a table in a database. It doesnt exist in a file; it exists in memory.
but other than that, it has all the characteristics of a database table. It has rows (records) and columns
(fields), and the rows and columns have properties of their own. It has a Record Pointer (which is also,
confusingly enough, referred to as a cursor!), which moves from one row or record to another. And it
has a host of other properties.
Illustration of a RecordSet Object
Column
We can use the invocation of a RecordSet to implicitly create your Command and Connection Objects.
rs.Open q, DSN=whatever;
q in this case refers to a SQL Query string, such as SELECT * FROM mytable, which has been
previously defined somewhere. DSN=whatever; is a Connection string.The Query string is the Query
string of the Command Object, and the Connection string is the Connection string of the Connection
Object. Both objects are created implicitly when you use the Open method of the RecordSet, and by
passing those arguments to the Open method, you set those properties of the 2 other objects. In most
cases, this is all you need to to with these other 2 objects. All of your work is going to be with the
records in the RecordSet, the RecordSet object is the only one you have to create!
RecordSet Properties
The following is a list of the properties available for a RecordSet, with a brief description of each:
AbsolutePage Page of current position
AbsolutePosition
ActiveConnection
BOF
Bookmark
CacheSize
CursorLocation
CursorType
Current position
Active Connection Object
Beginning of File
Bookmark of current position
Number of records cached
Server or Client
Forward, static, dynamic, keyset
120
EOF
EditMode
Filter
LockType
MaxRecords
PageCount
PageSize
RecordCount
Source
Status
End of File
Whether or not an edit is in progress
What kind of records to hide
Record lock type for edits or updates
Maximum number of records to retrieve
Total number of pages
Number of records per page
Total number of records
Source Command Object
Status of last action
You may never encounter some of these properties, as usually, the default settings for the Read/Write
properties are fine, and in fact, there are some properties listed here which are not supported by various
providers. For example, take the CursorType property. By default, this is forward only.
The most common properties that I personally use are EOF (You can test for this to find out if any
records have been returned - if you run a query and the pointer is at EOF, no records were returned)
and MaxRecords.
RecordSet Methods
The following is a list of the methods available for the RecordSet object, with a brief description of each:
AddNew
CancelBatch
CancelUpdate
Clone
Close
Delete
GetRows
Move
MoveNext
MovePrevious
MoveFirst
MoveLast
NextRecordSet
Open
Requery
Resync
Supports
Update
UpdateBatch
The Some of the commonly used Methods are listed below, with a detailed description of each:
Open
<RecordSetName>.Open source, connection, cursor, lock, type
source
Can be a Command Object or a string containing a query. This parameter is optional. If the RecordSets
Source property is set, it is unnecessary.
connection
Can be a Connection Object or a string containing Connection information (also known as a Connection
String separated by semicolons. This parameter is optional. If the RecordSets ActiveConnection
property has been set, then connection is not required.
cursor
A constant numeric value used to assign the RecordSets CursorType property. This parameter is optional.
By default, the CursorType is Forward Only, and if the RecordSets CursorType has been explicitly set
elsewhere then it is unnecessary.
lock
A constant numeric value used to assign the LockType property. This parameter is optional. The default
LockType property is Read Only, and if the RecordSets LockType property has been explicitly set
elsewhere, it is also unnecessary.
type
A constant numeric value used to assign the CommandType property of the Command object. This
parameter is optional. The default value is Unknown (8), and if the Command Objects CommandType
property has been set explicitly elsewhere, it is also unnecessary. This value can be helpful in optimizing
your code, to give a hint as to what the Command Type will be.
A note about using this method: I use this method even when executing an UPDATE, DELETE or
INSERT SQL statement. Even though these statements dont return a RecordSet, because of the fact
that the Open method executes the query you specify, it will execute these statements .
MoveNext
<RecordSetName>.MoveNext
This method simply moves the record pointer (or cursor) to the next record in the RecordSet. It is often
used in loops which display all the records returned in the current RecordSet. If you attempt to use this
method after the record pointer has moved beyond the last record, an error will be generated. Therefore,
it is always a good idea to test for EOF before using this method.
Close
<RecordSetName>.Close
This method takes no parameters. It is important to explicitly close the RecordSet, even though there
122
are built-in timeouts which will close the RecordSet without your specific invocation of the method.
Closing the RecordSet explicitly speeds up the process, and eases the burden on the Server. When the
RecordSet is closed, the Connection Object is also closed, as well as the Command Object.
Requery
<RecordSetName>.Requery
This method can be used to re-execute the same query initially used to open the RecordSet, without
having to close and reopen the RecordSet. It refreshes the RecordSet, which keeps the same properties
and parameters used when it was initially opened.
ODBC makes it easy for users to create ASP scripts that will connect to a database. Normally, each
ODBC will have a DSN (Data Source Name). The DSN is a complete index of a series of information
about the database. In essence, its a variable that is used between the server and the ASP script. The
DSN will be one word that means the specified driver type, file name, and location of the database.
There are several types of ODBC connections
System DSN
This Data Source name is a data source created on the web server by the administrator of the server.
This is the most popular type of DSN and generally a lot more reliable.
FileDSN
A connection that your script makes itself each time access to the database is required, specifying the
path to and name of the database. The database must reside on the server in a directory that your script
can access for this to work.
Connecting to a SQL Server Database
The script below contains the proper connection string for connecting to a Microsoft SQL Server database
using the Native OLE DB Provider for SQL Server. To use a Native OLE DB Connection, you do not
need to configure a DSN. You will need to have a recent version of the Microsoft Data Access
Components (MDAC) installed on your server. You can download the latest version of the MDAC by
visiting:http://www.microsoft.com/data
In the connection string below, both the DATABASE and SERVER parameters are optional. If you do
not specify the database, then the default database for the Login will be used. If you do not specify a
value for SERVER, then the local database will be used. You can use a domain name or IP address for
the server.
SqlOleDB.asp
<%
Create Instance of Connection Object
Set Con = Server.CreateObject( ADODB.Connection )
Con.Open
123
Provider=SQLOLEDB;UID=sa;PWD=xxx;DATABASE=myDatabase;SERVER=myServer
%>
Connecting SQL Server with a DSN
Before you can connect to SQL Server with a Data Source Name (DSN), you must first configure the
DSN. You do this by creating either a System DSN or File DSN with the ODBC Data Source
Administrator. This facility is located in the Windows Control Panel When you create a File DSN,
connection information is stored in a text file. When you create a System DSN, connection information
is stored in your computers registry.
Once you have a System DSN setup, you can use the following script to connect to SQL Server:
<%
Create Instance of Connection Object
Set Con = Server.CreateObject( ADODB.Connection )
Con.Open DSN=myDSN;UID=sa;PWD=xxx
%>
Using DSN-less Connection
Instead of putting connection information into the DSN , we can put it into connection string .
Another alternative to connecting to SQL Server is to use a Universal Data Link File (UDL). The main
advantage of using a UDL file is that you can save your database password outside of your Web
application. To create a UDL file, open Notepad and save a file with the extension UDL. After the UDL
file has been created, you can connect to SQL Server with the following script:
SqlUDL.asa
<%
Create Instance of Connection Object
124
<tr>
<td><%=RS( au_id )%></td>
<td><%=RS( au_lname )%></td>
<td><%=RS( au_fname )%></td>
</tr>
<%
RS.MoveNext
WEND
%>
</table>
</body>
</html>
Properties of the Connection
There is collection in the connection Object called the properties collection. This collection contains an
instance of the property object for every property supported by the connection .Most of the time we
may not require them but in case of testing and debugging database connections these properties can
be quite handy .
The code below will give you some idea:
<html>
<%
Dim oProp
set Conn=Server.CreateObject(ADODB.Connection)
For Each oProp in Conn.Properties
Response.Write oProp.Name & : & oProp.Value & <BR>
Next
Conn.close
Set Conn=Nothing
%>
</html>
Adovbs.inc
In case of Recordset many times we have to use constants.These constants are not built in asp.For using
these constants we need to include adovbs.inc file which contains all the ADO constant
ADOVBS demonstrates how to use ADO from Visual Basic, Scripting Edition and HTML. Additionally,
it demonstrates how ADO, VBScript, and HTML on the client can be used to build a two or three-tier
Web application for an intranet. Lastly, it demonstrates how to create a three-tier connection using
ADO and the Microsoft OLE DB Remoting Provider. It is installed to c:\Program Files\Common
Files\System\ado by default (in case of IIS and PWS)
126
Note This sample requires Microsoft Internet Explorer 4.01 Service Pack 1 or later, and you need
to set your security settings to low for the Web server youre connecting to.
Execute Method on connection Objet
On a Connection object:
Set recordset = connection.Execute(CommandText, RecordsAffected, Options)
connection.Execute CommandText, RecordsAffected, Options
The Execute method syntax has these parts.
Part
Description
recordset
connection
RecordsAffected
Optional. A Long variable to which the provider returns the number of records
that the operation affected.
Parameters
CommandText
Options
127
SaveData.asp
<%
Grab the HTML Form
bread
= Request(
meat
= Request(
extras
= Request(
Fields
bread )
meat )
extras )
Lock Types
If you have a website with many users and if there are many users
Then there coulb be condition that two people trying to change the same record at same time This could
cause all kind of problem
To prevent this the first person who tries to change the record puts a lock on it.While the lock is on
nobody else can change the record .
Lock Types
Cursur
Read-Only
Constant
adLockReadOnly
Pessimistic
Optimistic
adLockPessimistic
adLockOptimistic
properties
These records are read onlyand canot
be modified(default)
Record are locked immediately
Record are only locked when update
method is called
129
Batch Optimistic
AdLockBatchOptimistic
Updating a Database
The sample script below uses the Execute method of the Connection object to modify the value of
records in the foodOrders database table. The script changes the value of the Meat column to the value
Chicken wherever the Bread column has the value Wheat.
For example, assume that the foodOrders table has the following records before the script is executed:
Bread
Wheat
Wheat
Rye
Meat
Turkey
Chicken
Chicken
Extras
Tomatoes
Tomatoes
NULL
After the script is executed, the records in the table are modified like this:
Bread
Wheat
Wheat
Rye
Meat
Chicken
Chicken
Chicken
Extras
Tomatoes
Tomatoes
NULL
In the row where the bread column has the value wheat, the value of the meat column is changed to
chicken.
SqlUpdate.asp
<%
Open Database Connection
Set Con = Server.CreateObject( ADODB.Connection )
Con.Open PROVIDER=SQLOLEDB;UID=myLogin;PWD=secret
Execute the UPDATE statement
mySQL = UPDATE foodOrders SET meat=Chicken WHERE
bread=Wheat
Con.Execute mySQL
%>
Deleting Database Records
The SQL DELETE statement deletes records from a database table WHERE the records match some
criterion. The sample script below deletes all the records from the foodOrders table WHERE the Meat
column contains the value Chicken.
Be careful when using the DELETE statement. If you use the DELETE without specifying a WHERE
clause, the statement will delete all the records from a table.
SqlDelete.asp
<%
130
A table-type Recordset object can be created from a table in an Access database, but not from
an Open Database Connectivity (ODBC) or a linked table. A table-type Recordset can be
opened on only one table; it cannot be opened on a union query or a select query with a join.One
of the biggest advantages of this type of Recordset object is that you can index it by using an
index created for the underlying table. This allows much faster sorting and searching than is
possible with the other types.
A dynaset-type Recordset object can be created from either a local or a linked table, or with
a row-returning query that joins tables. Its actually a set of references to records in one or more
tables.With a dynaset, you can extract and update data from more than one table, including
linked tables from other databases.Changes made to records in the dynaset are also made in the
underlying table, and changes made by other users to data in the underlying tables while the
dynaset is open are reflected in the dynaset.The dynaset is the most flexible and powerful type of
Recordset object, although searches and other manipulations may not run as fast as with a
table-type Recordset.
A snapshot-type Recordset object is a static copy of a set of records as it exists at the time the
snapshot is created. A snapshot-type Recordset object can contain fields from one or more
tables in a database. You cant update a snapshot.
The main advantage of a snapshot is that it creates less processing overhead than the other
types, so it can run queries and return data faster, especially when working with ODBC data
sources.
The advantage of a forward-only-type Recordset object is that it usually provides the greatest
speed. It does, however, offer the least functionality of any Recordset.
Note : Since a snapshot stores a complete copy of all the records in a table, a snapshot may perform
more slowly than a dynaset if the number of records is large. To determine whether a snapshot or
dynaset is faster, you can open the Recordset as a dynaset and then open it as a snapshot to see which
131
Filtering
Filtering means to select the records which we want from a bigger massive group of records according
to the criteria which we set. In other words you can say that filtering is searching through all the records
of the database and selecting only those which satisfy our criteria whatever it may be.
Before understanding filtering and sorting practically we will consider a table containing the following
records in Ms Acess with database as fill and and tablename as filter
132
Here we will not create DSN and instead use a more faster and efficient way; DSN less connections.
These connections take a connection string as their argument.
Filter.asp
<% Option Explicit %>
<%
Sub ShowRec(qc1, qc2, qc3)
Response.Write <table width=500 border=0
cellpadding=0
cellspacing=0 & vbcrlf
Response.Write <tr>
Response.Write <td width=100>
Response.Write qc1
Response.Write </td><td width=200>
Response.Write qc2
Response.Write </td><td width=200>
Response.Write qc3
Response.Write </td></tr></table>
End Sub
Putting the values of ADO constants
Const adCmdTableDirect = &H0200
Const adLockReadOnly = 1
Const adOpenStatic = 1
Const adUseClient = 3
%>
<html>
<head>
<style>
133
134
Then we open the filter table and use our connection string which we created earlier as the argument to
ActiveConnection field. Next we set the CursorType to adOpenStatic. By default it is set to
adOpenForwardOnly which is more faster but it only allows us to move forward in the records and not
backwards. Since we will be moving the cursor back and forth and that we also need to use the
RecordCount property to count records, we set it to adOpenStatic which allows us to move both
ways in the recordset and also allowing us to use the RecordCount property. In the options field we use
adCmdTableDirect to tell the ASP interpreter that we are not using SQL statements and will connect
with the table directly.
filter3.asp
<% Option Explicit %>
<%
Sub ShowRec(qc1, qc2, qc3)
Response.Write <table width=500 border=0
cellpadding=0 cellspacing=0 & vbcrlf
Response.Write <tr>
Response.Write <td width=100>
Response.Write qc1
Response.Write </td><td width=200>
Response.Write qc2
Response.Write </td><td width=200>
Response.Write qc3
Response.Write </td></tr></table>
End Sub
Putting the values of ADO constants
Const adCmdTableDirect = &H0200
135
Const adLockReadOnly = 1
Const adOpenStatic = 1
Const adUseClient = 3
%>
<html>
<head>
<style>
body { font-family : Arial; font-size : 8pt; }
</style>
</head>
<body>
<%
Dim connStr
connStr = Provider=Microsoft.Jet.OLEDB.4.0; Data
Source= & _
Server.MapPath(/fill.mdb)
Dim rs
Set rs = Server.CreateObject(ADODB.Recordset)
rs.CursorLocation = adUseClient
rs.Open filter, connStr, adOpenStatic,
adLockReadOnly, adCmdTableDirect
If Not rs.EOF Then
Response.Write Records Found! & <br><br> &
vbcrlf
Response.Write Showing all records : &
rs.RecordCount & <br><br> & vbcrlf
While Not rs.EOF
ShowRec rs(id), rs(name), rs(country)
rs.MoveNext
Wend
Else
Response.Write No records Found!
End If
Now <b>filtering</b> the records and showing only
where country is USA : country = India
rs.Filter = country = India
Response.Write <br><br>Now <b>filtering</b> the
records
Response.Write and showing only where country is India :
136
Wend
rs.Close
Set rs = Nothing
%>
After showing the records in our filter.asp page, the record cursor will be present at the end of the records.
We move it back to the first record so that we can again iterate through the records and show them.
Next we sort the records using Recordset object Sort property. The way we show the records is the
same as explained in the last page by using our ShowRec Sub. Important thing to note is how we use
Sort property and then how records are displayed.
rs.Sort = name
It is the only line which is different from the code which we used in the previous example to show
records in the database. Sort property takes the name of column/s and then sorts the records according
to it. In this case we give it the name of name column from our filter table. So the records which will
now be shown will be sorted out according to that field.
rs.Sort =
rs.Sort = country
We can remove the sorting by setting Sort property to . Now the records are not sorted. Then we
again sort the records according to the column country from our filter table. This time when the
records are shown, they are sorted according to the country name alphabetically.
rs.Sort =
rs.Sort = country Desc
Then we remove the sorting. This time we sort according to the column name country and arranging
the records upside down by writing Desc in front of the country column field. Note that Sort property
takes one or more column name as its argument as well two more keywords; Asc and Desc. Desc
arranges the records upside down to those of Asc. So this time the records are sorted according to the
country column but are arranged upside down as we have appended Desc in front of it.
Filter property is used much the same way as Sort property is used. It takes a variety of arguments, one
of the criterion is very much like SQL WHERE clause.
rs.Filter = country = India
Now the above line of code will filter the records which contain string India in the column name
country. Thus only these records will be shown.
rs.Filter = name like %khan%
Much like the above code, this line will filter the records which contain the string %khan% in the name
column. Note in this case we have used wildcard % which matches any number of characters. Meaning there
by that we want to filter records which contain the string %khan% in the name column and we dont care
if there are any other characters present before or after the string khan in that column.
rs.Filter =
138
Above line removes the filter and works much like the Sort property.
rs.Filter = name like %khan%
rs.Sort = country
In the last paragraph of the code we use both Filter and Sort properties together to filter the records
based on the same above criteria but this time sorting out the records according the country name.
139
140
the scrollable cursor can move forward and backward in the result set.
Static Cursors
the static cursor can move forward and backward in the result set and
is usually not sensitive to changes in the underlying result set.
Keyset-Driven Cursors
the keyset-driven cursor can move forward and backward in the result
141
the dynamic cursor can move forward and backward in the result set
and is sensitive to all changes made to rows in the result set.
Mixed Cursors
Recordset Cursors(DAO) Describes the types of cursors available to applications that use the
Data Access Objects (DAO) Recordset object.
Recordset Cursors(ADO) the types of cursors available to applications that use the ActiveX
Data Objects (DAO) Recordset object.
The default cursor used when opening a recordset is forward only cursor
CursorTypeEnum values:
Constant
Value
Description
adOpenForwardOnly
adOpenKeyset
adOpenDynamic
adOpenStatic
The default settings are fine for a small result set if no updating is done, but a dynamic cursor is preferred
for a large result set in which the user is likely to find an answer before retrieving many of the rows.
Use default settings for singleton selects (returns one row), or other small result sets. It is more
efficient to cache a small result set on the client and scroll through the cache instead of asking the
server to implement a cursor.
Use the default settings when fetching an entire result set to the client, such as when producing a
report. Default result sets are the fastest way to transmit data to the client.
Default result sets cannot be used if the application is using positioned updates.
Default result sets cannot be used if the application is using multiple active statements. If cursors
are being used only to support multiple active statements, choose fast forward-only cursors.
Default result sets must be used for any Transact-SQL statement or batch of Transact-SQL
statements that will generate multiple result sets.
Dynamic cursors open faster than static or keyset-driven cursors. Internal temporary work tables
must be built when static and keyset-driven cursors are opened, but they are not required for
dynamic cursors.
In joins, keyset-driven and static cursors can be faster than dynamic cursors.
Each call to an API fetch function or method causes a roundtrip to the server when using server cursors.
Applications should minimize these roundtrips by using block cursors with a reasonably large number of
rows returned on each fetch.
In MS Access Open the table Select the Query Option and then select query in Design view
144
In the next promt Select Add then u will see table in design view Then click on all the fields that you want
to show.
Loop
Rs.Close
Set Rs=Nothing
Conn.Close
Set Conn=Nothing
%>
We generally Populate the Recordset object instance wth a database table from a SQL query, using the
Open method with the following syntax:
objRS. Source , objConn, CursorType, LockType, options
Where Source is the table name or SQL query.
a great deal of ASP code uses the Execute method to create Recordsets
implicitly;
Set Rs=Conn.Execute(CommandText,RecordsAffected,Options)
Command Text Parameter can be SQL query or database If it is a tablename then the Option need to be
adCmdTable
Use of command Object
ADO provides several different ways to accomplish a particular task.We are familiar with two ways to
generate a recordset
The first method :
Dim oRs
Set oRs Server.CreateObject(ADODB.Recordset);
ORs.open strsql,conn
The second one is using the Execute Method
Dim oRs
Set oRs=conn.Execute(strsql)
The Command Object can be used to implicitly create Recordsets
Using the Execute method on a Command object executes the query specified in the CommandText
property of the object. If the CommandText property specifies a row-returning query, any results the
execution generates are stored in a new Recordset object. If the command is not a row-returning
query, the provider returns a closed Recordset object. Most application languages allow you to ignore
this return value if no Recordset is desired.
If the query has parameters, the current values for the Command objects parameters are used unless
you override these with parameter values passed with the Execute call. You can override a subset of the
parameters by omitting new values for some of the parameters when calling the Execute method. The
146
order in which you specify the parameters is the same order in which the method passes them. For
example, if there were four (or more) parameters and you wanted to pass new values for only the first
and fourth parameters, you would pass Array(var1,,,var4) as the Parameters argument.
Note Output parameters will not return correct values when passed in the Parameters argument.
When all these properties have been correctly set we can issue the Execute method of Connection
Object
Syntax
On a Command object:
Set recordset = command.Execute(RecordsAffected,
command.Execute RecordsAffected, Parameters, Options
Parameters,
Options)
Description
recordset
command
RecordsAffected Optional. A Long variable to which the provider returns the number of records
that the operation affected.
Parameters
CommandText
Options
147
Following example shows selecting records from the database using Command object
<HTML>
<HEAD>
<TITLE>Selecting Data Script</TITLE>
</HEAD>
<BODY>
<%
set conn=Server.CreateObject(adodb.Connection)
conn.OpenDSN=example, ,
set rs=Server.CreateObject(adodb.Recordset)
Designate your SQL statement
sqlstmt = SELECT * from filter
set Comm=Server.CreateObject(adodb.Command)
Comm.ActiveConnection=conn
Comm.CommandText=sqlstmt
set rs=Comm.Execute
This area is a logical error routine. If there
is no data in the database (the rs.eof or record set end
of file),
then display that there are no records in the database.
Else, youre going to display the script as its written
If rs.eof then
response.write There are no records in the
database<br><br>
response.end
Else
This is an example of a loop. The Do statement
matches up with the Loop at the end of this script. It
is associated
with the do as it is a conditional loop. While the file is not
at the end, continue to do the following.
Do while not rs.eof
%>
<b> Player ID : <i> <%= rs(id) %></i><BR>
Player Name : <i> <%= rs(name) %></i><BR>
Players
Country :<i> <%=rs(country) %></i><BR></b>
<HR>
<%
rs.MoveNext
loop
148
149
PREFACE
A few years ago, various fields were researched independently, they never
assisted, interfered or interacted with other researches. Thereafter a few more
years down the line came in the set of INFORMATION TECHNOLOGY which
altered the entire globe. It plugged on all researches scientific and otherwise via
the tool named Internet. Today we are using these computer aided tools to
enhance and represent our business and information in a more appealing and
presentable manner. At the gateway of the 21 st century, the tools and connectivity
of digital age have given us better ways to obtain, share and act on information
in new and remarkable ways.
As a Director of Azure, my dream is to spread this Information technology
through the community to be successful and enterprising IT professionals leading
this industry to a brighter future by developing powerful tools for analysis and
aptly using the information provided by these solutions. I feel that the flow of
Information and knowledge always flow from father to son, like a child learn so
many things from family itself. So, when a father knows about IT he always insist
that his son should learn IT. This way only I think we can end this IT word in
the each corner of the world. This module will be just hit or help you to get
acquire of this technology and spared it through the community.
To achieve this objective we have succeeded to establish well equipped GLSIIT,
Gujarat Institute of Technology (GIT), Institute of Computer Technology (ICT),
H. K. Computer Centre, C. U. Shah Science College Computer Centre, H. A.
College of Commerce Computer Centre, City College Computer Centre, Jyoti
Sangh Computer Centre, Dharamsinh Desai Institute of Commerce Computer
Centre (Nadiad), Shri N. P. Patel Computer Science Centre (Kalol), Mohinaba
Computer Centre, Ahmedabad and are imparting training to more than 3500
students every year. Furthermore it has been a matter of pride that we have
successfully met the milestones on the road to success to impart the best and
latest technology to the students.
I highly appreciate the efforts put in by the staff members of our organization
who have jointly contributed to put together this module. In addition, I would
also like to thank our printers Moti Enterprise.
So, continue your strive to attain success with this module. All the best
Dushyant Joshi
Director
STUDY REFERENCE
Rev. 1.0/9-10-2001
CONTENT
Introduction to ASP ............................................................................................................... 01
- Working with Scripting Language
- Hardware and Software Requuirement
- Advantage Of ASP
- Installation of PWS/IIS
- Language support
First ASP Program ................................................................................................................. 11
- First Simple Script
- Comments
- Case Sensivity
- Line Continuation Character
- ASP Process
ASP Variables .......................................................................................................................... 16
- VBScript Data Types
- Declaring and Naming Variables
- Option Explicit
- Declaration of Variable
- VBScript Constants
- Arrays
VBScript Operator ................................................................................................................. 26
- Types of Operators
- Assignment Operator
- Arithmatic Operator
- Comparison Operator
- Logical Operator
- Concation Operator
Control Structure ................................................................................................................... 36
- Condition Logic
- Looping Logic
- Braching Logic
Typecasting of Variables
- Math Function
- Date Time Function
- String Function
Sub Procedures & Function Procedures
ASP Object ............................................................................................................................... 61
Properties,Methods,Events & Collection
ASP in built Objects
- Request
- Response
- Application
- Server
- Session
- ObjectContext
- ASP Error Object
- Component
Response & Request Object .............................................................................................. 66
Response Object
- Methods
- Cookies
- Properties
- Caching
Request Object
- Standard HTTP Header
- GET and POST Method
- Collection for Request
Session, Server, Application Object ................................................................................. 86
Session Object
- Method and Events
Application Object
- Method and Events
Global.asa
- Inclusion of file using Include/Vrtual
- #include in Global.asa
Server Object
- Methods
ASPError Object
ASP Transaction
- MTS
- Commit and Rollback