ASP – Active Server Pages

            Active Server Pages (ASP) is a technology created by Microsoft that allows you to dynamically generate browser-neutral HTML using server-side scripting.  That is, the web server will generate HTML code for you when your web browser asks for it.  Processing done by the server is called server-side scripting.  ASP codes are enclosed in special brackets that look like this:  <%…code here…%>.  The code is inserted into an HTML document, except the document has the .asp extension instead of the .html extension.  The server will process the ASP code enclosed in these brackets upon the web browser’s request.

So why is ASP useful?  In the early days, all web information was static.  This means that what you see on your web browser, would be the same as what I would see on my web browser.  The client, which is you when you load a web page, requests information from the web server, and the web server sends the information.  The web server sends every client the same information.  The web server does not dynamically generate any part of the HTML document.  There was no interactivity between the client and the server. 


                     Browser            

                                                            Browser Requests                    Server

                                                            Sample.html >From Server

 

                        Browser

                                                            Server Sends Sample.html        Server

                                                            To Browser

 

One of the first ways to make web servers non-static was the invention of Common Gateway Interfaces (CGI).  CGI’s can communicate with the web server to execute an application on the web server.  The result of the application is converted to a browser readable HTML form and sent back to the requesting browser.  Thus each request from the server may not return the same information.  What you see on your web browser, may be different from what I see on mine, although we are loading the same page.

            CGI’s changed the way information was shared on the Internet and played a big role in the rapid growth of business on the Internet.  Because of the inefficiencies of CGI, Microsoft introduced its own product, ASP.  ASP and CGI do similar things, but because ASP.DLL (the “thing” that interprets ASP code) resides in the same memory space as IIS (Microsoft’s Internet Information Server, a web server) and is never removed from memory, it is more efficient than CGI.  ASP quickly caught on and has become one of the most popular ways to code on the Internet.


            The following diagram shows how ASP works:

           

                        Browser                                                                      

                                                                                                            Server

                                                            Browser Requests

                                                            Sample.asp >From Server

 


                                                                                                                        IIS Passes

                                                                                                                        Request To

                                                                                                                        ASP.DLL

ASP.DLL
 
 

                        Browser

                                                                                                            Server

 

                                                                        ASP Passes New

                                                                        HTML Back to IIS For

Sending to Client

ASP.DLL
 
 

                        Browser

                                                                                                            Server

                                                            IIS Sends Sample.asp

                                                            Back to Client

ASP.DLL
 
 

Lets begin with collecting information.  Forms can be used to collect information from users of your website.  For example, textfields can be used to gather names, addresses, phone numbers and check boxes can be used to gather preferences.  When the user fills out a form on your website, you need some way to take what they filled out and put it to use.           

Here’s a simple page that takes down the users name.  When they press enter, we’ll load a page that greets them by the name they entered.

First, recall how to use forms and text-fields from HTML.  It’ll look something like this:

Then click enter you will get:

 

The code for the first page is as follows:

<HTML>

<HEAD></HEAD>

<BODY>

Please enter your name in the textfield, then press enter. <BR>

<FORM ACTION="tutorial1example2-1.asp" METHOD="Post">

<INPUT TYPE="text" NAME="NameTextField">

</FORM>

</BODY>

</HTML>

The form action is tutorial1example2-1.asp.  This means that when the user submits the form, tutorial1example2-1.asp will be loaded and the asp code contained in the page will be processed by asp.dll on your server.

The input type is a textfield and the textfield is named “NameTextField”.

This is the code for tutorial1example2-1.asp:

<HTML>

<HEAD></HEAD>

<BODY>

<%

Dim NameEntered

NameEntered = Request.Form(“NameTextField”) %>

Welcome <% =NameEntered %>.  So glad you could join us.

</BODY>

</HTML>

We first declare a variable.  Dim stands for dimensions, but you can think of it as simplying declaring the variable NameEntered.  Variables helps us store the information we gather and allows us to easily work with the information.  We can also alter the information if need be.

Once the variable is declared, we need to assign it a value.  The equal sign is used for this.  What comes after the equal sign is the value we are assigning to the variable.  In this case, we want the variable to be the information entered by the user.

When the user submitted the form, the data can be collected in the request object.  The request object has a method “form” that takes in the input type name as its argument.  The form method returns the value entered in that form.  In this case, Request.Form(“NameTextField”) will return whatever the user entered in the textfield.

