970 likes | 1.4k Views
Session and State Management. Introduction. ASP.NET, like traditional ASP, provides the facility to track a user's session using Session State. Web applications are built on Hypertext Transfer Protocol (HTTP).
E N D
Introduction • ASP.NET, like traditional ASP, • provides the facility to track a user's session using Session State. Web applications are built on Hypertext Transfer Protocol (HTTP). • HTTP being a stateless protocol, each request to the server from the client is understood as an independent request. ASP.NET provides a powerful way to store a user’s session specific data using the Session State which is accessible as long as the user’s session is alive • This module discusses Session State, its advantages and disadvantages, the Session storage modes and how we can configure the same using the application’s web.config file
Objectives • Types of State Management – • Applilcation State, Session state, Cookie state, View state • Application and Session Variables • Cookies and Cookieless Sessions • Storing Application and Session Data in different modes • In-process storage, Session State Service, Microsoft SQL Server • Using Session Variables • Using Cookies • Using Application Variables • Using the Cache Object
Objectives (Cont…) • Using ASP.Net Caching • Output Caching • Partial Page Caching • Using Dynamic Properties
State Management • ASP.NET provides four types of state: • Applilcation State • Session state • Cookie state • View state • ASP.NET, like its predecessor, ASP, • provides a pair of objects for managing application-level state and session-level state. • Application state • is where information that is global to the application may be stored. • This state is typically stored once and then read from many times.
State Management (Cont…) • Session state • is maintained on a per-client basis. • When a client first accesses any page in an application, an ASP.NET generated session ID is created. • That session ID is then transmitted between the server and the client via HTTP either using client-side cookies or encoded in a mangled version of the URL. • Cookies • provide the ability to store small amounts of data on a client's machine. • Once a cookie is set, all subsequent pages accessed by the same client will transmit the cookie and its value.
State Management (Cont…) View state is a another way of storing state on behalf of a client by saving and restoring values from a hidden field when a form is posted. Advantages & Disadvantages of State Type:
State Management (Cont…) Advantages & Disadvantages of State Type:
State Management (Cont…) Advantages & Disadvantages of State Type:
State Management (Cont…) Advantages & Disadvantages of State Type:
Application and Session Variables An object is initialized in the Application_Startevent and further access is read-only. The Refresh Variable Dialog is used to select the method for maintaining Session Variables in ASP.NET application. 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.
Application and Session Variables (Cont…) As the data is never modified after initialization, you do not have to make any provisions for serializing access. Net Sessions provides a simple and complete methodology for creating, using, and maintaining Session Variables in ASP.NET applications. The Refresh Variable Dialog is used to select the method for maintaining Session Variables in ASP.NET application.
Application and Session Variables (Cont…) • Session state features can be configured via the <sessionState> section in a web.config file. • 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: <sessionState cookieless="true" />
Application and Session Variables (Cont…) • To provide individual data for a user during a session, data can be stored with session scope. • 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.
Application and Session Variables (Cont…) • Set the mode attribute of the <sessionState> section to "StateServer". • Configure the stateConnectionStringattribute with the values of the machine on which you started aspnet_state.
The http cookie object • Cookie : • A cookie is a small file on the user’s computer that contains information specific to one web site. • This file can contains things such as username and passwords that will be used to customize a user’s visit to the site. • Cookies can contain any simple data type such as string, integer, floats, Booleans, and so on. • For example many sites that display news headlines will allow users to select which types of news they want to see . This information can be stored in cookies so that the next time the user visits, the site can read those values and customize accordingly.
The http cookie object • The http cookies object provides methods for accessing and creating these cookies. You can use this object to examine the property of the cookie. However the most common way to manipulate cookies is through the request and response object which both have a cookies properties that return a reference to an http cookie object.
Cookies and Cookieless Sessions A cookie is a piece of text that a Web site can store on a user's machine to be retrieved and reused later. The information stored consists of harmless name-value pairs. cookies are not part of the standard HTTP specification, so they imply a collaboration between browsers and Web sites to work. Not all browsers support cookies and not all users may have cookie support enabled in their own copy of the browser.
Cookies and Cookieless Sessions • 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; only a maximum of 4096 bytes to be acceptable.
Cookies and Cookieless Sessions (Cont…) • When the data is stored on the client, the Page_Loadmethod 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. • To make a cookie persistent between sessions, the Expires property on the HttpCookie class has to be set to a date in the future. • To enable cookieless sessions in ASP.NET application, change the following configuration setting: <sessionState cookieless="true" />
Cookies and Cookieless Sessions (Cont…) If the cookieless attribute of the <sessionState>section is set to true. The module generates a new session ID, twist the URL by adding the session ID just before the resource name, and redirects the browser to the new URL using the HTTP 302 command.
Storing Application and Session Data • We have three choices for storing session state in an ASP.NET application: • In-process storage • Session State Service • Microsoft SQL Server • In-process storage: • The default location for session state storage is in the ASP.NET process itself. • If we don’t change the default configuration of ASP.NET, then session state information is stored in memory of ASP.NET process itself. If we restart the WWW server (or if it crashes for some reason), all of this information is lost
Storing Application and Session Data (Cont…) • Session State Service: • To use the State Service, we need to edit the sessionState element in ASP.NET application's web.config file • <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString= "data source=127.0.0.1;user id=sa;password=" cookieless="false" timeout="20" /> • It need to start the ASP.NET State Service on the computer that we specified in the stateConnectionString attribute
Storing Application and Session Data (Cont…) • Session State Service (Cont…) • If we make the changes, it shows slightly different behavior: session state persists even if we recycle the ASP.NET process • There are two main advantages to using the State Service • First, it is not running in the same process as ASP.NET, so a crash of ASP.NET will not destroy session information. • Second, the stateConnectionString that's used to locate the State Service includes the TCP/IP address of the service, which need not be running on the same computer as ASP.NET.
Storing Application and Session Data (Cont…) • Session State Service (Cont…) • - This allows you to share state information across a web garden (multiple processors on the same computer) or even across a web farm (multiple servers running the application). • With the default in-process storage, we can't share state information between multiple instances of application.
Storing Application and Session Data (Cont…) Session State Service (Cont…) • The major disadvantage of using the State Service • is that it's an external process, rather than part of ASP.NET. • That means that reading and writing session state is slower than it would be if you kept the state in-process. (ie), it's one more process that need to be manage.
Storing Application and Session Data (Cont…) Microsoft SQL Server: • To use SQL Server for storing session state, you need to perform several setup steps: • - Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store session state. • This script will create the necessary database and database objects. • The .NET Framework installs this script in the same folder as its compilers and other tools— • for example, C:\WINNT\Microsoft.NET\Framework\v1.0.3705on a Windows 2000 computer with the 1.0 version of the Framework.
Storing Application and Session Data (Cont…) • Microsoft SQL Server (Cont…) • Edit the sessionState element in the web.config file for your ASP.NET application as follows: <sessionState mode="SQLServer" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString= "data source=SERVERHAME;user id=sa;password=" cookieless="false" timeout="20"/> • Supply the server name, user name, and password for a SQL Server account that has access to the session state database in the sqlConnectionString attribute.
Storing Application and Session Data (Cont…) • Microsoft SQL Server (Cont…) • Like the State Service, SQL Server lets you share session state among the processors in a web garden or the servers in a web farm • Like the State Service, SQL Server is slower than keeping session state in process
The session object • The session object presents a very interesting concept. • Because the web is a stateless medium information about a particular user is hard to keep track of. There’s no way to use HTTP to find out if a series of request comes from one user or a bunch of different users. This makes it hard to tailor a web site for one user.
The session object (Cont…) • The session object combats this limitation. • It allows you to store items that are pertinent to a specific user in a single location on the server. • Essentially it acts as that users personal storage locker of information. • Imagine lockers in a school you put your belonging in your locker to store while you are in class. When you leave for the day the locker is emptied. • New term- The session object works by the same mechanism . When a user visits your site he’s allocated a “locker” into which the developer can put whatever information she likes. The user’s time at the site is called a session. • Once the user leaves the site the locker is abounded the information is lost and the session ends.
The session object (Cont…) • Once the user leaves the site the locker is abounded the information is lost and the session ends. • Imagine that user comes to your site and enter his name in a form which you would like to remember. You can put the name into the session object and then recall it from anywhere you want assuming the session has not ended. The syntax is as follows: Session. add (variable name, value) Or: Session( variable name)= value;
Controlling session • There are various ways to control how the session object behaves in your ASP>NET applications. • The first is the time out value , which sets how long a session can be idle before ASP.NET abandons it. • In other words if a user visits your site but does not click on anything, or leaves the site for an amount of time equal to this time out value the session and all its information will be lost. This value is 20 minutes by default in IIS 5.0, but you can easily change it as follows: Session. timeout =x ‘x is the number of minutes
Controlling session • There are a number of reasons you may want to change this value. Let’s examine a typical web site: each user that comes to the site gets a unique session object which means each user gets his own piece of the server’s memory . Even if he leaves the site after only 30 seconds his session is still alive for another 19 minutes and 30 seconds. After a while this can add up to a lot of memory. • Table Slide table show the growth of session with the default timeout value assuming 100 visitors come to your site every half hour and a timeout value of 120 minutes.
Session • You have wasting a lot of memory 500 sessions for only 100 concurrent visitors. This can definitely slow down the operation of your whole site. • You can also cause a session to expire immediately by using the Abandon method. • Imagine a web site where user can check their email. After a user is done he wants to log out so that other people can not use his e-mail account when he’s away from his computer. • Abandoning the session is one way to accomplish this. Simply call the following : Session. Abandon() • The temporary cookie is deleted as well as any session information.
Working with session • The session object can be manipulated just like an array. You can loop through all the variables and manipulate them as needed. Uses the for … each statement in VB.NET to loop through and display the contents of the session.
Session without cookies • By default ASP.NET uses cookies to store session IDs and keep track of the users. What happens however if the user’s browser does not support cookies or the user just not accepting any? Luckily ASP.NET has another way to keep track of sessions. • New term- Cookie mugging is the process that ASP.NET uses to keep track of sessions without cookies. • Before a page Is sent to the browser ASP.NET scan the HTML code for any hyperlinks. At the end of each link ASP.NET track on an encoded version of the session ID. • When the user clicks a link ASP.NET grabs that string decodes it and passes it to the page the user is requesting. • This page can now use that ID to set or retrieve any session variables. ASP.NET also places the encoded session ID in each link on this page as well. This all happens automatically if ASP.NET detects that the visitor dose not support cookies.
Session (Cont…) • Session (Cont…)
Using Session Variables • We can create them and store data in them in exactly the same way: • // create a new Session variable to store the users name Session ( 'Name' ) = 'James'; • // display the name in any page on your site Out ( 'Your name is ' + Session ( 'Name' ) ); • The crucial difference between Application and Session variables is that Session variables are specific to each visitor to the site.
Using Session Variables (Cont…) • The stateless web: • Session variables have to overcome the problem that the HTTP protocol that we use to browse the web is stateless • Each request for a page is completely independant of earlier requests, so if we want subsequent pages to "remember" the users name that the user entered on front page, we have to store that information somewhere • This remembering of user-specific data is called "maintaining state"
Using Session Variables (Cont…) • Creating a new session: • The first time a new user visits a page on site a new session is automatically created • cookies are simply data stored on computer and automatically sent to the server by browsers when requesting a page • The first time a user visits, there's no cookie and the server creates a new session and sets a cookie with a unique value • As the user browses site the cookie is sent back and forth between computer and the server, allowing the server to recognize the user
Using Session Variables (Cont…) • Unless we have cookies disabled, or are using a browser that doesn't support them, we should see something like ASPSESSIONID • Tracking new sessions: • The server tell us when a new session is created by calling a function in global.asa file, Session_OnStart( ) • use the Session_OnStart( ) function to increment a count of how many users are currently on site, or more accurately how many active sessions there are -
Using Session Variables (Cont…) • <script language=JavaScript runat=server> function Session_OnStart ( ) { // you must lock the global Application object // when writing to it - ok to read without lock Application.Lock ( ); // one more active user Application ( 'ActiveUsers' )++; Application.Unlock ( ); } </script>
Using Session Variables (Cont…) Ending a session: • There are two ways to end a session • 1. The user doesn't request or refresh a page within a specific time period2. Session.Abandon( ) is called from ASP page Sessions timing out: • By default, if a user doesn't make any requests from the server for 20 minutes that session is ended. Similar to before, the Session_OnEnd( ) function in global.asa is called at that point. • Note: Use only Application, Session and Server objects in that function.
Using Session Variables (Cont…) • Setting timeout for the entire application: • Timeout value can be changed for all pages by configuring IIS. On earlier versions of IIS on Windows NT can be changed this setting in the Internet Service Manager, but that was renamed to the "Internet Information Services snap-in" in Windows 2000. • To find the IIS snap-in: Control Panel / Administrative Tools / Internet Services Manager and then view the properties for the Default Web Site. On that dialog go to the Home Directory tab, and choose the Configuration button. Choose the App Options tab, and <phew> there's the setting!
Using Session Variables (Cont…) • Set it to as small a number as possible to increase the efficiency of server. Set it larger than the time users to read largest page, or they could lose their session • Setting timeout for a single session: • We can override the timeout for a single session by adding the following line into code – • // this session will timeout after 5 minutes inactivity Session.Timeout = 5;
Using Session Variables (Cont…) • Abandoning a session: • We can end a session immediately by calling Session.Abandon( ). The rest of the page is still executed, and the Session object is still available for that page, but the session is ended when the page finishes executing. • To stop processing immediately in a page, call Response.End( ) • Note: Even though the session has ended, if the user requests a new page from site a new session will automatically start
Using Cookies • A cookie is stored on the client's machine by their web browser software. To set a cookie, include information in an HttpResponse that instructs the browser to save a cookie on the client's system • Basic code for writing a Cookie in ASP.NET: Using System.Web; Response.Cookies["BackgroundColor"].Value = "Red"; • To read the cookie back: Response.Write (Request.Cookies["BackgroundColor"].Value); • Note: For security reasons you can only read a cookie that was set within the same domain name
Using Cookies (Cont…) • To get a collection of stored items, such as user address details: HttpCookieCollection cookies = Request.Cookies; for(int n=0;n<cookies.Count;n++){ HttpCookie cookie = cookies[n]; Response.Write("<hr/>Name: <b>" + cookie.Name + "</b><br />"); Response.Write("Expiry: " + cookie.Expires + "<br />"); Response.Write("Address1: " + cookie.Address1+ "<br />"); Response.Write("Address2: " + cookie.Address2+ "<br />"); Response.Write("City: " + cookie.City+ "<br />"); Response.Write("Zip: " + cookie.Zip+ "<br />");}