CIS Logo SVC Logo

   Computing & Information Systems
   Department

 

Schoology Facebook        Search CIS Site      Tutorials

Maintaining Session State Information



The Goals for this Example


In many web applications we need to keep track of information about each particular user's session. This may be needed to keep track of each user's preferences. Also, if a web form collects user data that we want to use somehow in a second web page, then we need a way to get this session information to that second page. This does not happen automatically. Two typical methods that are used for this in VB .NET web apps include the use of cookies and HttpSessionState objects. We discuss the latter in this particular example. Cookies will be examined later.

As an example, we will modify our previous web app so that the results of the database lookup are displayed on a separate page. To do this we will take information collected on the first page and make it available to the second page.

Making the Modified Web App



What the App Should Do

  • Like the previous web app, this one will display auto parts data that fits the price range that the user inputs.
  • However, this time the results will be displayed on a new page.
  • The initial view of the application shows that the user begins with a page in which to enter the desired price range.
  • Once the "List Matches" button is clicked, the web app shows the selected auto parts data on a new page.
  • Thus the app works much the same as before, except that the results are not shown on the original page.

Copying the Previous Web App

  • It is simplest just to have Visual Studio produce a copy of the previous web app, though you can instead build a new one from the start in a different folder. We assume here that you choose to copy.
  • Have the previous web app open in Visual Studio.
  • Then use Project, Copy Project to create a new copy of your project. Be sure to tell it to copy all files belonging to your project. Use an appropriate URL as the place to which to copy, such as one of these:
    • https://cis3.stvincent.edu/studentc/StoreState
    • http://cis2.stvincent.edu/studentc/StoreState
  • Use File, Close Solution to close the old project.
  • Then use File, Open, Project From Web.
  • Pick the URL where you want to go to in finding the new project. It would be something like one of these examples:
    • https://cis3.stvincent.edu/studentc
    • http://cis2.stvincent.edu/studentc
  • Check this picture of the dialog box to see how this might look.
  • Find and open your new project. (If you cannot see the new project, close Visual Studio and start it up again.)
  • In Solution Explorer, right click on the project. Change the name of the project to StoreState. (This step is optional, but might help you to keep track of the several versions of the same application.)
  • Save your work so far by using File, Save All.

Adding another Web Form

  • We will use this new web form to display the results of the user's query for auto parts data.
  • In Solution Explorer, right click on the new StoreState project.
  • Select Add, Add Web Form.
  • In the dialog box, type in the name Results.aspx as the name of the new web form.
  • Move to the home.aspx web form in Design View.
  • Use the mouse to "rubber band" and select the 3 labels at the top of the form.
  • Do Edit, Copy.
  • Go to the Results.aspx web form in Design View and use Edit, Paste to paste in the 3 labels.
  • In a similar fashion, use Edit, Cut to cut the "List of Selected Parts" label and the data grid from home.aspx and paste them into Results.aspx, right below the 3 labels already there.
  • We also want to move from the icons for SqlDataAdapter1, SqlConnection1, and DataView1 from the bottom of the home.aspx web form to the bottom of the Results.aspx web form. Do this by selecting what you want to move and then using Edit, Cut. Then on the Results.aspx form use Edit, Paste. If you have trouble with this, you can always add the data adapter, data connection, and data view as was done in the previous web app, but modified as explained here:
    • Drag an SQLDataAdapter onto the Results.aspx form. Answer the wizard's questions as before, except that you should tell it to use an existing stored procedure. Then choose the stored procedure that you created in the previous web app.
    • Under Properties for SQLDataAdapter1, you may have to adjust the CommandText field (found by expanding SelectCommand). For CommandText fill in YourID.SelectByRange. (Fill in your userID, of course. For example, you might type in studentc.SelectByRange.) Answer Yes and Yes to the 2 questions about regenerating the parameters collection and applying the new parameter information. Note that the Properties viewer will now display the CommandText entry as YourID.[SelectByRange], which is correct.
    • SqlConnection1 will be created automatically.
    • You will have to add DataView1 as before.
  • Note that this data adapter uses the same SelectByRange stored procedure as before since all of the data adapter settings are the same.
  • Here is what the home.aspx web form should look like now.
  • On the Results.aspx form, check that the DataSource field under Properties for DataGrid1 is DataView1.
  • On the same form, add a label with ID NoDataLabel and text "No matching data was found" in red.
  • Still on the same form, add a label with ID ErrorLabel and text "Error in accessing database" in red.
  • Set the Visible property of both of these labels to false since we don't ordinary want to see them.
  • Compare your Results.aspx form with this picture of the Results.aspx form.
  • Do File, Save All.

