State Management in ASP.Net
A new instance
of the Web page class is created each time the page is posted to the server.
In traditional Web programming, this would typically mean that all information
associated with the page and the controls on the page would be lost with each
round trip. For example, if a user enters information into a text box, that
information would be lost in the round trip from the browser or client device
to the server.
ASP.NET
provides multiple ways to maintain state between server round trips. Which of
these options you choose depends heavily upon your application, and it should
be based on the following criteria:
· How much information do you need to
store?
· Does the client accept persistent or
in-memory cookies?
· Do you want to store the information
on the client or on the server?
· Is the information sensitive?
· What performance and bandwidth
criteria do you have for your application?
· What are the capabilities of the
browsers and devices that you are targeting?
· Do you need to store information per
user?
· How long do you need to store the
information?
· Do you have a Web form (multiple servers),
a Web garden (multiple processes on one machine), or a single process that
serves the application?
To overcome this inherent limitation of
traditional Web programming, ASP.NET includes several options that help you
preserve data on both a per-page basis and an application-wide basis. These
features are as follows:
1.
View state
2.
Control state
3.
Hidden fields
4.
Cookies
5.
Query strings
6.
Application state
7.
Session state
8.
Profile Properties
9.
Data Support
View state, control state, hidden fields,
cookies, and query strings all involve storing data on the client in various
ways. However, application state, session state, profile and data support
properties all store data in memory on the server. Each option has distinct
advantages and disadvantages, depending on the scenario.
The following sections describe options for
state management that involve storing information either in the page or on
the client computer. For these options, no information is maintained on the
server between round trips.
View State
The View
State property provides a dictionary object for retaining values between
multiple requests for the same page. This is the default method that the page
uses to preserve page and control property values between round trips.
When the page is processed, the current
state of the page and controls is hashed into a string and saved in the page
as a hidden field, or multiple hidden fields if the amount of data stored in
the View State property exceeds
the specified value in the MaxPageStateFieldLength property.
When the page is posted back to
the server, the page parses the view-state string at page initialization and
restores property information in the page.
Advantages
of using view state are:
· No server resources are required - The View state is
contained in a structure within the page code.
· Simple implementation - View State does not require any
custom programming to use. It is on by default to maintain state data on
controls.
· Enhanced security features - The values in view state are
hashed, compressed, and encoded for Unicode implementation, which provides
more security than using hidden fields.
Disadvantages
of using view state are:
· Performance considerations- Because the view state is
stored in the page itself, storing large values can cause the page to slow
down when users display it and when they post it. This is especially relevant
for mobile devices, where bandwidth is often a limitation.
· Device limitations- Mobile devices might not have the
memory capacity to store a large amount of view-state data.
Example:-
ViewState
can be disabled for a single control, for an entire page or for an entire web
application.
Create
ViewState manually …..
Step1:- Make a webpage as below page format
Step2:- Write some code on button click event
Control State
Sometimes you need to store control-state data in order for a
control to work properly. For example, if you have written a custom control
that has different tabs that show different information, in order for that
control to work as expected, the control needs to know which tab is selected
between round trips. The ViewState
property can be used for this purpose, but view state can be turned off at a page level by developers,
effectively breaking your control. To solve this, the ASP.NET page framework
exposes a feature in ASP.NET called control state.
The Control-State
property allows you to persist property information that
is specific to a control and cannot be turned off like the ViewState property.
Advantages
of using control state are:
· No server resources are required- By default,
control state is stored in hidden fields on the page.
· Reliability- Because control state cannot be turned
off like view state, control state is a more reliable method for managing the
state of controls.
· Versatility- Custom adapters can be
written to control how and where control-state data is stored.
Disadvantage
of using control state are:
· Some programming is required- While the ASP.NET
page framework provides a foundation for control state, control state is a
custom state-persistence mechanism. To fully utilize control state, you must
write code to save and load control state.
Example:
The following code example demonstrates how a
class that derives from the PageStatePersister
class initializes the ControlState property. In this example, the ControlState property has been assigned to the Second field of a Pair
object, and serialized using the ObjectStateFormatter
class. When the Load method
is called, the ObjectStateFormatter
class is used to desterilize view state and control state
information, and the ControlState property is initialized from the resulting Pair object's Second
field.
Hidden Fields
ASP.NET allows you to store information in a
Hidden-Field control, which renders
as a standard HTML hidden field. A
hidden field does not render visibly in the browser, but you can set its
properties just as you can with a standard control. When a page is submitted
to the server, the content of a hidden
field is sent in the HTTP form collection along with the values of other
controls. A hidden field acts as a repository for any page-specific
information that you want to store directly in the page.
A Hidden-Field control stores a single
variable in its Value property and
must be explicitly added to the page. In order for hidden-field values to be
available during page processing, you must submit the page using an HTTP POST
command. If you use hidden fields and a page is processed in response to a
link or an HTTP GET command, the hidden fields will not be available.
Advantages
of using hidden fields are:
· No server resources are required- The hidden field
is stored and read from the page.
· Widespread support- Almost all browsers and
client devices support forms with hidden fields.
· Simple implementation- Hidden fields are standard
HTML controls that require no complex programming logic.
Disadvantages
of using hidden fields are:
· Potential security risks- The hidden field can be
tampered with. The information in the hidden field can be seen if the page
output source is viewed directly, creating a potential security issue. You
can manually encrypt and decrypt the contents of a hidden field, but doing so
requires extra coding and overhead. If security is a concern, consider using
a server-based state mechanism so that no sensitive information is sent to
the client.
· Simple storage architecture- The hidden field does not
support rich data types. Hidden fields offer a single string value field in
which to place information. To store multiple values, you must implement
delimited strings and the code to parse those strings. You can manually
serialize and de-serialize rich data types to and from hidden fields,
respectively. However, it requires extra code to do so. If you need to store
rich data types on the client, consider using view state instead. View state
has serialization built-in, and it stores data in hidden fields.
· Performance considerations- Because hidden fields are
stored in the page itself, storing large values can cause the page to slow
down when users display it and when they post it.
· Storage limitations- If the amount of data in a
hidden field becomes very large, some proxies and firewalls will prevent
access to the page that contains them. Because the maximum amount can vary
with different firewall and proxy implementations, large hidden fields can be
sporadically problematic. If you need to store many items of data, consider
doing one of the following:
o Put each item in a separate hidden field.
o Use view state with view-state chunking
turned on, which automatically separates data into multiple hidden fields.
o Instead of storing data on the client,
persist the data on the server. The more data you send to the client, the
slower the apparent response time of your application will be because the
browser will need to download or send more data.
Example: Creating Headed
Field in ASP.Net
Cookies
A cookie
is a small amount of data that is stored either in a text file on the client
file system or in-memory in the client browser session. It contains
site-specific information that the server sends to the client along with page
output. Cookies can be temporary (with specific expiration times and dates)
or persistent.
You can use cookies to store information
about a particular client, session, or application. The cookies are saved on
the client device, and when the browser requests a page, the client sends the
information in the cookie along with the request information. The server can
read the cookie and extract its value. A typical use is to store a token
(perhaps encrypted) indicating that the user has already been authenticated
in your application.
Query Strings
A Query
String is information that is appended to the end of a page URL. A
typical Query String might look
like the following example:
http://www.contoso.com/listwidgets.aspx?category=basic&price=100
In the URL path above, the query string
starts with a question mark (?) and includes two attribute/value pairs, one
called "category" and the other called "price."
Query
strings provide a simple but limited way to
maintain state information. For example, they are an easy way to pass
information from one page to another, such as passing a product number from
one page to another page where it will be processed. However, some browsers
and client devices impose a 2083-character limit on the length of the URL.
In order for query string values to be
available during page processing, you must submit the page using an HTTP GET
command. That is, you cannot take advantage of a query string if a page is
processed in response to an HTTP POST command.
Example:-
Advantages
of using query strings are:
· No server resources are required- The query string
is contained in the HTTP request for a specific URL.
· Widespread support- Almost all browsers and
client devices support using query strings to pass values.
· Simple implementation- ASP.NET provides full support for the
query-string method, including methods of reading query strings using the Params property of the HttpRequest object.
Disadvantages
of using query strings are:
· Potential security risks- The information in the
query string is directly visible to the user via the browser's user
interface. A user can bookmark the URL or send the URL to other users,
thereby passing the information in the query string along with it. If you are
concerned about any sensitive data in the query string, consider using hidden
fields in a form that uses POST instead of using query strings.
· Limited capacity- Some browsers and client
devices impose a 2083-character limit on the length of URLs.
Client-Side
State Management Summary
The
following table lists the client-side state management options that are
available with ASP.NET, and provides recommendations about when you should
use each option.
Server Side
State Management
ASP.NET offers you a variety of ways to
maintain state information on the server, rather than persisting information
on the client. With server-based state management, you can decrease the
amount of information sent to the client in order to preserve state, however
it can use costly resources on the server. The following sections describe
three server-based state management features: application state, session
state, and profile properties.
Application State
ASP.NET allows you to save values using application state — which is an
instance of the HttpApplicationState
class — for each active Web application. Application
state is a global storage mechanism that is accessible from all pages in
the Web application. Thus, application state is useful for storing information
that needs to be maintained between server round trips and between requests
for pages. Application state is
stored in a key/value dictionary that is created during each request to a
specific URL. You can add your application-specific information to this
structure to store it between page requests.
Once you add your application-specific
information to application state, the server manages it.
Advantages
of using application state are:
· Simple implementation- Application state is easy
to use, familiar to ASP developers, and consistent with other .NET Framework
classes.
· Application scope- Because application state
is accessible to all pages in an application, storing information in
application state can mean keeping only a single copy of the information (for
instance, as opposed to keeping copies of information in session state or in
individual pages).
Disadvantages
of using application state are:
· Application scope- The scope of application
state can also be a disadvantage. Variables stored in application state are
global only to the particular process the application is running in, and each
application process can have different values. Therefore, you cannot rely on
application state to store unique values or update global counters in
Web-garden and Web-farm server configurations.
· Limited durability of data- Because global data that
is stored in application state is volatile, it will be lost if the Web server
process containing it is destroyed, such as from a server crash, upgrade, or
shutdown.
· Resource requirements- Application state requires
server memory, which can affect the performance of the server as well as the
scalability of the application.
Example:-
Session State
ASP.NET allows you to save values by using
session state — which is an instance of the HttpSessionState class — for each
active Web-application session.
Session
state is similar to application state, except that it is scoped to the current
browser session. If different users are using your application, each user
session will have a different session state. In addition, if a user leaves
your application and then returns later, the second user session will have a
different session state from the first.
Session state is structured as a key/value
dictionary for storing session-specific information that needs to be
maintained between server round trips and between requests for pages.
You can use session state to accomplish the
following tasks:
§ Uniquely identify browser or client-device
requests and map them to an individual session instance on the server.
§ Store session-specific data on the server
for use across multiple browser or client-device requests within the same
session.
§ Raise appropriate session management events.
In addition, you can write application code leveraging these events.
Once you add your application-specific
information to session state, the server manages this object. Depending on
which options you specify, session information can be stored in cookies, on
an out-of-process server, or on a computer running Microsoft SQL Server.
Advantages
of using session state are:
· Simple implementation- The session-state facility
is easy to use, familiar to ASP developers, and consistent with other .NET
Framework classes.
· Session-specific events- Session management events
can be raised and used by your application.
· Data persistence- Data placed in
session-state variables can be preserved through Internet Information
Services (IIS) restarts and worker-process restarts without losing session
data because the data is stored in another process space. Additionally,
session-state data can be persisted across multiple processes, such as in a
Web farm or a Web garden.
· Platform scalability- Session state can be used
in both multi-computer and multi-process configurations, therefore optimizing
scalability scenarios.
· Cookieless support- Session state works with
browsers that do not support HTTP cookies, although session state is most
commonly used with cookies to provide user identification facilities to a Web
application. Using session state without cookies, however, requires that the
session identifier be placed in the query string, which is subject to the
security issues stated in the query string section of this topic.
· Extensibility- You can customize and extend
session state by writing your own session-state provider. Session state data
can then be stored in a custom data format in a variety of data storage
mechanisms, such as a database, an XML file, or even to a Web service
Disadvantage
of using session state are:
· Performance considerations- Session-state variables
stay in memory until they are either removed or replaced, and therefore can
degrade server performance. Session-state variables that contain blocks of
information, such as large datasets, can adversely affect Web-server
performance as server load increases.
Example:-
Profile Properties
ASP.NET provides a feature called profile properties, which allows you
to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an
ASP.NET profile, which is stored in a persistent format and associated with
an individual user. The ASP.NET profile allows you to easily manage user
information without requiring you to create and maintain your own database.
In addition, the profile makes the user information available using a
strongly typed API that you can access from anywhere in your application. You
can store objects of any type in the profile. The ASP.NET profile feature
provides a generic storage system that allows you to define and maintain
almost any kind of data while still making the data available in a type-safe
manner.
To use profile
properties, you must configure a profile
provider. ASP.NET includes a SqlProfileProvider
class that allows you to store profile data in a SQL database, but you can
also create your own profile provider class that stores profile data in a
custom format and to a custom storage mechanism such as an XML file, or even
to a web service.
Because data that is placed in profile properties is not stored in
application memory, it is preserved through Internet Information Services
(IIS) restarts and worker-process restarts without losing data. Additionally,
profile properties can be persisted across multiple processes such as in a
Web form or a Web garden.
Advantages
of using profile properties are:
· Data persistence- Data placed in profile
properties is preserved through IIS restarts and worker-process restarts
without losing data because the data is stored in an external mechanism. Additionally,
profile properties can be persisted across multiple processes, such as in a
Web farm or a Web garden.
· Platform scalability- Profile properties can be
used in both multi-computer and multi-process configurations, therefore
optimizing scalability scenarios.
· Extensibility - In order to use profile
properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows
you to store profile data in a SQL database, but you can also create your own
profile provider class that stores profile data in a custom format and to a
custom storage mechanism, such as an XML file, or even to a Web service.
Disadvantages of using profile properties are:
· Performance considerations- Profile properties are
generally slower than using session state because instead of storing data in
memory, the data is persisted to a data store.
· Additional configuration requirements- Unlike session
state, the profile properties feature requires a considerable amount of
configuration to use. To use profile properties, you must not only configure
a profile provider, but you must pre-configure all of the profile properties
that you want to store.
· Data maintenance- Profile properties require
a certain amount of maintenance. Because profile data is persisted to
non-volatile storage, you must make sure that your application calls the
appropriate cleanup mechanisms, which are provided by the profile provider,
when data becomes stale.
Example:-
Web.Config settings
The following code is used to save
the users profiles. Profile.Save()
method updates the profile data source with changed profile property values.
Database Support
In
some cases, you might want to use database support to maintain state on your
Web site. Typically, database support is used in conjunction with cookies or
session state. For example, it is common for an e-commerce Web site to
maintain state information by using a relational database for the following
reasons:
· Security
· Personalization
· Consistency
· Data mining
The
following are typical features of a cookie-supported database Web site:
· Security The
visitor types an account name and password into a site logon page. The site
infrastructure queries the database with the logon values to determine
whether the user has rights to utilize your site. If the database validates
the user information, the Web site will distribute a valid cookie containing
a unique ID for that user on that client computer. The site grants access to
the user.
· Personalization With
security information in place, your site can distinguish each user by reading
the cookie on the client computer. Typically, sites have information in the
database that describes the preferences of a user (identified by a unique
ID). This relationship is known as personalization. The site can research the
user's preferences using the unique ID contained in the cookie, and then
place content and information in front of the user that pertains to the
user's specific wishes, reacting to the user's preferences over time.
· Consistency If you
have created a commerce Web site, you might want to keep transactional
records of purchases made for goods and services on your site. This
information can be reliably saved in your database and referenced by the
user's unique ID. It can be used to determine whether a purchase transaction
has been completed, and to determine the course of action if a purchase transaction
fails. The information can also be used to inform the user of the status of
an order placed using your site.
· Data mining Information
about your site usage, your visitors, or your product transactions can be
reliably stored in a database. For example, your business development
department might want to use the data collected from your site to determine
next year's product line or distribution policy. Your marketing department
might want to examine demographic information about users on your site. Your
engineering and support departments might want to look at transactions and
note areas where your purchasing process could be improved. Most
enterprise-level relational databases, such as Microsoft SQL Server,
contain an expansive toolset for most data mining projects.
By
designing the Web site to repeatedly query the database by using the unique
ID during each general stage in the above scenario, the site maintains state.
In this way, the user perceives that the site is remembering and reacting to
him or her personally.
Advantages
of using a database to maintain state are:
· Security- Access
to databases requires rigorous authentication and authorization.
· Storage capacity- you can store as much
information as you like in a database.
· Data persistence- Database information can
be stored as long as you like, and it is not subject to the availability of
the Web server.
· Robustness and data integrity- Databases include
various facilities for maintaining good data, including triggers and
referential integrity, transactions, and so on. By keeping information about
transactions in a database (rather than in session state, for example), you
can recover from errors more readily.
· Accessibility- The data stored in your database
is accessible to a wide variety of information-processing tools.
· Widespread support- there is a large range of
database tools available, and many custom configurations are available.
Disadvantages
of using a database to maintain state are:
· Complexity- Using a database to
support state management requires that the hardware and software
configurations be more complex.
· Performance considerations- Poor construction of the
relational data model can lead to scalability issues. Also, leveraging too
many queries to the database can adversely affect server performance.
Server-Side
State Management Summary
The
following table lists the server-side state management options that are
available with ASP.NET, and provides recommendations about when you should
use each option.
|
|||||||||||||||||||||||||||||||||||||
A Blog For MicroSoft Technologies Visual Studio .Net, SQL Server Developers.
Saturday, 2 February 2013
State Management in ASP.Net
Friday, 1 February 2013
document.cookie Property
document.cookie Property Javascript DOM The cookie property of the document object is used to set and access browser cookies. Cookies are used for creating persistent data storage that will be available over your entire domain because the file is stored in the user's browser software, and is associated with a particular domain name. SYNTAX document.cookie Javascript CODE EXAMPLE ![]() 1. Test this on a website and not your local machine so that the browser software can associate the stored cookies with a domain name. 2. An existing cookie can be updated(overwritten) with a new value by re-baking it. 3. Each cookie is called into each page of your site with each request, so using cookies uses extra resources. The more cookies you use, the heavier the resources. 4. Cookies can be read and removed by the user via their browser software. |
Subscribe to:
Posts (Atom)