Microsoft & .NET.NETAn Active Server Pages Tutorial, Part 2

An Active Server Pages Tutorial, Part 2

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Review Part 1

Session 6

Boolean
Functions in VBScript and Their Application in ASP

  Function

 Description

 VBScript

ASP

IsArray

Determines
whether a variable is an array or not.

Dim x(10)
document.write(IsArray(x))
Returns true
Dim x
document.write(IsArray(x))
Returns false

 

<%
Dim x(10)
Response.write(IsArray(x))
Returns true
Dim x
document.write(IsArray(x))
Returns false
%>
IsDate

 

Determines
whether a variable is a valid date or not.
Dim x
x = "12/10/00"
document.write(IsDate(x))
Returns true
x = “555”
document.write(IsDate(x))
Returns false

<%
Dim x
x = "12/10/00"
Response.write(IsDate(x))
Returns true
x = “555”
document.write(IsDate(x))
Returns false
%>

IsEmpty Determines
whether a variable has been initialized. Variables are empty when
you declare them or explicitly set them to empty
<% 
Dim x
document.write(IsEmpty(x))   Returns
true

x = "12/15/00"
document.write(IsEmpty(x)) Returns false
x = Empty
document.write(IsEmpty(x))  Returns
true
%>

 

<%
Dim x
Response.write(IsEmpty(x))  Returns
true

x = "12/15/00"
Response.write(IsEmpty(x))  Returns
false

x = Empty
Response.write(IsEmpty(x))  Returns
true

%>

 

IsNull

 

Determines
whether a variable is null or not
Dim x
document.write(IsNull(x)) Returns false
x = Empty
document.write(IsNull(x)) Returns false

x = Null
document.write(IsNull(x)) Returns true
<%
Dim x
Response.write(IsNull(x)) Returns
false

x = Empty
Response.write(IsNull(x)) Returns false
x = Null
Response.write(IsNull(x)) Returns true
%>

 

IsNumeric Returns
true if the variable can be evaluated as a number 

 

Dim x, y
x = 20
document.write(IsNumeric(x)) Returns
true

y= "Hello"
document.write(IsNumeric(x)) Returns
false
<% 
Dim
x, y
x = 20
Response.write(IsNumeric(x)) Returns
true

y= "Hello"
Response.write(IsNumeric(x)) Returns
false
%>

Session
7

Using
Session,
Application and Cookies

Session

This object will manage information on individual user sessions. A
session object is created when a user does not have session access to a page in the
application. The object persists until
it times out or is explicitly abandoned. For example, if you use the
free email facility of Yahoo or another provider, your email address will appear on the top of the
inbox as long as you exit from that page or log out from your inbox.

The whole process is very simple. First we will assign a session variable and then we will attach the
session code at the appropriate location on the page. A sample script is
given below for your reference.

<% session("permission") = "yes" 
session("urname") = Request("urname") %>

We will then apply the above variable, somewhere on the script
like
welcome<% session("urname")
%>
to Mark Inc members area
I will explain this concept with a detailed
example later while we discuss database access. 

Application

You can use the application object to share information among all users.
Because all users of your application share the same application object you
can use two methods to prevent multiple users from modifying information
at the same time. Using lock and unlock methods, you can prevent these
types of collisions from happening and thereby providing reliable access
to the server to all users. This method is commonly used to create counters on the
web pages.

For
example the following code creates a simple counter. The counter value
will increment each time when the page loads. But the value will reset if you shut down your computer. 

<body>
<% application.lock %>
<% application("counts") = application("counts") +1 %>
<% application.unlock %>
This page has been visited by <%= application("counts") %> Times
</body>

Request

When you clicks a form button, you are
requesting the server to perform the necessary actions. This is done via
the request object. For example to update the database we use to give a
code like this <%
rs("name") =
request.form("name") %>. 

This piece of code will add
the entered name to a database on the server. We will discuss more about this
object later while covering database access.

Response

When you request some information from the server, naturally the server
sends its feedback to you. This is done via the response object. This
object has an important method called redirect
which transfers you to the page specified. If you want your users to be
forwarded to www.internet.com after a
successful login from your site, you should code the script as 

<% response.redirect("http://www.internet.com")
%>

For example, to print your name on
the top of a page, we can give a code like this 
Your 
name is
<% response.write("David") %>.

This
object is commonly used in applications, which provides access to
databases and 
in sites which require generation of user’s data dynamically.

