2. ī¨ 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
3. ī¨ 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
4. ī¨ Using ASP.Net Caching
īĄ Output Caching
īĄ Partial Page Caching
ī¨ Using Dynamic Properties
5. ī¨ 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.
6. ī¨ 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.
7. ī¨ 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
Scope of State Advantages Disadvantages
Application Global to the
application
âĸshared across
all clients
âĸOveruse limits scalability
âĸNot shared across multiple
machines in a Web farm or
processors in a Web garden
âĸPrimary purpose subsumed
by data cache in ASP.NET
8. ī¨ Advantages & Disadvantages of State Type:
Type of
State
Scope of
State
Advantages Disadvantages
Session Per client âĸCan configure
to be shared
across
machines in a
Web farm and
processors in a
Web Garden
âĸRequires cookies or
URL managing to
mange client
association
âĸOff-host storage can
be inefficient
9. ī¨ Advantages & Disadvantages of State Type:
Type of
State
Scope of
State
Advantages Disadvantages
Cookie Per client âĸWorks
regardless of
server
configuration
âĸState stored on
client
âĸState can live
beyond current
session
âĸLimited memory (-
4KB)
âĸClients may not
support cookies or may
explicitly disable them
âĸState is sent back and
forth with each request
10. ī¨ Advantages & Disadvantages of State Type:
Type of
State
Scope of
State
Advantages Disadvantages
View Across
POST
request to
the same
page
âĸWorks
regardless of
server
configuration
âĸState is retained only
with POST request
made to the same page
âĸState is sent back and
forth with each request
11. ī¨ 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.
12. ī¨ 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.
13. ī¨ 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" />
14. ī¨ 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_MACHINESYSTEMCurrentContr
olSetServicesaspnet_stateParametersPort.
15. īĄ 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.
16. ī¨ 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.
17. ī¨ 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.
18. ī¨ 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.
19. ī¨ 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.
20. ī¨ 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" />
21. ī¨ 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.
22. ī¨ 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
23. ī¨ 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
24. ī¨ 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.
25. ī¨ 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.
26. 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.
27. 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:WINNTMicrosoft.NETFrameworkv1.0.3705 on a
Windows 2000 computer with the 1.0 version of the
Framework.
28. ī¨ 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.
29. ī¨ 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
30. ī¨ 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.
31. ī¨ 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.
32. ī¨ 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;
33. ī¨ 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
34. ī¨ 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.
35. TimeUser SessionDescription
0:00
0:30
1:00
1:30
2:00
2:30
3:00
100
100
100
100
100
100
100
100
200
300
400
500
500
500
100 sessions are created for the first 100 site visitors.
The first 100 sessions are still active weather or not the
visitors are still on the site. 100 new visitors means 100 new
sessions.
Another 100 visitors adds 100 new session while the first two
group sessions still have not expired.
100 new visitors=100 new sessions
âĻâĻ..
100 new visitors create 100 new sessions but the first groupâs
sessions finally expire after 2 hours.
It just keeps going and goingâĻâĻ..
36. ī¨ 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.
37. ī¨ 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.
38. ī¨ 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.
39. ī¨ Session (ContâĻ)
Do Donât
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 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.
40. ī¨ 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.
41. ī¨ 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"
42. ī¨ 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
43. ī¨ 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 -
44. ī¨ <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>
45. 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 Session_OnEnd( ) function in
global.asa is called at that point.
ī¨ Note: Use only Application, Session and Server objects
in that function.
46. ī¨ 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!
47. ī¨ 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;
48. ī¨ 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
49. ī¨ 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
50. ī¨ 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 />");
}
51. ī¨ 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â
52. ī¨ 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.
53. ī¨ 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" %>
54. ī¨ 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
55. ī¨ 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.
56. ī¨ 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.
57. ī¨ 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
58. ī¨ 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)
59. 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
60. ī¨ 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 in-
memory or state server option. We can protect
data more easily by configuring SQL Server
security
61. ī¨ 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 out-
of-process modes
62. 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.
63. īĄ 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.
64. 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 license. This can add
to overall cost of Web site
65. ī¨ 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
66. ī¨ 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
67. ī¨ 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 Partial-
Page Output Caching)
3. Programmatic or Data Caching
68. ī¨ 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
69. ī¨ 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
70. ī¨ 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
71. 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.
72. ī¨ 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
73. ī¨ 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
74. ī¨ 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
75. 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
76. ī¨ 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
77. ī¨ 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
78. ī¨ 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.xml
")))
ī¨ The cache engine takes care of removing the object
bar from the cache when BarData.xml file is
changed
79. ī¨ 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.
80. ī¨ 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.
81. 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);
82. ī¨ - 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
83. ī¨ 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
84. ī¨ 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
85. ī¨ 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
86. ī¨ 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.
87. ī¨ 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.
ī¨ ASP.NET does this by outputting hidden
HTML form field whenever you tell a form
runat=âserverâ .
88. ī¨ 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.