Enabling Session Tracking

  • Actually, session tracking is enabled by default. You just need to know how to use it.
  • Click somewhere on the Results.aspx web form (in Design View), being sure not to click on any of the items that are placed on the form.
  • Then, in Properties look for enableSessionState. Make sure that this is set to True.
  • Check the home.aspx web form in the same way.
  • In web applications that do not require the tracking of session information, it is advisable to set enableSessionState to false. This reduces the amount of overhead. Thus, in our previous web examples we really should have turned off enableSessionState.
  • With enableSessionState turned on, information from a web form that you add to an HttpSessionState object is sent to the server and stored there, where it can be used by your code for another web form. Note that every user's browser session gets its own session state. Session state information expires after 20 minutes of activity by default, though the timeout interval can be adjusted. (Note that cookies use the opposite approach, saving the information at the client PC. There are 2 flavors of cookies, those that store the information on disk and those that just save their information temporarily in RAM.)
  • Security note: Since each user's session information is stored on the server, you should worry about what happens if too many users are active at the same time. Could someone use this as a denial of service attack on your web site, for example?
  • There is also a property called enableViewState. Although the details of this are beyond what we want to discuss here, it has to do with saving certain information about what you see in a web form or control so that this information is still present if the page posts back to itself. If a page does not post back to itself, it should be possible to turn enableViewState off and reduce the amount of overhead. This method saves the information (as a hashed string) in a hidden field of the web page. You can find this hidden field on the web apps that we have produced thus far in our sequence of examples, as we never turned enableViewState off. Just view the page in a browser and use View, Source.
  • Go ahead and set enableViewState to False in the Results.aspx web form.
  • For more information, look up enableViewState and enableSessionState under Help, Search. The help articles "Introduction to Web Forms State Management" and "State Management Recommendations" are particularly useful.

The Code for home.aspx.vb

  • In Solution Explorer double click on home.aspx.vb, the "code-behind" file for your web form, to bring it up in the editor. This is where we add the code for your web page.
  • Click on the + to show the code inside of the "Web Form Designer Generated Code" region.
  • Find the section of code that sets up your labels and other items as protected fields.
  • Since we copied the previous web app, it still contains the data table that we placed here.
  • We no longer need a data table for this page, so find and remove the line:
    Protected dTable As New DataTable
  • Once again we will not add a click handler for the button on your form. Instead, we will use the fact that a postback happens whenever the user click on this button.
  • Thus, we just write code to handle the postback in the Page_Load procedure.
  • Make your Page_Load procedure match the following:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
	
    'Put user code to initialize the page here
    Dim Min, Max As String

    If IsPostBack Then
        Page.Validate()
        If Page.IsValid Then
            Min = MinTextBox.Text.ToString()
            Max = MaxTextBox.Text.ToString()
            Session.Add("MinKey", Min)
            Session.Add("MaxKey", Max)
            Response.Redirect("Results.aspx")
        End If
    End If
