Managing Application State
![](http://samples.gotdotnet.com/quickstart/images/bullet.gif)
![](http://samples.gotdotnet.com/quickstart/images/bullet.gif)
![](http://samples.gotdotnet.com/quickstart/images/bullet.gif)
![](http://samples.gotdotnet.com/quickstart/images/bullet.gif)
![](http://samples.gotdotnet.com/quickstart/images/bullet.gif)
Using Application State
This sample illustrates the use of application state to read a dataset in Application_Start.
![](http://samples.gotdotnet.com/quickstart/aspplus/images/application2.gif)
VB Application2.aspx |
[ Run Sample] | [ View Source]
LateBreaking Samples: |
Because an application and all the objects it stores can be concurrently accessed by different threads, it is better to store only infrequently modified data with application scope. Ideally an object is initialized in the Application_Start event and further access is read-only.
In the following sample a file is read in Application_Start (defined in the Global.asax file) and the content is stored in a DataView object in the application state.
<script language="JavaScript" type="text/javascript"> function doClick(index, numTabs, id) { document.all("tab" + id, index).className = "tab"; for (var i=1; i < numTabs; i++) { document.all("tab" + id, (index + i) % numTabs).className = "backtab"; } document.all("code" + id, index).style.display = ""; for (var j=1; j < numTabs; j++) { document.all("code" + id, (index + j) % numTabs).style.display = "none"; } } </script>
void Application_Start() { DataSet ds = new DataSet(); FileStream fs = new FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read); StreamReader reader = new StreamReader(fs); ds.ReadXml(reader); fs.Close(); DataView view = new DataView(ds.Tables[0]); Application["Source"] = view; } Sub Application_Start() Dim ds As New DataSet() Dim fs As New FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read) Dim reader As New StreamReader(fs) ds.ReadXml(reader) fs.Close() Dim view As New DataView (ds.Tables(0)) Application("Source") = view End Sub function Application_Start() : void { var ds:DataSet = new DataSet(); var fs:FileStream = new FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read); var reader:StreamReader = new StreamReader(fs); ds.ReadXml(reader); fs.Close(); var view:DataView = new DataView(ds.Tables[0]); Application("Source") = view; } | |||
C# | VB | JScript |
In the Page_Load method, the DataView is then retrieved and used to populate a DataGrid object:
void Page_Load(Object sender, EventArgs e) { DataView Source = (DataView)(Application["Source"]); ... MyDataGrid.DataSource = Source; ... } Sub Page_Load(sender As Object, e As EventArgs) Dim Source As New DataView = CType(Application("Source"), DataView) ... MyDataGrid.DataSource = Source ... End Sub function Page_Load(sender:Object, e:EventArgs) : void { var Source:DataView = DataView((Application("Source"))); ... MyDataGrid.DataSource = Source; ... } | |||
C# | VB | JScript |
The advantage of this solution is that only the first request pays the price of retrieving the data. All subsequent requests use the already existing DataView object. As the data is never modified after initialization, you do not have to make any provisions for serializing access.
The following sample illustrates the use of session state to store volatile user preferences.
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
void Session_Start() { Session["BackColor"] = "beige"; ... } Sub Session_Start() Session("BackColor") = "beige" ... End Sub function Session_Start() : void { Session("BackColor") = "beige"; ... } | |||
C# | VB | JScript |
protected void Submit_Click(Object sender, EventArgs e) { Session["BackColor"] = BackColor.Value; ... Response.Redirect(State["Referer"].ToString()); } Protected Sub Submit_Click(sender As Object, e As EventArgs) Session("BackColor") = BackColor.Value ... Response.Redirect(State("Referer").ToString()) End Sub protected function Submit_Click(sender:Object, e:EventArgs) : void { Session("BackColor") = BackColor.Value; ... Response.Redirect(State("Referer").ToString()); } | |||
C# | VB | JScript |
The individual values are retrieved using the GetStyle method:
protected String GetStyle(String key) { return Session[key].ToString(); } Protected GetStyle(key As String) As String Return(Session(key).ToString()) End Sub protected function GetStyle(key:String) : String { return Session(key).ToString(); } | |||
C# | VB | JScript |
The GetStyle method is used to construct session-specific styles:
- Start the ASP.NET state service, either using the Services snap-in or by executing "net start aspnet_state" on the command line. The state service will by default listen on port 42424. To change the port, modify the registry key for the service: HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/aspnet_state/Parameters/Port
- Set the mode attribute of the <sessionState> section to "StateServer".
- Configure the stateConnectionString attribute with the values of the machine on which you started aspnet_state.
<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" />
iisreset
on the command line) and the session state value will persist.
The following sample illustrates the use of client-side cookies to store volatile user preferences.
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
protected void Page_Load(Object sender, EventArgs e) { if (Request.Cookies["preferences1"] == null) { HttpCookie cookie = new HttpCookie("preferences1"); cookie.Values.Add("ForeColor", "black"); ... Response.AppendCookie(cookie); } } Protected Sub Page_Load(sender As Object, e As EventArgs) If Request.Cookies("preferences1") = Null Then Dim cookie As New HttpCookie("preferences1") cookie.Values.Add("ForeColor", "black") ... Response.AppendCookie(cookie) End If End Sub protected function Page_Load(sender:Object, e:EventArgs) : void { if (Request.Cookies("preferences1") == null) { var cookie:HttpCookie = new HttpCookie("preferences1"); cookie.Values.Add("ForeColor", "black"); ... Response.AppendCookie(cookie); } } | |||
C# | VB | JScript |
protected String GetStyle(String key) { HttpCookie cookie = Request.Cookies["preferences1"]; if (cookie != null) { switch (key) { case "ForeColor" : return cookie.Values["ForeColor"]; break; ... } } return ""; } Protected Function GetStyle(key As String) As String Dim cookie As HttpCookie = Request.Cookies("preferences1") If cookie <> Null Then Select Case key Case "ForeColor" Return(cookie.Values("ForeColor")) Case ... End Select End If Return("") End Function protected function GetStyle(key:String) : String { var cookie:HttpCookie = Request.Cookies("preferences1"); if (cookie != null) { switch (key) { case "ForeColor" : return cookie.Values("ForeColor"); break; ... } } return ""; } | |||
C# | VB | JScript |
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
protected void Submit_Click(Object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("preferences2"); cookie.Values.Add("ForeColor",ForeColor.Value); ... cookie.Expires = DateTime.MaxValue; // Never Expires Response.AppendCookie(cookie); Response.Redirect(State["Referer"].ToString()); } Protected Sub Submit_Click(sender As Object, e As EventArgs) Dim cookie As New HttpCookie("preferences2") cookie.Values.Add("ForeColor",ForeColor.Value) ... cookie.Expires = DateTime.MaxValue ' Never Expires Response.AppendCookie(cookie) Response.Redirect(State("Referer").ToString()) End Sub protected function Submit_Click(sender:Object, e:EventArgs) : void { var cookie:HttpCookie = new HttpCookie("preferences2"); cookie.Values.Add("ForeColor",ForeColor.Value); ... cookie.Expires = DateTime.MaxValue; // Never Expires Response.AppendCookie(cookie); Response.Redirect(State("Referer").ToString()); } | |||
C# | VB | JScript |
This sample illustrates the use of the ViewState property to store request-specific values.
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
protected void Next_Click(Object sender, EventArgs e ) { String PrevPanelId = "Panel" + ViewState["PanelIndex"].ToString(); ViewState["PanelIndex"] = (int)ViewState["PanelIndex"] + 1; String PanelId = "Panel" + ViewState["PanelIndex"].ToString(); ... } Protected Sub Next_Click(sender As Object, e As EventArgs) Dim PrevPanelId As String = "Panel" + ViewState("PanelIndex").ToString() ViewState("PanelIndex") = CType(ViewState("PanelIndex") + 1, Integer) Dim PanelId As String = "Panel" + ViewState("PanelIndex").ToString() ... End Sub protected function Next_Click(sender:Object, e:EventArgs) : void { var PrevPanelId:String = "Panel" + ViewState("PanelIndex").ToString(); ViewState("PanelIndex") = int(ViewState("PanelIndex") + 1); var PanelId:String = "Panel" + ViewState("PanelIndex").ToString(); ... } | |||
C# | VB | JScript |
Section Summary
Using Session StateThe following sample illustrates the use of session state to store volatile user preferences.
![](http://samples.gotdotnet.com/quickstart/aspplus/images/session1.gif)
VB Session1.aspx |
[ Run Sample] | [ View Source]
LateBreaking Samples: |
To provide individual data for a user during a session, data can be stored with session scope. In the following sample, values for user preferences are initialized in the Session_Start event in the Global.asax file.
void Session_Start() { Session["BackColor"] = "beige"; ... } Sub Session_Start() Session("BackColor") = "beige" ... End Sub function Session_Start() : void { Session("BackColor") = "beige"; ... } | |||
C# | VB | JScript |
In the following customization page, values for user preferences are modified in the Submit_Click event handler according to user input.
protected void Submit_Click(Object sender, EventArgs e) { Session["BackColor"] = BackColor.Value; ... Response.Redirect(State["Referer"].ToString()); } Protected Sub Submit_Click(sender As Object, e As EventArgs) Session("BackColor") = BackColor.Value ... Response.Redirect(State("Referer").ToString()) End Sub protected function Submit_Click(sender:Object, e:EventArgs) : void { Session("BackColor") = BackColor.Value; ... Response.Redirect(State("Referer").ToString()); } | |||
C# | VB | JScript |
The individual values are retrieved using the GetStyle method:
protected String GetStyle(String key) { return Session[key].ToString(); } Protected GetStyle(key As String) As String Return(Session(key).ToString()) End Sub protected function GetStyle(key:String) : String { return Session(key).ToString(); } | |||
C# | VB | JScript |
The GetStyle method is used to construct session-specific styles:
<style> body { font: <%=GetStyle("FontSize")%> <%=GetStyle("FontName")%>; background-color: <%=GetStyle("BackColor")%>; } a { color: <%=GetStyle("LinkColor")%> } </style>
To verify that the values are really stored with session scope, open the sample page twice, then change one value in the first browser window and refresh the second one. The second window picks up the changes because both browser instances share a common Session object.
Configuring session state: Session state features can be configured via the <sessionState> section in a web.config file. To double the default timeout of 20 minutes, you can add the following to the web.config file of an application:
&amp;lt;sessionState timeout=&amp;quot;40&amp;quot; /&amp;gt;
By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. If cookies are not available, a session can be tracked by adding a session identifier to the URL. This can be enabled by setting the following:
&amp;lt;sessionState cookieless=&amp;quot;true&amp;quot; /&amp;gt;
By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. Additionally, ASP.NET can store session data in an external process, which can even reside on another machine. To enable this feature:
- Start the ASP.NET state service, either using the Services snap-in or by executing "net start aspnet_state" on the command line. The state service will by default listen on port 42424. To change the port, modify the registry key for the service: HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/aspnet_state/Parameters/Port
- Set the mode attribute of the <sessionState> section to "StateServer".
- Configure the stateConnectionString attribute with the values of the machine on which you started aspnet_state.
<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" />
iisreset
on the command line) and the session state value will persist.
The following sample illustrates the use of client-side cookies to store volatile user preferences.
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
protected void Page_Load(Object sender, EventArgs e) { if (Request.Cookies["preferences1"] == null) { HttpCookie cookie = new HttpCookie("preferences1"); cookie.Values.Add("ForeColor", "black"); ... Response.AppendCookie(cookie); } } Protected Sub Page_Load(sender As Object, e As EventArgs) If Request.Cookies("preferences1") = Null Then Dim cookie As New HttpCookie("preferences1") cookie.Values.Add("ForeColor", "black") ... Response.AppendCookie(cookie) End If End Sub protected function Page_Load(sender:Object, e:EventArgs) : void { if (Request.Cookies("preferences1") == null) { var cookie:HttpCookie = new HttpCookie("preferences1"); cookie.Values.Add("ForeColor", "black"); ... Response.AppendCookie(cookie); } } | |||
C# | VB | JScript |
protected String GetStyle(String key) { HttpCookie cookie = Request.Cookies["preferences1"]; if (cookie != null) { switch (key) { case "ForeColor" : return cookie.Values["ForeColor"]; break; ... } } return ""; } Protected Function GetStyle(key As String) As String Dim cookie As HttpCookie = Request.Cookies("preferences1") If cookie <> Null Then Select Case key Case "ForeColor" Return(cookie.Values("ForeColor")) Case ... End Select End If Return("") End Function protected function GetStyle(key:String) : String { var cookie:HttpCookie = Request.Cookies("preferences1"); if (cookie != null) { switch (key) { case "ForeColor" : return cookie.Values("ForeColor"); break; ... } } return ""; } | |||
C# | VB | JScript |
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
protected void Submit_Click(Object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("preferences2"); cookie.Values.Add("ForeColor",ForeColor.Value); ... cookie.Expires = DateTime.MaxValue; // Never Expires Response.AppendCookie(cookie); Response.Redirect(State["Referer"].ToString()); } Protected Sub Submit_Click(sender As Object, e As EventArgs) Dim cookie As New HttpCookie("preferences2") cookie.Values.Add("ForeColor",ForeColor.Value) ... cookie.Expires = DateTime.MaxValue ' Never Expires Response.AppendCookie(cookie) Response.Redirect(State("Referer").ToString()) End Sub protected function Submit_Click(sender:Object, e:EventArgs) : void { var cookie:HttpCookie = new HttpCookie("preferences2"); cookie.Values.Add("ForeColor",ForeColor.Value); ... cookie.Expires = DateTime.MaxValue; // Never Expires Response.AppendCookie(cookie); Response.Redirect(State("Referer").ToString()); } | |||
C# | VB | JScript |
This sample illustrates the use of the ViewState property to store request-specific values.
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
protected void Next_Click(Object sender, EventArgs e ) { String PrevPanelId = "Panel" + ViewState["PanelIndex"].ToString(); ViewState["PanelIndex"] = (int)ViewState["PanelIndex"] + 1; String PanelId = "Panel" + ViewState["PanelIndex"].ToString(); ... } Protected Sub Next_Click(sender As Object, e As EventArgs) Dim PrevPanelId As String = "Panel" + ViewState("PanelIndex").ToString() ViewState("PanelIndex") = CType(ViewState("PanelIndex") + 1, Integer) Dim PanelId As String = "Panel" + ViewState("PanelIndex").ToString() ... End Sub protected function Next_Click(sender:Object, e:EventArgs) : void { var PrevPanelId:String = "Panel" + ViewState("PanelIndex").ToString(); ViewState("PanelIndex") = int(ViewState("PanelIndex") + 1); var PanelId:String = "Panel" + ViewState("PanelIndex").ToString(); ... } | |||
C# | VB | JScript |
Section Summary
Using Client-Side CookiesThe following sample illustrates the use of client-side cookies to store volatile user preferences.
![](http://samples.gotdotnet.com/quickstart/aspplus/images/cookies1.gif)
VB Cookies1.aspx |
[ Run Sample] | [ View Source]
LateBreaking Samples: |
Storing cookies on the client is one of the methods that ASP.NET's session state uses to associate requests with sessions. Cookies can also be used directly to persist data between requests, but the data is then stored on the client and sent to the server with every request. Browsers place limits on the size of a cookie; therefore, only a maximum of 4096 bytes is guaranteed to be acceptable.
When the data is stored on the client, the Page_Load method in the file cookies1.aspx checks whether the client has sent a cookie. If not, a new cookie is created and initialized and stored on the client:
protected void Page_Load(Object sender, EventArgs e) { if (Request.Cookies["preferences1"] == null) { HttpCookie cookie = new HttpCookie("preferences1"); cookie.Values.Add("ForeColor", "black"); ... Response.AppendCookie(cookie); } } Protected Sub Page_Load(sender As Object, e As EventArgs) If Request.Cookies("preferences1") = Null Then Dim cookie As New HttpCookie("preferences1") cookie.Values.Add("ForeColor", "black") ... Response.AppendCookie(cookie) End If End Sub protected function Page_Load(sender:Object, e:EventArgs) : void { if (Request.Cookies("preferences1") == null) { var cookie:HttpCookie = new HttpCookie("preferences1"); cookie.Values.Add("ForeColor", "black"); ... Response.AppendCookie(cookie); } } | |||
C# | VB | JScript |
On the same page, a GetStyle method is used again to provide the individual values stored in the cookie:
protected String GetStyle(String key) { HttpCookie cookie = Request.Cookies["preferences1"]; if (cookie != null) { switch (key) { case "ForeColor" : return cookie.Values["ForeColor"]; break; ... } } return ""; } Protected Function GetStyle(key As String) As String Dim cookie As HttpCookie = Request.Cookies("preferences1") If cookie <> Null Then Select Case key Case "ForeColor" Return(cookie.Values("ForeColor")) Case ... End Select End If Return("") End Function protected function GetStyle(key:String) : String { var cookie:HttpCookie = Request.Cookies("preferences1"); if (cookie != null) { switch (key) { case "ForeColor" : return cookie.Values("ForeColor"); break; ... } } return ""; } | |||
C# | VB | JScript |
Verify that the sample works by opening the cookies1.aspx page and modifying the preferences. Open the page in another window, it should pick up the new preferences. Close all browser windows and open the cookies1.aspx page again. This should delete the temporary cookie and restore the default preference values.
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
To make a cookie persistent between sessions, the Expires property on the HttpCookie class has to be set to a date in the future. The following code on the customization.aspx page is identical to the previous sample, with the exception of the assignment to Cookie.Expires:
protected void Submit_Click(Object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("preferences2"); cookie.Values.Add("ForeColor",ForeColor.Value); ... cookie.Expires = DateTime.MaxValue; // Never Expires Response.AppendCookie(cookie); Response.Redirect(State["Referer"].ToString()); } Protected Sub Submit_Click(sender As Object, e As EventArgs) Dim cookie As New HttpCookie("preferences2") cookie.Values.Add("ForeColor",ForeColor.Value) ... cookie.Expires = DateTime.MaxValue ' Never Expires Response.AppendCookie(cookie) Response.Redirect(State("Referer").ToString()) End Sub protected function Submit_Click(sender:Object, e:EventArgs) : void { var cookie:HttpCookie = new HttpCookie("preferences2"); cookie.Values.Add("ForeColor",ForeColor.Value); ... cookie.Expires = DateTime.MaxValue; // Never Expires Response.AppendCookie(cookie); Response.Redirect(State("Referer").ToString()); } | |||
C# | VB | JScript |
Verify that the sample is working by modifying a value, closing all browser windows, and opening cookies2.aspx again. The window should still show the customized value.
This sample illustrates the use of the ViewState property to store request-specific values.
![]()
[ Run Sample] | [ View Source] | LateBreaking Samples: |
protected void Next_Click(Object sender, EventArgs e ) { String PrevPanelId = "Panel" + ViewState["PanelIndex"].ToString(); ViewState["PanelIndex"] = (int)ViewState["PanelIndex"] + 1; String PanelId = "Panel" + ViewState["PanelIndex"].ToString(); ... } Protected Sub Next_Click(sender As Object, e As EventArgs) Dim PrevPanelId As String = "Panel" + ViewState("PanelIndex").ToString() ViewState("PanelIndex") = CType(ViewState("PanelIndex") + 1, Integer) Dim PanelId As String = "Panel" + ViewState("PanelIndex").ToString() ... End Sub protected function Next_Click(sender:Object, e:EventArgs) : void { var PrevPanelId:String = "Panel" + ViewState("PanelIndex").ToString(); ViewState("PanelIndex") = int(ViewState("PanelIndex") + 1); var PanelId:String = "Panel" + ViewState("PanelIndex").ToString(); ... } | |||
C# | VB | JScript |
Section Summary
Using ViewStateThis sample illustrates the use of the ViewState property to store request-specific values.
![](http://samples.gotdotnet.com/quickstart/aspplus/images/pagestate1.gif)
VB PageState1.aspx |
[ Run Sample] | [ View Source]
LateBreaking Samples: |
ASP.NET provides the server-side notion of a view state for each control. A control can save its internal state between requests using the ViewState property on an instance of the class StateBag. The StateBag class provides a dictionary-like interface to store objects associated with a string key.
The file pagestate1.aspx displays one visible panel and stores the index of it in the view state of the page with the key PanelIndex:
protected void Next_Click(Object sender, EventArgs e ) { String PrevPanelId = "Panel" + ViewState["PanelIndex"].ToString(); ViewState["PanelIndex"] = (int)ViewState["PanelIndex"] + 1; String PanelId = "Panel" + ViewState["PanelIndex"].ToString(); ... } Protected Sub Next_Click(sender As Object, e As EventArgs) Dim PrevPanelId As String = "Panel" + ViewState("PanelIndex").ToString() ViewState("PanelIndex") = CType(ViewState("PanelIndex") + 1, Integer) Dim PanelId As String = "Panel" + ViewState("PanelIndex").ToString() ... End Sub protected function Next_Click(sender:Object, e:EventArgs) : void { var PrevPanelId:String = "Panel" + ViewState("PanelIndex").ToString(); ViewState("PanelIndex") = int(ViewState("PanelIndex") + 1); var PanelId:String = "Panel" + ViewState("PanelIndex").ToString(); ... } | |||
C# | VB | JScript |
Note that if you open the page in several browser windows, each browser window will initially show the name panel. Each window can independently navigate between the panels.
Section Summary
Section Summary- Use application state variables to store data that is modified infrequently but used often.
- Use session state variables to store data that is specific to one session or user. The data is stored entirely on the server. Use it for short-lived, bulky, or sensitive data.
- Store small amounts of volatile data in a nonpersistent cookie. The data is stored on the client, sent to the server on each request, and expires when the client ends execution.
- Store small amounts of non-volatile data in a persistent cookie. The data is stored on the client until it expires and is sent to the server on each request.
- Store small amounts of request-specific data in the view state. The data is sent from the server to the client and back.