Cookies

In cookies the information
is saved on the clients computer and not in the server. This
is suitable for sites with a lot of visitors like job sites. A
user filling up 
a resume form need not re-enter all the information each time when he/she updates the page. All the
previous information will be
retrieved back and the user need only edit the required fields. The server stores
the relevant information on
the client’s computer.&nbsp

This
feature will not be available if the cookie is deleted, expired etc. If
a user formats the hard drive after submitting, the information will no
longer be available. Some cookies automatically gets deleted and will be
having an expiration date. In some cases we have to manually delete the
cookies. Generally, in the Windows operating system, cookies are stored in c:windowscookies
folder.

The following code stores the cookie on the
client’s system.

<% response.cookies("whatever") = "information"
%>

The following statement will return the cookie if the user request it at a
later time

<% request.cookies("whatever") %>

Now let us examine an
example which uses cookies to store the data. The program requests to
enter your name and when the button is clicked, the value in the textbox
will be stored in a cookie. However this cookie will expire when you
close the browser. 


<% if request("content_length") <> 0 then
Response.Cookies("data") = request("coo")
end if
%>
<html>
<head>
<title>
Exploring cookies
</title>
</head>
<body>
Current value is
<%= Request.Cookies("data") %><br>
<form action = "http://localhost/cookie007.asp" method = "post">
<input type = "text" name = "coo" 
value = '<%= Request.Cookies("data") %>'>
<input type = "submit" value = "submit">
</form>
</body>
</html>

Session
8

Text Files in ASP

It is possible to open and read content from a text file. It is also
possible to create and write a text file using ASP. Necessary commands
should be written in order to access the file. The file operations are
done with the help of built in Scripting.FileSystemObject
component. 

We can read a file and write to a file by making use of  this
component. Whatever is the file content, it will be displayed on the
browser directly. You have to specify the file which is to be read. You
should take care to close all the objects by using the keyword nothing.
The following example shows how to read a file by using ASP.

<% set fs = createobject("scripting.FileSystemObject")
set rfile = fs.OpenTextFile("c:session9fileread.txt")
filecontent = rfile.ReadAll
rfile.close
set rfile = nothing
set fs = nothing
response.write(filecontent)
%>

Here, the content
of the file fileread.txt will be displayed, provided the file exists on
the appropriate directory. Otherwise the system will show a error. The
contents are being read by using ReadAll function.
Finally the contents are displayed by using

response.write
method and the objects are released from the
memory. The following example shows how to write the contents to a text
file.

<%
mytext = "This will be written to the text file"
set fs = createobject("scripting.FileSystemObject")
set wfile = fs.CreateTextFile("c:session9filewrite.txt",true)
wfile.write(mytext)
wfile.close
set wfile = nothing
set fs = nothing
response.write("Text Created")
%>

In the above code
the contents in the second line will be written to filewrite.txt file.
Finally, a string is being displayed to inform the user that the contents
has been written to the file. The parameter, true in line 4 indicates
that overwriting is allowed.

Session 9

Accessing Databases

Introduction to Databases

Databases are used to store information that are arranged in a specific
manner. Each and every entry in a database is called a record and are
organized into tables. Each table in turn contains fields which contains
information. For example, in a student management database there may be
tables pertaining to students general info, assignments, fee status,
exams etc. Each of these tables contains fields according to the
requirements. We use to browse the net mainly for getting information related to
various topics. But the most important point is that nearly 85% of the sites 
on the internet
are relying upon databases for specific needs. 
 
For example consider the following scenarios:
You are searching the web using yahoo.com by entering a keyword and
you are viewing the search results immediately. So how does the
information come from, it is through the databases 
stored on the server.
You are using
emails, have you ever imagined where your mails are
stored safely till you retrieve them from the server -yes it is in databases. Hence we
can conclude that without databases there will be no business over the web.

The most powerful and easiest database application now
available is Microsoft Access. You can easily create a database with a
few mouse clicks if you are using packages like these. 
Moreover
you can use distributed database languages such as Oracle, SQL Server
etc. Suppose you have been asked to develop
a database project using Visual basic and Microsoft Access by
your employer. After sometime your employer decides to implement the
same project on the web by using ASP and this time by making use of
distributed databases like Oracle or SQL Server. 
What is the difference between the
first and second projects?