To see that this was done correctly, we just need to printout the value of the variable.  One quick way to do this is to use =variablename within your asp tags.  We used <%=NameEntered%> to output the variable NameEntered.

Exercise 1:

Create a page with a text-field gathering a person’s name, another text-field gathering their credit card number, a radio button where they can check off which credit card they have (Visa, Mastercard, Discover, or American Express), and create a button for them to click on when they are done.  Then, generate a page telling them the information they entered.  This is similar to what we just did but with a radio button.  Try to figure out how data from a radio button can be collected.

So your page will look something like this:

When you click Submit, you’ll get:

And when you view source, you’ll see something like this:

excersise

create a page that opens an account for the user.  The page should have textfields for a user name, password (the password textfield should be hidden, that means when they enter their password, stars should appear instead of text), another textfield that confirms password.  Also, add textfields to gather billing information, shipping information, and phone numbers.  Call this page openAccount.asp.  Create a page that displays this information so the user can confirm that the information they entered is correct.  Call this page accountConfirm.asp.  this page should have a button that says, “create account” and a button that says, “change information”.  When the user clicks change information, bring them back to openAccount.asp with the information already entered (so they don’t have to re-enter correct information) and when the user clicks create account, bring them to a page that says, “your account is created”, and list the information they entered.


Control statements:

An ‘if, else’ statement is a conditional statement that does one operation if true, and another operation if false.

For example:

<% If Count = 1 Then %>

            Count equals 1.

<% Else %>

            Count does not equal 1.

<% End If %>

If the variable count is equal to 1, the statement “Count equals 1” will be printed.  If count does not equal 1, then the statement “Count does not equal 1” will be printed.  It is important to include the <% End If %> statement.  This tells the server when to stop the ‘if, else’ statement.

Excersise

In your accountConfirm.asp page, add a control statement that checks to see if the password entered in the password field matches the confirm password in the confirm password field.  If it doesn’t match, return the user to openAccount.asp and tell them the passwords don’t match.  If they match, continue as normal.

A for loop executes code a given number of times.  In the next example, the for loop will print hello world 5 times because the for loop goes from 1 to 5.

<HTML>

<HEAD></HEAD>

<BODY>

Welcome to ASP.

<%For intCounter = 1 to 5 %>

<FONT SIZE = <%=intCounter%> >

Hello World.  Font Size is <%=intCounter%>. <BR>

<%Next%>

</BODY>

</HTML>

-           The <%…%> brackets indicates ASP code to be interpreted by the server.  <%For intCounter = 1 to 5 %> initialized the variable intCounter which will be incremented to set the font size.  It is a simple ‘for loop’ that makes intCounter equal to 1, then 2, then 3, until it reaches 5.

-           The <%=intCounter%> statement takes the current value of intCounter.  For example, suppose intCounter is at 3.  Then <FONT SIZE = <% =intCounter %> is equivilant to saying <FONT SIZE = 3>.

-           The <%Next%> tells the ‘for loop’ to increment intCounter, that is, change intCount from 1 to 2, or from 2 to 3, or from 3 to 4, etc.

The HTML code sent to the browser is the following:

What you should see in your browser is this:

Subprocedures can be used to help not re-typing code in several places.  Subprocedures can also help make your code look cleaner and clearer.  Instead of explaining what a subprocedure is, it will be clearer with an example.

<%sub contactInfo(location)

Response.write “you can contact me at “

Select Case location

            Case “east coast”

                        Response.write “212-555-5555”

            Case “west coast”

                        Response.write “301-555-5555”

            End Select

End sub

%>

…some html code here…

<%call contactInfo(“east coast”)%>

this will allow me to print the correct information depending on which coast was put into the subprocedure.  When call is used, the subprocedure is run.

One limitation that subprocedures have is that it can only print things or other actions. What if you wanted back an answer?  For example, what if you needed to calculate commission fee for an item purchased?  Functions can allow you to do this.

Here is an example of a function

<%

function commission(ItemPrice)

            commission = ItemPrice * .1

end function

%>

…some html code here…

<%commissionFee = commission(300)%>

This function calculates 10% of the purchase price for commission.


The Time() function returns the current time on the server.  You could use <% =Time() %> to get the time.  Similarly, the Date() function returns the date on the server.  Write an HTML page using ASP to generate the following:

 


Request and Response objects.

The request and response objects allows the client to communicate with the server.  The request is used by the client to request information from the server, and the response objects lets the server to respond to the client’s request.