End Sub

  • Notice that none of the above code deals with getting data from the database. That will be handled in the code-behind file for the Results.aspx form, since that is where we now have the data connection, data adapter, data grid, etc.
  • If a postback has occurred and the user input validates as reasonable, the above code gets the minimum and maximum values from the text boxes.
  • Then we use Session.Add to add a pair of items to the HttpSessionState object. The pair consists of the key "MinKey" and the minimum value just retrieved from the appropriate text box.
  • In a similar way we add another pair of items to this object. This pair has key "MaxKey" and value Max, the maximum number taken from the other text box.
  • These key/value pairs will be available for our use in the code for our Results.aspx web form. This is what we mean by session state information. Note that this information (the minimum and maximum prices defining the user's desired price range) are associated with a particular user's web session. Another user may be using the same web app at the same time with different session state information (that is, a different price range).

The Code for Results.aspx.vb

  • In Solution Explorer double click on Results.aspx.vb, to get it into the editor.
  • For this page we do need a data table.
  • Click on the + to show the code inside of the "Web Form Designer Generated Code" region.
  • Find the section of code that sets up your labels and other items as protected fields.
  • Add to the bottom of this list the following line to set up your data table:
    Protected dTable As New DataTable
  • The Page_Load procedure in this code-behind file is where we get the desired data from the database and display it. Note that we only need to do this the first time we go to this web page. If there is a postback we leave the page alone. Why do a time-consuming database query if the results will be the same as before?
  • Make your Page_Load procedure match the following:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
	
    'Put user code to initialize the page here
    Dim Min, Max As String

    NoDataLabel.Visible = False
    DataGrid1.Visible = True

    If Not IsPostBack Then
        If Session.Count = 0 Then   ' No session items were supplied.
            NoDataLabel.Visible = True
            DataGrid1.Visible = False
        Else
            Min = Session("MinKey")
            Max = Session("MaxKey")
            Try
                SqlConnection1.Open()
                SqlDataAdapter1.SelectCommand.Parameters("@Min").Value = Min
                SqlDataAdapter1.SelectCommand.Parameters("@Max").Value = Max
                SqlDataAdapter1.Fill(dTable)
                If dTable.Rows.Count = 0 Then
                    NoDataLabel.Visible = True
                    DataGrid1.Visible = False
                Else
                    DataView1 = New DataView(dTable)
                    DataGrid1.DataBind()
                End If
            Catch exception As System.Data.SqlClient.SqlException
                ErrorLabel.Visible = True
            Catch exception As Exception
                ErrorLabel.Visible = True
            Finally
                SqlConnection1.Close()
            End Try
        End If
    End If
End Sub

  • Note that the code is very similar to what was used in the previous web app. Review the explanation under that link if need be.
  • One thing that we have added here is some extra checking.
  • First, if Session.Count is 0, that means that we have no session state information and cannot do a database query or display any resulsts. This should not happen, but just in case, we can check for this. In such a case, we make the label visible that says that there was no matching data. Here is a picture of what is displayed in the user's browser.
  • It is very easy to look up session information when it is present. All you need is the key in order to find the value associated with the key. For example, Min = Session("MinKey") retrieves the value that was associated with "MinKey" on the home.aspx web form.
  • The code to do the database query is really the same as before, so we will not analyze it here.
  • However, we do check the count of the number of rows in the data table to see if this count is 0. This is done with the dTable.Rows.Count = 0 test. If so, then the database query found no matches and we make the label visible that says this. Otherwise, we display the matching data in the data grid.

Build Your App

  • Save all of your files in Visual Studio.
  • Then use Build, Build StoreState (or whatever you named your application).
  • Fix any problems until you get the build to succeed.

Testing and Debugging The App



Finding Errors

  • Look at your app in a browser by going to the appropriate URL. For example, the URL might be something like one of the following:
    • http://cis3.stvincent.edu/studentc/StoreState/home.aspx
    • http://cis2.stvincent.edu/studentc/StoreState/home.aspx
  • Fill in reasonable minimum and maximum values (such as 5 and 50) and click on the List Matches button to see what you get.
  • If it does not work, you might try setting the Web.config file so that you can see any error messages, as we have done in previous web apps. Double click the Web.config file in Solution Explorer and edit the line that says <customErrors mode="RemoteOnly" /> so that it instead reads as <customErrors mode="Off" />
  • Save everything, rebuild your application, and refresh the initial page in your browser.
  • See if you get an error message now when you click on the button.
  • When finished with debugging, undo all of your changes to Web.config, save everything, and rebuild your app.

Back to the main page for ASP .NET Web Apps



Author: Br. David Carlson
Last updated: October 07, 2008
Disclaimer