ASP Tutorial Lesson 9: Sessions

Sessions have been given a bit of a bad name but they are still useful if used with careful consideration.

A session deals with the time a user is visiting your site. By default, when a user visits a page on your site a new session begins and they are allocated an ID to identify them while they are visiting. When the user closes their browser or after a set amount of time (usually around 20mins) their session ends. Their session ID is stored in a cookie on the users machine. Later versions of ASP allow more flexibility, with ASP.NET even allowing the session information to be stored on another machine.

While a session is open you can store information in the servers memory for them, much like a dictionary. This is done like in the following;

session(“usersName”)=request(“name”)

According to Microsoft:

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

This is not to be confused with session variables.

There are problems with classic ASP sessions such as memory hogging and the information being fixed to the machine you first visit, making problems for efficient load-balancing, etc. This meant people ended up developing their own session/state management options. For smaller sites with few visitors or web farms that allow users to return to the same server this shouldn’t be as much of a problem and as I say earlier, ASP.NET has a lot more flexible options.

Here’s a great tutorial video on the difference between ViewState, SessionState and ApplicationState in asp.net:

 

ASP Tutorial Lesson 8: Loops

Looping is an important part of programming. It allows you to perform the same operation over and over.

Following are the main loops used in ASP.

For .. Next

This loop will be familiar to anyone who has done basic programming. With this loop you can iterate a specified number of times while setting a variable to the current loop number. In the following example the code between the for and next statements would execute ten times, and would set x to be the current loop number from 1 to 10.

For x=1 to 10

next x

For each

This loop runs code for each item in a collection, setting a variable to contain the value of the current item in the collection.

For each item in array

next

Do .. while

This loop will iterate while the condition is met, so it is kind of like a mixture of an “if” and a loop.

do while [not] x<=>y

loop

 

Questions on loops? You can always find great illustrations, tutorials, and helpful hints at www.asp.net

 

ASP Tutorial Lesson 6: Decisions

Making decisions is a key part of the function of a script. The two main methods in ASP are “IF” and “Case”.

IF

What we are talking about here is basically “If this condition is true then do this”. The syntax is very close to this.

IF 10 > 5 THEN
response.write(“10 is more than 5”)
END IF

The condition in the above statement is the maths bit (“10 > 5”) but could just as easily be

IF name = “fred” THEN ..

These conditions have to evaluate to true, so if you want to know if something is not true then you can use “not”, as in the following example.

IF NOT name = “fred” THEN ..

Sometimes you want to do something if the condition is true and something else otherwise. We can use “ELSE” to do this.

IF this = true THEN
DoThis()
ELSE
DoTheOtherThing()
END IF

Multiple Choice

There is a little more we can discuss with IF but the above will give you enough flexibility for now. Another important decision making facility in ASP is the SELECT CASE.This takes a number of options a value could match plus has an ELSE to allow you to catch all other possibilities.

SELECT CASE value
CASE “this”
doThis()
CASE “that”
doThat()
CASE ELSE
doTheOther()
END SELECT

 

ASP Tutorial Lesson 5: Request

To get information back from a user the data needs to be transmitted from a web form, passed in the web address URL or stored in a cookie. Some information is also provided by the headers which are sent by the browser when making a page request.

These approaches are all dealt with by a built-in request object and values can be accessed using

myValue = request(“value”)

This will find a value that matches the name specified. A more robust approach is to use the seperate methods of the request object to prevent naming conflicts.

  • Request.Form for form values submitted using “POST”
  • Request.Querystring for values supplied on the URL or from a form submitted with “GET”
  • Request.Cookies for cookie values
  • Request.Servervariables for information sent in the header or internal server values

For example, take a look at the url of this page and you will see a portion says “?article=96”. Everything after the question mark is the “querystring”. We can access the article value by doing

requestedArticle = request.querystring(“article”)

 

 

ASP Tutorial Lesson 4: Dates and Times

Dates and times are important data formats for your pages. Just think of how often they are used in real world contexts. This lesson shows you how they are implemented in Classic ASP.

Here is a list of the main date and time format functions.

now returns 12/10/2001 17:10:33

date() returns 12/10/2001

time() returns 17:10:33

formatDateTime(now,vbLongDate) returns 12 October 2001

formatDateTime(now,vbShortDate) returns 12/10/2001

day(now) returns 12

weekday(now) returns 6

weekdayname(weekday(now)) returns Friday

month(now) returns 10

monthname(month(now)) returns October

year(now) returns 2001

If you want to get really complex then check out the 4guys site.

 

ASP Tutorial Lesson 3: Variables

This lesson deals with working with data using variables, one of the most important concepts to get to grips with when learning programming.

Variables are places where a programmer can store data in the web servers memory. This data will be kept in memory for the life of the current page and are wiped when the page has finished executing.

You can name variables using letters, numbers or underscores, but the name must begin with a letter or an underscore. Names in VBScript are not case sensitive but in other languages such as JScript they can be.

Example

Take a look at the following statement:

annualSpend = monthSpend * 12

Pretty clear what is going on isn’t it? Anyone who has done some algebra should not have a problem working with variables.

Types

One of the major failings of VBScript and Classic ASP is the fact that variable types are not enforced properly. ASP pretty much has one type of variable called a Variant and it can take the form of text (a ‘string’ such as “hello world” or ‘character’ such as the letter ‘A’), a number or a logical bit/boolean (true/false).

You are not forced to “declare” your variables before using them but this could get you into trouble with complex scripts. To switch the feature on you use

Option Explicit

at the top of your script.

Declaring Variables

You declare variables in VBScript using Dim, eg.

Dim myVar

