Session State


Cookies are a way to maintain state, but they have several limitations:

  • They can only store strings. No other object types can be stored within them.

  • Cookies can only hold 4k of data.

  • Some web browsers don't support cookies, and even with those that do, most give the user the option of turning cookie support off.

  • Since the information within cookies is stored on the client, it is possible with some clients for an unauthorized user to access the data in the cookies, either by physically accessing the client, or by exploiting browser bugs.

These limitations are overcome through the use of server-side sessions. Server-side sessions give you the ability to save values on the server side for each user accessing your site. A session is started when the user first access the site, and it ends when they close their browser. A new browser instance causes the start of a new session. So, the session values will exist until the user's session times out or they close their browser. Values on the server are associated with the client by use of one of two methods, described below under the Cookieless option text.

The values are not stored on the user's browser. Instead, you can configure the server to store them in one of three places. You configure your choice in the Mode attribute, shown below.

The Web.config file, which we looked at in more detail in previous chapters, is used to configure session state on your server. You need to place the settings in a <sessionstate/> tag, which must, in turn, be placed within the <configuration><system.web> tag. Here is the syntax required:

 <sessionState mode="Off|InProc|StateServer|SQLServer"  cookieless="true|false"  timeout="number of minutes"  stateConnectionString="tcpip=server:port"  sqlConnectionString="sql connection string" /> 

and here is an explanation of each option:

Attribute

Value

Description

Mode

Off

Session state is disabled.

InProc

Stores the session state in memory within the website process. This is the fastest mode.

StateServer

Stores the session state in memory via the use of a process running out of the website's process. This mode is fast, yet will still work with web farms.

SQLServer

Stores the session state in a SQL Server. This method is the most reliable, since the web server can crash without losing session state, but it is slower than the other methods.

Cookieless

true or false

The session state values are associated with the browser by one of two methods you choose when you configure your website. The first method uses a cookie to uniquely identify the user's session (false). Each time they access the site, this unique key is used to retrieve the session values. The second method is by having the unique key automatically appended to the URL each time the user accesses the site. This method is good for those times when the user doesn't allow cookies on their system (false). Note that you can only use one method or the other.

Timeout

Integer value

Number of minutes of inactivity before the session times out and the values are cleared on the server. Each time the user accesses the site, the number of minutes before timeout is reset to this value.

StateConnection
String

tcpip=server:port

When using the StateServer mode, you must specify the server and port that the remote state server is listening on.

SqlConnection
String

SQL connection string

When you use the SQLServer mode, you must specify the connection string to the SQL server that is storing the session state.

As shown above, session state is keyed to the user's browser through the use of a cookie, or, in the case of cookieless operation, through the use of a modified URL. This technique is called URL rewriting. Either way, a unique session key is used to relate the client to the session data. In the case of cookies, the key is stored within the client's cookie. With cookieless operation enabled, any URLs within the HTTP stream that is returned to the client are modified to include the session key within the URL itself. This key then serves to relate the client to the stored session information. Here's an example of a URL when cookieless operation is used:

http://localhost/(srivxx55mux14fngwbxadz45)/GuestBook.aspx

Unlike with cookies that you create, session state cannot be persisted between browser visits. Session state times out after the period of inactivity defined above, no matter what – it is meant to be temporary. If you need to permanently track user information, use a database. Also, realize that if you restart the web server, or update the website in such a way that a new application instance is created, you will have a new instance of session state for your users as well, unless you use the StateServer or SQLServer mode. The bottom line is that you shouldn't count on session state being there in your application. Session state is very useful to enable advanced features within a website, but you should always build logic into your application to handle those times that session data isn't available.

Global Functions

All of the code we've used so far in the book has either existed within a page, or within a separate component class. The latter of these allows code to be shared among pages. Sometimes, ASP.NET also needs to have code that's not part of a page, but which isn't shareable among pages. An example of this is code that can be run when a session starts or ends. To achieve this you have a special file, called Global.asax, which can be created in the root directory of your web application. It's an ASP.NET page, but only contains code for these global event procedures. Web Matrix has a template for this file.

There are two events in the Global.asax file that you can use when a new user session is started and when it ends. Their code shells as generated by Web Matrix are shown below:

  Sub Session_Start(Sender As Object, E As EventArgs)  ' Code that runs when a new session is started  End Sub  Sub Session_End(Sender As Object, E As EventArgs)  ' Code that runs when a session ends  End Sub 

Data is stored in key-value pairs. You add data to the session state via the following statement:

 Session.Add("MyData", "Testing") 

or:

 Session("MyData") = "Testing" 

There are many properties and methods for the Session object. Here are the most commonly used:

Property/Method

Description

Count

The number of objects contained in the session state.

IsCookieless

Used to determine whether the session is being tracked with a cookie or with the URL identifier.

IsNewSession

Determines if the session was created with the current request. If this property always returns True, then the client isn't able to persist the session key across requests.

Item

Allows you to get or set values in the session.

Keys

The collection of keys in the object.

Timeout

Gets or sets the number of minutes before the session will timeout.

Add()

Adds a new value to the session.

Clear()

Clears all objects from the session.

Remove()

Removes a single object from the session.

RemoveAll()

Same as Clear() – removes all objects from the session.

RemoveAt()

Removes a session object at the specified index.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net