When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
ASP ASP.NET ASP FAQs Message Board Feedback
Print this page.
Teach Yourself Active Server Pages in 21 Days!
Teach Yourself Active Server Pages 3.0 in 21 Days


Using Session Variables
As discussed in the previous section, an instance of the Session object serves as a warehouse for a specific user's information. What use is a warehouse, though, if you put nothing inside it? If you have a user-specific piece of information that you need to persist, you need to save this information to a variable and put that variable into the user's Session. Such variables are referred to as session variables.

To write a value to a session variable, use the following syntax:

Session(sessionVariableName) = Value

This, essentially, stores a variable into a user's personal warehouse. A session variable can be read by using:

Value = Session(sessionVariableName)

Imagine that you were creating a site, and at the top of each Web page you wanted to put a quote of the day. It would be nice to present the user with an option to hide the quote. Listing 11.7 shows the source code for an ASP page that shows both the quote of the day and an option to hide the quote.

Listing 11.7 - Hiding the Quote of the Day

1:  <%@ Language=VBScript %>
2:  <% Option Explicit %>
3:  <%
4:      'Do we want to show the quote of the day?
5:      If Session("ShowQuote") = False then
6:         'The user doesn't want to see the quote
7:         'Show them an option to see the quote again
8:  %>
9:         <A HREF="/scripts/ShowQuote.asp">Show Quote of the Day</A>
10: <%
11:     Else
12:        'The user wants to see the quote, so show it!
13: %>
14:        A stitch in time saves nine.<BR>
15:        <A HREF="/scripts/HideQuote.asp">Hide Quote</A>
16: <%
17:     End If
18: %>
19:
20:   <P><HR><P>
21:   <I>Blah blah blah blah...</I>

The code in Listing 11.7 first determines whether the user is interested in seeing the quote of the day. In line 5, an If statement determines whether the session variable ShowQuote is False. If ShowQuote is False, you don't want to show the quote of the day. Line 9 provides a hyperlink that, when clicked, allows users to see the quotes of the day. If, on the other hand, ShowQuote is not False, the code after the Else on line 11 is executed. Line 14 displays a famous quote from Ben Franklin, and line 15 provides a link that, when clicked, turns off the quote of the day. Figure 11.6 shows the output of Listing 11.7 when a user visits the site for the first time.

Figure 11-6: Initially, the user won't see the quote of the day. In Figure 11.6, the quote of the day isn't shown on the user's first visit. This is because the session variable ShowQuote has not yet been created in the user's Session. Because ShowQuote doesn't yet exist, when you ask for ShowQuote in line 5 of Listing 11.7, you are returned an empty string, which evaluates to False. There's nothing wrong with this unless you want to have the quote of the day shown by default. Later today, in the section, "Initializing Application and Session Variables," we will discuss how to have session variables created automatically upon a new user's visit.

Note Figure 11.6 and line 9 in Listing 11.7. If the ShowQuote session variable is False, you need to provide the user with a link to start showing the quotes of the day again. This link, if clicked, will take the user to ShowQuote.asp. This ASP page needs to "turn on" the quote of the day. This is done by setting the ShowQuote session variable to True. After ShowQuote has been set to True, ShowQuote.asp needs to redirect the user back to the page he came from. Listing 11.8 presents the code for ShowQuote.asp.

Listing 11.8 - ShowQuote.asp "Turning On" the Quote of the Day

1:  <%@ Language=VBScript %>
2:  <% Option Explicit %>
3:  <%
4:      'Set ShowQuote to True
5:      Session("ShowQuote") = True
6:
7:      'Send the user back to the page from which they came
8:      Response.Redirect Request.ServerVariables("HTTP_REFERER")
9:  %>

ShowQuote.asp needs to do two things: set the ShowQuote session variable to True, thereby turning on the quote of the day; and redirect the user back to the page from which he came. The first task is accomplished on line 5. The second task is completed on line 8, using the Redirect method of the Response object. The user is sent to the URL specified by the Referer HTTP header, which is the URL of the page he came from. The Request.ServerVariables collection and the HTTP headers were discussed on Day 10.

By clicking the Show Quote of the Day hyperlink in Figure 11.6 (created on line 9 in Listing 11.7), ShowQuote.asp was loaded. ShowQuote.asp then set the ShowQuote session variable to True and sent the user back to the Web page he came from. When the user arrives back at the page he started on, the quote is now showing. Figure 11.7 shows the results of the code in Listing 11.7 after the user clicks the Show Quote of the Day hyperlink. Figure 11.8 presents a diagram of the steps taken to show and hide the quote of the day.

Figure 11-7: The quote of the day is now showing.

Figure 11-8: The steps involved in showing/hiding the quote of the day.

