Aspnet Applications And State Management

Exlrfet

ASP.NET uses a pool of HttpApplication instances to service requests made by your application. These managed instances handle their requests for the lifetime of the request. With ASP.NET, you can write code that will run when HttpApplication instances are created and destroyed.

You can write code in the Global.asax file to override the creation and destruction methods for the HttpApplication instance, the Init, and the Dispose methods. The Init method executes for each HttpApplication instance that is created, whereas the Dispose method executes when the HttpApplication instance is destroyed.

% Untitled Notepad

Fib Edit Format Help

New Ctrl+N

Save Ctrl+S

% Untitled Notepad

Fib Edit Format Help

New Ctrl+N

Save Ctrl+S

îgSiteName = "My Lifetime Goals"; )ri["applicationSiteName"] - stringSiteName;

Hjext Documen

|ansi

îgSiteName = "My Lifetime Goals"; )ri["applicationSiteName"] - stringSiteName;

Hjext Documen

|ansi

"0 Click File O Save As to open the dialog box.

Click 0 to select the folder where you want to store your file.

Type a name for the Web page.

Click Save to save the Web page.

Note: Click the Yes button If you are prompted about replacing the file.

E Request an ASP.NET Web page from your site to initiate the creation of a new application.

The BeginRequest and EndRequest methods are called on the page.

Note: In this example, the Comments.aspx file was requested.

Note: The Web browser is in full-screen mode in this screenshot so you can see all of the event messages.

APPLICATION STATE

rou can share global information throughout your application by using the

HttpApplicationState class. This class stores state in Application variables that are available to all users of the site. An instance of the HttpApplicationState class is created the first time any user requests a URL resource from within your ASP.NET application.

Creating and using Application variables is very simple. However, you need to weigh the benefits of simplicity against the cost of memory. The memory allocated for these application level variables is not released until the Web application is shut down or the variable is removed or replaced programmatically.

Application variables should only hold information that is necessary for all users of the site. You will also find it beneficial to place objects that take a long time to instantiate and are used frequently in Application variables. If the instantiation is expensive, you want to keep the object around after the client is done using the object, so the next client does not pay the same instantiation penalty. This being said, you still need to limit the number of objects and other variable types stored in the application, due to the constraint of available memory on your server.

USING APPLICATION STATE

USING APPLICATION STATE

'-H Open CreateApplication Template.aspx from the Code Templates directory, click where you want to create application information, and type Application[""]=.

0 Between the quotation ^Q Save the page as marks (""), type the name of the Application variable you want to create.

CreateApplication.aspx to the Default Web site and display the ASP.NET page in a Web browser.

■ The Application variable is set, and a message appears.

'-H Open CreateApplication Template.aspx from the Code Templates directory, click where you want to create application information, and type Application[""]=.

0 Between the quotation ^Q Save the page as marks (""), type the name of the Application variable you want to create.

After the equal sign (=), type a value for the Application variable in quotes.

CreateApplication.aspx to the Default Web site and display the ASP.NET page in a Web browser.

■ The Application variable is set, and a message appears.

Note: After the page is executed, you can access the information stored in the Application variable.

ASP.NET APPLICATIONS AND STATE MANAGEMENT

Because everyone can access the Application object, you should lock the object when updating. When you finish updating the variable, you can unlock the variable to free it for further updating. It is not required to unlock (it will be automatically unlocked when the page goes out of scope), but it is good to explicitly unlock.

Example:

Application.Lock

Application["applicationSiteName"] = "My Sample Site"; Application.UnLock

Extra

_O Save the page as ReadApplication.aspx and display the ASP.NET page in a Web browser.

■ The Application variable's value appears.

Open ReadApplication Template.aspx from the Code Templates directory, click where you want to access application information, and type Application^'"].

L0 Between the quotation marks (""), type the name of the Application variable you want to read.

□ Use the ToStringO

function to convert the variable to a string and place a Response.Write ();

around code that accesses the Application variable.

_O Save the page as ReadApplication.aspx and display the ASP.NET page in a Web browser.

■ The Application variable's value appears.

CONTINUED

USING APPLICATION STATE

All users of your site share Application variables. You can create Application variables on any ASP.NET page on your site. However, programmers often use the

Application_Start event handler to create your

Application variables.

After you create the variables, you can read them from any page on the site. Because of the scope of Application variables, you should generally practice using Application variables for read-only data that is accessed often across the entire site. Application settings and common lookup values are good candidates for Application variables. For example, you can store state codes in an

Application variable. Note that you can also update and delete Application variables from any page on your Web site at any time.

Synchronization support is not built into Application variables. You must explicitly use the Lock and Unlock methods provided by the HttpApplicationState class in order to synchronize requests in a multi-user environment. Note that this can impact scalability by blocking other requests to the Application when you are updating or reading a value with a lock in place. Another scalability issue of using the Application object is that its state can not be shared across multiple servers.

USING APPLICATION STATE (CONTINUED)

USING APPLICATION STATE (CONTINUED)

• Open UpdateApplication Template.aspx from the Code Templates directory.

Between the quotation marks (""), type the updated value.

Save the page as UpdateApplication.aspx to the default Web site and display the ASP.NET page in a Web browser.

■ The Web browser displays the result of updating the application information.

• Open UpdateApplication Template.aspx from the Code Templates directory.

Click where you want to update the Application variable and type Application ["applicationSiteMotto"] = "";.

Between the quotation marks (""), type the updated value.

Save the page as UpdateApplication.aspx to the default Web site and display the ASP.NET page in a Web browser.

■ The Web browser displays the result of updating the application information.

ASP.NET APPLICATIONS AND STATE MANAGEMENT

You can treat the Application variables as a collection. This enables you to access all of the variables in your application in a looping structure.

TYPE THIS:

Application["applicationSiteName"] = "My Lifetime Goals"; Application["applicationSiteMotto"] = "Out goal is to help you reach yours";

The Application variables have been set.<BR/><BR/>

The Application variables are:<BR/><BR/>

int intCount = Application.Count.ToInt32();

Response.Write(Application.GetKey(i).ToString()); Response.Write(" = ");

Response.Write(Application.Get(i).ToString()); Response.Write("<BR/>");

RESULT:

The application variables have been set.

The application variables are:

applicationSiteName = My Lifetime Goals applicationSiteMotto = Our goal is to help you reach yours

E Open DeleteApplication Template.aspx from the Code Templates directory.

le Click where you want to delete the Application variable and type Application. Contents.Remove("");.

£ Between the quotation Save the page as marks (""), type the name of the variable you want to delete.

DeleteApplication.aspx to the default Web site and display the ASP.NET page in a Web browser.

■ The Web browser displays the result of deleting the application information.

USING SESSION STATE

You can manage user-specific information from page to page in your application by using the HttpSessionState class. This class stores state in Session variables that are tied back to the requesting client. An instance of the HttpApplicationState class is created the first time the client requests a URL resource from within your ASP.NET application or when the client requests a URL resource after the session has expired or has been programmatically abandoned.

Session state management is critical to building Web applications that rely on information that crosses from one page to the next. Page personalization demonstrates the benefits of using Session variables. For personalization, you might load a user's preferences at the beginning of his session and access the Session variables on each page request to customize the user's page presentation.

Starting the session will initiate the Session_Start event handler. The Session_Start event handler is the most common location for initializing Session variables (Session[ "sessionvariable"]=nsome value" ;). After a Session variable has been initialized in the Global.asax file or any page in the Web application, you can read this data from any page in the Web application (string strStorage = Session[ "sessionvariable"];). Using Session variables are not the only way to manage session data, but they are one of the easiest ways.

USING SESSION STATE

USING SESSION STATE

_D Open CreateSession Template.aspx from the Code Templates directory and type Session[""] = .

< After the equal sign (=), type a value for the session variable in quotes.

Save the page as CreateSession.aspx to the Default Web site and display the ASP.NET page in a Web browser.

Note: After this page has been executed, you can access the information stored in the session variable.

_D Open CreateSession Template.aspx from the Code Templates directory and type Session[""] = .

Between the quotation marks (""), type the session variable you want to create.

< After the equal sign (=), type a value for the session variable in quotes.

Save the page as CreateSession.aspx to the Default Web site and display the ASP.NET page in a Web browser.

Note: After this page has been executed, you can access the information stored in the session variable.

ASP.NET APPLICATIONS AND STATE MANAGEMENT

The Session object has many properties that you can configure. One of the important properties is the Session.Timeout. This value determines the amount of time that a user can go idle on your site without having to obtain a new session. You can set this property and read from this property.

TYPE THIS:

Session.Timeout = 5;

Response.Write("The Session Timeout is currently "

+ Session.Timeout +

11 minutes.");

The Session Timeout is currently 5 minutes.

_Q Save the page as ReadSession.aspx to the Default Web site and display the ASP.NET page in a Web browser.

■ The Web browser displays the result of reading the application information.

Open ReadSession Template.aspx from the Code Templates directory and click where you want to access application information and type Session[""].

Between the quotation marks (""), type the session variable you want to read.

□ For the value to appear as output on the Web page, use the ToString() function to convert the variable to a string and place a Response.Write (); around code that accesses the Application variable.

_Q Save the page as ReadSession.aspx to the Default Web site and display the ASP.NET page in a Web browser.

■ The Web browser displays the result of reading the application information.

CONTINUED

USING SESSION STATE

Web applications on IIS, by design, do not retain state as the user goes from page to page on the site. Therefore, you must have some mechanism of tracking information from page to page. Using the Session object is one of the easiest ways to manage user-specific information.

Session state management has improved with ASP.NET Applications. Session objects in ASP 3.0 could not be shared across Web forms, and therefore, many developers would avoid the use of Session in their applications.

To overcome the session state issues in ASP 3.0, ASP.NET gives you three options for session state management. The first option is in-process (runs in the same memory space as ASP.NET). This gives the best performance if you are only going to deploy to one Web server. The second option is SQL Server. This is a persistent storage mechanism that has the slowest performance of all the options, but it is the most resilient to Web site failures (for example, power outage) and can be used in Web forms. The third option is out-of-process. This falls between in-process and SQL Server in terms of performance, and it can also be configured for Web forms. This option holds session data in volatile memory, so it is not as resilient as the SQL Server option.

USING SESSION STATE (CONTINUED)

USING SESSION STATE (CONTINUED)

• Open UpdateSession Template.aspx from the Code Templates directory.

Between the quotation marks (""), type the updated value.

Save the page as UpdateSession.aspx to the Default Web site and display the ASP.NET page in a Web browser.

■ The Web browser displays the result of updating the session information.

• Open UpdateSession Template.aspx from the Code Templates directory.

Click where you want to update the session variable and type Session["sessionUser FavoriteColor"] = "";.

Between the quotation marks (""), type the updated value.

Save the page as UpdateSession.aspx to the Default Web site and display the ASP.NET page in a Web browser.

■ The Web browser displays the result of updating the session information.

ASP.NET APPLICATIONS AND STATE MANAGEMENT

You can treat the session variables as a collection. This enables you to access all of the variables in your application in a looping structure.

TYPE THIS:

Session["sessionUserFavoriteColor"] = "Blue"; Session["sessionUserSecondFavoriteColor"] = "Green";

Session["sessionUserThirdFavoriteColor"] = "Red"

The User Favorite Color Session variables have been set.<BR/><BR/>

The User Favorite Color Session variables are:<BR/><BR/>

System.Collections.IEnumerator SessionEnumerator =

Session.GetEnumerator(); while ( SessionEnumerator.MoveNext() ) i

Response.Write(SessionEnumerator.Current.ToString()); Response.Write(" = ");

Response.Write(Session[SessionEnumerator.Current.

ToString()].ToString()); Response.Write("<BR/>");

RESULT:

The User Favorite Color Session variables have been set.

The User Favorite Color Session variables are:

sessionUserFavorite Color = Blue sessionUserSecond FavoriteColor = Green sessionUserThird FavoriteColor = Red

E Open DeleteSession Template.aspx from the Code Templates directory.

Click where you want to delete the Application variable and type Session.Contents.Remove("");.

£ Between the quotation marks (""), type the name of the variable you want to delete.

le Save the page as DeleteSession.aspx to the default Web site and display the ASP.NET page in a Web browser.

■ The Web browser displays the result of deleting the session information.

Was this article helpful?

0 0

Post a comment