Session and State Management 1 Company Confidential 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 applicationlevel 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: Type of State Application Scope of State Advantages Global to the application Disadvantages •shared across •Overuse limits scalability all clients •Not shared across multiple machines in a Web farm or processors in a Web garden •Primary purpose subsumed by data cache in ASP.NET State Management (Cont…) • Advantages & Disadvantages of State Type: Type of State Session Scope of Advantages Disadvantages State Per client •Can configure •Requires cookies or to be shared URL managing to across mange client machines in a association Web farm and •Off-host storage can processors in a be inefficient Web Garden State Management (Cont…) • Advantages & Disadvantages of State Type: Type of Scope of Advantages State State Cookie Per client •Works regardless of server configuration •State stored on client •State can live beyond current session Disadvantages •Limited memory (4KB) •Clients may not support cookies or may explicitly disable them •State is sent back and forth with each request State Management (Cont…) • Advantages & Disadvantages of State Type: Type of State View Scope of State Across POST request to the same page Advantages Disadvantages •Works •State is retained only regardless of with POST request server made to the same page configuration •State is sent back and forth with each request Application and Session Variables • An object is initialized in the Application_Start event 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\CurrentCont rolSet\Services\aspnet_state\Parameters\Port. Application and Session Variables (Cont…) – 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. 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_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. • 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.3705 on 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 Time User Session Description 0:00 100 100 100 sessions are created for the first 100 site visitors. 0:30 100 200 The first 100 sessions are still active weather or not the visitors are still on the site. 100 new visitors means 100 new sessions. 1:00 100 300 Another 100 visitors adds 100 new session while the first two group sessions still have not expired. 1:30 100 400 2:00 100 500 2:30 100 500 100 new visitors=100 new sessions …….. 100 new visitors create 100 new sessions but the first group’s sessions finally expire after 2 hours. 3:00 100 500 It just keeps going and going…….. 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 : 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…) Do Do use session variable s if you have a small amount of information for a single user that you need to maintain for the current session such as a user name or password. Don’t Don’t use session variables when you have a lot of information to store for each user. There are other methods that won’t eat up your server’s memory as fast, such as cookies and databases. 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' )++; 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 period 2. 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 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 />"); } Creating cookies • The response object allows you to create cookies easily. There are two ways to create cookies: – you can create multiple cookies each with a single value or – you can create a single cookies with multiple key/value pairs. The following code snippet demonstrates both methods: • ‘set up some cookie variables • Response. Cookies(“ My Cookie”). Value=“ single cookie” • Response. Cookies(“ 21dayscookie”)( “username”) = “Chris” • Response. Cookies(“ 21dayscookie”)( “ preference”) = “800 * 640” Accessing cookies • The browser sends all cookies information to the server when it makes a request. Therefore you can use the request object to gather that information. • Accessing a cookie follows the exact same syntax as creating a cookie. In the following listing you will use response .write to the cookie value to the browser: ‘set’ up some cookie variables Response. write(Request. Cookies(“ my cookie”). Value) Response. Write(Request. Cookies(“ 21dayscookie”) (“username”) Response. Write(Request. Cookies(“ 21dayscookie”) (“preference”) Again notice the difference between accessing a value and key/ value pairs– specifically, the use of the value property. Using Cookies (Cont…) • We can get the details of cookies during development, by turning on tracing in ASP.NET. By adding Trace=“true”, within the @Page directive at the start of the page: <%@ Page trace="true" language="c#" Codebehind="page.aspx.cs" Inherits="MyPage" %> Using Application Variables • Application variables are available to all pages on site, pages that have the same application name. But they are gone forever if the server is restarted • To use Application variables write the statements like: // to set the data Application ( 'Data' ) = 'something'; // to use the data Response.Write ( 'data is ' + Application ( 'Data' ) ); • We can use application variables for information including the application name, background color, data source names, or contact information Using Application Variables (Cont…) • A key reason that the Application object exists in ASP.NET is for compatibility with classic ASP code—to allow easier migration of existing applications to ASP.NET. • If we are creating an ASP.NET application from scratch, store the data in static members of the application class rather than in the Application object. • This will yield a performance increase over using the Application object. Using Application Variables (Cont…) • Read/Write - We can add or modify items in code while the application is running. • To copy read-only code, set the variable's value in the Application_Start event and then do not change it anywhere else. • Application variables are popular for storing static items that need to be globally accessible and yet modifiable at run time. Using Application Variables (Cont…) • Application state – variables are, global variables for each ASP.NET application. – We can share values of these variables throughout the application. – These variables are usually set in the Application_OnStart event and then accessed and modified in individual ASP.NET pages – The lifetime of application variables spans through the lifetime of the ASP.NET application until the application is unloaded Storing Session Variables in a Database • HTTP is a stateless protocol. To allow users save to state information across requests, ASP.NET provides Session storage. • The session variables are stored on per-user basis. In ASP.NET 2.0, we can customize the session state store as per the requirement. ASP.NET 2.0 and Session Storage: • ASP.NET 2.0 allows user to store session variables at three distinct locations: 1. In the memory of the Web server (in process) Storing Session Variables in a Database(Cont…) 2. In the memory of a machine dedicated to storing session variables (state server) 3. In an SQL Server database • The first mode is the default. Modes 2 and 3 are often called "out-of-process" modes because the session store is independent of the Web site • Storing session variables in the SQL server has the following advantages: • Scalability: Web farm architecture can very easily access the session variables because they are stores in an independent database Storing Session Variables in a Database(Cont…) • It is a much more scalable option than the others • Reliability: Because the data is physically persisted in a database, it is more reliable than the other options. It has the ability to survive server restarts • Security: SQL Server is more secure than the inmemory or state server option. We can protect data more easily by configuring SQL Server security Storing Session Variables in a Database(Cont…) • The session state mode can be configured via a <sessionState> tag of the web.config file • Note: In Web farm scenarios, the application path of the Web site in the IIS metabase should be identical in all the Web servers in the Web farm • Session_End event never fires for any of the outof-process modes Storing Session Variables in a Database(Cont…) Configuring SQL Server to Store a Session State: • Before store a session state in SQL server, we need to configure it. This configuration is done via a command line tool called ASPNET_REGSQL.EXE. We can store the session state in three possible locations within the SQL Server: – Temporary storage: In this case, the session state is stored in the "tempdb" database of SQL Server. The tool creates a database called ASPState and adds certain stored procedures for managing session to it. Storing Session Variables in a Database(Cont…) – The tool also creates required tables in the "tempdb" database. If we restart the SQL server, the session data is not persisted – Persistent storage: The tool creates a database called ASPState and adds stored procedures for managing a session to it. The session state is stored in the ASPState database. The advantage of this method is that the data is persisted even if we restart the SQL server – Custom storage: Both the session state data and the stored procedures are stored in a custom database. The database name must be specified in the configuration file. Storing Session Variables in a Database(Cont…) Disadvantages of Storing the Session State in SQL Server: • Performance: In terms of performance, a SQL Server-based session store is possibly the slowest option. Because session variables are stored in a physical database, it takes more time to get them in and out of the database. This affects the performance of Web site • Cost: To store data in a SQL Server database, we need to have a SQL Server Storing Session Variables in a Database(Cont…) • Serializable data: This method requires that all the data stored in session variables must be serializable. Mark the classes as [Serializable] if we want to store them in a session Using the Cache Object • Cache Object – By using caching we can speed up processing – There were also third-party options, like XCache – The main benefits of caching are performance-related: operations like accessing database information can be one of the most expensive operations. – If the database information is fairly static, this database-information can be cached – When information is cached, it stays cached either indefinitely, until some relative time, or until some absolute time Using ASP.NET Output Caching • Caching Options in ASP.NET: ASP.NET supports three types of caching for Web-based applications: 1. Page Level Caching (called Output Caching) 2. Page Fragment Caching (often called PartialPage Output Caching) 3. Programmatic or Data Caching Using ASP.NET Output Caching (Cont…) • Page Level Caching/Output Caching: – Caches the HTML output of dynamic requests to ASP.NET Web pages – ASP.NET implements this through an Output Cache engine. – Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. – If it does, this cached HTML is sent as a response; otherwise, the page is dynamically turned and, its output is stored in the Output Cache engine – Output Caching is particularly useful when we have very static pages Using ASP.NET Output Caching (Cont…) • Page Level Caching/Output Caching (Conti..) – Output caching can be implement in ASP.NET by simply using the @OutputCache page directive <%@OutputCache Duration="60" VaryByParam="none" %> – The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache – When the duration expires, the cache becomes invalid and, with the next visit, the cached content is flushed, – The ASP.NET Web page's HTML dynamically generated, and the cache repopulated with this HTML Using ASP.NET Output Caching (Cont…) • Page Level Caching/Output Caching (Conti..) – The VaryByParam parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached (ie) – multiple versions of a page can be cached if the output used to generate the page is different for different values passed in via either a GET or POST Using ASP.NET Output Caching (Cont…) Page Fragment Caching/Partial-Page Output Caching: • Partial-Page Output Caching, or page fragment caching, allows specific regions of pages to be cached • ASP.NET requiring part(s) of the page we wish to have cached appear in a User Control • Since Output Caching caches the HTML of the entire ASP.NET Web page, clearly Output Caching cannot be used for these scenarios: enter Partial-Page Output Caching • Contents of a User Control should be cached is to supply an OutputCache directive at the top of the User Control • The content inside the User Control will now be cached for the specified period, while the ASP.NET Web page that contains the User Control will continue to serve dynamic content. Partial Page Caching • Partial page caching allows user to cache parts of a response. • This mechanism is useful when pages contain volatile content such as calculation results, static content such as headers and footers. • Partial page caching is supported by a tag library for use in JSPs, and a public API for use in servlets • The tag library implementation is provided in CacheTags.jar, installed in the extensions subdirectory of EAServer installation Partial Page Caching (Cont…) • To use the library in a JSP, add the following directive: <%@ taglib url="http://www.sybase.com/EAServer/cachetags.tld" prefix="ct"%> • To cache a portion of a page, surround it with this tag, as in: <prefix:cache attributes>... page content ...</prefix:cache> • Where prefix is the tag prefix that we assigned the tag library when declaring it in the taglib directive Partial Page Caching (Cont…) • Using the caching API: • We can call the caching API to cache response parts in servlets. The API is implemented by class CacheManager, described below: package com.sybase.jaguar.servlet; public class CacheManager • Allows user to cache responses or parts of a response in Java servlets Using ASP.NET Output Caching (Cont…) Note : that for this we should not place an OutputCache directive in the ASP.NET Web page that contains the User Control - just inside of the User Control Programmatic or Data Caching: • Programmatic or data caching takes advantage of the .NET Runtime cache engine to store any data or object between responses (ie), • we can store objects into a cache, similar to the storing of objects in Application scope in classic ASP Using ASP.NET Output Caching (Cont…) • Data cache is kept in memory and "lives" as long as the host application does (ie), when the ASP.NET application using data caching is restarted, the cache is destroyed and recreated • To store a value in the cache, use syntax like this: Cache[“check"] = bar; // C# Cache(“check") = bar ' VB.NET • To retrieve a value, simply reverse the syntax like this: bar = Cache[“check"]; // C# bar = Cache(“check") ' VB.NET Using ASP.NET Output Caching (Cont…) • Since Data Caching uses an in-memory cache, there are times when cache elements may need to be evicted. • To add an instance of the object bar to the cache named foo, use syntax like this: Cache.Insert(“Check", bar); // C# Cache.Insert(“Check", bar) ' VB.NET Using ASP.NET Output Caching (Cont…) • If we want to pull data out of an XML file, but don't want to constantly go to disk to read the data, we can tell the ASP.NET caching engine to expire the cached XML file whenever the XML file on disk is changed. To do this, use the following syntax: Cache.Insert(“Check", bar, new CacheDependancy(Server.MapPath("BarData.xm l"))) • The cache engine takes care of removing the object bar from the cache when BarData.xml file is changed Using Dynamic Properties • Using the power of dynamic properties, we can declare property values not only as constants, but also as formulas. The formulas used in a dynamic property can reference property values from other elements, thereby allowing authors unique flexibility when designing their Web pages • Benefits of Dynamic Properties: • Dynamic properties are similar to a spreadsheet's implementation of a formula. In a spreadsheet, a cell's value can be a constant or a formula. A formula can include references to any number of other cells in the spreadsheet. Likewise, a dynamic property can reference other properties on the same document. Using Dynamic Properties (Cont…) • Dynamic properties enable Web authors to describe relationships between objects, properties, and variables in terms of functions, rather than specify an explicit sequence of steps to follow • Implementing Dynamic Properties: • Dynamic properties are introduced through four new methods: 1. The getExpression method returns the current formula used for the dynamic property 2. The recalc method allows authors to explicitly cause the values of dynamic properties to be updated. Using Dynamic Properties (Cont…) 3. The removeExpression method clears formulas set with the setExpression method 4. The setExpression method specifies a formula for a given value • Dynamic property formulas are assigned in script with the setExpression method. They can also be assigned inline using the global possible value, expression, in the style block or in the STYLE attribute • Ex: Dynamic HTML (DHTML) can be used to position objects based on the location and measurement of other objects. • - Center the object horizontally: object.style.left=(document.body.clientWidth/2) (object.offsetWidth/2); Using Dynamic Properties (Cont…) • - Center the object vertically: object.style.top=(document.body.clientHeight/2) (object.offsetHeight/2); • Note: For some earlier versions of Windows Internet Explorer, the style object is not updated after using setExpression or removeExpression until the recalc method is called. For backwards compatibility, always include a recalc after dynamically modifying an expression • The parameters of setExpression are first evaluated by the scripting language engine Using Dynamic Properties (Cont…) • When specifying a string constant for a parameter of setExpression, nest the constant in single quotes. The single quotes force the parameter to be evaluated as a string object.style.setExpression("backgroundColor","red"); • To allow the Cascading Style Sheets (CSS) parser to interpret this string as the natural color constant "red", the string must be wrapped in single quotes object.style.setExpression("backgroundColor","'red'"); • Dynamic properties can be retrieved and removed using the getExpression and removeExpression methods Using Dynamic Properties (Cont…) • The getExpression method returns a variant containing the expression used to compute the dynamic property. This expression is recalculated when the getExpression method is invoked • Expressions are cleared using the removeExpression method. This method is the only way to clear dynamic property values set with the setExpression method. When an expression is cleared, the property value is equal to the last expression calculation and a Boolean value is returned indicating whether the expression was removed Using Dynamic Properties (Cont…) • The recalc method is used to recalculate dynamic properties in a document. Calling recalc(true) will recalculate all expressions in the current document, regardless of whether referenced properties have been changed. After a dynamic property has been recalculated, references to that property will retrieve the new calculated value • Notes on Implicit Dependencies: • Implicit dependencies refer to properties that may be altered by changes in other properties. For instance, the offsetWidth of an element depends on the width and possibly even the height value in a style sheet View state • The viewstate describe how an object looks at that particular moment. • An application that keeps track of this information is said to maintain state. • If you fill out an HTML form and come back to it later chances are the fields you’ve filled out will be empty. • This is because the web is a stateless medium it does not allow you to keep track of view state or other such information. View state (Cont…) • This was often a pain for traditional ASP developer because it required mechanism to maintain and retrieve this information ASP.NET makes this much easier. • ASP.NET automatically keeps track of the viewstate for you. This means that if you fill out an HTML form and click submit the value will still be there when the page comes back! • This is an important part of ASP.NET and is integral to a number of different mechanisms. View state (Cont…) • That string of the seemingly random character is ASP.NET way of telling itself what each control looks like. • When the form is submitted ASP.NET automatically retrieves this string and uses it to fill out the form information again. • ASP.NET uses the fact that browsers can only understand HTML and writes itself reminders in the page that are send to the client. For example look at the following line written on the server: <form runat =“server”> This sends the following HTML code to the browser: <form name =“ ctrl2”method = “post” action = “listing0201.aspx” id=“ctrl2”> <input type =“hidden” name” __VIEWSTATE” value =“YTB6LTEwNzAy0TU3NjJfX1949e1355cb”/> • Viewstate management show cases ASP.NET focus on making the web a more traditional application environment. Thank You Classification : Confidential