When the quote of the day is shown, not only do you need to display the quote of the day, you also need to provide the user with an option to turn off the quote of the day. Line 15 in Listing 11.7 creates a link to HideQuote.asp, which needs to do nearly the exact same thing as ShowQuote.asp. HideQuote.asp should set the ShowQuote session variable to False and then redirect the user back to the page he came from. The code for HideQuote.asp can be found in Listing 11.8. After turning off the quote of the day, the output is the same as when you initially visited. You no longer see a quote but instead see the Show Quote of the Day hyperlink. This output was shown previously in Figure 11.6.

The Session object can be used to store any type of variable. With cookies, you are restricted to only saving simple data types on the client's computer. The Session object, however, can be used to store arrays. To show this, create an ASP page named CreateSessionArray.asp and enter the code shown in Listing 11.9.

Listing 11.9 - Using the Session Object to Store Arrays

1:  <%@ Language=VBScript %>
2:  <% Option Explicit %>
3:  <%
4:      'Create an array
5:      Dim aSentence(4)
6:      aSentence(0) = "I "
7:      aSentence(1) = "like "
8:      aSentence(2) = "Active "
9:      aSentence(3) = "Server "
10:     aSentence(4) = "Pages!"
11:
12:     Dim iLoop
13:     For iLoop = LBound(aSentence) to UBound(aSentence)
14:        Response.Write aSentence(iLoop)
15:     Next
16:
17:     'Store the array in the Session object
18:     Session("Sentence") = aSentence
19: %>

Listing 11.9 starts out by creating an array, aSentence (line 5). This array contains five elements, 0 through 4. Lines 6 through 10 set the values of each of these five array elements. Next, the contents of the array are printed out. Line 13 uses the LBound and UBound functions to iterate through the array aSentence one element at a time. Recall from Day 5, "VBScript's Built-in Functions," that the LBound function returns the starting index of an array, while UBound returns the ending index, or upper bound, of an array. UBound and LBound can be used in conjunction with a For loop to iterate through an array. Refer to Appendix B for a more thorough description of LBound and UBound.

Next, line 14 prints out the current element on each iteration of the loop. Finally, line 18 creates a session variable named Sentence and sets it equal to the array aSentence. Note how simple it is to set a session variable equal to an array. The output of Listing 11.9 is I like Active Server Pages!

Now that you have your array in a session variable, you can access the contents of that array on another ASP page. Listing 11.10 shows the code for PrintSessionArray.asp, which, as the name suggests, prints out the contents of the Sentence session variable array.

Listing 11.10 - Displaying the Contents of the Session Variable Array

1:  <%@ Language=VBScript %>
2:  <% Option Explicit %>
3:  <%
4:    Dim iLoop
5:
6:    'First, make sure that the Session variable
7:    'Sentence is a valid array
8:    If IsArray(Session("Sentence")) then
9:      'Print out each element in the array
10:     For iLoop = LBound(Session("Sentence")) to UBound(Session("Sentence"))
11:       Response.Write Session("Sentence")(iLoop)
12:     Next
13:   Else
14:     'If Session("Sentence") is not a valid array,
15:     'display an error message
16:     Response.Write "No sentence to process!"
17:   End If
18: %>

The code in Listing 11.10 displays the contents of the Sentence session variable array, if it exists. Before attempting to read from Session("Sentence"), line 8 checks to make sure that Sentence is a valid array by using the IsArray function. If the user had not visited CreateSessionArray.asp prior to visiting PrintSessionArray.asp, the session variable Sentence would not have existed and would have returned an empty string. Passing LBound an empty string, as opposed to an array, would have generated an error. Therefore, it is essential that you first check to make sure that Sentence is a valid array.

If Sentence is an array, line 10 loops through each element of the array, displaying the contents of each element (line 11), similar to lines 13 through 15 in Listing 11.9. The syntax for referring to a specific element in a session variable array may seem a bit confusing (line 11). With an array, you refer to a specific variable with ArrayName(index). When you store an array in the Session object, the ArrayName is Session(sessionVariableName). Therefore, to read an element from a session variable array, the syntax is Session(sessionVariableName) (index).

If you were to leave out the If statement starting on line 8, an error would occur when you asked to compute LBound(Session("Sentence")). The error message displayed would read:

Microsoft VBScript runtime error '800a000d'

Type mismatch: 'LBound'

/PrintSessionArray.asp, line 9

Because the If statement is on line 8, if the Sentence session variable array hasn't been created, IsArray(Session("Sentence")) will return False, and the code following the Else statement on line 13 will execute. Line 16 simply displays an error message, indicating to the user that there was no sentence to display. This type of error message is preferred to the VBScript runtime error message shown previously.