The response objects contains a collection called write.  This collection is used to write html code directly to the page.  For example, I could say:

<% response.write “hello”%> and the word “hello” would appear on your browser.  Response.write doesn’t only take in strings, it could also write variables.  For example,

<% dim variable

variable = 15

response.write variable %>

would write 15 on your browser.

A shorthand of using response.write is <%=”hello”%> or <%=variable%>.

These two ways produce the same result.  So when do you use which?

The shorthand way is useful when you need to insert a single piece of dynamic code.  It’ll reduce the amount of code you have to write.

<html>

hello everybody, today is <%=date%>.  The time is <%=time%>.

</html>

as opposed to

<%response.write “hello everybody, today is “

response.write date

response.write “.  The time is “

response.write time

response.write .

%>

 

keep in mind the shortcut method is not always the most efficient.  If you have a large block of asp script code, the response.write might be more efficient because you don’t have to jump into and out of scripts.

Request.querystring

The querystring collection is used to gather information that the “get” method puts in the url.  When you submit a form, if you used the “get” method instead of the “post” method, the information is attached to the url address.  You will see something like this in your address bar:

www.howdydoody.com/learn.asp?firstname=john&lastname=doe

the querystring is appended with the “?”.  If I use the request.querystring, firstname=john&lastname=doe is returned.  In other words, I could say

<%response.write(request.querystring)%> and I would see the querystring on my browser.  This is one way to gather data from the user.

Response.redirect

The response.redirect collection allows you to redirect the client to different pages.  The collections works like this

<%response.redirect = destination page%>

One important thing to keep in mind is the redirect method must be used before any code is processed or html code printed.  In other words,

<html>

<head></head>

<body>

hello.

<%response.redirect = “hello.html”%>

byebye

</body>

</html>

would cause an error.

*****

here’s an example I stole from the wrox book

pagechoice.html

<html>

<head>

<title>redirection example</title>

</head>

<body>

<h2>choose which page you wish to display</h2>

<form action=”choosepage.asp” method=”post”>

<input type=”radio” name=”pagechoice” value=”page1” checked>page number 1<br>

<input type=”radio” name=”pagechoise” value=”page2”>page number 2<p>

<input type=”submit” value=”choose page”>&nbsp;&nbsp; <input type=”reset”>

</form>

</body>

</html>

choosepage.asp

<%

option explicit

dim strchoice

strchoice=request.form(“pagechoice”)

if strchoice=”page1” then

            response.redirect “page1.html”

else

            response.redirect “page2.html”

end if

%>

page1.html

<html>

<head>

<title>page1</title>

<body>

<h1>this is page number 1</h1>

</body>

</html>

page2.html

<html>

<head>

<title>page2</title>

<body>

<h1>this is page number 2</h1>

</body>

</html>


Tracking users with cookies.

A store might be looking at how many hits they have to their site and discover they had 100 hits within the first hour.  This number may not be accurate.  It may be one person sitting at their computer hitting the refresh button 100 times.  The store owner needs a way to track users to see how many different users access the site.  Cookies can be used to do that, and much more.

A cookie is a text file that is implanted on the client’s machine to keep information about the user.  For instance, a cookie could keep names, addresses, phone numbers, email addresses, what pages they have been to within the same domain, etc.  The cookie is placed by the server, on the client’s machine, and is completely voluntary.  The client can choose not to accept the cookie if they wish, and then the server would not be able to store information about the user.

The cookie is a collection of the request object.  The cookie collection holds information from all the cookies set by any one application.  So when a client establishes a connection with the server, all of the values from the clients cookies are read and stored into the request.cookie collection.  These values are now available and easy to work with.

The general syntax for retrieving cookies is:

Request.cookies(“cookieName”)[(“key”)].attribute

So to display the contents of a cookie you would say:

Response.write request.cookies(“cookieName”)

To write cookies to the clients machine:

Response.cookies(“cookieName”) = value

One important thing to keep in mind is a cookie can store multiple amounts of information.  You can use a key to keep track of what information you are storing and which to retrieve.

To use keys when writing a cookie:

Response.cookies(“cookieName”)(“key”) = value

Response.cookies(“cookieName”)(“anotherKey”) = anotherValue

Retrieving values of cookies:

Request.cookies(“cookieName”)(“key”)

Request.cookies(“cookieName”)(“anotherKey”)

You could put expiration dates on cookies.  A cookie would go away once the expiration date is reached.  This is done as follows:

Response.cookies(“cookieName”).expires = date + 365

This cookie will expire in one year from today.

Here’s an excellent example I found from the wrox book:

<html>

<head>

<title>Cookie Test – Login</title>

</head>

<body>

Please enter your e-mail address and password to login to the system.

<form action = “checkLogin.asp” method=”post”>

E-Mail Address: <input type = “text” name = “email” size = “40”><br>

Password: <input type = “password” name = “password” size = “10”><p>

<input type = “checkbox” name = “saveLogin”>Save Login as a cookie?<p>

<input type = “Submit” value = “login”> &nbsp; &nbsp;

<input type = “reset”>

</form>

</body>

</html>

**save this file as login.asp**

create another file with the following code:

<%dim bLoginSaved

if request.form(“saveLogin”) = “on” then

response.cookies(“savedLogin”)(“email”) = request.form(“email”)

response.cookies(“savedLogin”)(“pw”) = request.form(“password”)

response.cookies(“savedLogin”).expires = date + 30

bLoginSaved = true

else

bLoginSaved = false

end if

%>

<html>

<head>

<title>Cookie Test – Check Login</title>

</head>

<body>

<%

if bLoginSaved then

response.write “Saving Login information to a cookie<hr>”

end if

%>

Thank you for logging into the system.<p>

Email address confirmation: <%=request.form(“email”)%>

</body>

</html>

save this as checkLogin.asp


Application object and global.asa

The application object can store information that every user can use.  For example, say the site manage wants to put a special announcement for this week.  This announcement applies to this week only and everyone who comes to the site has to be informed of it.  One way to do this is to put the announcement in an application-scope variable.  This means everyone will be able to access the variable, and in some cases, change the variable.  To use application variable, they must be stored in a special file that every user can access.  This file is called global.asa.  each application can have only one global.asa and this file is stored in the root directory of the application.

Here’s an example of what application variables would look like and how they are declared.  In your global.asa file, you’ll have something that looks like this:

<script language=”vbscript” runat=”server”>

Sub Application_OnStart

            Application(“variable”) = “hello”

            Application(“variable2”) = 0

End sub

</script>

the subroutine must be included in the script tags.

To use the variables, you can just use application(“key”).

The application object has a lock and unlock methods.  These methods are used to allow the variables to be changed and not changed.  When you use lock, the variables will only be able to be changed by the current user.  When you use unlock, the variables will now be able to be changed by all users.  Usually what you want to do is lock the variables before you change it, and unlock it when you are done.  This prevents two people from changing the variables at the same time.

Here’s an example:

<html>

<head></head>

<body>

<%dim x

x = application(“variable2”)

x=x+1

response.write(“variable”)

response.write(“variable2”)

application.lock

application(“variable”) = time

application(“variable2”) = x

application.unlock

%>

each time you click refresh on your browser, the number should increment and the time should change to the current time on the server.

Global.asa can contain 4 subprocedures.

Application_onstart

Application_onend

Session_onstart

Session_onend

Application_onstart is run once when the first user requests a page from the server.  All the application starting procedures you need to do should be contained in the method (ie. Initializing variables).

Once this method is done, session_onstart funs for the first session.  (we’ll discuss sessions right after this). 

**application_onend and session_onend is less important for what we’re doing**

Session variables

When you browse from page to page, it would be annoying if you had to login or enter your information each time you went to a different page.  It would be nice if you could login once, then as you browse the domain, you could keep all your information.  Session variables allows you to do this.  Session variables are used with similar syntax as application variables.

<%session(“key”)%>

there are a few session methods that come in very handy.  The timeout property allows you to end a users session in a set amount of time.  Keep in mind that if a user is connected to your server and has session variables, these variables are using up your system’s memory.  You would want to remove those users who are no longer at your site or have been idle for a long time.  The timeout method lets you do this.

<%session.timeout = 30%>  this will cause the session to timeout in 30 minutes if there is no activity.

Session.abandon on the otherhand terminates the users sessions when the page is finished processing.  This could be useful when the user chooses to logout.  This will free up system resourses immediately.  A good combination to use with session.abandon is response.redirect.  you end the session of the user and redirect them to another page.

In your global.asa file, you can have a session_onstart subprocedure.  This subprocedure is called immediately after application_onstart finishes.  this procedure can let you initialize any variables you need for the current user.  For example, you could grab cookie information during session.onstart.  when your user opens their first page, they could be greeted with a personal message.