This tells the server to allocate some spare memory for future use. Once your variable is declared you can fill it with data.

Using Variables

As we have already seen you can do mathematical operations on variables and set the value of a variable quite simply just by saying the variable is equal to another value. Strings require quotes around the value.

myNumber = 10
myString = “hello world”

Once a variable contains a value you can output that value. If you want to add one string to another (“concatenate”) you can use an ampersand.

myVariable = “hello” & “world”
response.write myVariable

Let’s take a look at an example.

http://www.aspalliance.com/chrisg/tools/variables.asp

If we take a look at the code you will see it’s really simple

http://www.aspalliance.com/chrisg/tools/view-variables.asp.aspx

As we progress through this tutorial you will see we can also do some pretty powerful things with strings (text variables) and more complex data types such as arrays and collections.

 

ASP Tutorial Lesson 2: Response

So far we haven’t done anything useful in this tutorial. I expect now you know what ASP is you are itching to have a go at making it do something! Let’s start nice and easy by outputting some text to the users browser.

We can do this two ways, the long way and the shorthand way.

Long way

Outputting text requires the “Response” objects “Write” method, as in the following:

response.write “foo”

or

response.write(“foo”)

<%

response.write “Hello World”

%>

We will re-visit the the response object further on in this tutorial.

Shorthand

If you want to display an ASP value within a block of HTML you can also use the alternative approach of <%=value%>as in the following:

< % =”foo” % >

<%=”Hello World”%>

This internally still uses the response object but makes it easier to slip values into your layout. We used this method in the example in the previous installment that output a date/time.

http://www.aspalliance.com/chrisg/tools/helloworld.asp

This page simply displays takes todays date and time that is returned by calling “now” and sends it to the users browser
http://www.aspalliance.com/chrisg/tools/view-helloworld.asp.aspx

 

Line breaks

If your lines start getting too long you can break it over multiple lines using the following

response.write “This is a very long line so we must ” &_ “continue another line even though when output ” &_ “it will all appear together”

Whitespace is not necessary in your HTML but can help when debugging or when reading it so you might want to output a line break. You do this with the VBCRLF value (Carriage Return and Line Feed).

response.write VBCRLF

 

ASP Tutorial Lesson 1: “Hello World”

In this lesson we will look at the most basic example of an ASP script. Following programming tradition it is called “Hello World”.

Take a look at the following code and enter it into the text editor of your choice, saving the file as “helloworld.asp” into your web root (usually “C:\inetpub\wwwroot” by default, but check your IIS/PWS installation).

The observant among you will be saying “but that is just a HTML file!”, and you would be right. This demonstrates one of the basic principals of ASP – ASP is at its most basic just HTML with programming instruction (“code”) added. With the later versions of ASP (ASP 3 and ASP.NET) once the page has been visited this would even not execute much slower than had it been named .html

Let’s take a look at an example page
http://www.aspalliance.com/chrisg/tools/helloworld.asp

This page simply displays todays date and time and a little message. You can look at how we did this with the following link.
http://www.aspalliance.com/chrisg/tools/view-helloworld.asp.aspx

We will look at how exactly this works in the next installment, first let’s look at how code is inserted ..

Adding ASP CodeThere are two ways we can add code directly into our page.

<SCRIPT runat=”server”>

‘ comment

</SCRIPT>

and the shorthand

<%

‘ comment

%>

As you can see, we can add code comments by starting the line with an apostrophe.

We can also include code from another page using

<!– #include file|virtual=”filepath” –>

Virtual uses your web servers virtual paths, while File can locate a file from the current directory.

For the moment you are probably best off keeping all your code in the one page until you are confident, but seperating your code like this will pay dividends later on when your sites become more complex and you begin building up large collections of useful routines.

How does it work

The ASP interpretter reads in your ASP file and executes any instructions that it finds, sending the resulting output to the visitors browser. Included files will be processed before any other code, so be careful of this.

 

ASP Tutorial

Welcome!

My name is Chris Garrett and this is my ASP tutorial. I hope it is useful to you and you can help make it even more useful by contacting me with your comments, hopefully it will improve over time.

About this tutorial

This is not the first (or the best) tutorial out there, just my take on things. There will be many people out there who know more than me and I hope if you are one of those people you will give me some advice on how I can make this tutorial better.

I have tried to just give you enough information for what you need and no more. Once you have digested this you should be equipped to dig into the many reference materials out there with confidence.

About ASP

Active Server Pages (ASP) is a compile-free, text-based scripting environment for creating dynamic web sites. It allows a developer to quickly and easily create dynamic database-driven web sites, intranets and extranets.

To write an ASP script all you need is a text editor, Notepad will do. To run ASP you will need an installation of IIS or a version of personal web server. ASP can connect to all popular databases but most ASP programmers start out with Access or SQL Server. There are also ASP environments available for other operating systems such as Chilisoft ASP which will run on operating systems such as Unix.

The History of ASP

ASP first became available to developers in October 1996 with the release of the public beta for Internet Information Server 3 (IIS). Up until this point, ASP had been known by the project name “Denali”. Microsoft followed up with ASP 2 in August 1997 as part of IIS 4 and with IIS 5 and Windows 2000, ASP is now at version 3.

Microsoft has developed a new replacement for what many people call “Classic ASP” called ASP.NET as part of their huge .NET initiative, but many people and companies will need to keep their classic asp systems for a while even once ASP.NET is officially released.

Installing ASP

To run your ASP scripts you either need Internet Information Server (IIS) on Windows NT/2000 or Personal Web Server (PWS) for Win9x. IIS is an optional part of the Windows 2000 installation, just add it with “add/remove”. Windows NT 4 requires the NT4OptionPack from Microsoft.