The Session object can also contain session variable objects, although it is vital that, as a developer, you use prudence when placing objects into the Session object. Because each user has his own Session, if your Web site has many concurrent users, Session scoped objects can quickly eat the Web server's memory. Objects should only be placed in the Session on small Internet or intranet sites, where the number of concurrent users is guaranteed to be low. The ramifications of using session variable objects are discussed in detail later today in the section "Pitfalls of Session Variables."

Recall from Day 6, "Working with Objects," that to create and store a new instance of an object into a variable, the Set keyword must be used. When storing an object in the Session, the Set keyword is also used, as in the following example:

Set Session(sessionVariableName) = ObjectInstance

The following lines of code show how to set a session variable to an instance of an object:

1: Set Session("MyDict") = Server.CreateObject("Scripting.Dictionary")
2: Set Session("Connection") = Server.CreateObject("ADODB.Connection")
3: Set Session("CustomObject") = Server.CreateObject("My.Object")

Line 1 creates a session variable named MyDict that is an instance of the Scripting.Dictionary object. Line 2 creates an instance of the ADODB.Connection object, storing it in the session variable Connection. Similarly, line 3 creates an instance of an object named My.Object and assigns it to the session variable CustomObject. Although these three examples create instances of objects as session variables, it is not wise to place such objects in the Session, due to performance and memory concerns. This topic is addressed later today in the section "Pitfalls of Session Variables."

The Session object provides two collections containing the session variables.

  • Contents contains the non-object session variables.
  • StaticObjects contains session variable objects.

The code in Listing 11.11 displays all the non-object session variables in a user's Session.

Listing 11.11 - The Contents Collection Contains All Non-Object Session Variables

1:  <%@ Language=VBScript %>
2:  <% Option Explicit %>
3:  <%
4:    'How many session variables are there?
5:    Response.Write "There are " & Session.Contents.Count & _
6:              " Session variables<P>"
7:
8:    Dim strName, iLoop
9:    'Use a For Each ... Next to loop through the entire collection
10:   For Each strName in Session.Contents
11:     'Is this session variable an array?
12:     If IsArray(Session(strName)) then
13:       'If it is an array, loop through each element one at a time
14:       For iLoop = LBound(Session(strName)) to UBound(Session(strName))
15:          Response.Write strName & "(" & iLoop & ") - " & _
16:               Session(strName)(iLoop) & "<BR>"
17:       Next
18:     Else
19:       'We aren't dealing with an array, so just display the variable
20:       Response.Write strName & " - " & Session.Contents(strName) & "<BR>"
21:     End If
22:   Next
23: %>

Listing 11.11 displays all the user's session variables and values. Line 5 uses the Count property of the Contents collection to display the number of session variables. Line 10 starts the For Each ... Next loop through the Contents collection. Because the Contents collection contains all non-object session variables, it also contains session variable arrays. For this reason, before you display a session variable, you need to first determine whether it is an array. Line 12 accomplishes this, using the IsArray function. This is identical to the syntax used on line 8 in Listing 11.10 to determine whether a session variable is an array.

If the session variable is an array, lines 14 through 17 are executed. Line 14 is a For loop, which iterates through each element in the session variable array. The contents of each session variable array element are displayed (line 16). If, however, the session variable is not an array, the Else block starting on line 18 is executed. The session variable's name and value are then displayed (line 20). Figure 11.9 shows an example of the output of Listing 11.11.

Figure 11-9: A listing of the Contents collection. Before running this page, I created another session variable array, Message. As you can see, there are four session variables, two of which are arrays, and two of which are not. These session variables, except for Message, were all created with earlier examples in today's lesson. Specifically, Name was created in Listing 11.5, Age in an example in the section "Using the Session Object," and Sentence in Listing 11.9.

The other session variable collection, StaticObjects, cannot be used to list session variable objects created in an ASP page. Objects created in this manner are referred to as dynamic objects because they are created on-the-fly, only when a user visits an ASP page that contains code similar to the following:

Set Session(sessionVariableName) = ObjectInstance

Rather, the StaticObjects collection, as its name implies, can only be used to iterate through static objects in the Session object. Static objects are objects that are created for each user when she first visits the site. We will discuss how to create such objects later in today's lesson, in the section "Initializing Application and Session Variables." The syntax for iterating through the StaticObjects collection is straightforward. You can access each static object in a user's Session by issuing a For Each[el]Next construct. The following example lists all the session variable names that are holding a static object instance:

Dim strName
For Each strName in Session.StaticObjects
   Response.Write strName & "<BR>"
Next

Using these two collections, Contents and StaticObjects, you can loop through the session variables stored in a user's Session (except for session variable objects created on an ASP page). When using the Session object to maintain state on your Web site, it helps to think of the Session object itself as a warehouse and session variables as the goods inside the warehouse. Because each user has her own Session, each user can have unique session variables values. This allows for user-specific state to be maintained across a Web site.


  • Read Page 5!


  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article