Active Server Pages
Active Server Pages
Active Server Pages
ASP stands for Active Server Pages. ASP is a development framework for building web
pages. ASP is an old (but still powerful) tool for making dynamic Web pages. ASP is a
technology (much like PHP) for executing scripts on a web server. Active Server Pages
(ASPs) are Web pages that contain server-side scripts in addition to the usual mixture of text
and HTML (Hypertext Markup Language) tags.
What is an ASP File?
An ASP file has the file extension ".asp". An ASP file is just the same as an HTML file. An
ASP file can contain server scripts in addition to HTML. Server scripts in an ASP file are
executed on the server.
How does it Work?
When a browser requests a normal HTML file, the server just returns the file. When a
browser requests an ASP file, the server passes the request to the ASP engine which reads the
ASP file and executes the server scripts in the file. Finally the ASP file is returned to the
browser as plain HTML.
Concepts of ASP
ASP Objects
Response object
The ASP Response object is used to send output to the user from the server. Its collections,
properties, and methods are described below:
Collections
Collection Description
Cookies Sets a cookie value. If the cookie does not exist, it will be created, and
take the value that is specified
Properties
Property Description
CacheControl Sets whether a proxy server can cache the output generated by ASP or
not
ContentType Sets the HTTP content type for the Response object
Expires Sets how long (in minutes) a page will be cached on a browser before
it expires
ExpiresAbsolute Sets a date and time when a page cached on a browser will expire
Status Specifies the value of the status line returned by the server
1
Methods
Method Description
AddHeader Adds a new HTTP header and a value to the HTTP response
BinaryWrite Writes data directly to the output without any character conversion
Request object
The Request object is used to get information from a visitor. Its collections, properties, and
methods are described below:
Collections
Collection Description
ClientCertificate Contains all the field values stored in the client certificate
Form Contains all the form (input) values from a form that uses the post
method
TotalBytes Returns the total number of bytes the client sent in the body of the
request
Methods
Method Description
BinaryRead Retrieves the data sent to the server from the client as part of a post
request and stores it in a safe array
Application object
A group of ASP files that work together to perform some purpose is called an application.
The Application object is used to tie these files together.
2
Collections
Collection Description
StaticObjects Contains all the objects appended to the application with the
HTML <object> tag
Methods
Method Description
Application_OnEnd Occurs when all user sessions are over, and the application ends
Application_OnStart Occurs before the first new session is created (when the
Application object is first referenced)
Session object
A Session object stores information about, or change settings for a user session. The Session
object's collections, properties, methods, and events are described below:
Collections
Collection Description
Contents Contains all the items appended to the session through a script
command
StaticObjects Contains all the objects appended to the session with the
HTML <object> tag
Properties
Property Description
CodePage Specifies the character set that will be used when displaying
dynamic content
3
SessionID Returns a unique id for each user. The unique id is generated by
the server
Timeout Sets or returns the timeout period (in minutes) for the Session
object in this application
Methods
Method Description
ScriptTimeout Sets or returns the maximum number of seconds a script can run
before it is terminated
Methods
Method Description
GetLastError() Returns an ASPError object that describes the error condition that
occurred
Transfer Sends (transfers) all the information created in one ASP file to a
second ASP file
4
Features of ASP
Active Server Pages allow special tags and script code in some language, typically
VBScript, embedded in HTML files. These tags and code are processed by the web
server to obtain a dynamically produced HTML page to the browser.
It produce dynamic web pages on the server side but separate application logic from
the appearance of the page.
The tags allow previously compiled code, in the form of ActiveX components to be
used.
It allows fast development and testing.
ASP only runs on Microsoft IIS (Internet Information Server) and Personal Web
Servers and O’Reilly’s Website Pro.
There has grown up a full suite of software including ASP editors, such as the ones in
MS Visual Studio and from Macromedia. There is also a MS script debugger.
ASP is free of windows NT and other Microsoft platforms.
ASP has recently become available for Unix platforms from Chilisoft and Halcyon.
An ASP page looks like a standard HTML page with additional elements processed
by the ASP engine. Typically, these elements create text that is inserted into the
resulting document.
ASP elements
Scripts: Anything within a script tag <script runat=server and </script> or more commonly
between the <% and %> markers is interpreted as a script.
The script language is usually VBScript, but may also be any language supported by the
ActiveX scripting host, which are Jscript and PerlScript.
Expressions: Anything between <%=and %> markers is evaluated by the ASP engine as an
expression in the server environment.
Variables
Variables are items you create to store information in your code.
Rules for VBScript variable names:
Must begin with a letter
Cannot contain a period (.) and other special characters.
Cannot exceed 255 characters
In VBScript, all variables are of type variant, that can store different types of data.
You can declare VBScript variables with the Dim, Public or the Private statement. Like this:
Dim carname
Types of Variable Declaration:
There are 2 ways in which a variable can be declared. They are as given below.
1) Implicit Declaration
When variables are used directly without declaration, it is termed as Implicit Declaration.
However, it’s not a good practice because if at times a variable name is not spelled correctly
in the script then it can produce weird results while running and sometimes, it will not be
easy as well to detect this by the user.
Let’s understand this with a simple Example:
age = 10
In this case, if you misspell “age” variable for “aeg”, the script will automatically create a
new variable with the name ‘aeg’.
To overcome this, you can use ‘Option Explicit’, which is discussed below.
2) Explicit Declaration
Declaring variables before using them is called as Explicit Declaration of variables.
5
Option Explicit
Dim age
Option Explicit:
In option explicit, if a user tries to use the variables which are not declared in case of Option
Explicit then an error occurs. It is always recommended to use ‘Option Explicit’ at the top of
the code so that even if unintentionally you used a wrong name of the variable then you can
correct it immediately without any confusion.
String Manipulation Functions
UCase() - The UCase function converts a specified string to uppercase. The string argument
of the UCase function can be any valid string. All lower case letters in the string passed as an
argument to UCase are converted to upper case, while all upper case letters and special
characters remain the same. If string contains Null, Null is returned.
Syntax of UCase function is : UCase(string)
Example:
dim text
txt=”This is a beautiful day!”
document.write(UCase(txt))
Output: THIS IS A BEAUTIFUL DAY!
LCase()-LCase is a commonly used ASP function that allows you to convert all characters in
a string to their lower case versions. It only takes in one parameter, the string variable to
operate on. All upper case letters in the string passed as an argument to LCase are converted
to lower case, while all lower case letters and special characters remain the same. If string
contains Null, Null is returned.
Syntax of LCase function is : LCase(string)
Example:
dim text
txt=”THIS IS A BEAUTIFUL DAY!”
document.write(LCase(txt))
Output: this is a beautiful day!
Left() -The Left function returns a specified number of characters from the left side of a
string. There are Two Mandatory Arguments
The string variable to operate on
An integer representing how many characters to copy
The Syntax of the Left function is: Left(string,length)
Example:
dim txt
txt=”This is a beautiful day!”
document.write(Left(txt,11))
Output: This is a b
Len()- The Len function returns the number of characters in a string.
The Syntax of the Len function is: Len(string|varname)
Example:
dim txt
txt=”This is a beautiful day!”
document.write(Len(txt))
Output: 24
Right()- The Right function returns a specified number of characters from the right side of a
string. There are Two Mandatory Arguments.
String - name of the string you wish to truncate.
6
Length - The Length argument is the number of characters (including blanks) you
wish to save counting from the right side towards the left side of the string.
The Syntax of the Right Function is : Right(string,length)
Example:
dim txt
txt=”This is a beautiful day!”
document.write(Right(txt,11))
Output: utiful day!
Mid() - The Mid function returns the portion of the designated string for a designated length
starting from any position in the string. It explains the Two Mandatory Arguments
String - name of the string you wish to abbreviate
Start - The Start argument is a numeric position anywhere in the string counting from
the left side.
It explains One Optional Argument
Length- The optional Length argument is the number of characters (including blanks)
in the string you wish to save counting from the position designated by the Start
argument.
The Syntax of the Mid function is: Mid(string,start[,length])
Example:
<%
String1="michael"
Response.write Mid(String1,3,3)
%>
Output: cha
LTrim() - The LTrim function removes spaces on the left side of a string.
The syntax of the LTrim function is: LTrim(string)
Example:
dim txt
txt=" This is a beautiful day! "
document.write(LTrim(txt))
Output: "This is a beautiful day! "
InStr() - The InStr function returns the position of the first occurrence of one string within
another. The Function will return 0 if String To Find is not found.
The Syntax of the InStr function is: InStr([start,]string1,string2[,compare])
Its Description is
Parameter Description
start Optional. Specifies the starting position for each search. The search begins at
the first character position by default. This parameter is required if compare is specified
string1 Required. The string to be searched
string2 Required. The string expression to search for
compare Optional. Specifies the string comparison to use. Default is 0
Can have one of the following values:
0 = vbBinaryCompare - Perform a binary comparison
1 = vbTextCompare - Perform a textual comparison
2=vbDatabaseCompare-Perform a comparison based upon information contained in the
database where the comparison is to be performed.
Example:
dim txt,pos
txt="This is a beautiful day!"
7
'A textual comparison starting at position 4
pos=InStr(4,txt,"is",1)
document.write(pos)
Output : 6
Time & Date functions
Date() - To display the current date by itself in a Web page, type
<% =date %>
at the point where you want it to appear. When you view the page in your browser, you
should see something like this
Thu, Jan 23, 2019
Day() - The Day function returns a number between 1 and 31 that represents the day of the
month. The Day function in ASP lets you find out what day in the current month it is.
The syntax of the day function is: Day(date)
Example:
document.write(Date & "<br />")
document.write(Day(Date))
Output: 5/14/2019 14
Hour() - The Hour function returns a number between 0 and 23 that represents the hour of
the day.
The Syntax of the Hour function is: Hour(time)
Example:
document.write(Now & "<br />")
document.write(Hour(Now))
Output:5/15/2019 10:07:47 AM 10
Minute() - The Minute function returns the minute by using the Time function as an
argument. The Minute function returns a number between 0 and 59.
The Syntax of the Minute function is: Minute(time)
Example:
document.write(Now & "<br />")
document.write(Minute(Now))
Output: 5/15/2019 10:07:47 AM 07
Month() - The Month() function is used to determine the month from a date variable or
formatted string. The Month function returns a number between 1 and 12 that represents the
month of the year.
The Syntax of the Month function is: Month(date)
Example:
document.write(Date & "<br />")
document.write(Month(Date))
Output: 1/15/2019 1
MonthName() - The MonthName function returns the name of the specified month. The
MonthName consists numeric designation of the month. For example, January is 1, February
is 2, and so on. A Boolean value that indicates if the month name is to be abbreviated. If
omitted, the default is False, which means that the month name is not abbreviated.
MonthName returns a string indicating the specified month.
The Syntax of the MonthName function is:MonthName(month[,abbreviate])
Example:
document.write(MonthName(8,true))
Output: Aug
8
Now() - The Now function returns the current date and time according to the setting of your
computer's system date and time.
The Syntax of the Now Function is: Now
Example:
<%
document.write(Now)
%>
Output:
1/15/2019 10:52:15 AM
Arrays
An array is a contiguous space of memory allocated for storing some data. An array index
starts from 0 and ends at the size of the array, minus 1. If array's size is 10, its first index will
be 0 and the last index will be 9. An array is declared with the keyword DIM and then the
array name and then the size of the array in parentheses. Like variables, we do not specify the
data type of an array. The following shows the general syntax for declaring an array:
DIM ArrayName(ArraySize)
In the above statement ArrayName is the name of the array and ArraySize is the size of the
array.
Array () function
An Array () function can be used to initialize values to an array. The following initializes an
array without referencing each of the cells in an array of size 3:
arrayName = Array (value1, value2, vlaue3)
The function Array () initializes the each of the values or parameters to the corresponding
index. For example, "value1" will be assigned to index 0 and value3 will be assigned to index
2.
One dimensional Array
An array which has only one subscript is known as one dimensional array.
<%
Dim myFixedArray(3)
myFixedArray(0) = "Einstein"
myFixedArray(1) = "Mother Teresa"
myFixedArray(2) = "Bill Gates"
myFixedArray(3) = "Mark Zuckerberg."
For Each item In myFixedArray
Response.Write(item & "<br />")
Next
%>
Two dimensional arrays
An array of arrays is known as 2D array. It can be represented as a table of rows and
columns.
<%
Dim arrCars(2,4)
'arrCars(col,row)
arrCars(0,0) = "BMW"
arrCars(1,0) = "2004"
arrCars(2,0) = "45.000"
arrCars(0,1) = "Mercedes"
arrCars(1,1) = "2003"
arrCars(2,1) = "57.000"
9
Response.Write(" <TABLE border=0>")
Response.Write("<TR><TD>Row</TD> <TD>Car</TD>")
Response.Write("<TD>Year</TD><TD>Price</TD></TR>")
For i = 0 to UBound(arrCars, 2)
Response.Write("<TR><TD>#" & i & "</TD>")
Response.Write("<TD>" & arrCars(0,i) & "</TD>")
Response.Write("<TD>" & arrCars(1,i) & "</TD>")
Response.Write("<TD>" & arrCars(2,i) & "</TD></TR>")
Next
Response.Write("</TABLE>")
%>
Procedures and Functions
There are two types of procedures, subs and functions. The main difference between the two
is that function returns something when it is called and sub does not.
<%
WriteMessage
%>
<%
Sub WriteMessage()
Response.Write “TheStuff”
End Sub
%>
The code calls the sub WriteMessage, which then writes a message out to the browser.
Nothing is returned by the sub. It starts with the word Sub followed by the name of the Sub
and then any parameters. The sub ends with the End Sub statement.
A function should be written like this
<%
Response.Write WriteMessage
%>
<%
Function WriteMessage()
WriteMessage=”Thestuff”
End Function
%>
The function has a similar structure to the sub, it starts with the keyword Function followed
by the name of the function. Then somewhere in the code block you would set the return
value by setting the name of the function equal to something. The function ends with the End
Function statement. Procedures can also include parameters.
The ADO framework
ADO or ActiveX Data Objects is a collection of objects that allow applications to
communicate with data sources in a consistent manner. There are four step process involved
when you use ActiveX Data Objects to work with databases
Connect to the database
Define the data you want
Manipulate that data
Display the data
Connecting with databases
Creation of DSN
10
A DSN is a device that makes it easy for your script to connect to a database using ODBC
(Open Database Connectivity, an open protocol for connecting to SQL data sources)
When you create a DSN, you are assigning a unique name to a database and telling the
ODBC software how to connect to a database. Once you have created a DSN for a database,
any number of programs and scripts that know how to use ODBC data sources will be able to
connect easily to your database.
Steps to create DSN:
In the Start menu, select Settings/Control Panel. This opens the control panel window,
which contains a number of control panel icons.
Double click on the ODBC icon. This opens the ODBC control panel.
Go to the system DSN tab. It should look something like the below figure.
Click on the Add… button. This pops up a window that lists the different ODBC
drivers that are available on your computer.
Select Microsoft Access Driver (*.mdb) then click on the finish button. This opens the
ODBC Microsoft Access 97 setup window.
11
You will need to do two things in this window: Assign a name to your data source and
give the ODBC software the path to your database.
In the Data Source Name field, type a database name for your DSN. Finally click ok.
Understanding OLEDB(Object Linking and Embedding, Database)
OLE DB powerful as ODBC, it has a significant shortcoming. It only works with databases.
There are other types of data sources out there. For example, there are email systems, index
servers that search and index various types of documents on a hard disk and the files system
of your computer. OLEDB allows you to work with these data sources in very much the same
way you work with standard databases.
OLEDB is the first important step toward implementing microsoft’s vision of universal data
Universal data is a model in which all data can be treated the same way regardless of the
source In the universal data model there is little difference between querying data in an SQL
server database or querying data in an email server. Data is data, regardless of source.
OLEDB is a set of standard objects and methods that are exposed for any given data source.
The nice thing about OLE DB is that you work with the same set of objects and methods
regardless of the data source behind the objects. What this means in real life is that you do
not have to worry too much about the data sources.
12