Introduction to ASP
ASP is a powerful tool for making dynamic and
interactive web pages.
ASP scripts are Server Side Scripting language, executed
on the server.
You can not view ASP code in a browser, you will only
see the output from ASP which is plain HTML.
ASP is a program that runs inside IIS(Internet Information
Services) with Windows NT,2000, XP and Vista.
PWS(Personal Web Server) can be found on your
Windows 95/98.
ChiliASP, InstantASP is a technology that runs ASP
without Windows OS .
What is an ASP File?
An ASP file can contain text, HTML, XML, and scripts
Scripts in an ASP file are executed on the server
An ASP file has the file extension ".asp"
An ASP file can also contain server scripts, surrounded by
the delimiters <% and %>.
How Does ASP Differ from HTML?
When a browser requests an HTML file, the server returns the
file
When a browser requests an ASP file, IIS passes the request to
the ASP engine. The ASP engine reads the ASP file, line by
line, and executes the scripts in the file. Finally, the ASP file is
returned to the browser as plain HTML
Working of Active Server Pages
Any Web Browser
Visual A
HTTP
Basic
IIS 4.0 D Data
COM base
Server O
HTML
HTML
ASP
ASP
• Plain HTML on client site
• Active Server Pages: VBScript
• Application in Visual Basic
Client Server
Active Server Pages:
Technology Overview
In te rn e t
< bo dy> In f o r m a t io n
M y A S P P ag e
M y A S P P a ge ... S e rv e r
< ta b le > ...< /ta b le >
6 ....
< /b o d y >
5
3
C O M O b je c t " A B C "
< % 2 P u b lic F u n c t io n G e t D a t a ( p a r m A s I n t ) A s S t r in g
o b j = C r e a te O b je c t( " A B C " ) D im R s A s A D O D B . R e c o r d S e t
d a ta = o b j.G e tD a ta (p a rm ) ...
% > R s = C o n n .E x e c u te ("S E L E C T * F R O M ....")
< bo dy>
M y A S P P ag e 4 G e tD a ta = " < ta b le > ...< /ta b le > "
...
< % = d a ta % >
....
< /b o d y >
1
S e r v e r F ile S y s t e m
How to Install IIS on Windows XP and Windows 2000?
Follow these steps to install IIS on Windows XP and Windows 2000:
On the Start menu, click Settings and select Control Panel.
Double-click Add or Remove Programs.
Click Add/Remove Windows Components.
Click Internet Information Services (IIS).
Click Details.
Select the check box for World Wide Web Service, and click OK.
In Windows Component selection, click Next to install IIS.
Test Your Web
After you have installed IIS follow these steps:
Look for a new folder called Inetpub on your hard drive.
Open the Inetpub folder, and find a folder named wwwroot.
Create a new folder, like "MyWeb", under wwwroot.
Write some ASP code and save the file as "test1.asp" in the
new folder.
Make sure your Web server is running (see below).
Open your browser and type
"http://localhost/MyWeb/test1.asp", to view your first
web page.
Example
<html>
<body>
<% response.write("Welcome to D10!") %>
<% ="Hello Welcome!"%> // Shorthand method of
response.write command.
</body>
</html>
Note:
Default scripting language is VBScript.
To set JavaScript, use the following specification at the top of
the page:
<%@ language="javascript"%> before <html> tag.
ASP Variables
A variable is used to store information.
Global Variable : If the variable is declared outside a
procedure it can be changed by any script in the ASP file.
Local Variable : If the variable is declared inside a procedure,
it is created and destroyed every time the procedure is
executed. No scripts outside the procedure can access or
change the variable.
To declare variables accessible to more than one ASP file,
declare them as session variables or application variables.
Variables
Session Variables :
Session variables are used to store information about ONE
single user, and are available to all pages in one application.
Typically information stored in session variables are name, id,
and preferences.
Application Variables :
Application variables are also available to all pages in one
application.
Application variables are used to store information about ALL
users in a specific application.
Example
<%
dim name
name="Priya"
response.write("My name is: " & name)
%>
Iterative Statement
Example :
<%
dim i
for i=1 to 6
response.write("<h" & i & ">Header " & i &
"</h" & i & ">")
next
%>
Arrays
Example
<% Dim firstname(5),i
firstname(0) = "Sneha"
firstname(1) = "sindhu"
firstname(2) = "shreya"
firstname(3) = "Shruti"
firstname(4) = "sheeba"
firstname(5) = "soniya"
For i = 0 to 5
response.write(firstname(i) & "<br />")
Next
%>
Example : Time Display
<%
dim h
h=hour(now())
response.write("<p>" & now())
response.write("</p>")
If h<12 then
response.write("Good Morning!")
else
response.write("Good day!")
end if
%>
Output:
3/30/2010 2:07:11 PM
Good day!
ASP Objects
Object Used For
Request Getting information from the User
Response Sending information to the User
Application Sharing information for the entire application
Session Storing information about a User's Session
Server Accessing the server resources
Request Object
Used to retrieve the information from the from in a HTML
Page.
The Request Object has the following Collections, Property
and Method:
Form - To access value from a form submitted using POST
method.
QueryString - To access variables sent with URL after "?" or
from a from submitted using GET method.
Cookies - To access the value of a Cookie.
ServerVariables -To access information from HTTP Headers.
TotalBytes: A read only property indicating the total number
of bytes in this request.
BinaryRead(): A method to read all names and values sent
from the browser by the POST method.
Request Object
The syntax to access the variables of any of these collections
is
Request.Collections("Variables") Or
Request("Variables")
To use the Form collection, we need to pass the name of the
element that we create in HTML Form as the Variable to the
Request Object. For example:
<input type="text" name="Text1" value="">
then, your request statement should be,
Request.Form("Text1") or Request("Text1").
when using Querystring, need to pass the variable name used
in the URL after the ? symbol.
How to retrieve the User input?
User input can be retrieved in two different ways:
• With Request.QueryString
• Request.Form.
Form example:
<form method="get" action="simpleform.asp">
First Name: <input type="text" name="fname" /><br />
Last Name: <input type="text" name="lname" /><br />
<br />
<input type="submit" value="Submit" />
</form>
Request.QueryString
The Request.QueryString command is used to collect values in
a form with method="get".
Information sent from a form with the GET method is visible
to everyone (it will be displayed in the browser's address bar)
And has limits on the amount of information to send.
In the form example above, the URL sent to the server would
look like this:
http://www.yahoo.com/simpleform.asp?fname=Priya&lname=Nair
Assume that the ASP file "simpleform.asp" contains the
following script:
<body>Welcome <%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%></body>
Output: Welcome Priya Nair
Request.Form
The Request.Form command is used to collect values in a
form with method="post".
Information sent from a form with the POST method is
invisible to others
And has no limits on the amount of information to send.
Example:
http://www.yahoo.com/simpleform.asp
Assume that the ASP file "simpleform.asp" contains the
following script:
<body>Welcome <%
response.write(request.form("fname"))
response.write(" " & request.form("lname"))%>
</body>
Output : Welcome Priya Nair
What is a Cookie?
• A cookie is often used to identify a user.
• A cookie is a small file that the server embeds on
the user's computer.
• Each time the same computer requests a page with
a browser, it will send the cookie too.
• With ASP, you can both create and retrieve cookie
values.
How to Create a Cookie?
The "Response.Cookies" command is used to create cookies.
The Response.Cookies command must appear before the
<html> tag.
Example:
we will create a cookie named "firstname" and assign the
value "Alex" to it:
<%Response.Cookies("firstname")="Alex"%>
It is also possible to assign properties to a cookie, like
setting a date when the cookie should expire:
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2010#
%>
How to Retrieve a Cookie Value?
The "Request.Cookies" command is used to retrieve a
cookie value.
For example, we retrieve the value of the cookie
named "firstname" and display it on a page:
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
A Cookie with Keys
If a cookie contains a collection of multiple values, we say that
the cookie has Keys.
Example :
we will create a cookie collection named "user".
The "user" cookie has Keys that contains information about a
user:
<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Shah"
Response.Cookies("user")("country")="India"
Response.Cookies("user")("age")="25"
%>
Read all Cookies
Assume that your server has sent all the cookies above to a user.
The example below shows how to read all the cookies sent to a
user
Note: The code below checks if a cookie has Keys with the
HasKeys property
<% dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br />")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br />") end if
response.write "</p>“
next%>
What if a Browser Does NOT Support Cookies?
If your application deals with browsers that do not support cookies, use
other methods to pass information from one page to another in your
application.
There are two ways of doing this:
1. Add parameters to a URL
2. Use a form
You can add parameters to a URL:
<a href="welcome.asp?fname=John&lname=Smith">Go to Welcome
Page</a>
And retrieve the values in the "welcome.asp" file like this:
<% fname=Request.querystring("fname")
lname=Request.querystring("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>
Use a form
The form passes the user input to "welcome.asp" when the user
clicks on the Submit button:
Retrieve the values using Request.form command.
Note :
• When you request a Web page with a URL contains a "?",
everything after "?" in the URL will be received by the
server as the query string.
• The query string will be store in the server variable called
"QUERY_STRING". It will also be split into pairs of
names and values and stored in "QueryString" collection.
• "&" is used in the query string as delimiters.
• Special characters in the query string need to be encoded.
For example, " " is encoded as "+". I believe ASP offers
both URL encoding and decoding methods.
Server Variable
The ServerVariables object contains a lot of information, including remote
host IP address, URL, translated path name, etc.
Few Server Variables are:
APPL_PHYSICAL_PATH = c:\inetpub\wwwroot\
AUTH_PASSWORD =
LOCAL_ADDR = 127.0.0.1
REMOTE_HOST = 127.0.0.1
REQUEST_METHOD = GET
SCRIPT_NAME = /request_test.asp
SERVER_NAME = localhost
SERVER_PORT = 80
SERVER_PROTOCOL = HTTP/1.1
SERVER_SOFTWARE = Microsoft-IIS/5.0
HTTP_ACCEPT_LANGUAGE = en-us
HTTP_CONNECTION = Keep-Alive
HTTP_HOST = localhost
HTTP_USER_AGENT = Mozilla/4.0 (compatible; MSIE 6.0; MSNIA;
Windows NT...
Response Object
o This object is used to send information to the user ( i.e. to the
browser)
o The most used methods of Response object are:
o Write - Used to send information to be displayed on the
browser.
o Redirect - Used to send the user to a new Page.
o The syntax to use these method is Response.MethodName
o Eg: <% Response.Redirect("newpage.html") %>
o Eg: <% Response.Write("Write Method") %>
Properties, Methods of Response object
Cookies: A collections of cookie objects the server wants to
send to the browser.
Buffer: A boolean property indicating whether to buffer the
page until the contents are completed.
Charset: A property representing the character set name in
HTTP response header.
ContentType: A property representing the content type name
in the HTTP reponse header.
Expires: A property representing the period of time before the
page cached on a proxy server expires.
IsClientConnected: A boolean property indicating whether
the browser has disconnected from the server.
Status: A property representing the status in the HTTP
response header.
Properties, Methods of Response object
AddHeader name, value: A method to set or change the
value of a variable in the HTTP response header.
AppendToLog(string): A method to append the specified
string to the log file of the Web server.
BinaryWrite(data): A method to send binary data to the
browser.
Clear(): A method to clear any buffered HTML output.
End(): A method to stop add data to the HTML output from
both script statements and static HTML data.
Flush(): A method to sends buffered HTML output
immediately to the browser.
Redirect(url): A method to redirect the browser to another
URL.
Write(string): A method to write the specified string to the
HTML output.
Session Object
This object is used to store information with a scope to that
user session.
The information stored are maintained even when the user
moves through various pages in the web application.
When a session starts ?
A new user requests an ASP file, and the Global.asa file
includes a Session_OnStart procedure
A value is stored in a Session variable
A user requests an ASP file, and the Global.asa file uses the
<object> tag to instantiate an object with session scope
When does a Session End?
A session ends if a user has not requested or refreshed a page
in the application for a specified period. (Default :20 minutes).
If you want to set a timeout interval that is shorter or longer
than the default, use Timeout property.
Example : <% Session.Timeout=5 %>
To end a session immediately, use Abandon method:
<% Session.Abandon %>
The main problem with sessions is WHEN they should end.
We do not know if the user's last request was the final one or
not. So we do not know how long we should keep the session
"alive". Waiting too long for an idle session uses up resources
on the server, but if the session is deleted too soon the user has
to start all over again because the server has deleted all the
information. Finding the right timeout interval can be difficult!
Tip: If you are using session variables, store SMALL amounts of
data in them.
Session Object
The session object has two properties.
SessionID - Created by the web application and sent as a cookie
to client.
TimeOut - To set Session timeout period.
Store and Retrieve Session Variables
<% Session("username")="Priya Nair"
Session("dept")= "Computer " %>
When the value is stored in a session variable it can be reached
from ANY page in the ASP application:
Retrieved using :
<% Response.Write(Session("username"))%>
You can also store user preferences in the Session object, and
then access that preference to choose what page to return to the
user.
Session Object
The example below specifies a text-only version of the page if
the user has a low screen resolution:
<% If Session("screenres")="low" Then %>
This is the text version of the page
<% Else %>
This is the multimedia version of the page
<% End If %>
Remove Session Variables
The Contents collection contains all session variables.
It is possible to remove a session variable with the
Remove method.
Remove Session Variables
The example below removes the session variable "fname" if
the value of the session variable "salary" is lower than 10000
<% If Session.Contents("salary")<10000 then
Session.Contents.Remove("fname")
End If %>
To remove all variables in a session, use the RemoveAll
method:
<% Session.Contents.RemoveAll()%>
Loop Through the Contents Collection
The Contents collection contains all session variables.
You can loop through the Contents collection, to see what's
stored in it:
<% Session("username")="Priya Nair“
Session("age")=30
dim I
For Each i in Session.Contents
Response.Write(i & "<br />")
Next
%>
Output :
username
age
Loop Through the Contents Collection
If you do not know the number of items in the Contents
collection, you can use the Count property:
<% dim I
dim jj=Session.Contents.Count
Response.Write("Session variables: " & j)
For i=1 to j
Response.Write(Session.Contents(i) & "<br />")
Next
%>
Result:
Session variables: 2
Priya Nair
30
Application Object
• This object is used to share information among the users of the
web application.
• The variable becomes alive, when the first request to the
application comes in.
• This object is typically used to create variables that need to
maintain application level scope.
Store and Retrieve Application Variables
Application variables can be accessed and changed by any
page in the application.
You can create Application variables in "Global.asa" like this:
<script language="vbscript" runat="server">
Sub Application_OnStart
application("vartime")="“
application("users")=1
End Sub
</script>
You can access the value of an Application variable like this:
There are <%Response.Write(Application("users"))%> active
connections.
Loop Through the Contents Collection
The Contents collection contains all application variables. You can loop
through the Contents collection, to see what's stored in it:
<% dim I
For Each i in Application.Contents
Response.Write(i & "<br />")
Next
%>
If you do not know the number of items in the Contents collection, you can
use the Count property:
<% dim I
dim jj=Application.Contents.Count
For i=1 to j
Response.Write(Application.Contents(i) & "<br />")
Next
%>
Methods of Application Object
Lock and Unlock
When an application is locked, the users cannot change the
Application variables (other than the one currently accessing
it).
Unlock method removes the lock from the Application
variable:
Example :
<% Application.Lock
'do some application object operations
Application.Unlock
%>
Server Object
This object gives access to Server components, its methods
and properties.
Property :
ScriptTimeout : Sets or returns the maximum number of seconds a script
can run before it is terminated.
Methods :
CreateObject() : Creates an instance of an object – Server components
Execute() : Executes an ASP file from inside another ASP file
GetLastError() : Returns an ASPError object that describes the error
condition that occurred
HTMLEncode() : Applies HTML encoding to a specified string
MapPath() : Maps a specified path to a physical path
Transfer() : Sends (transfers) all the information created in one ASP file to
a second ASP file.
URLEncode() : Applies URL encoding rules to a specified string
Server Object
The syntax to use any of these methods is Server.Method. For
Eg: Server.CreateObject("ADODB.Connection")
We use Createobject method to access Active Server
Components.
There are components like Data Access Component, Browser
Capabilities Component, Ad Rotator Component etc.
Each component exposes certain objects and methods. We can
use these methods in our ASP Pages.
We will use the Server.CreateObject method to access
various methods and properties of Browser Capabilites
component.
Browser Capabilites Component is used to find out the
capabilities of the browser.
For example, we can verify whether a browser supports
frames or not and depending on the result, you can direct
the user to a page with frames or to a page without frames.
Browser Capabilities
Property Result
Browser Type Netscape
Version 4.00
Frames True
Tables True
Cookies True
Javascript True
VBScript False
ActiveX unknown
Example
<% Set myb= Server.CreateObject("MSWC.BrowserType")%>
<table border=2 bordercolor="#000080">
<THEAD>
<tr><th>Property</th><th>Result</th></tr>
</THEAD>
<TBODY>
<tr><td>BrowserType</td>
<td><%=myb.Browser%></td></tr>
<tr><td>Version</td><td><%=myb.Version%></td></tr>
<tr><td>Frames</td><td><%=myb.Frames%></td></tr>
<tr><td>Tables</td><td><%=myb.Tables%></td></tr>
<tr><td>Cookies</td><td><%=myb.Cookies%></td></tr>
<tr><td>JavaScript</td><td><%=myb.Javascript%></td>
</tr>
<tr><td>VBScript</td><td><%=myb.VBScript%></td></tr>
<tr><td>ActiveX</td><td><%=myb.ActiveX%></td></tr>
</tbody></table>
Example
Mappath( ):
<% response.write(Server.MapPath("test.asp") & "<br />") %>
Output: c:\inetpub\wwwroot\script\test.asp
Execute( ): File1.asp:
<% response.write("I am in File 1!<br />")
Server.Execute("file2.asp")
response.write("I am back in File 1!") %>
File2.asp:
<% response.write("I am in File 2!<br />") %>
Output:
I am in File 1!
I am in File 2!
I am back in File 1!
What is ADO?
ADO stands for ActiveX Data Objects
ADO is a Microsoft Active-X component
ADO is automatically installed with Microsoft IIS
ADO is a programming interface to access data in a database
Accessing a Database from an ASP Page
The common way to access a database from inside an ASP
page is to:
Create an ADO connection to a database
Open the database connection
Create an ADO recordset
Open the recordset
Extract the data you need from the recordset
Close the recordset
Close the connection
Example : DB Connectivity
<% dim connstr,conn,rs,sqlstmt
set conn=Server.CreateObject("ADODB.Connection")
connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=c:\Inetpub\wwwroot\db2.mdb;"
conn.open connstr
set rs= Server.CreateObject("ADODB.RecordSet")
%><body>
The Category is: <br>
<% rs.Open "select * from category", conn
do until rs.EOF
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br />")
next
Response.Write("<br />")
rs.MoveNext
loop
rs.close
conn.close
%></body>
The Global.asa file
The Global.asa file is an optional file that can contain
declarations of objects, variables, and methods that can be
accessed by every page in an ASP application.
All valid browser scripts (JavaScript, VBScript, JScript,
PerlScript, etc.) can be used within Global.asa.
The Global.asa file can contain only the following:
• Application events
• Session events
• <object> declarations
• the #include directive
• 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 Global.asa
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. The "Session_OnStart" event occurs
immediately after this event.
Session_OnStart - This event occurs EVERY time a NEW
user requests his or her first page in the ASP application.
Session_OnEnd - This event occurs EVERY time a user ends
a session. A user ends a session after a page has not been
requested by the user 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.
<object> declarations
The objects declared in the Global.asa file can be used by any
script in the application:
GLOBAL.ASA:
<object runat="server" scope="session"
id="MyAd"progid="MSWC.AdRotator">
</object>
You could reference the object "MyAd" from any page in the
ASP application : SOME .ASP FILE:<
%=MyAd.GetAdvertisement("/banners/adrot.txt")%>
Include directive
You can insert the content of one ASP file into another ASP
file before the server executes it, with the #include directive.
The #include directive is used to create functions, headers,
footers, or elements that will be reused on multiple pages.
How to Use the #include Directive
Here is a file called "mypage.asp":
<html> <body> <h3>Words of Wisdom:</h3><p>
<!--#include file="wisdom.inc"--></p>
<h3>The time is:</h3><p>
<!--#include file="time.inc"--></p>
</body> </html>
Example : Counting the no of current Visitors
<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>
Display it using : <p>There are <%response.write(Application("visitors"))%>
online now!</p>
Note : Script delimiters are not allowed in Global.asa file.