Вы находитесь на странице: 1из 154

Introduction to ASP

- Working with Scripting Language


- Hardware and Software Requuirement
- Advantage Of ASP
- Installation of PWS/IIS
- Language support

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.

Script: Working with Scripting Languages


Programming languages such as Visual Basic, C++, and Java provide low-level access to computer
resources and are used to create complex, large-scale programs. Scripting languages, however,
are used to create programs of limited capability, called scripts, that execute Web site functions
on a Web server or browser. Unlike more complex programming languages, scripting languages
are interpreted, instruction statements are sequentially executed by an intermediate program called
a command interpreter. Scripts can be embedded in HTML pages to format content or used to
implement COM components encapsulating advanced business logic.

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

Server Side Scripting Language


Server-side just means that the Web Server rather than running a script on each users personal
computer handles the control of the script. Web Server runs the scripts and sends standard HTML
(web pages) to each users browser. All the end users browser has to worry about is displaying
the results and does not have to worry about the underlying script used to generate the web
pages.
Request

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.

Hardware and Software Requirement


ASP is a Microsoft product, so you are going to have to use a machine with either Windows95/
98 or an NT machine .If you have a choice, go for the NT machine every time (NT is normally
more stable that Win9x, plus the chances are your web host will be using NT and it is always
safest to develop your pages on as similar a machine to the eventual host as you can) but either
type will do in the end.
Operating System

Softwares

NT - Server (v4)

NT Service Pack 3, and Internet Information Server 3, but preferably


the NT Option Pack (provides the new ASP 2)
As with NT Server, but the Workstation version is called Peer Web
Server (with Active Server Pages - a separate install option)
Personal Web Server (with Active Server Pages a separate install
option)
Internet Information Server

NT - Workstation (v4)
Windows 95/98
Windows 2000

System Requirements
Microsoft Windows NT Server 4.0
Computer/Processor

For Intel and compatible systems: 486/33 MHz or higher, or


Pentium or Pentium PRO processor RISC-based systems: RISC
processor compatible with the Microsoft Windows NT Server
version 4.0 operating system.

Memory

16 MB of memory (RAM)

Hard Disk

For Intel and compatible systems: 125 MB of available hard-disk


space minimum RISC-based systems: 160MB of available hard
disk space

Drive

CD-ROM drive

Display

VGA, Super VGA, or video graphics adapter compatible with


Windows NT Server 4.0

Computer/Processor

486DX/66 MHz or higher processor

Memory

24mb of RAM; more memory improves performance

Hard Disk

When using FAT16 File system, typical installation requires 260


MB of available hard-disk space, but may range between 210 MB
and 400 MB, depending upon system configuration and options
selected When using FAT32 File system, typical installation requires
210 MB of available hard-disk space, but may range between 190
MB and 305 MB, depending upon system configuraiton and options
selected.

Drive

CD-ROM or DVD-ROM Drive

Display

VGA or higher resolution monitor

Peripherals

Microsoft Mouse or compatible pointing device

Miscellaneous

Additional items or services required to use certain features:


14,400 or higher-baud modem or fax modem required for internet access

Minimum Requirements
Computer/Processor

133 MHz or higher Pentium-compatible CPU

Memory

64 megabytes (MB) of RAM recommended minimum; more


memory generally improves responsiveness

Hard Disk

2GB hard disk with a minimum of 650MB of free space

CPU Support

Windows 2000 Professional supports single and dual CPU systems

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.

Installing Personal Web Server


If you are running Windows 95/98 then you will most probably need PWS to run .asp pages. Just
in case if you dont know what PWS stands for, PWS stands for Personal Web Server. If you
have got Windows CD with yourself then you can install PWS from there. Or if you want then you
can download the latest version of Personal Web Server from www.microsoft.com. Run the setup
file and PWS will install just as any other application is installed on your system. Once the setup
finishes you will be ready to run the PWS.
On Installation of PWS we will she the following the desktop

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.

At the end of installation you will see the following prompt

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.

From your Start Button, go to Settings, and Control Panel


In the Control Panel window select Add/Remove Programs
In the Add/Remove window select Add/Remove Windows Components
In the Wizard window check Internet Information Services, click OK
An Inetpub folder will be created on your harddrive
Open the Inetpub folder, and find a folder named wwwroot
8

7.
8.
9.
10.

Create a new folder, like MyWeb, under wwwroot.


Use a text editor to write some ASP code, save the file as test1.asp in the MyWeb
folder.
Make sure your Web server is running.
Open your browser and type in http://localhost/MyWeb/test1.asp, to view your first
ASP page.

To Launch the Internet Service Manager choose Start,Programs,Administrative tool,Internet Service


Manager .The Internet Service Manager allows you to configure your web site,FTP Server and
SMTP Service . The Internet Service Manager displays the directory structure for your web site.

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.

Setting the Language for an Application


To set the primary scripting language for all pages in an application, set the Default ASP Language
property on the App Options tab in the Internet Information Services snap-in.

Setting the Language for a Page


To set the primary scripting language for a single page, add the <%@ LANGUAGE %> directive
to the beginning of your .asp file. The syntax for this directive is:
<%@ LANGUAGE=ScriptingLanguage %>
where ScriptingLanguage is the primary scripting language that you want to set for that particular
page. The setting for a page overrides the global setting for all pages in the application.

Using VBScript and JScript on the Server


When using VBScript on the server with ASP, two VBScript features are disabled. Because scripts
written with Active Server Pages are executed on the server, the VBScript statements that present
user-interface elements, InputBox and MsgBox, are not supported.
For a list and description of all VBScript and JScript operators, functions, statements, objects,
properties, and methods, refer to the VBScript Language Reference and JScript Language
Reference.You can find this reference at the Microsoft Windows Script Technologies Web site,
located at http://msdn.microsoft.com/scripting/.

10

First ASP Program


-

First Simple Script


Comments
Case Sensivity
Line Continuation Character
ASP Process

11

First ASP Program


Before we start to build our first program we should know how to run an asp file in browser. To
see an .asp file in action, you need to place the file the web servers content directory space. This
directory space begins in a directory called the Web root.
ASP code
<%
%>

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.

Creating a simple script:

Open Windows Notepad or any other simple text editor.


Type the following code into the text editor:
<HTML>
<HEAD>
<TITLE>Hello World</TITLE>
</HEAD>
<BODY>
<% @ Language=VBScript %>
<%
This will print to the browser the
words Hello World.
response.write Hello World!
%>
</BODY>
</HTML>
12

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.

Line Continuation Character


Many times we may encounter a problem that Statement is too Long in that case we can use Line
continuation character.
Here is a example:
<HTML>
<BODY>
<%
response.Write
This is areallllllllllyy
BigggggggggggStateement!!!!!!!
%>
</BODY>
</HTML>
This will give an error Expected statement . If the same thing is written with the Line continuation
character _ it will show the big statement in the browser
14

<HTML>
<BODY>
<%
response.Write(This is areallllllllllyy _
BigggggggggggStateement!!!!!!!)
%>
</BODY>
</HTML>

The ASP Process


Request
Preprocessing
Execution
Translation
Respones

:
:
:
:
:

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
-

VBScript Data Types


Declaring and Naming Variables
Option Explicit
Declaration of Variable
VBScript Constants
Arrays

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.

What are the VBScript Data Types?


VBScript has only one data type and its called a Variant. A Variant is a special kind of data type
that can contain different kinds of information, depending on how its used. Because Variant is the
only data type in VBScript, its also the data type returned by all functions in VBScript.
A Variant can contain either numeric or string information. A Variant behaves as a number when
youre using it in a numeric context and as a string when you use it in a string context. That is, if
youre working with data that looks like numbers, VBScript assumes that it is numbers and does
the thing that is most appropriate for numbers. Of course, you can always make numbers behave
as strings, by enclosing them in quotation marks. Similarly, if youre working with data that can
only be string data, VBScript treats it as string data.
Beyond the simple numeric or string classifications, a Variant can make further distinctions about
the specific nature of numeric information. For example, you can have numeric information that
represents a date or a time. When used with other date or time data, the result is always expressed
as a date or a time. Of course, you can also have a rich variety of numeric information ranging in
size from Boolean values to huge floating-point numbers. These different categories of information
that can be contained in a Variant are called subtypes. Most of the time, you can just put the kind
of data you want in a Variant and it behaves in a way that is most appropriate for the data it
contains.
The following table shows the various subtypes of data that a Variant can contain.
Subtype

Description

Empty

Variant is uninitialized. Value is either 0 for numeric variables or a zerolength string () for string variables.

Null

Variant intentionally contains no valid data.

Boolean

Contains either True or False.

17

Byte
Integer

Contains integer in the range 0 to 255.


Contains integer in the range -32,768 to 32,767.

Currency

-922,337,203,685,477.5808 to 922,337,203,685,477.5807.

Long

Contains integer in the range -2,147,483,648 to 2,147,483,647.

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)

Contains a number that represents a date between January 1, 100 to


December 31, 9999.

String

Contains a variable-length string that can be up to approximately 2 billion


characters in length.

Object

Contains an object.

Error

Contains an error number.

Declaring and Naming Variables


Declaring a variable means telling the script engine that a variable with a particular name exists so
that you can use references to the variable throughout a script. Variables can not start with a
number, nor have a period (.) in it.

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.

How to declare a variable


During declaration we need not to specify the type of variable because in ASP and VBScript by
default the type of variable is Variant. It means can accept any type like Integer, Float, Double,
Date, String. We can initialized a variable by = operator.
It is better to give descriptive name to your variables as compared to small or single letter variable
because as the code size increases it becomes more difiicult to debug .If a variable is a String then
it is a lot better to give variable name like strName as compared to x,y or z.
20

Suggested Type prefixes for Variables names


Variable Type

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

Perform a binary comparison.

vbTextCompare

Perform a textual comparison.

Date and Time Constant


Constant

Value

Description

vbSunday

Sunday

vbMonday

Monday

vbTuesday

Tuesday

vbWednesday

Wednesday

vbThursday

Thursday

vbFriday

Friday

vbSaturday

Saturday

vbUseSystem

Use the date format contained in the


regional settings for your computer.

vbUseSystemDayOfWeek

Use the day of the week specified


in your system settings for the first
day of the week.

vbFirstJan1

Use the week in which January 1


occurs (default).

vbFirstFourDays

Use the first week that has at least


four days in the new year.

vbFirstFullWeek

Use the first full week of the year.

Date Format Constants


Constant

Value

Description

vbGeneralDate

Display a date and/or time. For real numbers,


display a date and time. If there is no fractional
part, display only a date. If there is no integer
part, display time only. Date and time display is
determined by your system settings.

vbLongDate

Display a date using the long date format


specified in your computers regional settings.

22

vbShortDate

Display a date using the short date format


specified in your computers regional settings.

vbLongTime

Display a time using the long time format


specified in your computers regional settings.

vbShortTime

Display a time using the short time format


specified in your computers regional settings.

String Constant
Constant

Value

Description

vbCr

Chr(13)

Carriage return.

vbCrLf

Chr(13)
& Chr(10)

Carriage returnlinefeed combination.

vbFormFeed

Chr(12)

Form feed; not useful in Microsoft Windows.

vbLf

Chr(10)

Line feed.

vbNewLine

Chr(13) & Chr(10)


or Chr(10)

vbNullChar

Chr(0)

vbNullString

Platform-specific newline character; whatever is


appropriate for the platform.
Character having the value 0.
String having value 0 Not the same as a zerolength string (); used for calling external
procedures.

vbTab

Chr(9)

Horizontal tab.

vbVerticalTab

Chr(11)

Vertical tab; not useful in Microsoft Windows.

Constant

Value

Description

vbUseDefault

-2

Use default from computers regional settings.

vbTrue

-1

True

vbFalse

False

TriState Constant

23

VarType constants
Constant

Value

Description

vbEmpty

Uninitialized (default)

vbNull

Contains no valid data

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

Variant ( for arrays of variants)


Data access object

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

How to Store the value in Arrays


According to above Syntax:
<%
ArrayName(0)=10
ArrayName(1)=20
ArrayName(2)=30
ArrayName(3)=40
ArrayName(4)=50
ArrayName(5)=60
%>
Now Index Number 2 is having the value 30, which is third element of the array ArrayName.
Arrays arent limited to a single dimension. You can have as many as 60 dimensions, although most
people cant comprehend more than three or four dimensions. Multiple dimensions are declared by
separating an arrays size numbers in the parentheses with commas. In the following example, the MyTable
variable is a two-dimensional array consisting of 6 rows and 11 columns:
Dim MyTable(5, 10)
If u want to iterate through an array of unknown size We ca use syntax like this:
For iVal=Lbound(ArrayName) to Ubound(ArrayName)
Next
The ReDim statement is used to size or resize a dynamic array that has already been formally declared
using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). We
can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
If you use the Preserve keyword, you can resize only the last array dimension, and you cant change the
number of dimensions at all. For example, if your array has only one dimension, you can resize that
dimension because it is the last and only dimension. However, if your array has two or more dimensions,
you can change the size of only the last dimension and still preserve the contents of the array.
The following example shows that you can increase the size of the last dimension of a dynamic array
without erasing any existing data contained in the array.
ReDim X(10, 10, 10)
ReDim Preserve X(10, 10, 15)

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

The + operator syntax has these parts:


Part
Result
Expression1
Expression2

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

Both expressions are numeric


Both expressions are strings
One expression is numeric
and the other is a string
One expression is Empty and the
other is numeric
One expression is Empty and the
other is a string
Both expressions are Empty

Perform a numeric comparison.


Perform a string comparison.
The numeric expression is less than the string
expression.
Perform a numeric comparison, using 0 as the Empty
expression.
Perform a string comparison, using a zero-length string
() as the Empty expression.
The expressions are equal.

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

And bit in expression2 is The result is


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

And bit in expression2 is


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

And bit in expression2 is Then result is

0
0
1
1

0
1
0
1

Concatenation Operator
& Operator

34

0
1
1
0

Forces string concatenation of two expressions.


Syntax
result = expression1 & expression2
The & operator syntax has these parts:
Part
Result
Expression1
Expression2

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.

Select Case....End Select


This is a very useful instruction in case we want to check different values for variable.Lets check
an example:
<%mynumber=3
Select Case mynumber
Case 1
Response.write (Number 1)
Case 2
Response.write (Number 2)
Case 3
39

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)

Type Casting of Variables


Many times we want facility to change between datatypes like we want to convert string value
120 into an integer value or we need to convert convert the string 12/06/1998 into a data value
or vice versa. Here is the list of some useful typecaste functions

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)

Check contains True.


Define variable.
Check contains False.

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

MySingle1 = CSng(MyDouble1) MySingle1 contains 75.34211.


MySingle2 = CSng(MyDouble2) MySingle2 contains 75.34216.

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

A String containing True or False.


A String containing a date in the short-date format of your system.
A run-time error.
A zero-length String ().
A String containing the word Error followed by the error number.
A String containing the number.

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

Date time Functions


Date
Returns the current system date.

Remarks
The following example uses the Date function to return the current system date:
Dim MyDate
MyDate = Date
MyDate contains the current system date.

DateDiff( interval , date1 , date2 [, firstdayofweek [,z firstweekofyear ]])


Returns the number of intervals between two dates.
The DateDiff function syntax has these parts:
intervalRequired. String expression that is the interval you want to use to calculate the differences
between date1 and date2..date1, date2Required. Date expressions. Two dates you want to use
47

in the calculation.firstdayofweekOptional. Square brackets[ ] indicates that, argument is optinonal