The basic idea behind the first project is that, Microsoft Access is
primarily meant for applications having a  single user at a time.
They are mainly located on a single computer and can be used only by one
person at a time. But these types of projects cannot be avoided and are
still used by large number of concerns. The concept behind the second
project is that of Multi user databases which means they are located on
a network and can be accessed by many users at a time. Moreover it is
implemented over the web also and any user can access the application
irrespective of the operating system they are using.  Normally
databases used for building the web projects may be Oracle, SQL Server
because of their ability to handle large number of records.

But instead of VB forms, HTML forms are used in web projects.
We cannot use HTML directly for accessing databases. Instead we have to
use  server-side technologies like ASP. ASP uses either VBScript or
JavaScript as its scripting language.

Front-end and Back-end
Concept

The front-end is the program with which the user interact. It mainly
consists of text fields, checkboxes, radio buttons, combo boxes, command
buttons etc to facilitate data entry and other related tasks like
updating, deletions
etc. The back-end lies between the front-end and the database itself.
The back-end is actually provided as part of the operating system. The
Microsoft Jet Database Engine is an example of a back-end. The jet engine
interacts with the database file to perform the data manipulations. The
database backend running on the web server should support the database
file format.

For example a Microsoft Access 2000 database does not
support Microsoft Jet 3.51.Instead we have to use 4.0 version. If you
are using Oracle or SQL Server, you have to configure the ODBC driver
setup (from the control panel ODBC32 bit icon)  and choose the
appropriate drivers for the same. After that you have to link your application and the database via
a appropriate data source name.
Hence you
have to consider the following aspects while designing a database
application.
(1) Front-end designing 
(2) Designing of a database
(3) Linking with an appropriate data source.

Connecting Databases

You can connect web pages to databases via numerous backend engines. The
best way is to use ActiveX Data Objects or ADO. But before examining ADO
let us examine OLEDB. It is a set of Component Object Model (COM) interfaces that you can use to access a variety of information Sources.
But you cannot access OLEDB directly, but indirectly by means of ADO.

ADO
provide programmers with an application level interfaces to OLEDB.
However several earlier technologies such as RDO / DAO are still
supported and can use them in your ASP programming. However ADO is
preferred due to its simplicity and easy maintainability. The ADO object
model consists of the following objects viz Connection, Command, Recordset, Field, Error & Parameter. We should
understand the functioning of the Connection, Recordset objects before proceeding further.

Connection Object

It represents connection to a data source. We have to open a connection
to a data source with the Open method. To execute a specified query we
have to use Execute method.
But before opening a connection, you  have to
create an instance of the connection object, the coding of which looks like this
<% Set conn =
Server.createobject("ADODB.Connection") %>
.
To open
the data source use the following code
<%
conn.Open <your DSN Name> %>.
 

Recordset Object

This is the main interface to data. It represents the set of records
from a table in a database. You have to create a Recordset object
similar to the connection object and use that object to open the
connection to the records. The coding looks like this 
<% Set
rs = server.createobject("ADODB.Recordset") %>.


After
that you have to open the record set by using the following coding 

<% rs.Open <your table name>,conn %>
.
conn
is our connection object which we created above. 
The Recordset object
contains several methods to create a new record, delete a record, update
a record etc. For example to add new records to a record set use the
following code 
<% rs.addnew %>
and update that record set
using
<% rs.update
%>
.

Field Object

It represents a column of data in a
Recordset. For example
while searching you may want to populate the records in the
corresponding textboxes. For that purpose you have to make use of fields
object and its item property. The coding for fetching the field age from
a record set is as follows
<%
rs.fields.item("age") %>. 

Case
Study

Mark Inc decides to build a web application so that users can register
at their site and login with their username and password to enter the
members’ area. They had decided to use HTML as the front-end and ASP
scripting using VBScript. The database being used is Microsoft Access
2000. The first step will be to build an HTML Form. Click
here
to get the HTML Form. If you need the source code, right click
on the page and select View Source from the pop-up menu.

When the user fills out the form and clicks on the submit button, the
data contained in the form should have to be passed on to a database on
the server. For this purpose, the necessary .asp file is to be written and the
complete code for the same is given below:



<% set conn = Server.createobject("ADODB.Connection") 
conn.Open "Member" 
set rs = Server.CreateObject("ADODB.Recordset") 
conn.BeginTrans 
rs.Open "newcustomer",conn,3,3 
rs.AddNew 
rs("urname") = Request("urname") 
rs("pass") = Request("pass") 
rs("email") = Request("email") 
rs("address") = Request("address") 
rs("country") = Request("country") 
rs.Update 
session("permission") = "YES" 
session("urname") = Request("urname") 
conn.CommitTrans 
rs.Close 
conn.Close
response.write("Your data has been successfully submitted")
%>
<body><form>
<input type = "text" name = "name">
<input type = "password" name = "pass">
<input type = "submit" value = "Login">
</form></body>


When this code is run, the form data will be
passed to the
database on the server, and you will get a confirmation message. After
that you will be provided with an HTML form so that you can login to the
members’ area by entering your username and password. The site should
check the validity of your username and password. If both are correct,
then you will be either redirected to a new page or you will be shown
your account details and other relevant information. If the entered
information is not correct, then you will be shown an error message
asking you to login again. 

Typically sites will provide a login form on their home page so that registered
users can login straight away. In order to validate the username and
password as mentioned above, the database will have to be searched. The complete code to
search the database is given below:

<%if Request.Form("urname") = "" then%>
<%Response.Write("Please correct your entries again ")%>
<%else%>
<% set conn = Server.createobject("ADODB.Connection") conn.Open "capker" set rs = Server.CreateObject("ADODB.Recordset") conn.BeginTrans rs.Open "newcustomer",conn,3,3 rs.AddNew rs("urname") = Request("urname") rs("pass") = Request("pass") rs("email") = Request("email") rs("address") = Request("address") rs("country") = Request("country") rs.Update session("permission") = "YES" session("urname") = Request("urname") conn.CommitTrans rs.Close conn.Close%>
<%if Request.Form("urname") = "" then%>
<%Response.Write("Please correct your entries again ")%>
<%else%>
<% set conn = Server.createobject("ADODB.Connection") conn.Open "capker" set rs = Server.CreateObject("ADODB.Recordset") conn.BeginTrans rs.Open "newcustomer",conn,3,3 rs.AddNew rs("urname") = Request("urname") rs("pass") = Request("pass") rs("email") = Request("email") rs("address") = Request("address") rs("country") = Request("country") rs.Update session("permission") = "YES" session("urname") = Request("urname") conn.CommitTrans rs.Close conn.Close%>

<% set conn = server.CreateObject("ADODB.Connection") 
conn.Open "Member" 
set rs = server.CreateObject("ADODB.Recordset") 
rs.Open "newcustomer",conn,3,3
flag = 0 
rs.MoveFirst 
do while not rs.EOF 
if request("pass") = rs("pass") and request("name") = rs("name") then 
session("permission") = "YES" 
session("urname") = Request.Form("urname") %>
<body>Welcome<% session("urname") %> to Mark Inc's members area</body>
<% flag = 1 
end if 
rs.MoveNext 
loop 
if flag = 0 then 
Response.Write("Please reenter your username and password") 
end if %>

When you execute this code, if your
username and password are correct then you will be shown   a
message
Welcome<your user name> to Mark Inc.’s members area. The user name is displayed here by creating a session
variable. The above code assumes that you have created a data source name
called Member and a table named 
newcustomer
(using Microsoft Access). If
you do not follow these steps, then you cannot run this application.

However, you can run this application without creating a data source name
on the control panel by applying the following piece of code. The code
directly uses the database name as a parameter to the MapPath method of
the server object. This method will automatically map this database to a
proper WinNT path. If your web server supports .asp files but doesn’t
permit creation of data source names, then this code will be useful for
you to test and deploy your .asp scripts.

<% set conn= server.CreateObject("ADODB.Connection") 
set rs = server.CreateObject("ADODB.Recordset") 
openstring = "data source =" & server.MapPath("customers.mdb") 
openstring = openstring & ";Provider=Microsoft.Jet.OLEDB.4.0;" 
conn.Open openstring 
rs.Open "newcustomer",conn,3,3 %>

I hope by now you have a
clear idea about programming with Active Server Pages using VBScript as
the scripting tool. In this two-part tutorial, I covered almost all
aspects of this scripting language, by way of examples wherever necessary.
However, I will be glad to
assist you further in case you have any questions.

About the Author

Anand Narayanaswamy is a graduate, in commerce, from the University of Kerala. He is currently working as an instructor teaching Java, Visual Basic, and other Web technologies, such ASP and XML. Currently, Anand lives in Thiruvananthapuram, Kerala State, India. He can be reached via his Website http://www.learnxpress.com.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories