Web pages rarely stand alone. Applications almost always need to track users who visit multiple pages within a Web site, whether to provide personalization, store information about a user, or track usage for reporting purposes.
At a high level, ASP.NET provides two different types of state management: client-side and server-side. Client-side state management stores information on the client’s computer by embedding the information into a Web page, a Uniform Resource Locator (URL), or a cookie. Server-side state management tracks the user with a cookie or a URL but stores the information about a user in the server’s memory or a database.
Using Client-Side State Management
1.View state ASP.NET uses view state to track values in controls. You can add custom values to view state, too.
2.Control state If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.
3.Hidden fields Like view state, hidden fields store data in an HTML form without displaying it in the user’s browser. That data is available only when the form is processed.
4.Cookies Cookies store a value in the user’s browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a Web site.
5.Query strings Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.
Using Server-Side State Management
ASP.NET provides two ways to share information between Web pages without sending the data to the client: application state and session state. Application state information is available to all pages, regardless of which user requests a page. Session state information is available to all pages opened by a user during a single visit. Both application state and session state information are lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.
Application State
ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Therefore, you can use application state to store information that must be maintained between server round trips and between requests for pages.
Application state is stored in the Application key/value dictionary (an instance of the HttpApplicationState class). You can add application-specific information to this structure to store it between page requests. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data.
Data stored in the Application object is not permanent and is lost any time the application is restarted. IIS regularly restarts ASP.NET applications to improve reliability, and applications are restarted if the computer is restarted. To persist information, read and write the values using application events, as described in the next section.
Responding to Application Events
ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:
Application_Start Raised when the application starts. This is the perfect place to initialize Application variables.
Application_End Raised when an application shuts down. Use this to free application resources and perform logging.
Application_Error Raised when an unhandled error occurs. Use this to perform error logging.
//C#
void Application_Start(object sender, EventArgs e)
{ // Code that runs on application startup Application["UsersOnline"] = 0;
}
void Session_Start(object sender, EventArgs e)
{ // Code that runs when a new session is started Application.Lock(); Application["UsersOnline"] = (int)Application["UsersOnline"] + 1; Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{ // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. Application.Lock(); Application["UsersOnline"] = (int)Application["UsersOnline"] - 1; Application.UnLock();
}
Reading and Writing Application State Data
You can read and write application state data using the Application object (an instance of the HttpApplicationState class) just like you would read and write data to the View-State object—as a collection. However, because multiple Web pages might be running simultaneously, you must lock the Application object when making calculations and performing updates, exactly as you need to lock a shared resource in a multi-threaded application. For example, the following code locks the Application update and increments a variable:
//C#
Application.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"]+1;
Application.UnLock();
If you don’t lock the Application object, it is possible for another page to change the variable between the time that the process reads the current value and the time it
writes the new value, causing a calculation to be lost. You do not need to lock the Application object when initializing variables in Application_Start.
To read Application values, simply cast the value to the correct type. The following example demonstrates how to read an Integer that has been stored in Application:
//C#
(int)Application["PageRequestCount"]
Session State
ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information that must be maintained between server round trips and between requests for pages.
Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user.
Session state is stored in the Session key/value dictionary (an instance of the HttpSessionState class). You can add session-specific information to this structure to store it between page requests. Once you add your session-specific information to session state, the server manages it, and it is never exposed to the client.
You can use session state to accomplish the following tasks:
Uniquely identify browser or client-device requests and map them to individual session instances on the server. This allows you to track which pages a user saw on your site during a specific visit.
Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information.
Raise appropriate session management events. In addition, you can write appli
cation code leveraging these events. Once you add your application-specific information to session state, the server manages this object. Depending on which options you specify, session information can be
stored in cookies, on out-of-process servers, or on computers running Microsoft SQL Server. Because session state can be centrally stored, it is perfect for storing data when using multiple front-end Web servers.
Reading and Writing Session State Data
The following code sample demonstrates how to store the time the user last loaded a page in a session variable and then later retrieve that value by casting it to the appropriate type. While this performs a similar function to the ViewState example in Lesson 1, the Session object is available to any page, the count is incremented whether the user submits a form or just clicks a link, and the count is stored on the server rather than the client:
//C#
// Check if Session object exists, and display it if it does if (Session["lastVisit"] != null)
Label1.Text = ((DateTime)Session["lastVisit"]).ToString();else
Label1.Text = "Session does not have last visit information.";
// Define the Session object for the next page view Session["lastVisit"] = DateTime.Now;
To track a user’s session, ASP.NET uses the ASP.NET_SessionId cookie with a random 24-byte value. Values stored in Session must be serializable.
Configuring Cookieless Session State
By default, session state uses cookies to track user sessions. This is the best choice for the vast majority of applications. Almost all Web browsers support cookies, and those that don’t are typically clients you don’t want to track session data for, such as search engines or other robots.
However, you can enable a cookieless session state to have ASP.NET track sessions using a query string in the URL. The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or virtual directory identifier. For example, the following URL has been modified by ASP.NET to include the unique session ID lit3py55t21z5v55vlm25s55:
http://www.example.com/s(lit3py55t21z5v55vlm25s55)/orderform.aspx
Responding to Session Events
ASP.NET provides two events that help you manage user sessions:
Session_Start Raised when a new session begins. This is the perfect place to initialize session variables.
Session_End Raised when a session is abandoned or expires. Use this to free per-session resources.
To implement these events, add the Global.asax file to your project and write code in the appropriate event handler, as discussed in the section "Responding to Application Events," earlier in this lesson.
Choosing a Session State Mode
ASP.NET session state supports several different storage options for session data:
1.InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use StateServer or SQLServer.
2.StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic.
3.SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities.
4.Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider.
5.Off Disables session state. You should disable session state if you are not using it to improve performance.
Configuring Session State Modes
You can specify which mode you want ASP.NET session state to use by assigning SessionStateMode enumeration values to the mode attribute of the sessionState element in your application’s Web.config file. Modes other than InProc and Off require additional parameters, such as connection-string values. You can examine the currently selected session state by accessing the value of the System.Web.SessionState.HttpSession-State.Mode property.
While you can configure session state for your application, that is typically the responsibility of systems administrators. For example, a systems administrator might initially configure your Web application on a single server using the InProc mode. Later, if the server gets too busy or requires redundancy, the systems administrator adds a second Web server, configures the ASP.NET state service on a server, and modifies the Web.config file to use the StateServer mode. Fortunately, the session state mode is transparent to your application, so you won’t need to change your code. Besides configuring the Web.config file, you don’t need to change how your application deals with session states to support different modes.
H1B Interview Sample Questions & Answers
17 years ago
No comments:
Post a Comment