SlideShare a Scribd company logo
1 of 89
ī‚¨ 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
ī‚¨ 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
ī‚¨ Using ASP.Net Caching
ī‚Ą Output Caching
ī‚Ą Partial Page Caching
ī‚¨ Using Dynamic Properties
ī‚¨ 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.
ī‚¨ 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.
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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.
ī‚¨ 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.
ī‚¨ 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" />
ī‚¨ 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.
ī‚Ą 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.
ī‚¨ 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 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.
ī‚¨ 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.
ī‚¨ 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.
ī‚¨ 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" />
ī‚¨ 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.
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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.
ī‚¨ 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.
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.
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.
ī‚¨ 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.
ī‚¨ 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 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 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.
ī‚¨ 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;
ī‚¨ 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
ī‚¨ 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.
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â€Ļâ€Ļ..
ī‚¨ 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.
ī‚¨ 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.
ī‚¨ 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â€Ļ)
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.
ī‚¨ 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.
ī‚¨ 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"
ī‚¨ 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
ī‚¨ 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 -
ī‚¨ <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>
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.
ī‚¨ 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!
ī‚¨ 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;
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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 />");
}
ī‚¨ 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”
ī‚¨ 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.
ī‚¨ 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" %>
ī‚¨ 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
ī‚¨ 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.
ī‚¨ 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.
ī‚¨ 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
ī‚¨ 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)
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
ī‚¨ 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
ī‚¨ 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
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.
ī‚Ą 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.
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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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
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 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
ī‚¨ 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
ī‚¨ 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
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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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.
ī‚¨ 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.
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);
ī‚¨ - 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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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
ī‚¨ 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.
ī‚¨ 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” .
ī‚¨ 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.
Classification : Confidential

More Related Content

What's hot

14 relationship between processes
14 relationship between processes14 relationship between processes
14 relationship between processesmyrajendra
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling WebStackAcademy
 
servlet in java
servlet in javaservlet in java
servlet in javasowfi
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentationManeesha Caldera
 
Sessions in php
Sessions in php Sessions in php
Sessions in php Mudasir Syed
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
Bug Tracking System
Bug Tracking SystemBug Tracking System
Bug Tracking SystemKishan Acharya
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)UC San Diego
 
Php array
Php arrayPhp array
Php arrayNikul Shah
 
Event handling
Event handlingEvent handling
Event handlingswapnac12
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NETShingalaKrupa
 

What's hot (20)

Binary Semaphore
Binary SemaphoreBinary Semaphore
Binary Semaphore
 
14 relationship between processes
14 relationship between processes14 relationship between processes
14 relationship between processes
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
 
Php session
Php sessionPhp session
Php session
 
servlet in java
servlet in javaservlet in java
servlet in java
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentation
 
Sessions in php
Sessions in php Sessions in php
Sessions in php
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
Bug Tracking System
Bug Tracking SystemBug Tracking System
Bug Tracking System
 
Jsp element
Jsp elementJsp element
Jsp element
 
Dom
DomDom
Dom
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Php array
Php arrayPhp array
Php array
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
Java swing
Java swingJava swing
Java swing
 
Event handling
Event handlingEvent handling
Event handling
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
 

Similar to Session and state management

05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07Vivek chan
 
State management
State managementState management
State managementIblesoft
 
State management
State managementState management
State managementteach4uin
 
State management
State managementState management
State managementLalit Kale
 
StateManagement in ASP.Net.ppt
StateManagement in ASP.Net.pptStateManagement in ASP.Net.ppt
StateManagement in ASP.Net.pptcharusharma165
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07Mani Chaubey
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2Julie Iskander
 
WEB Mod5@AzDOCUMENTS.in.pdf
WEB Mod5@AzDOCUMENTS.in.pdfWEB Mod5@AzDOCUMENTS.in.pdf
WEB Mod5@AzDOCUMENTS.in.pdfPrathimaMahapurush1
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3sandeep54552
 
WEB MODULE 5.pdf
WEB MODULE 5.pdfWEB MODULE 5.pdf
WEB MODULE 5.pdfDeepika A B
 
C# cookieless session id and application state
C# cookieless session id and application stateC# cookieless session id and application state
C# cookieless session id and application stateMalav Patel
 
Session viii(state mngtserver)
Session viii(state mngtserver)Session viii(state mngtserver)
Session viii(state mngtserver)Shrijan Tiwari
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.pptJayaprasanna4
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08Vivek chan
 
ASP.NET 12 - State Management
ASP.NET 12 - State ManagementASP.NET 12 - State Management
ASP.NET 12 - State ManagementRandy Connolly
 
