Hidden FieldsThere is an older method of storing state that can be useful. It uses hidden HTML fields to hold state data. For example, you can create a text field in your .aspx page (possible with a Label or TextBox object) and set its Visible property to false. The data in the object will persist between page round trips as long as the objects are in the <form> . |
Synchronization
It is important in many cases to synchronize access to application
Session variables don't succumb to this same problem because there's only one client access to any session variable at a time. The following code shows how to ensure that only a single thread can modify the contents of an application variable. The code calls the Lock() method, alters the variable, and then calls the Unlock() method.
' C#
Application.Lock();
Application["SomeKey"]++;
Application.Unlock();
' VB
Application.Lock()
Application("SomeKey") = Application("SomeKey") + 1
Application.Unlock()
|
Global.asax
Every ASP.NET application, by default, gets a Global.asax file. This file contains six methods that the ASP runtime calls when appropriate. The
Listing 17.1 The Default Code for a C# Global.asax File
C# Global.asax
protected void Application_Start(Object sender, EventArgs e)
{
}
protected void Session_Start(Object sender, EventArgs e)
{
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
}
protected void Session_End(Object sender, EventArgs e)
{
}
protected void Application_End(Object sender, EventArgs e)
{
}
Listing 17.2 The Default Code for a VB Global.asax File
'VB Global.asax
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session is started
End Sub
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires at the beginning of each request
End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As
[ic:ccc]EventArgs)
' Fires upon attempting to authenticate the user
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Fires when an error occurs
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session ends
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application ends
End Sub
|