16.12 Managing Application and Session State

 <  Day Day Up  >  

You want to persist data across an entire user 's session or across all users currently using the ASP .NET application.


Technique

Whenever a user connects to an ASP.NET application, an HttpSessionState object is created to serve as a repository of data that should persist as the user navigates through pages of the application. Previous recipes showed that each time a page is loaded due to a post-back event, data connections are reestablished and the data adapter is created to extract data from a database table into a DataSet object. In other words, the data from these data objects was not persisted across each page-load event. The HttpSessionState object is designed to handle such situations as well as serve as a collection of data that needs to persist across the session but can be thrown out when the session has ended.

You can access the HttpSessionState object through the Session property of the System.Web.UI.Page class that your class inherits from. In addition to being able to store data in a dictionary-based collection, the Session object also contains statistical information that you can access. For instance, the SessionID property is a unique value that is created when a new session starts, and it is guaranteed to be unique for each user accessing the site. The Timeout property determines when a session should end. Because you are not guaranteed to be notified that a user has finished interacting with your site, you use a timeout value, and when that time period elapses, the session has ended. By changing the Timeout property, you control the amount of time that can elapse between the last communication from the client and the end of the session. In the following example for a Page_Load event, a DataSet object is filled with data from a SqlDataAdapter and placed within the Session collection. Additionally, the Timeout property is changed to shorten the time it takes for a session to end:

 
 private void Page_Load(object sender, System.EventArgs e) {     if( !Page.IsPostBack )     {         sqlDataAdapter1.Fill( productsDS1 );         Session["DataSet"] = productsDS1;         Session.Timeout = 5;         DataBind();     } } 

The Session is an object that is unique for each user who is accessing the Web application. Another object that serves the same purpose, temporary object storage, but is designed to work across all users currently engaged in using the application is the Application object. It too should only be used for temporary in-memory storage because it is destroyed whenever the last user session ends. Listing 16.8 uses the Application object to create an ASP.NET chat application. The actual ASP.NET code itself simply consists of a large read-only TextBox named tbTranscript used to display the chat messages; a TextBox named tbMessage used by a user to enter a message; and a simple Button named Send , which causes the form post back to occur. Individual messages are placed into the Application collection using an incrementing ID, which itself is placed into the collection as well.

Listing 16.8 Persisting Data with the Application Object
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace _12_ApplicationState {     public class WebForm1 : System.Web.UI.Page     {         protected System.Web.UI.WebControls.TextBox tbTranscript;         protected System.Web.UI.WebControls.TextBox tbMessage;         protected System.Web.UI.WebControls.Button btnSend;         private void Page_Load(object sender, System.EventArgs e)         {             RefreshTranscript();         }         override protected void OnInit(EventArgs e)         {             InitializeComponent();             base.OnInit(e);         }         private void InitializeComponent()         {             this.btnSend.Click += new System.EventHandler(this.btnSend_Click);             this.Load += new System.EventHandler(this.Page_Load);         }         public void RefreshTranscript()         {             int msgID = 0;             string transcript = "";             // enumerate through application collection             while( Application[msgID.ToString()] != null )             {                 transcript += Application[msgID.ToString()].ToString()+"\r\n";                 msgID++;             }             tbTranscript.Text = transcript;         }         private void btnSend_Click(object sender, System.EventArgs e)         {             int lastMsgID;             if( Application["lastMsgID"] == null )             {                 lastMsgID = 0;             }             else             {                 lastMsgID = Int32.Parse(                     Application["lastMsgID"].ToString() ) + 1;             }             // save data in application collection             Application[lastMsgID.ToString()] = Session.SessionID.ToString() +                 ": " + tbMessage.Text;             Application["lastMsgID"] = lastMsgID.ToString();             RefreshTranscript();         }     } } 

Comments

Software development contains a lot of opposites. A bit is on or it's off. A value can be either true or false . You either save time or you save money. If you want performance, you must sacrifice memory. This last truth corresponds to this recipe. It was mentioned that the Session and Application collections can hold any .NET object. This feature has tremendous advantages and opens a lot of possibilities that otherwise weren't available. Using these collections also boosts performance because objects don't have to be constructed and destroyed over and over again, spending clock cycles doing so. You can place a DataSet object, which normally is filled with data during each post-back event, within the Session object to limit the number of database accesses . As far as performance goes, this step has tremendous advantages if you want your site to run quickly. (Of course, we assume that your server contains enough memory.) Without using any type of storage mechanism for a DataSet , the object is destroyed once the data is sent to the client's browser for rendering. Once you add the DataSet to the Session object, it stays around for the lifetime of the session. Multiply a single DataSet by the number of users currently interacting with your application, and you'll see that the memory grows tremendously.

One possible solution to the situation is to move the DataSet into the Application object. Once you do so, however, you must ensure proper synchronization, which itself is no easy task. If the DataSet is merely a read-only entity, then the problem is solved . If, on the other hand, the application updates the DataSet , you run the risk of data stagnation ”when data becomes out of date because one user updates the data while multiple users still retain the older data ”and synchronous data writing, in which multiple users update the database at the same time. In short, if you place data within the Application object, you should look for any place where a data update can occur and make sure the proper synchronization is in place.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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