State management
State managementState management
State managementIblesoft
 

Similar to Session and state management (20)

05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07
 
State management
State managementState management
State management
 
Asp.net
Asp.netAsp.net
Asp.net
 
State management
State managementState management
State management
 
State management
State managementState management
State management
 
StateManagement in ASP.Net.ppt
StateManagement in ASP.Net.pptStateManagement in ASP.Net.ppt
StateManagement in ASP.Net.ppt
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
 
WEB Mod5@AzDOCUMENTS.in.pdf
WEB Mod5@AzDOCUMENTS.in.pdfWEB Mod5@AzDOCUMENTS.in.pdf
WEB Mod5@AzDOCUMENTS.in.pdf
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
 
WEB MODULE 5.pdf
WEB MODULE 5.pdfWEB MODULE 5.pdf
WEB MODULE 5.pdf
 
C# cookieless session id and application state
C# cookieless session id and application stateC# cookieless session id and application state
C# cookieless session id and application state
 
Chapter 8 part2
Chapter 8   part2Chapter 8   part2
Chapter 8 part2
 
Session viii(state mngtserver)
Session viii(state mngtserver)Session viii(state mngtserver)
Session viii(state mngtserver)
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
 
UNIT 3 web iiiBCA.pptx
UNIT 3 web iiiBCA.pptxUNIT 3 web iiiBCA.pptx
UNIT 3 web iiiBCA.pptx
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08
 
ASP.NET 12 - State Management
ASP.NET 12 - State ManagementASP.NET 12 - State Management
ASP.NET 12 - State Management
 
State management
State managementState management
State management
 

More from Paneliya Prince

140120107044 ins ala.ppt
140120107044 ins ala.ppt140120107044 ins ala.ppt
140120107044 ins ala.pptPaneliya Prince
 
To create a web service
To create a web serviceTo create a web service
To create a web servicePaneliya Prince
 
Introduction to ado.net
Introduction to ado.netIntroduction to ado.net
Introduction to ado.netPaneliya Prince
 
Asp.net validation
Asp.net validationAsp.net validation
Asp.net validationPaneliya Prince
 
Wt oep visiting card
Wt oep visiting cardWt oep visiting card
Wt oep visiting cardPaneliya Prince
 
SE OEP online car service booking
SE OEP online car service bookingSE OEP online car service booking
SE OEP online car service bookingPaneliya Prince
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connectionPaneliya Prince
 
processing control input
processing control inputprocessing control input
processing control inputPaneliya Prince
 
static dictionary technique
static dictionary techniquestatic dictionary technique
static dictionary techniquePaneliya Prince
 
Ajava oep shopping application
Ajava oep shopping applicationAjava oep shopping application
Ajava oep shopping applicationPaneliya Prince
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connectionPaneliya Prince
 

More from Paneliya Prince (20)

140120107044 ins ala.ppt
140120107044 ins ala.ppt140120107044 ins ala.ppt
140120107044 ins ala.ppt
 
To create a web service
To create a web serviceTo create a web service
To create a web service
 
Master pages
Master pagesMaster pages
Master pages
 
Master page
Master pageMaster page
Master page
 
Managing states
Managing statesManaging states
Managing states
 
Introduction to ado.net
Introduction to ado.netIntroduction to ado.net
Introduction to ado.net
 
Grid view control
Grid view controlGrid view control
Grid view control
 
Asp.net validation
Asp.net validationAsp.net validation
Asp.net validation
 
Asp.net control
Asp.net controlAsp.net control
Asp.net control
 
Wt oep visiting card
Wt oep visiting cardWt oep visiting card
Wt oep visiting card
 
SE OEP online car service booking
SE OEP online car service bookingSE OEP online car service booking
SE OEP online car service booking
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
 
processing control input
processing control inputprocessing control input
processing control input
 
static dictionary technique
static dictionary techniquestatic dictionary technique
static dictionary technique
 
Ajava oep
Ajava oep Ajava oep
Ajava oep
 
Ajava oep shopping application
Ajava oep shopping applicationAjava oep shopping application
Ajava oep shopping application
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
 
DCDR
DCDRDCDR
DCDR
 
static dictionary
static dictionarystatic dictionary
static dictionary
 
ADO.net control
ADO.net controlADO.net control
ADO.net control
 

Recently uploaded

School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdfKamal Acharya
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...ppkakm
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxpritamlangde
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementDr. Deepak Mudgal
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxNANDHAKUMARA10
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptxrouholahahmadi9876
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...ronahami
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfsumitt6_25730773
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 

Recently uploaded (20)

School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 

Session and state management

  • 1.
  • 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.