.Constant that specifies the day of the week. If not specified, Sunday is assumed.. Constant that
specifies the first week of the year. If not specified, the first week is assumed to be the week in
which January 1 occurs.
You can use the DateDiff function to determine how many specified time intervals exist between
two dates. For example, you might use DateDiff to calculate the number of days between two
dates, or the number of weeks between today and the end of the year.
To calculate the number of days between date1 and date2, you can use either Day of year (y)
or Day (d). When interval is Weekday (w), DateDiff returns the number of weeks between
the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2.
It counts date2 but not date1. If interval is Week (ww), however, the DateDiff function returns
the number of calendar weeks between the two dates. It counts the number of Sundays between
date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesnt count date1, even
if it does fall on a Sunday.
If date1 refers to a later point in time than date2, the DateDiff function returns a negative number.
The firstdayofweek argument affects calculations that use the w and ww interval symbols.
If date1 or date2 is a date literal, the specified year becomes a permanent part of that date.
However, if date1 or date2 is enclosed in quotation marks ( ) and you omit the year, the current
year is inserted in your code each time the date1 or date2 expression is evaluated. This makes it
possible to write code that can be used in different years.
When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for
Year (yyyy) returns 1 even though only a day has elapsed.
The following example uses the DateDiff function to display difference of year, month and days
between two given dates.
<%
diffyear=DateDiff("yyyy", # 3/04/1999 #,# 3/04/2000 #)
'Output 1
diffmonth=DateDiff("m", # 3/04/1999 #,# 3/04/2000 #)
'Output 12
diffdays=DateDiff("d", # 3/04/1999 #,# 3/04/2000 #)
'Output 366
%>
<html><body>
DateDiff("yyyy", #3/04/1999#,#3/04/2000) :<%= diffyear
%><br>
DateDiff("m", #3/04/1999#,#3/04/2000) : <% =diffmonth
%><br>
DateDiff("d", #3/04/1999#,#3/04/2000) : <% =diffdays%>
</body></html>
48

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.

Weekday( date, [ firstdayofweek ])


Returns a whole number representing the day of the week.
The Weekday function syntax has these arguments:
dateAny expression that can represent a date. If date contains Null Null is returned.firstdayofweek
A constant that specifies the first day of the week. If omitted, vbSunday is assumed.
The following example uses the Weekday function to obtain the day of the week from a specified
date:
Dim MyDate, MyWeekDay
MyDate = #October 19, 1962# Assign a date.
MyWeekDay = Weekday(MyDate)
MyWeekDay contains 6 because
MyDate represents a Friday.

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.

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


Returns a zero-based array containing a subset of a string array based on a specified filter criteria.
The Filter function syntax has these parts:
InputStringsRequired. One-dimensional array of strings to be searched.ValueRequired. String to
search for.IncludeOptional. Boolean value indicating whether to return substrings that include or
exclude Value.If Include is True,Filter returns the subset of the array that contains Value as a
substring.If Include is False, Filter returns the subset of the array that does not contain Value as
a substring.CompareOptional.Numeric value indicating the kind of string comparison to use.
Settings
The Compare argument can have the following values:
Constant

Value

Description

vbBinaryCompare

Perform a binary comparison.

vbTextCompare

Perform a textual comparison.

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.

InStrRev( string1 , string2 [, start [, compare ]])


Returns the position of an occurrence of one string within another, from the end of string.
The InStrRev function syntax has these parts:
Part
Description
string1
Required. String expression being searched.
string2
Required. String expression being searched for.
start
Optional. Numeric expression that sets the starting position for each search.
If omitted, -1 is used, which means that the search begins at the last character
position. If start contains Null, an error occurs.
compare
Optional. Numeric value indicating the kind of comparison to use when
evaluating substrings. If omitted, a binary comparison is performed.

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

The following examples use the InStrRev function to search a string:


Dim SearchString, SearchChar, MyPos
SearchString =XXpXXpXXPXXP
String to search in.
SearchChar = P
Search for P.
MyPos = InstrRev(SearchString,SearchChar,10,0)comparison
A binary comparison starting at position 10. Returns 9.
MyPos = InstrRev(SearchString, SearchChar, -1, 1)
51

Comparison starting at last position returns 12


MyPos = InstrRev(SearchString, SearchChar, 8)
Returns 0.
Note The syntax for the InStrRev function is not the same as the syntax for the InStr function.

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.

Mid( string , start [, length ])


Returns a specified number of characters from a string.
The Mid function syntax has these arguments:
stringString expression from which characters are returned. If string contains Null, Null is returned.
startCharacter position in string at which the part to be taken begins. If start is greater than the
number of characters in string, Mid returns a zero-length string ().lengthNumber of characters
to return. If omitted or if there are fewer than length characters in the text (including the character
at start), all characters from the start position to the end of the string are returned.

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

Right( string, length )


The Right function syntax has these arguments:
string String expression from which the rightmost characters are returned. If string contains Null,
Null is returned.length Numeric expression indicating how many characters to return. If 0, a
zero-length string is returned. If greater than or equal to the number of characters in string, the
entire string is returned.Remarks
To determine the number of characters in string, use the Len function.
The following example uses the Right function to return a specified number of characters from the
right side of a string:
Dim AnyString, MyStr
AnyString = Hello World

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.

Replace( expression , find , replacewith [, start [, count [, compare ]]])


The Replace function syntax has these parts:
Part
expression
find
replacewith
start

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

Perform a binary comparison.


Perform a textual comparison.

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

Copy of expression with all occurences of


find removed.
Zero-length string.
Copy of expression.

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.

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


Returns a zero-based, one-dimensional array containing a specified number of substrings.
The Split function syntax has these parts:
expressionRequired. String expression containing substrings and delimiters. If expression is a
zero-length string, Split returns an empty array, that is, an array with no elements and no
data.delimiterOptional. String character used to identify substring limits. If omitted, the space
character ( ) is assumed to be the delimiter. If delimiter is a zero-length string, a single-element
array containing the entire expression string is returned.countOptional. Number of substrings to
be returned; -1 indicates that all substrings are returned.compareOptional. Numeric value indicating
the kind of comparison to use when evaluating substrings. See Settings section for values.Settings
The compare argument can have the following values:
Constant

Value

Description

vbBinaryCompare

Perform a binarycomparison.

vbTextCompare

Perform a textual comparison.

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

MyArray(1) contains is.


MyArray(2) contains fun!.
Msg = MyArray(0) & & MyArray(1)
Msg = Msg & & MyArray(2)
Response.write Msg

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.

LTrim( string ) RTrim( string ) Trim( string )


Returns a copy of a string without
leading spaces (LTrim),
trailing spaces (RTrim),
both leading and trailing spaces (Trim).
The string argument is any valid string expression If string contains Null Null is returned.

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

Getting Data into and out of Procedures


Each piece of data is passed into your procedures using an argument. Arguments serve as

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.

Using Sub and Function Procedures in Code


A Function in your code must always be used on the right side of a variable assignment or in an
expression. For example:
Temp = Celsius(fDegrees)
or
Response.write The Celsius temperature is & _
Celsius(fDegrees) & degrees.
To call a Sub procedure from another procedure, you can just type the name of the procedure
along with values for any required arguments, each separated by a comma. The Call statement is
not required, but if you do use it, you must enclose any arguments in parentheses.
The following example shows two calls to the MyProc procedure. One uses the Call statement in
the code; the other doesnt. Both do exactly the same thing.
1) Call MyProc(firstarg, secondarg)
2) MyProc firstarg, secondarg
Note that the parentheses are omitted in the call when the Call statement isnt used.
In the next two examples, we have given our visitors name, and depending on that answer a
different response is sent to the client.
<%
TheName=Abhy
if TheName=Abhy then
ResponseToAbhy()
else
ResponseToUnknown()
end if
Sub ResponseToAbhy()
response.write Hi, Abhay How are you?
End Sub
58

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

formatted as brown and bold.Example for function


<%
FUNCTION bigBlue( theText )
theText = <big> & theText & </big>
bigBlue = <font color=blue> & theText & </font>
END FUNCTION
FUNCTION smallRed( theText )
theText = <small> & theText & </small>
smallRed = <font color=red> & theText & </font>
END FUNCTION
FUNCTION brownBold( theText )
theText = <b> & theText & </b>
brownBold = <font color=brown> & theText & </font>
END FUNCTION
%>
<html>
<head><title>functions.asp</title></head>
<body>
<%=bigBlue( Hello World! )%>
<p>
<%=smallRed( This is small and red )%>
<p>
<%=bigBlue( This is big and blue! )%>
<p>
<%=brownBold( This is bold and brown! )%>
</body>
</html>

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

Properties Methods, Events and Collection


Properties defines or descripbes about the Object
Take a Window, for example. A Window is an object. It has properties, such as the property of
being maximized, minimized, or sized.
Methods defines the behaviour of object it gives funcationality to our objects
for eg.A window has methods, such as the Open and Close method.
Events define ability of an object to notify other object that some relevant action has occurred
.And events can occur, which will affect the Window object, such as a mouse-click on the minus
sign in the upper right-hand corner of the Window, which minimizes the Window.
62

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.

Objects and Components


ASP inbuilt Objects
Request Object
The Request object lets you tap into the information passed through an HTTP request. You can
use the Request object to parse encoded URLs, access information from a form, and read cookies,
client certificates, and the HTTP headers.

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.

ASP Error Object


You can use the ASPError object to trap ASP error and return more informative descriptions to
users.It can help a lot in testing and debugging.

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:

Microsoft ASP Component Catalog


ASP Central
Active Server Pages.Com

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

Response & Request Object


Response Object
- Methods
- Cookies
- Properties
- Caching
Request Object
- Standard HTTP Header
- GET and POST Method
- Collection for Request

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

Response.Cookies( firstVisit ).Expires = 1/1/2005


END IF
%>
<html>
<head><title>cookies.asp</title></head>
<body>
Your first recorded visit to this page was on:
<br> <%=Request.Cookies( firstVisit )%>
</body>
Iterating through a Collection with Subkeys in cookies Scripts might embed several related values
in a single cookie to reduce the number of cookies passed between the browser and the Web
server. The Cookies collection of the Request and Response objects can thus hold multiple values
in a single item. These subitems, or subkeys, can be accessed individually. Subkeys are supported
only by the Request.Cookies and Response.Cookies collections. Request.Cookies supports only
read operations; Response.Cookies supports only write operations.
The following code creates a regular cookie and a cookie with a subkeys:
<%
'Send a cookie to the browser.
Response.Cookies("Fruit") = "Pineapple"
'Send a cookie with subkeys to browser.
Response.Cookies("Mammals")("Elephant") = "African"
Response.Cookies("Mammals")("Dolphin") = "Bottlenosed"
%>
The cookie text in the HTTP response sent to the browser would appear as the following:
HTTP_COOKIE= Mammals=ELEPHANT=African&DOLPHIN=Bottlenosed; Fruit=Pineapple;
You can also enumerate all the cookies in the Request.Cookies collection and all the subkeys in a
cookie. However, iterating through subkeys on a cookie that does not have subkeys will not produce
an item. You can avoid this situation by first checking to see whether a cookie has subkeys by
using the HasKeys attribute of the Cookies collection. This technique is demonstrated in the
following example.
<%
'Declare counter variables.
Dim Cookie, Subkey
'Display the entire cookie collection.
For Each Cookie In Request.Cookies
Response.Write Cookie
If Request.Cookies(Cookie).HasKeys Then
Response.Write "<BR>"
'Display the subkeys.
72

For Each Subkey In Request.Cookies(Cookie)


Response.Write " ->" & Subkey & " = " &
Request.Cookies(Cookie)(Subkey) & "<BR>"
Next
Else
Response.Write " = " & Request.Cookies(Cookie) &
"<BR>"
End If
Next
%>
This script would return the following results:
Mammals
->ELEPHANT = African
->DOLPHIN = Bottlenosed
Fruit = Pineapple

Preserving State without Cookies


Not all browsers support cookies. Even with browsers that do support cookies, some users prefer to
turn off cookie support. If your application needs to be responsive to browsers that dont support
cookies, you cannot use ASP session management.In this case, you must write your own mechanism to
pass information from page to page in your application. There are two general ways to do this:
Add parameters to a URLs query string. For example:
http://MyServer/MyApp/start.asp?name=Jeff
Some browsers, however, will discard any explicit parameters passed in a query string if a form is
submitted with the GET method.
Add hidden values to a form. For example, the following HTML form contains a hidden control, which
does not appear on the actual form and remains invisible in the users Web browser. The form passes a
user identification value, in addition to the information supplied by the user, by using the HTTP POST
method.
<FORM METHOD=POST ACTION=/scripts/inform.asp>
<INPUT TYPE=text NAME=city VALUE=>
<INPUT TYPE=text NAME=country VALUE =>
<INPUT TYPE=hidden NAME=userid VALUE= <%= UserIDNum(i)
%>
<INPUT TYPE=submit
VALUE=Enter>
This method requires all link destinations that pass user information to be coded as HTML forms.To
overcome this problem Microsoft has released a utility called Cookie Munger.
The Cookie Munger filter is a utility that enables Active Server Pages to work with browsers that do not
73

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.

The Request Object


What is HTTP Header
An HTTP Header is a single piece of information sent either from client to server (when requesting
page) or from server to client when responding to page request

Standard HTTP Header


HTTP Header Name

Description

HTTP_ACCEPT
HTTP_ACCEPT_LANGUAGE
HTTP_CONNECTION
HTTP_HOST
HTTP_USER_AGENT
HTTP_COOKIE
HTTP_REFER

A List Of MIME types


Type of Language the browser Accepts
Type of Connection between the client and the Web Server
Hostname of the Client Computer
The browser Type ,version and OS information of the client
The Cookie sent from the browser
Full URL of the Web page containing the hyperlink

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>

Syntax for Request


Request.collection
Request.property
Request.method
The Request object makes available all the values that client browser passes to the server during
an HTTP request. It includes client browser info, cookie details (of this domain only), client certificates (if accessing through SSL) etc
The Web browser uses the method attribute of the <FORM> tag to determine how to send the
forms data to the Web server. There are two submission methods.
GET: The Web browser submits the forms data as a part of a URL.
POST: The Web browser sends the forms data separately from the URL as streams of bits.

The GET Method


The GET method is so called because the browser used the HTTP GET command to submit the
data.The GET command sends a URL to the Web server. If the forms data use sent to Web
server using the GET command, the browser must include all the data in the URL.
The Key features of the GET method of data submission are as follows:
The values of all the fields are concatenated and passed to the URL specified in the action attribute of the <form> tag. Each fields values appear in the name-value format.
Any character with a special meaning in the forms data is enclosed using a special encoding
scheme commonly referred to as URL encoding. In this encoding scheme a space is replaced by a
77

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

The POST Method


In the POST method of data submission, the Web browser uses the POST command to submit the
data to the server and includes the forms data in the body of that command. The POST method
can handle any amount of data, because the browser sends the data as a separate stream. The
POST method should be used to send potentially large amounts of data to a web server.
Eg.
The two pages below illustrate how you can grab and display the fields from an HTML form. The
first page, named survey.asp contains a simple HTML form that asks the user for their first and
last name.
The HTML form in survey.asp submits the form information to a page named surveyresults.asp.
This page uses the Form collection of the Request object to grab the information the user entered
into the form fields and display it.
Survey.asp
<html>
<head><title>survey.asp</title></head>
<body>
<form method=post action=surveyresults.asp>
Please complete the following information:
<p>Enter your first name:
<br><input name=fname type=text size=30">
<p>Enter your last name:
<br><input name=lname type=text size=30">
<p>
<input type=submit value=Submit Form>
</form>
</body>
</html>
SurveyResults.asp
<html>
<head><title>surveyresults.asp</title></head>
<body>
<%
fname = Request.Form( fname )
lname = Request.Form( lname )
%>

78

Hello <%=fname%> <%=lname%>!


</body>
</html>

Collection for Request


QueryString
The QueryString collection retrieves the values of the variables in the HTTP query string. The
HTTP query string is specified by the values following the question mark (?). Several different
processes can generate a query string. For example, the anchor tag
<A HREF= example?string=this is a sample>string sample</A>
Generates a variable named string with the value this is a sample. Query strings are also generated by sending a form, or by a user typing a query into the address box of the browser.
Syntax
Request.QueryString(variable)[(index)|.Count]
Parameters
variable
Specifies the name of the variable in the HTTP query string to retrieve.
index
79

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

<BR><input type=Submit value=Submit></input>


</form>
</body>
</html>

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

Session, Server, Application Object


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

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.

The Global.asa file


The Global.asa file is an optional file where you can specify event scripts and declare session and
application objects that can be accessed by every page in an ASP application.
Note: The Global.asa file must be stored in the root directory of the ASP application, and each application
can only have one Global.asa file.
Events
In the Global.asa file you can tell the application and session objects what to do when the application/
session starts and what to do when the application/session ends. The code for this are placed into event
handlers. The Global.asa file can contain four types of events:
Application_OnStart - This event occurs when the FIRST user calls the first page from an ASP
application. This event occurs after the Web server is restarted or after the Global.asa file is
edited. When this procedure is complete, the Session On_Start procedure runs.
Session_OnStart - This event occurs EVERY time a new user requests the first page in the ASP
application.
Session_OnEnd - This event occurs EVERY time a user ends a session. A user ends a session
after the user has not requested a page for a specified time (by default this is 20 minutes).
Application_OnEnd - This event occurs after the LAST user has ended the session. Typically,
this event occurs when a Web server stops. This procedure is used to clean up settings after the
Application stops, like delete records or write information to text files.
You can create a subroutine to handle each of these events in the
Global.asa file:
<Script language=vbscript runat=server>
Sub Application_OnStart
......some vbscript code
End sub
91

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.

Using the Virtual Keyword


Use the virtual keyword to indicate a path beginning with a virtual directory. For example, if a file named
Footer.inc resides in a virtual directory named /Myapp, the following line would insert the contents of
Footer.inc into the file containing the line:
<! #include virtual =/myapp/footer.inc >

Using the File Keyword


Use the file keyword to indicate a relative path. A relative path begins with the directory that contains
the including file. For example, if you have a file in the directory Myapp, and the file Header1.inc is in
Myapp\Headers, the following line would insert Header1.inc in your file:
92

<! #include file =headers\header1.inc >


Note that the path to the included file, Headers\header1.inc, is relative to the including file; if the script
containing this #include statement is not in the directory /Myapp, the statement would not work.
You can also use the file keyword with the syntax (..\) to include a file from a parent, or higher-level,
directory if the Enable Parent Paths option is selected in the Internet Information Services snap-in.

Location of Included Files


ASP detects changes to an included file regardless of its location and inserts the files content the next
time a browser requests an .asp file which includes this file. However, in general, it is easier to secure
include files if they reside within the same application or Web site. For better security, it is advisable to
place include files in a separate directory within your application, such as \Includes, and apply only
appropriate Execute (Web server) permissions.
Important By default, Web server Read permissions are applied to all files. However, to prevent users
from viewing the contents of your include files, disable Read permissions for the Include directory.
In the next example we will use the include option of SSI in our asp script (response.asp).This command
allows us to add a set of instructions from different files (file1.txt and file2.txt bellow) and execute them.
response.asp
<%
TheName=Abhy
if TheName=Abhy then
%>
<!#include virtual=/file1.html >
<% else %>
<!#include virtual=/file2.asp >
<% end if %>
File1.html
<html>
<body>
Hi, Abhy.<br>
I know your are 31 years old, you are married to Sue, and
you are living in New York.
</body>
</html>
File2.asp
<%
for i=1 to 3
response.write(Thename & ...<BR>)
next

93

response.write(Who are you?)


%>
In this case, if the name of the person who is visiting our page is Abhy, then we will respond with
file1.html. If not, then we will execute asp instructions from file2.asp.
The include file must be a text file (.txt, .html, .htm, .shtml, .asp...). Although we have used file1.html
and file2.asp, the script will work exactly in the same way with file1.txt and file2.txt (changing the
name of the files would have no effect). By using SSI and asp we may also get a secret page:
secret_page.asp
<%
UserName=AZURE
Password=GID
If UserName=AZURE and Password=GID then
%>
<!#include virtual=/cgi-bin/secret_info.txt >
<% else %>
<%Response.write(Invalid User Name and Password)%>
<% end if %>
secret_info.txt
This is my
My name is
My surname
<BR>End of

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.

How to use the Subroutines


The Global.asa file is often used to initialize variables.
94

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

We will discuse about ADODB Connection in next chapter.

Use the #include directive in Global.asa


It is possible to use the #include directive in the Global.asa file.
The including must be done within the standard events, like this:
<Script language=vbscript runat=server>
Sub Application_OnStart
</script>
<! #include file=whatever.asp>
<script language=vbscript runat=server>
End sub
</script>

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

The Global.asa file:


<script language=vbscript runat=server>
Sub Application_OnStart
Application(visitors)=0
End Sub
Sub Session_OnStart
Application.Lock
Application(visitors)=Application(visitors)+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application(visitors)=Application(visitors)-1
Application.UnLock
End Sub
</script>
To display the number of current visitors in an ASP file:
<html>
96

<head></head>
<body>
<p>
There are <%=Application(visitors)%>
online now!
</p>
</body>
</html>

The Server Object


The Server object is an object that provides a variety of properties and methods that can be used in
almost every Active Server Page.While seemingly unrelated, these methods and properties are in fact
abstractions of the properties and methods provided by the web server itself. This object will allow us to
do things such as:

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

The ASPError Object


The ASPError object contains details of any errors generated by an ASP script or by the asp.dll itself.
Previously, there was no facility in ASP for storing details of errors that occurred.The ASPError object
with help from the Server.GetLastError method, allows more complex customized handling of error
messages.It directs the user to a standard error page, or to a user-created page depending on the option
selected in MMC.
The ASPError object is implemented in ASP 3.0 and it is only available in IIS5.The ASP Error object
is used to display detailed information of any error that occurs in scripts in an ASP page. The ASPError
object is created when Server.GetLastError is called, so the error information can only be accessed by
using the Server.GetLastError() method.
Eg.
<html>
<body>
<%
The following line creates an error
I=1
for i=1 to iI
next
Call the GetLastError() to trap the error
objerr=Server.GetLastError()
The variable objerr now contains the ASPError object
%>
98

<p>ASP Code: <%Response.Write(objerr.ASPCode)%>.</p>


<p>Number: <%Response.Write(objerr.Number)%>.</p>
<p>Source: <%Response.Write(objerr.Source)%>.</p>
<p>FileName: <%Response.Write(objerr.FileName)%>.</p>
<p>LineNumber: <%Response.Write(objerr.LineNumber)%>.</p>
</body>
</html>
Properties
Property

Description

ASPCode
ASPDescription
Category

Returns an error code that was generated by IIS


Returns a detailed description of the error (if the error is ASP-related)
Returns the source of the error (was the error generated by ASP?
By the scripting language? By an object?)
Returns the column position within the file that generated the error
Returns a short description of the error
Returns the name of the file that was being processed when the error occurred
Returns the line number where the error was detected
Returns the standard COM error code for the error
Returns the actual source code of the line where the error occured

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

What are Transactions?


Basically, using a transaction means its an all-or-none deal. No halfways, no maybes. Lets suppose
youre modifying a database, and you have to add 100 new items, one at a time. Before adding each
item, however, you have to check to make sure it fits certain criteria - if it doesnt, then your database
can have problems, you receive an error, and the process quits. It may not be desirable to quit halfway
- for whatever reason, you either want all the new rows or none of them.
Enter transactions. If you put the process in a transaction, and if an error occurs, the transaction will roll
back to a state just before you started your process. Thus, if any of the new items doesnt meet the
criteria, none of items gets added, instead of only the first few.
The classic example is a banking application. Suppose someone wants to transfer funds from one account
to another. You would deduct x amount from account A, and then add it to account B. Suppose after
99

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

The script will always start a new transaction.


The script will use a transaction, and will participate in any open
transaction, or create a new one if none are open.
The script will use any open transaction but will not start a new one if
none are currently open.
The script will neither initiate nor participate in a transaction.

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.

Committing and Rolling Back


There are two ways to commit a transaction . The first (and more simple) method is to do this inline with
100

your code. Lets take a look:


<%@ TRANSACTION = Required %>
<%
If Request.Form(submit) = Accept then
ObjectContext.SetComplete
Response.write(Operation completed successfully)
End if
%>
Use the ObjectContext.SetComplete method to tell MTS that this process is ready to be committed,
and no roll backs are required. You can then do whatever you want after you know the transaction is
committed (for instance, transfer funds in the bank scenario, or simply alert the user). This method is
easy to use since you can do this anywhere in the code you wish - you can use it as a simple error
checking procedure.
To roll back the transaction, you use the ObjectContext.SetAbort method:
<%
If Request.Form(submit) = Decline then
ObjectContext.SetAbort
Response.write(Operation was unsuccessful)
End if
%>
This tells MTS that there were errors, and we need to roll back to the previous state. Calling
ObjectContext.SetAbort rolls back any data that has changed, and then you can perform any tasks
necessary.
The second method to commit changes is a bit more complex, but offers you much more functionality.Here
we use transaction events to perform the functions.
<%@ TRANSACTION = Required %>
<%
strText = Request.form(Textbox)
if strText = then
ObjectContext.SetAbort
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)
101

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

COM Objects and MTS


Many times you will want to use transactions with custom built components, or COM objects, in your
ASPs. In the bank scenario, for example, it would probably be a good idea to encapsulate the business
logic of transferring the funds in a separate COM object for security, flexibility, and architecture reasons.
When using COM objects with transactions, you can either build the transaction logic into the component,
or keep it in the ASP. For example, if your COM object has a method called TransferFunds, then you
can either build in error checking and call SetAbort in the TransferFunds method itself, or keep that
code in the ASP script as weve done aboveIn order for a COM object to work transactionally, you
must register it with MTS. The Microsoft Transaction Server keeps track of all components on your
system that can participate in transactions, and tells each component how to do so (i.e. required,
requires_new, support, or not_supported). If you do not register your component, it may function normally,
but will not be able to work transactionally, and may also produce errors when asked to do so.

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.

Active Server Components


ASP comes with some built-in components that can handle common tasks:

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.

Write an Ad Rotator Include file


Include files are used to store information that will be used by more than one ASP or HTML file. By
creating an Ad Rotator Include file, when changes need to be made to specific information, you only
need to change the information in one location. The following example will guide you in creating an Ad
Rotator Include file containing a function named getAd(). This function randomly selects ads to display
106

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

Create an ad images data file


An ad images data file is created to provide information about the ads to be displayed. By placing the
data in one text file, when changes need to be made, you only need to change the data in one location.The
ASP page (with the logic in the Include file) sends data in the ad images data file to the Ad Rotator
component. The component then selects an ad for display.
The data file is divided into two sections that are separated by an asterisk (*). The first section provides
information common to all the ads to be displayed. The second section lists data relevant to each ad.
The following outlines the structure of an ad images data file:
REDIRECTION URL : the path and name of the ASP file that redirects browsers that select ad
images.
WIDTH : The width of ad images in pixels. Default is 440.
HEIGHT : The height of ad images in pixels. Default is 60.
BORDER : The border thickness around ad images. Default is 1.
* Separates the first section from the second section.
AdURL : Virtual path and filename of the image file containing the advertisement.
AdHomeURL : URL to jump to when this link is selected. To indicate there is no link, use a hyphen.
Text Text to display if browser does not support graphics.
Impressions : An integer indicating the relative weight, or probability, that this ad will be selected for

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

Test the Ad Rotator


To test the system, you will need an ASP page that calls the Ad Rotator Include file and the ad images
data file, and then displays the ads. First, you will need test ad images stored on your site.
Acquire and store the ad images as follows:
1. Create a directory named Images in the tutorial folder: C:\Inetpub\Wwwroot\Tutorial\Images.
2. Download the Office logo file, available at http://www.microsoft.com/office/images/office_logo.gif,
from the Microsoft Office Web site, and save it as Office_logo.gif in
C:\Inetpub\Wwwroot\Tutorial\Images.
3. Download the Windows logo file, available at http://www.microsoft.com/windows/images/
bnrwinfam.gif, from the Microsoft Windows Web site, and save it as Windows_logo.gif in
C:\Inetpub\Wwwroot\Tutorial\Images.
If you can not download these images ,then look for some other images in your system and name them
accordingly ( ie Windows_logo.gif ,Office_logo.gif in Images folder).
Create a new file as Displayad.asp:
<%@ Language=VBScript %>
<!Call the Include file, which in turn >
<!calls the ad images data text file>
<!#include file=adrotatorlogic.inc>
<html>
<head>
108

<title>Test Ad Display Page</title>


</head>
<body>
<h1>Test Ad Display Page</h1>
<!Display the ad banner>
<p><%=getAd()%></p>
<p>The space above should contain an image displaying either the Microsoft Windows family logo or the Microsoft
Office family logo.</p>
<ul>
<li type=disc>This indicates that Displayad.asp,
Adrotatorlogic.inc, and Adimagedata.txt are working together to correctly display the images.</li>
<li type=disc>Repeatedly refreshing the page should result in the Windows and Office logos displaying in random
order.</li>
<li type=disc>After you save Adrotatorredirect.asp,
clicking on the displayed image should cause a new window
to open, displaying the home page corresponding to the
displayed logo.</li>
<li type=disc>After you add the hit counter script to
this page, under Statistics you should see the number of
page hits since the script was added.</li>
</ul>
<br><br><br><br><br>
<h3>Statistics</h3>
<% Set pageCount = Server.CreateObject(MSWC.PageCounter)
%>
<!Increment the counter>
<% pageCount.PageHit %>
<p>You are visitor number <% =pageCount.Hits %> to this
Web page.</p>
</body>
</html>
NOTE : MSWC.PageCounter will not work in PWS

Redirect Users from Ad Links


When a user clicks the ad, the browser appends a query string to the request to the server. Then, the
server directs the users browser to the ads URL.
Create a new file as Adrotatorredirect.asp:
109

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

Count Page Hits


It is important to know how many hits your Web pages get. This data helps determine how changes to
your Web site may affect your customers viewing habits. More importantly, it provides useful insight as
to how customers are navigating through your site and where ads should be placed. Sites with high
trafficking have higher advertisement prices associated with them. The data gathered from a page-hit
counter provides you with trafficking information to begin negotiating advertisement prices for your Web
pages.
The Page Counter component uses an internal object to record page hit-count totals for all pages on the
server. At regular intervals, this object saves all information to a text file so that no counts are lost due to
power loss or system failure. The Page Counter component uses the following three methods:
Hits () This displays the number of hits for a Web page. The default is the current page.
PageHit(). These increments the hit count for the current page.
Reset (). This resets the hit count for a page to zero. The default is the current page.
An in-use sample of this script can be seen at the bottom of the Displayad.asp script. To place a page hit
counter on a Web page, place the following script where you want the counter displayed on the page:
<% Set pageCount = Server.CreateObject(MSWC.PageCounter) %>
<% pageCount.PageHit %>
You are visitor number <% =pageCount.Hits %> to this Web site.
110

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

Open and Read content from a text file


In ASP pages have the capabilities to store and recall Information.There are various ways to do the
same. One is Database, which we will discuss, in later chapters. Another way is to use files on the
server,With the File system object, ASP provides a way to access properties to files and folders, read
data in from them, create new ones, write over the old ones, and more.
This one will be the basic code we need to open a text file (do not write line nos. in your code !)

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

Create and Write a text file


The basic code we need to create a file is very similar to that one we have used to open a file:

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

Line 6 will write in the file the string in variable thetext.


Let suppose we want to record the IP address of all visitor to our page to a file named mylog.txt.
1
2
3
4
5
6
7
8
9
10
11
12

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

Database and ASP


Introduction to Active X Data Objects
Command,Connection and Recordset
Recordset Metods and Properties
Connecting Server with DSN and DSN-less Connection
Properties of the Connection
ADOVBS.inc
Insert Update and Delete
Lock Types
Filtering and Sorting Records

117

Database and ASP


As we know a database is a collection of organized data that can be queried and modified .Most of the
Organization use database to maintain all sorts of Information. Using Active X data object you can
connect to database through an ASP page ,perform a query and display results .
Previouly It was difficult to connect to database .Databases came in variety of format and for that you
have to know low level API(Application Programming Interface) for every database you wanted to use.
There was need for common standard to connect to Database irrespective of the typeand hence came
the ODBC Open database connectivity.Many databases confirmed to the standard and became known
as ODBC complaint databases such as Oracle,MS-SQL,Acess etc.

Introduction to ActiveX Data Objects


Before discussing the ADO we will discuss how it interacts with the request Engine and the ADO. When
the browser requests an ASP page from the server,either by URL (typed in, or hyperlink), or form input.
the server sees the .asp extension, and sends the ASP page to the ASP engine on the server. The ASP
engine reads the file, which usually contains a mixture of server-side scripting and HTML, although it
doesnt have to have server-side scripting or HTML (it can have one or the other alone).
As the ASP engine reads the file, whenever it comes to a server-side script, it executes it.
ASP scripts can call (invoke instances) of COM (Component Object Model) objects stored on the
server. COM objects are DLLs (Dynamic Link Libraries). They are sort of pre-packaged programming
that is bundled up into neat little packets which can be executed from within another program. MS
developed the Component Object model, and it has become a software industry standard, because
these objects can be used by any application, regardless of the language it was written in. We can
think of a COM object as a toolThe application grabs the tool whenever it needs it, then puts it back,
where it can be used again, by any application that needs it.
There are all sorts of COM objects. Some are built right into the web server. Others can be installed on
the web server.. If youre not familiar with Object-oriented programming, lets just say that most of the
functionality (or coding) is hidden from the application calling the object. In other words, All you have to
know about a COM object is basically the same. The ADODB COM object (also referred to as the
ADO (ActiveX Data Objects) technology) has all the necessary functions built into it to communicate
with ODBC-compliant databases.
118

Step 1: Browser requests


ASP Page From Server

Browser

Server

Step 7: Server returns


HTML to Browser
Step 6: ASP Engine returns
HTML to Browser

Step 2: Server sends ASP Page


To ASP Engine
Step 3: ASP Engine Executes
Server-side Scripts

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, Connection, and RecordSet.


One of the coolest things about ADO is that when you use one of these objects, the other 2 are created
automatically! So, why have 3 objects to start with? Well, because each object has different properties,
events, and methods, and from time to time you may want to do something with some of them. So, which
object you invoke, how you use it, etc., are more or less dictated by what your needs are.
So, lets start with a brief description of each object:

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

Add a new record to the RecordSet


Cancel pending batch updates
Cancel pending update
Copy the RecordSet
Close the RecordSet
Delete current record
Retrieve multiple records
Move the record pointer to a specific record
Move the record pointer to the next record
Move the record pointer to the previous record
Move the record pointer to the first record
Move the record pointer to the last record
Load the next RecordSet in a multi-set query
Open the RecordSet (execute the query)
Re-execute the last query executed
Synchronize the data with the server
Determine if a feature is supported by provider
Update the current record
Update pending batched record updates
121

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

Set Con = Server.CreateObject( ADODB.Connection )


Con.Open File Name=c:\myDataLink.UDL
%>
Closing the Connection
Should be done at the end of each page for each Datasource opened.
<%
Con.close
set Con = Nothing
%>
Reading Data from Database
The code sample below retrieves all the records from the Authors database table and displays them
within an Active Server Page. The records are retrieved in no particular order.
Each record is displayed within a VBScript WHILE..WEND loop. The MoveNext method of the
Recordset object is used to move to the next record.
<%
Open Database Connection
Set Con = Server.CreateObject( ADODB.Connection )
Con.Open
Provider=SQLOLEDB;UID=myLogin;PWD=secret;DATABASE=pubs
Retrieve All the Records into Recordset
mySQL = SELECT au_id, au_lname, au_fname, phone FROM Authors
Set RS = Con.Execute( mySQL )
%>
<html>
<head><title>displayrecords.asp</title></head>
<body>
<h2> Authors: </h2>
<table width=400" bgcolor=#eeeeee border=1
cellpadding=4 cellspacing=0>
<tr>
<th>ID</th>
<th>Last Name</th>
<th>First Name</th>
</tr>
<%
Loop through the Records displaying them
WHILE NOT RS.EOF
%>
125

<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

An object variable representing the Recordset object in which the results of


the query are stored.

connection

An object variable representing a Connection object on which the query is


executed.

RecordsAffected

Optional. A Long variable to which the provider returns the number of records
that the operation affected.

Parameters

Optional. A Variant array of parameter values passed with an SQL statement.


(Output parameters will not return correct values when passed in this
argument.)

CommandText

A String containing the SQL statement, table name, or stored procedure to


execute.

Options

Optional. A CommandTypeEnum value that indicates how the provider


should evaluate the CommandText argument. Can be one of the following
constants:

adCmdText, 1 Evaluate CommandText as a textual definition of a command.


adCmdTable, 2 Evaluate CommandText as a table name.
adCmdStoredProc, 4 Evaluate CommandText as a stored procedure.
adCmdUnknown, 8 The type of command in the CommandText argument is not known.
See the CommandType property for a more detailed explanation of these constants.
The Execute method on a Connection object executes whatever query you pass to the method in the
CommandText argument on the specified connection. If the CommandText argument specifies a rowreturning 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.
The contents of the CommandText argument are specific to the provider and can be standard SQL
syntax or any special command format that the provider supports.
Excute Method on Command Object is discussed later

127

Insert Update and Delete


Inserting
You can insert a new row of data into a database table by using the ADO Connection object.The code
sample listed below contains a simple HTML form that posts to a page named savedata.asp. In the
savedata.asp page, the Execute method of the Connection object is used to save the form information.
The data is saved to a table named foodOrders. Form for taking the input from the user is taken in
Form.asp
Form.asp
<html>
<head><title>form.asp</title></head>
<body>
<h3>What would you like on your sandwich?</h3>
<form method=post action=savedata.asp>
<p><b>Bread:</b>
<select name=bread>
<option value=Wheat> Wheat
<option value=White> White
<option value=Rye> Rye
</select>
<p><b>Meat:</b>
<select name=meat>
<option value=Turkey> Turkey
<option value=Ham> Ham
<option value=Chicken> Chicken
</select>
<p><b>Extras:</b>
<blockquote>
<input name=extras type=checkbox value=Bacon> Bacon
<br><input name=extras type=checkbox value=Mustard>
Mustard
<br><input name=extras type=checkbox
value=Tomatoes> Tomatoes
<br><input name=extras type=checkbox
value=Mayonaise> Mayonaise
</blockquote>
<input type=submit value=Submit Order!>
</form>
/body>
</html>
128

SaveData.asp
<%
Grab the HTML Form
bread
= Request(
meat
= Request(
extras
= Request(

Fields
bread )
meat )
extras )

Open Database Connection


Set Con = Server.CreateObject( ADODB.Connection )
Con.Open Provider=SQLOLEDB;UID=myLogin;PWD=secret
Build the SQL String
mySQL = INSERT into foodOrders ( bread, meat, extras )
VALUES ( & bread & , & meat & , & extras & )
Execute the SQL String
Con.Execute mySQL
Clean Up
Con.Close
Set Con = Nothing
%>
<html>
<head><title>savedata.asp</title></head>
<body>
<Big>Thank you for placing your order! </big>
</body>
</html>

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

The records are not lockeduntil a batch


update ocurs

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

Create and Open Database Connection


Set Con = Server.CreateObject( ADODB.Connection )
Con.Open PROVIDER=SQLOLEDB;UID=myLogin;PWD=secret
Execute SQL DELETE statement
mySQL = DELETE from foodOrders WHERE meat=Chicken
Con.Execute mySQL
%>
Using Recordset Objects
A Recordset object represents the records in a base table or the records that result from running a
query. You use Recordset objects to manipulate the data in a database at the record level.
Note You use Field objects to manipulate the data in a database at the field level.
The four types of Recordset objectstable, dynaset, snapshot, and forward-onlydiffer from each
other in significant ways:

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

provides faster performance.


The type of Recordset object you use depends on what you want to do and whether you want to change
or simply view the data. For example, if you must sort the data or work with indexes, use a table.
Because table-type Recordset objects are indexed, they also provide the fastest way to locate data. If
you want to be able to update a set of records selected by a query, use a dynaset. If the table-type is
unavailable and you only need to scan through a set of records, using a forward-only snapshot may
improve performance.
All other things being equal, if a table-type Recordset object is available, using it almost always results
in the best performance.

Example For Sorting and Filtering Records


Sorting
When records are shown mostly they are shown according to the AutoNumber field. Sorting allows us
to arrange the records and make them appear the way we want them to. We can sort the records
according to one or more column names. This makes the records more readable.
For example you have a database which contains title, description, keywords, date submitted and URL
fields of your whole site in a table. Your site is divided into several sections.Now what you want to do is
to show the relevant articles of your site according to the section of your site. it would be better if we
could allow the user to see the records by title i.e. pages with title starting with A coming first and that
with B coming second and so on. You could also show the records according to the date submitted with
new articles coming first and older ones down at the bottom. You can achieve these tasks by simply
sorting them out according to one of the fields and you are done.

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

body { font-family : Verdana; font-size : 8pt; }


</style>
</head>
<body>
<%
Dim connStr
connStr = Provider=Microsoft.Jet.OLEDB.4.0; Data
Source= & _
Server.MapPath(/filter.mdb)
Dim rs
Set rs = Server.CreateObject(ADODB.Recordset)
rs.CursorLocation = adUseClient
rs.Open Names, 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
rs.Close
Set rs = Nothing
%>
We then create a Sub routine to display the records. Since we will be showing records again and again
with different filters and sorts later, it will be useful for us to display the results in a simple HTML tables
thus making it more readable to the user. we use Server.MapPath method to map the relative path of our
database into complete physical path.
Notice: that we have set the CursorLocation of our Recordset to adUseClient. By default it is set to
adUseServer. If we are to use Sort property of Recordset object we have to set it to adUseClient.

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

Response.Write country = India<br><br> & vbcrlf


While Not rs.EOF
ShowRec rs(id), rs(name), rs(country)
rs.MoveNext
Wend
Moving the record pointer to the beginning
rs.MoveFirst
Removing the filter
rs.Filter =
Now <b>filtering</b> the records and showing only
where name
contains word khan = name like %khan%
rs.Filter = name like %khan%
Response.Write <br><br>Now <b>filtering</b> the
records and showing
Response.Write only where name contains word khan
= name like
Response.Write %khan%<br><br> & vbcrlf
While Not rs.EOF
ShowRec rs(id), rs(name), rs(country)
rs.MoveNext
Wend
Moving the record pointer to the beginning
rs.MoveFirst
rs.Filter =
Using both Filter and Sort
rs.Filter = name like %khan%
rs.Sort = country
Response.Write <br><br>Now <b>filtering</b> the
records and showing
Response.Write only where name contains word khan
= name like
Response.Write %khan%<br> & vbcrlf
Response.Write And then sorting the records by country
name.<br>
Response.Write Note this example uses both <b>Filter</
b> and <b>Sort</b>
Response.Write together :<br><br>
While Not rs.EOF
ShowRec rs(id), rs(name), rs(country)
rs.MoveNext
137

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

Advance Database Technique


Using Right Cursur
Guidlines for Choosing Cursor Type
Calling Stored Procedure
Properties of Command Object

140

Using Advanced Database Technique


A Recordset object represents the records in a base table or the records that result from running a
query. We can think of Recordset object as two dimensional matrix. When you open a recordset object
you create a matrix in the recordset object that contains as many rows and column as the databse table
contains.For moving into the next row we use the recordsets Move Next method. Most of our SQL
Select query have been runtime sql statements ie database has no idea what we are going to ask
(through h the sql statement)it to do until we needed that information . We can make the process of
querying data more efficient by using stored procedure, which are precompiled sql Queries.The database
knows more about these stored procedure queries because they have already been run at least once
before
Now the database can increase its efficiency when performing a stored procedure SQL query

Using Right Cursor


Because there are many ways for a cursor to interact with the result set and your application, there are
many types of cursors that your application can use. As a general rule, your application should use the
simplest cursor that provides the required data access. Each additional cursor characteristic beyond the
basics (static, read-only, forward-only, scrolling, unbuffered) has a price either in client memory,
network load, or performance. In many cases, the default cursor options generate a far more complex
cursor than your application actually needs.
Your cursor type choice depends on how your application uses the result set and on several design
considerations, including the size of the result set, the percentage of the data likely to be used, sensitivity
to data changes, and application performance requirements.
Use the CursorType property to specify the type of cursor that should be used when opening the
Recordset object. The CursorType property is read/write when the recordset is closed and read-only
when it is open.
Type of cursors
Scrollable Cursors

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

set, move directly to a specific row, and, under certain circumstances,


detect some types of changes to the underlying result set.
Dynamic Cursors

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

the mixed cursor combines the features of both a keyset-driven and


dynamic cursor.

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

Forward-only cursor. Identical to a static cursor except that


you can only scroll forward through records. This improves
performance in situations when you only need to make a single
pass through a recordset. (Default.)

adOpenKeyset

Keyset cursor. Like a dynamic cursor, except that you cant


see records that other users add, although records that other
users delete are inaccessible from your recordset. Data
changes by other users are still visible.

adOpenDynamic

Dynamic cursor. Additions, changes, and deletions by other


users are visible, and all types of movement through the
recordset are allowed, except for bookmarks if the provider
doesnt support them.

adOpenStatic

Static cursor. A static copy of a set of records that you can


use to find data or generate reports. Additions, changes, or
deletions by other users are not visible.

Choosing a Cursor Type


Choosing a cursor type depends on several variables, including:
Size of the result set.
Percentage of the data likely to be needed.
Performance of the cursor open.
Need for cursor operations, such as scrolling or positioned updates.
Level of visibility to data modifications made by other users.
142

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.

Rules for Choosing a Cursor Type


Some simple rules to follow in choosing a cursor type are:

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.

Keyset-driven or static cursors must be used if you want to do absolute fetches.

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.

Calling Stored Procedure


If you find yourself performing complex data manipulation, consider organizing database dependencies
and rules into stored procedures.
Stored procedures are precompiled queries stored on the database server. They can simplify development
and significantly speed up complex queries. When a stored procedure is called, it controls which operations
are performed and which database fields are accessed. A single stored procedure can even execute
multiple queries.
Stored procedures have explicitly defined parameters, each with a specific data type, direction, and
size. Before calling a stored procedure, the Parameter collection of the Command object must be
prepared to precisely match the number and type of parameters defined for the procedure on the server.
Calling this method results in faster execution and avoids a network round-trip to the server. (Also,
some providers do not support populating the Parameter collection with the Refresh method.
You can create your own procedure in in following way
143

CREATE PROCEDURE ListMail AS


SELECT * from example ORDER BY Email
MS SQL Provides the dialog promt for writing the Procedure
While in MS Acess Stored Procedures are referred as Queries .
Before Considering the example We assume that we have a table in MS Access with following records

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.

<!# include virtual=/adovbs.inc >


<%
Opening the database connection
set Conn=Server.CreateObject(ADODB.Connection)
Conn.ConnectionString=DSN=example
Conn.Open
Creating our SQL String for the Procedure
Dim strSQL
StrSQL=ListMail
Creating yhe recordset object
Dim Rs
Set Rs=Server.CreateObject(ADODB.RecordSet)
RS.Open strSQL,Conn
Displaying the results
Response.Write<B> Listing of Emails</B><BR>
Do While NOT Rs.EOF
Response.Write Name : & Rs(Name)& <BR>
Response.Write Email : & Rs(Email)&<BR>
Response.Write Phone : & Rs(Phone)& <BR>
Response.Write <HR>
Rs.MoveNext
145

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.

Properties of Command Object


ActiveConnection
CommandText
CommandType

The variable name of the database connection you want to retrieve.


Thje table name or SQl query you want to perform
It should be adCmdTable if you want to retrieve contents of database

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)

The Execute method syntax has these parts.


Part

Description

recordset

An object variable representing the Recordset object in which the results of


the query are stored.

command

An object variable representing a Command object whose CommandText


property contains the query to execute.

RecordsAffected Optional. A Long variable to which the provider returns the number of records
that the operation affected.
Parameters

Optional. A Variant array of parameter values passed with an SQL statement.


(Output parameters will not return correct values when passed in this argument.)

CommandText

A String containing the SQL statement, table name, or stored procedure to


execute.

Options

Optional. A CommandTypeEnum value that indicates how the provider should


evaluate the CommandText argument. Can be one of the following constants:

adCmdText, 1 Evaluate CommandText as a textual definition of a command.


adCmdTable, 2 Evaluate CommandText as a table name.
adCmdStoredProc, 4 Evaluate CommandText as a stored procedure.
adCmdUnknown, 8 The type of command in the CommandText argument is not known.

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

ACTIVE SERVER PAGES


Prepared by

AZURE Technologies & Information Services Pvt. Ltd.


Ahmedabad
2001 AZURE Technologies & Information Services Pvt. Ltd.

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

ASP Components .................................................................................................................. 104


- ASP Components
- Adrotator include file
- Image data file
- Redirecting users from AD Links
- Counting Page Hits
- Browser Capabilities
- Opening and Reading ,Writing Textfiles
Database and ASP ................................................................................................................ 117
Introduction to Active X Data Objects
- Command,Connection and Recordset
- Recordset Metods and Properties
- Connecting Server with DSN and DSN-less Connection
- Properties of the Connection
- ADOVBS.inc
- Insert Update and Delete
Lock Types
Filtering and Sorting Records
Advance Database Technique .......................................................................................... 140
- Using Right Cursur
- Guidlines for Choosing Cursor Type
- Calling Stored Procedure
- Properties of Command Object

Вам также может понравиться