Sunteți pe pagina 1din 54

CAC Abhinav .

Net Notes
• Entries (RSS)

• Comments (RSS)

• Home
• .Net Framework
• Ado.Net
• Asp.Net
• C# .net
• C# Notes
• Java Script
• Project 2011

Asp.Net
ASP.NET State Management Overview
A new instance of the Web page class is created each time the page is posted to the server. In traditional Web
programmin
g, 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.
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:

• View state
• Control state
• Hidden fields
• Cookies
• Query strings
• Application state
• Session state
• Profile Properties
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, and profile properties all store data in memory on the server. Each option has
distinct advantages and disadvantages, depending on the scenario.
Client-Based State Management Options
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
StateThe ViewState 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 ViewState 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.You can store values in view state as well.
For more information on using View State, see ASP.NET View State Overview. For recommendations about when you
should use view state, see ASP.NET State Management Recommendations.Control StateSometimes 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 ControlState property allows you to persist property information that
is specific to a control and cannot be turned off like theViewState property.
Hidden Fields
ASP.NET allows you to store information in a HiddenField 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.
Security Note
It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any
information in a hidden field that is sensitive or that your application relies on to work properly.
For more information, seeASP.NET State Management Recommendations.
A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. For more
information, see HiddenField Web Server Control Overview.
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. For usage recommendations, see ASP.NET State Management Recommendations.
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.

Security Note
The browser can only send the data back to the server that originally created the cookie.
However, malicious users have ways to access cookies and read their contents. It is
recommended that you do not store sensitive information, such as a user name or password, in a
cookie. Instead, store a token in the cookie that identifies the user, and then use the token to look
up the sensitive information on the server.
For more information about using cookies, see Cookies and ASP.NET State Management Recommendations.
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:
Copy
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.
Security Note
Information that is passed in a query string can be tampered with by a malicious user. Do not
rely on query strings to convey important or sensitive data. Additionally, a user can bookmark
the URL or send the URL to other users, thereby passing that information along with it. For more
information, see ASP.NET State Management Recommendations and How to: Protect Against
Script Exploits in a Web Application by Applying HTML Encoding to Strings.
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. For usage recommendations, see ASP.NET State Management Recommendations.
Server-Based State Management Options

Once you add your application-specific information to application state, the server manages it. For usage
recommendations, see ASP.NET State Management Recommendations.
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. For an overview, see ASP.NET Session State Overview.
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. For more information, see ASP.NET Session State Overview.
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. For usage recommendations, see ASP.NET State Management Recommendations.
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 farm or a Web garden. For more information, see ASP.NET Profile
Properties Overview.
ASP.NET State Management Recommendations
State management is the process by which you maintain state and page information over multiple requests for the same or
different pages. As is true for any HTTP-based technology, Web Forms pages are stateless, which means that they do not
automatically indicate whether the requests in a sequence are all from the same client or even whether a single browser
instance is still actively viewing a page or site. Furthermore, pages are destroyed and re-created with each round trip to
the server; therefore, page information will not exist beyond the life cycle of a single page. For more information about
server round trips and the life cycle of Web Forms pages, see ASP.NET Page Life Cycle Overview.
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 farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that
serves the application?
Client-Side State Management Options
Storing page information using client-side options doesn’t use server resources. These options typically have minimal
security but fast server performance because the demand on server resources is modest. However, because you must
send information to the client for it to be stored, there is a practical limit on how much information you can store this
way.The following are the client-side state management options that ASP.NET supports:
• View state
• Control state
• Hidden fields
• Cookies
• Query strings
View State
Web Forms pages provide the ViewState property as a built-in structure for automatically retaining values between
multiple requests for the same page. View state is maintained as a hidden field in the page. For more information,
see ASP.NET State Management Overview.
You can use view state to store your own page-specific values across round trips when the page posts back to itself. For
example, if your application is maintaining user-specific information — that is, information that is used in the page but is
not necessarily part of any control — you can store it in view state.
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
implementations, 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.
• Potential security risks The view state is stored in one or more hidden fields on the page. Although view state stores
data in a hashed format, it can still 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. For more information, see ASP.NET Web Application
Security and Basic Security Practices for Web Applications.
For more information about using view state, see View State Overview.
Control State
The ASP.NET page framework provides the ControlState property as way to store custom control data between server
trips. For example, if you have written a custom control that has different tabs showing different information, in order for
that control to work as expected, the control needs to know which tab is selected between round trips. View state can be
used for this purpose, but developers can turn view state off at the page level, effectively breaking your control. Unlike
view state, control state cannot be turned off, so it provides a more reliable way to store control-state data.
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.
Hidden Fields
You can store page-specific information in a hidden field on your page as a way of maintaining the state of your page.
If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.
Note
If you use hidden fields, you must submit your pages to the server using the HTTP POST method
rather than requesting the page via the page URL (the HTTP GET method).
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. For more information, see ASP.NET
Web Application Security and Basic Security Practices for Web Applications.
• 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:
○ Put each item in a separate hidden field.
○ Use view state with view-state chunking turned on, which automatically separates data into multiple hidden fields.
○ 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.
Cookies
Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with
the request to the server. For details about creating and reading cookies, see ASP.NET Cookies Overview.
Advantages of using cookies are:
• Configurable expiration rules The cookie can expire when the browser session ends, or it can exist indefinitely on the
client computer, subject to the expiration rules on the client.
• No server resources are required The cookie is stored on the client and read by the server after a post.
• Simplicity The cookie is a lightweight, text-based structure with simple key-value pairs.
• Data persistence Although the durability of the cookie on a client computer is subject to cookie expiration processes on
the client and user intervention, cookies are generally the most durable form of data persistence on the client.
Disadvantages of using cookies are:
• Size limitations Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies
is becoming more common in newer browser and client-device versions.
• User-configured refusal Some users disable their browser or client device’s ability to receive cookies, thereby limiting
this functionality.
• Potential security risks Cookies are subject to tampering. Users can manipulate cookies on their computer, which can
potentially cause a security risk or cause the application that is dependent on the cookie to fail. Also, although cookies are
only accessible by the domain that sent them to the client, hackers have historically found ways to access cookies from
other domains on a user’s computer. You can manually encrypt and decrypt cookies, but it requires extra coding and can
affect application performance because of the time that is required for encryption and decryption. For more information,
see ASP.NET Web Application Security and Basic Security Practices for Web Applications.

Note
Cookies are often used for personalization, where content is customized for a known user. In
most of these cases, identification is the issue rather than authentication. Thus, you can typically
secure a cookie that is used for identification by storing the user name, account name, or a
unique user ID (such as a GUID) in the cookie and then using the cookie to access the user
personalization infrastructure of a site.
Query Strings
A query string is information that is appended to the end of a page URL. For more information, see ASP.NET State
Management Overview.
You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a
simple but limited way of maintaining some state information. For example, query strings are an easy way to pass
information from one page to another, such as passing a product number to another page where it will be processed.
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 Paramsproperty 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. For more information, see ASP.NET Web Application Security and Basic
Security Practices for Web Applications.
• Limited capacity Some browsers and client devices impose a 2083-character limit on the length of URLs.
Client-Side Method 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.
State Recommended usage
management
option
View state Use when you need to store small amounts of information for a page that will
post back to itself. Using the ViewStateproperty provides functionality with
basic security.
Control state Use when you need to store small amounts of state information for a control
between round trips to the server.
Hidden fields Use when you need to store small amounts of information for a page that will
post back to itself or to another page, and when security is not an issue.NoteYou
can use a hidden field only on pages that are submitted to the server.
Cookies Use when you need to store small amounts of information on the client and
security is not an issue.
Query string Use when you are transferring small amounts of information from one page to
another and security is not an issue.NoteYou can use query strings only if you
are requesting the same page, or another page via a link.
Server-Side State Management Options

• Application state
• Session state
• Profile properties
• Database support
Application State
ASP.NET provides application state via the HttpApplicationState class as a method of storing global application-specific
information that is visible to the entire application. Application-state variables are, in effect, global variables for an
ASP.NET application. For more information, see ASP.NET Application State Overview
You can store your application-specific values in application state, which is then managed by the server. For more
information, see ASP.NET State Management Overview.
Data that is shared by multiple sessions and does not change often is the ideal type of data to insert into application-state
variables.
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.
Careful design and implementation of application state can increase Web application performance. For example, placing a
commonly used, relatively static dataset in application state can increase site performance by reducing the overall number
of data requests to a database. However, there is a performance trade-off. Application state variables containing large
blocks of information reduce Web server performance as server load increases. The memory occupied by a variable stored
in application state is not released until the value is either removed or replaced. Therefore, it is best to use application-
state variables only with small, infrequently changed datasets. For more information, see ASP.NET Performance Overview.
Session State
ASP.NET provides a session state, which is available as theHttpSessionState class, as a method of storing session-specific
information that is visible only within the session. ASP.NET session state identifies requests from the same browser during
a limited time window as a session, and provides the ability to persist variable values for the duration of that session. For
more information, see ASP.NET State Management Overviewand ASP.NET Session State Overview.
You can store your session-specific values and objects in session state, which is then managed by the server and available
to the browser or client device. The ideal data to store in session-state variables is short-lived, sensitive data that is
specific to an individual session.
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. For more information about using session state without cookies,
see ASP.NET Web Site Administration.
• 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. For more information, seeImplementing a Session-State Store Provider.
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.
Profile Properties
ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session
state, except that unlike session state, 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. For more information, see ASP.NET Profile Properties Overview.
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. For more information, see ASP.NET Profile Providers and Implementing a Profile Provider.
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. For more information, see ASP.NET Profile Properties
Overview and Defining ASP.NET Profile Properties.
• 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.
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 Method 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.
State Recommended usage
management
option
Application Use when you are storing infrequently changed, global information that is used
state by many users, and security is not an issue. Do not store large quantities of
information in application state.
Session state Use when you are storing short-lived information that is specific to an individual
session and security is an issue. Do not store large quantities of information in
session state. Be aware that a session-state object will be created and maintained
for the lifetime of every session in your application. In applications hosting many
users, this can occupy significant server resources and affect scalability.
Profile Use when you are storing user-specific information that needs to be persisted
properties after the user session is expired and needs to be retrieved again on subsequent
visits to your application.
Database Use when you are storing large amounts of information, managing transactions,
support or the information must survive application and session restarts. Data mining is a
concern, and security is an issue.
.NET Framework 4 – ASP.NET
ASP.NET Cookies Overview
A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The
cookie contains information the Web application can read whenever the user visits the site.
A Visual Studio project with source code is available to accompany this topic:Download.
This topic contains the following:
• Scenarios
• Background
• Code Examples
• Class Reference
• Additional Resources
• What’s New
Scenarios
Cookies provide a means in Web applications to store user-specific information. For example, when a user visits your site,
you can use cookies to store user preferences or other information. When the user visits your Web site another time, the
application can retrieve the information it stored earlier.Back to topBackground
A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The
cookie contains information the Web application can read whenever the user visits the site.For example, if a user requests
a page from your site and your application sends not just a page, but also a cookie containing the date and time, when the
user’s browser gets the page, the browser also gets the cookie, which it stores in a folder on the user’s hard disk.Later, if
user requests a page from your site again, when the user enters the URL the browser looks on the local hard disk for a
cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request.
Your application can then determine the date and time that the user last visited the site. You might use the information to
display a message to the user or check an expiration date.Cookies are associated with a Web site, not with a specific page,
so the browser and server will exchange cookie information no matter what page the user requests from your site. As the
user visits different sites, each site might send a cookie to the user’s browser as well; the browser stores all the cookies
separately.Cookies help Web sites store information about visitors. More generally, cookies are one way of maintaining
continuity in a Web application—that is, of performing state management. Except for the brief time when they are actually
exchanging information, the browser and Web server are disconnected. Each request a user makes to a Web server is
treated independently of any other request. Many times, however, it’s useful for the Web server to recognize users when
they request a page. For example, the Web server on a shopping site keeps track of individual shoppers so the site can
manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting
pertinent identification that helps an application know how to proceed.Cookies are used for many purposes, all relating to
helping the Web site remember users. For example, a site conducting a poll might use a cookie simply as a Boolean value
to indicate whether a user’s browser has already participated in voting so that the user cannot vote twice. A site that asks
a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep
entering credentials.
Cookie Limitations
Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small
amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read
user information from a database or other data store. (See the section “Cookies and Security” below for information about
security implications of storing user information.)
Browsers also impose limitations on how many cookies your site can store on the user’s computer. Most browsers allow
only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute
limit, usually 300, on the number of cookies they will accept from all sites combined.
A cookie limitation that you might encounter is that users can set their browser to refuse cookies. If you define a P3P
privacy policy and place it in the root of your Web site, more browsers will accept cookies from your site. However, you
might have to avoid cookies altogether and use a different mechanism to store user-specific information. A common
method for storing user information is session state, but session state depends on cookies, as explained later in the section
“Cookies and Session State.”
Note
For more information on state management and options for saving information in a Web
application, see ASP.NET State Management Overviewand ASP.NET State Management
Recommendations.
Although cookies can be very useful in your application, the application should not depend on being able to store cookies.
Do not use cookies to support critical features. If your application must rely on cookies, you can test to see whether the
browser will accept cookies. See the “Checking Whether a Browser Accepts Cookies” section later in this topic.

Writing Cookies
The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via
the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as
theResponse property of your Page class. Any cookies that you want to send to the browser must be added to this
collection. When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be
identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will
cause one to be overwritten.
You can also set a cookie’s date and time expiration. Expired cookies are deleted by the browser when a user visits the site
that wrote the cookies. The expiration of a cookie should be set for as long as your application considers the cookie value
to be valid. For a cookie to effectively never expire, you can set the expiration date to be 50 years from now.
Note
Users can clear the cookies on their computer at any time. Even if you store cookies with long
expiration times, a user might decide to delete all cookies, wiping out any settings you might
have stored in cookies.
If you do not set the cookie’s expiration, the cookie is created but it is not stored on the user’s hard disk. Instead, the
cookie is maintained as part of the user’s session information. When the user closes the browser, the cookie is discarded.
A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security
reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is
working on a public computer, where you do not want to write the cookie to disk.
You can add cookies to the Cookies collection in a number of ways. The following example shows two methods to write
cookies:
VB
C#
C++
F#
JScript
Copy
Response.Cookies["userName"].Value = “patrick”;
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie(“lastVisit”);
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
The example adds two cookies to the Cookies collection, one named userName and the other named lastVisit. For the first
cookie, the values of the Cookies collection are set directly. You can add values to the collection this way
because Cookies derives from a specialized collection of typeNameObjectCollectionBase.
For the second cookie, the code creates an instance of an object of typeHttpCookie, sets its properties, and then adds it to
the Cookies collection via the Add method. When you instantiate an HttpCookie object, you must pass the cookie name as
part of the constructor.
Both examples accomplish the same task, writing a cookie to the browser. In both methods, the expiration value must be
of type DateTime. However, the lastVisited value is also a date-time value. Because all cookie values are stored as strings,
the date-time value has to be converted to a String .
Cookies with More Than One Value
You can store one value in a cookie, such as user name and last visit. You can also store multiple name-value pairs in a
single cookie. The name-value pairs are referred to as subkeys. (Subkeys are laid out much like a query string in a URL.)
For example, instead of creating two separate cookies named userName and lastVisit, you can create a single cookie
named userInfo that has the subkeys userName and lastVisit.
You might use subkeys for several reasons. First, it is convenient to put related or similar information into a single cookie.
In addition, because all the information is in a single cookie, cookie attributes such as expiration apply to all the
information. (Conversely, if you want to assign different expiration dates to different types of information, you should store
the information in separate cookies.)
A cookie with subkeys also helps you limit the size of cookie files. As noted earlier in the “Cookie Limitations” section,
cookies are usually limited to 4096 bytes and you can’t store more than 20 cookies per site. By using a single cookie with
subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50
characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which
counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the
separate cookies and can save around 200 bytes.
To create a cookie with subkeys, you can use a variation of the syntax for writing a single cookie. The following example
shows two ways to write the same cookie, each with two subkeys:
VB
C#
C++
F#
JScript
Copy
Response.Cookies["userInfo"]["userName"] = “patrick”;
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie(“userInfo”);
aCookie.Values["userName"] = “patrick”;
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
Controlling Cookie Scope
By default, all cookies for a site are stored together on the client, and all cookies are sent to the server with any request to
that site. In other words, every page in a site gets all of the cookies for that site. However, you can set the scope of
cookies in two ways:
• Limit the scope of cookies to a folder on the server, which allows you to limit cookies to an application on the site.
• Set scope to a domain, which allows you to specify which subdomains in a domain can access a cookie.
Limiting Cookies to a Folder or Application
To limit cookies to a folder on the server, set the cookie’s Path property, as in the following example:
VB
C#
C++
F#
JScript
Copy
HttpCookie appCookie = new HttpCookie(“AppCookie”);
appCookie.Value = “written ” + DateTime.Now.ToString();
appCookie.Expires = DateTime.Now.AddDays(1);
appCookie.Path = “/Application1″;
Response.Cookies.Add(appCookie);
Note
You can also write cookies by adding them to the Cookies collection directly as shown in earlier
examples.
The path can either be a physical path under the site root or a virtual root. The effect will be that the cookie is available
only to pages in the Application1 folder or virtual root. For example, if your site is called www.contoso.com, the cookie
created in the previous example will be available to pages with the path http://www.contoso.com/Application1/ and to any
pages beneath that folder. However, the cookie will not be available to pages in other applications such as
http://www.contoso.com/Application2/ or just http://www.contoso.com/.

Note
In some browsers, the path is case sensitive. You cannot control how users type URLs into their
browsers, but if your application depends on cookies tied to a specific path, be sure that the
URLs in any hyperlinks you create match the case of the Path property value.

Limiting Cookie Domain Scope


By default, cookies are associated with a specific domain. For example, if your site is www.contoso.com, the cookies you
write are sent to the server when users request any page from that site. (This might not include cookies with a specific
path value.) If your site has subdomains—for example, contoso.com, sales.contoso.com, and support.contoso.com—then
you can associate cookies with a specific subdomain. To do so, set the cookie’sDomain property, as in this example:
VB
C#
C++
F#
JScript
Copy
Response.Cookies["domain"].Value = DateTime.Now.ToString();
Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["domain"].Domain = “support.contoso.com”;
When the domain is set in this way, the cookie will be available only to pages in the specified subdomain. You can also use
the Domain property to create a cookie that can be shared among multiple subdomains, as shown in the following
example:
Response.Cookies["domain"].Value = DateTime.Now.ToString();
Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["domain"].Domain = “contoso.com”;
The cookie will then be available to the primary domain as well as to sales.contoso.com and support.contoso.com domains.
Reading Cookies
When a browser makes a request to the server, it sends the cookies for that server along with the request. In your
ASP.NET applications, you can read the cookies using the HttpRequest object, which is available as theRequest property of
your Page class. The structure of the HttpRequestobject is essentially the same as that of the HttpResponse object, so you
can read cookies out of the HttpRequest object much the same way you wrote cookies into the HttpResponse object. The
following code example shows two ways to get the value of a cookie named username and display its value in
a Label control:
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}
Before trying to get the value of a cookie, you should make sure that the cookie exists; if the cookie does not exist, you
will get aNullReferenceException exception. Notice also that the HtmlEncode method was called to encode the contents of a
cookie before displaying it in the page. This makes certain that a malicious user has not added executable script into the
cookie. For more about cookie security, see the “Cookies and Security” section.
Note
Because different browsers store cookies differently, different browsers on the same computer
won’t necessarily be able to read each other’s cookies. For example, if you use Internet Explorer
to test a page one time, but then later use a different browser to test again, the second browser
won’t find the cookies saved by Internet Explorer.
Reading the value of a subkey in a cookie is likewise similar to setting it. The following code example shows one way to get
the value of a subkey:
VB
C#
C++
F#
JScript
Copy
if(Request.Cookies["userInfo"] != null)
{
Label1.Text =
Server.HtmlEncode(Request.Cookies["userInfo"]["userName"]);
Label2.Text =
Server.HtmlEncode(Request.Cookies["userInfo"]["lastVisit"]);
}
In the preceding example, the code reads the value of the subkey lastVisit, which was set earlier to the string
representation of a DateTime value. Cookies store values as strings, so if you want to use the lastVisit
DateTime dt;
dt = DateTime.Parse(Request.Cookies["userInfo"]["lastVisit"]);
The subkeys in a cookie are typed as a collection of typeNameValueCollection. Therefore, another way to get an individual
subkey is to get the subkeys collection and then extract the subkey value by name, as
if(Request.Cookies["userInfo"] != null)
{
System.Collections.Specialized.NameValueCollection
UserInfoCookieCollection;
UserInfoCookieCollection = Request.Cookies["userInfo"].Values;
Label1.Text =
Server.HtmlEncode(UserInfoCookieCollection["userName"]);
Label2.Text =
Server.HtmlEncode(UserInfoCookieCollection["lastVisit"]);
}
Changing a Cookie’s Expiration Date
The browser is responsible for managing cookies, and the cookie’s expiration time and date help the browser manage its
store of cookies. Therefore, although you can read the name and value of a cookie, you cannot read the cookie’s expiration
date and time. When the browser sends cookie information to the server, the browser does not include the expiration
information. (The cookie’s Expires property always returns a date-time value of zero.) If you are concerned about the
expiration date of a cookie, you must reset it, which is covered in the “Modifying and Deleting Cookies” section.
Note
You can read the Expires property of a cookie that you have set in theHttpResponse object,
before the cookie has been sent to the browser. However, you cannot get the expiration back in
the HttpRequest object.

Reading Cookie Collections


You might occasionally need to read through all the cookies available to the page. To read the names and values of all the
cookies available to the page, you can loop through the Cookies collection using code such as the following.
System.Text.StringBuilder output = new System.Text.StringBuilder();
HttpCookie aCookie;
for(int i=0; i<Request.Cookies.Count; i++)
{
aCookie = Request.Cookies[i];
output.Append(“Cookie name = ” + Server.HtmlEncode(aCookie.Name)
+ “<br />”);
output.Append(“Cookie value = ” + Server.HtmlEncode(aCookie.Value)
+ “<br /><br />”);
}
Label1.Text = output.ToString();
Note
When you run this code, you might see a cookie named ASP.NET_SessionId. That is a cookie
that ASP.NET uses to store a unique identifier for your session. The session cookie is not
persisted on your hard disk. For more about session cookies, see the “Cookies and Session State”
later in this topic.
A limitation of the preceding example is that if the cookie has subkeys, the display shows the subkeys as a single
name/value string. You can read a cookie’s HasKeys property to determine whether the cookie has subkeys. If so, you can
read the subkey collection to get individual subkey names and values. You can read subkey values from the Values
collection directly by index value. The corresponding subkey names are available in the AllKeys member of
theValues collection, which returns an array of strings. You can also use the Keysmember of the Values collection.
However, the AllKeys property is cached the first time it is accessed. In contrast, the Keys property builds an array each
time it is accessed. For this reason, the AllKeys property is much faster on subsequent accesses within the context of the
same page request.
The following example shows a modification of the preceding example. It uses the HasKeys property to test for subkeys,
and if subkeys are detected, the example gets subkeys from the Values collection:
for(int i=0; i<Request.Cookies.Count; i++)
{
aCookie = Request.Cookies[i];
output.Append(“Name = ” + aCookie.Name + “<br />”);
if(aCookie.HasKeys)
{
for(int j=0; j<aCookie.Values.Count; j++)
{
subkeyName = Server.HtmlEncode(aCookie.Values.AllKeys[j]);
subkeyValue = Server.HtmlEncode(aCookie.Values[j]);
output.Append(“Subkey name = ” + subkeyName + “<br />”);
output.Append(“Subkey value = ” + subkeyValue +
“<br /><br />”);
}
}
else
{
output.Append(“Value = ” + Server.HtmlEncode(aCookie.Value) +
“<br /><br />”);
}
}
Label1.Text = output.ToString();
Alternatively, you can extract the subkeys as a NameValueCollection object as shown in the following example:
System.Text.StringBuilder output = new System.Text.StringBuilder();
HttpCookie aCookie;
string subkeyName;
string subkeyValue;
for (int i = 0; i < Request.Cookies.Count; i++)
{
aCookie = Request.Cookies[i];
output.Append(“Name = ” + aCookie.Name + “<br />”);
if (aCookie.HasKeys)
{
System.Collections.Specialized.NameValueCollection CookieValues =
aCookie.Values;
string[] CookieValueNames = CookieValues.AllKeys;
for (int j = 0; j < CookieValues.Count; j++)
{
subkeyName = Server.HtmlEncode(CookieValueNames[j]);
subkeyValue = Server.HtmlEncode(CookieValues[j]);
output.Append(“Subkey name = ” + subkeyName + “<br />”);
output.Append(“Subkey value = ” + subkeyValue +
“<br /><br />”);
}
}
else
{
output.Append(“Value = ” + Server.HtmlEncode(aCookie.Value) +
“<br /><br />”);
}
}
Label1.Text = output.ToString();
Modifying and Deleting Cookies
You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and
then sending the cookie to the browser to overwrite the old version on the client. The following code example shows how
you can change the value of a cookie that stores a count of the user’s visits to the site:
int counter;
if (Request.Cookies["counter"] == null)
counter = 0;
else
{
counter = int.Parse(Request.Cookies["counter"].Value);
}
counter++;
Response.Cookies["counter"].Value = counter.ToString();
Response.Cookies["counter"].Expires = DateTime.Now.AddDays(1);
Deleting Cookies
Deleting a cookie—physically removing it from the user’s hard disk—is a variation on modifying it. You cannot directly
remove a cookie because the cookie is on the user’s computer. However, you can have the browser delete the cookie for
you. The technique is to create a new cookie with the same name as the cookie to be deleted, but to set the cookie’s
expiration to a date earlier than today. When the browser checks the cookie’s expiration, the browser will discard the now-
outdated cookie. The following code example shows one way to delete all the cookies available to the application:
HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i<limit; i++)
{
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(aCookie);
}
Modifying or Deleting Subkeys
Modifying an individual subkey is the same as creating it, as shown in the following example:
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
To delete an individual subkey, you manipulate the cookie’s Valuescollection, which holds the subkeys. You first recreate
the cookie by getting it from the Cookies object. You can then call the Remove method of theValues collection, passing to
the Remove method the name of the subkey to delete. You then add the cookie to the Cookies collection so it will be sent
in its modified form back to the browser. The following code example shows how to delete a subkey. In the sample, the
name of the subkey to remove is specified in a variable.
string subkeyName;
subkeyName = “userName”;
HttpCookie aCookie = Request.Cookies["userInfo"];
aCookie.Values.Remove(subkeyName);
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
Cookies and Security
The security issues with cookies are similar to those of getting data from the client. In your application, cookies are
another form of user input and are therefore subject to examining and spoofing. A user can as a minimum see the data
that you store in a cookie, since the cookie is available on the user’s own computer. The user can also change the cookie
before the browser sends it to you.
You should never store sensitive data in a cookie, such as user names, passwords, credit card numbers, and so on. Do not
put anything in a cookie that should not be in the hands of a user or of someone who might somehow steal the cookie.
Similarly, be suspicious of information you get out of a cookie. Do not assume that the data is the same as when you
wrote it out; use the same safeguards in working with cookie values that you would with data that a user has typed into a
Web page. The examples earlier in this topic showed HTML-encoding the contents of a cookie before displaying the value in
a page, as you would before displaying any information you get from users.
Cookies are sent between browser and server as plain text, and anyone who can intercept your Web traffic can read the
cookie. You can set a cookie property that causes the cookie to be transmitted only if the connection uses the Secure
Sockets Layer (SSL). SSL does not protect the cookie from being read or manipulated while it is on the user’s computer,
but it does prevent the cookie from being read while in transit because the cookie is encrypted. For more information,
see Basic Security Practices for Web Applications.
Determining Whether a Browser Accepts Cookies
Users can set their browser to refuse cookies. No error is raised if a cookie cannot be written. The browser likewise does
not send any information to the server about its current cookie settings.
Note
The Cookies property does not indicate whether cookies are enabled. It indicates only whether
the current browser inherently supports cookies.
One way to determine whether cookies are accepted is by trying to write a cookie and then trying to read it back again. If
you cannot read the cookie you wrote, you assume that cookies are turned off in the browser.
The following code example shows how you might test whether cookies are accepted. The sample consists of two pages.
The first page writes out a cookie, and then redirects the browser to the second page. The second page tries to read the
cookie. It in turn redirects the browser back to the first page, adding to the URL a query string variable with the results of
the test.
The code for the first page (AcceptsCookies.aspx) looks like the following example:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["AcceptsCookies"] == null)
{
Response.Cookies["TestCookie"].Value = “ok”;
Response.Cookies["TestCookie"].Expires =
DateTime.Now.AddMinutes(1);
Response.Redirect(“TestForCookies.aspx?redirect=” +
Server.UrlEncode(Request.Url.ToString()));
}
else
{
Label1.Text = “Accept cookies = ” +
Server.UrlEncode(
Request.QueryString["AcceptsCookies"]);
}
}
}
The page first tests to see if this is a postback, and if not, the page looks for the query string variable name
AcceptsCookies that contains the test results. If there is no query string variable, the test has not been completed, so the
code writes out a cookie named TestCookie. After writing out the cookie, the sample calls Redirect to transfer to the test
page TestForCookies.aspx. Appended to the URL of the test page is a query string variable named redirect containing the
URL of the current page; this will allow you to redirect back to this page after performing the test.
The test page can consist entirely of code; it does not need to contain controls. The following example illustrates the test
page (TestForCookies.aspx).
protected void Page_Load(object sender, EventArgs e)
{
string redirect = Request.QueryString["redirect"];
string acceptsCookies;
if(Request.Cookies["TestCookie"] ==null)
acceptsCookies = “no”;
else
{
acceptsCookies = “yes”;
// Delete test cookie.
Response.Cookies["TestCookie"].Expires =
DateTime.Now.AddDays(-1);
}
Response.Redirect(redirect + “?AcceptsCookies=” + acceptsCookies,
true);
}
After reading the redirect query string variable, the code tries to read the cookie. For housekeeping purposes, if the cookie
exists, it is immediately deleted. When the test is finished, the code constructs a new URL from the URL passed to it in the
redirect query string variable. The new URL also includes a query string variable containing test results. The final step is to
use the new URL to redirect the browser to the original page.
An improvement in the example would be to keep the cookie test results in a persistent store such as a database so that
the test does not have to be repeated each time the user views the original page. (Storing the test results in session state
by default requires cookies.)
Cookies and Session State
When a user navigates to your site, the server establishes a unique session for that user that lasts for the duration of the
user’s visit. For each session, ASP.NET maintains session state information where applications can store user-specific
information. For more information, see ASP.NET Session State Overview topic.
ASP.NET must track a session ID for each user so that it can map the user to session state information on the server. By
default, ASP.NET uses a non-persistent cookie to store the session state. However, if a user has disabled cookies on the
browser, session state information cannot be stored in a cookie.
ASP.NET offers an alternative in the form of cookieless sessions. You can configure your application to store session IDs
not in a cookie, but in the URLs of pages in your site. If your application relies on session state, you might consider
configuring it to use cookieless sessions. However, under some limited circumstances, if the user shares the URL with
someone else—perhaps to send the URL to a colleague while the user’s session is still active—then both users can end up
sharing the same session, with unpredictable results. For more information on configuring your application to use
cookieless sessions, see the ASP.NET State Management Overviewtopic.
ASP.NET View State Overview
View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips.
When the HTML markup for the page is rendered, the current state of the page and values that must be retained during
postback are serialized into base64-encoded strings. This information is then put into the view state hidden field or fields.
This topic contains the following sections:
• Scenarios
• Features
• Background
• Class Reference
Scenarios
View state is used automatically by the ASP.NET page framework to persist information that must be preserved between
postbacks. This information includes any non-default values of controls.You can also use view state to store application
data that is specific to a page.Back to topFeatures
View state is a repository in an ASP.NET page that can store values that have to be retained during postback. The page
framework uses view state to persist control settings between postbacks.You can use view state in your own applications
to do the following:
• Keep values between postbacks without storing them in session state or in a user profile.
• Store the values of page or control properties that you define.
• Create a custom view state provider that lets you store view state information in a SQL Server database or in another data
store.
For example, you can store information in view state that your code can access during the page load event the next time
that the page is sent to the server. For usage recommendations, see ASP.NET State Management Recommendations.
Back to top
Background
A Web application is stateless. A new instance of the Web page class is created every time that the page is requested from
the server. This would ordinarily mean that all information in the page and in its controls would be lost with each round
trip. For example, by default if a user enters information into a text box on an HTML Web page, that information is sent to
the server. However, it is not returned to the browser in the response.To overcome this intrinsic limitation of Web
programming, the ASP.NET page framework includes several state-management features to preserve page and control
values between round trips to the Web server. One of these features is view state. For information about other state
management features, see ASP.NET State Management Overview.By default, the ASP.NET page framework uses view state
to preserve page and control values between round trips. When the HTML for the page is rendered, the current state of the
page and values that must be retained during postback are serialized into base64-encoded strings. They are then put into
a hidden field or fields in the page.You can access view state in your code by using the page’s ViewState property.
The ViewState property is a dictionary that contains key/value pairs that contain the view state data.
Security Note
It is easy for a malicious user to see and modify the contents of a hidden field. For more
information about how to secure view state data, seeSecuring View State later in this topic.
For recommendations about when you should store information in view state, see ASP.NET State Management
Recommendations.
You can change the default behavior and store view state in another location such as a SQL Server database by
implementing a custom PageStatePersisterclass to store page data. For an example of how to store page state in a stream
instead of in a hidden field, see the example for the PageStatePersister class.

Considerations for Using View State


View state provides state information for a specific ASP.NET page. If you need to use information on more than one page,
or if you need the information to persist across visits to the Web site, you must use another method for maintaining state.
You can use application state, session state, or profile properties. For more information, see How to: Pass Values Between
ASP.NET Web Pages.
View state information is serialized into XML and then encoded by using base-64 encoding, which can generate large
amounts of data. When the page is posted to the server, the contents of view state are sent as part of the page postback
information. If view state contains a large amount of information, it can affect performance of the page. Test the
performance of your pages by using typical data for your application to determine whether the size of view state is causing
performance problems.
Another consideration is that if the amount of data in a hidden field becomes large, some proxies and firewalls will prevent
access to the page that contains them. Because the maximum allowed amount can vary with different firewall and proxy
implementations, large hidden fields can cause intermittent problems. If the amount of data that is stored in
the ViewStateproperty exceeds the value specified in the page’sMaxPageStateFieldLength property, the page splits view
state into multiple hidden fields. This reduces the size of individual hidden fields below the size that firewalls reject.
View state is enabled by default, but some controls on a page might not need view state. For example, if a control is
refreshed from the data store on each postback, you can turn view state off for that control in order to reduce the size of
view state.
You can configure controls so that view state is disabled by default for all controls within a page or a container control, and
you can then enable view state for specific controls. You can also configure controls so that view state is disabled and
cannot be enabled for child controls.
To disable view state for a control by default so that it can be enabled for child controls, set the ViewStateMode property of
the control to Disabled. To disable view state by default for an entire page, set the ViewStateMode attribute of
the @ Page directive to Disabled.
To disable view state for a control and its children so that it cannot be enabled for child controls, set
the EnableViewState property of the control to false. To disable view state for an entire page and all of its child controls,
set the EnableViewState attribute of the @ Page directive to false.
Note
Even when you explicitly turn view state off, a hidden field is still sent to the browser to indicate
that postback is occurring for the page.
For alternatives to using view state, see ASP.NET State Management Recommendations.
Some mobile devices do not allow hidden fields at all. Therefore, view state will not work for those devices. For more
information and alternatives, see ASP.NET Web Sites for Mobile Devices.

Control State
In addition to view state, ASP.NET supports control state. The page uses control state to persist control information that
must be retained between postbacks, even if view state is disabled for the page or for a control. Like view state, control
state is stored in one or more hidden fields.
Saving Values in View State
You can access view state information by using the page’s ViewStateproperty, which exposes a dictionary object. You can
use this dictionary to store custom values. A typical use is to store the value of custom properties that you define in the
page.
Because view state is sent as a hidden field, you can make changes to view state until the
page’s PreRenderComplete event. After the page is rendered to the browser, changes to view state will not be saved.
The information in the hidden view state field can be seen by users if they view the source of the Web page and can
decode base-64 encoded strings. This creates a potential security issue. For more information about security issues with
view state, see Securing View State later in this topic.
Note
To use the ViewState property, the ASP.NET Web page must have a form element that has the
attribute runat=”server”.
To save a value to view state, create a new item that contains the value to save and add the item to the view state
dictionary. The following example shows an ASP.NET Web page with code that saves a string and an integer value in view
state.
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd”>
<script runat=”server”>
// Sample ArrayList for the page.
ArrayList PageArrayList;
ArrayList CreateArray()
{
// Create a sample ArrayList.
ArrayList result = new ArrayList(4);
result.Add(“item 1″);
result.Add(“item 2″);
result.Add(“item 3″);
result.Add(“item 4″);
return result;
}
void Page_Load(object sender, EventArgs e)
{
if (ViewState["arrayListInViewState"] != null)
{
PageArrayList = (ArrayList)ViewState["arrayListInViewState"];
}
else
{
// ArrayList isn’t in view state, so it must be created and populated.
PageArrayList = CreateArray();
}
// Code that uses PageArrayList.
}
void Page_PreRender(object sender, EventArgs e)
{
// Save PageArrayList before the page is rendered.
ViewState.Add(“arrayListInViewState”, PageArrayList);
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>View state sample</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
</div>
</form>
</body>
</html>
Data Types You Can Store in View State
You can store objects of the following types in view state:
• Strings
• Integers
• Boolean values
• Array objects
• ArrayList objects
• Hash tables
• Custom type converters (see the TypeConverter class for more information)
You can store other types of data also, but the class must be compiled with the Serializable attribute so that its values can
be serialized for view state.
Reading Values from View State
To read a value from view state, you get the ViewState property of page and then read the value from the view state
dictionary.
The following example shows how you can get an ArrayList object named arrayListInViewState from view state and then
bind a GridView control to the object as a data source.
arrayList = new ArrayList();
arrayList = (ArrayList)ViewState["arrayListInViewState"];
this.GridView1.DataSource = arrayList;
this.GridView1.DataBind();
Values in view state are typed as String. In Visual Basic, if you set Option Strict On, you must cast view state values to the
appropriate type before you use them, as shown in the previous example. In C#, you must always cast to the appropriate
type when you read view state values.
If you try to get a value out of view state that does not exist, no exception is thrown. To make sure that a value is in view
state, check first whether the object exists. The following example shows how to check for a view state entry.
if (ViewState["color"] == null)
// No such value in view state, take appropriate action.
If you try to use a nonexistent view state entry in some other way (for example, to examine its type),
a NullReferenceException exception is thrown.
Back to top
Securing View State
By default, view state data is stored in the page in a hidden field and is encoded using base64 encoding. In addition, a
hash of the view state data is created from the data by using a machine authentication code (MAC) key. The hash value is
added to the encoded view state data and the resulting string is stored in the page. When the page is posted back to the
server, the ASP.NET page framework re-computes the hash value and compares it with the value stored in view state. If
the hash values do not match, an exception is raised that indicates that view state data might be invalid.
By creating a hash value, the ASP.NET page framework can test whether the view state data has been corrupted or
tampered with. However, even if it is not tampered with, view state data can still be intercepted and read by malicious
users.
Usign the MAC for Computing the View State Hash Value
The MAC key that is used to compute the view state hash value is either auto-generated or specified in the Machine.config
file. If the key is auto-generated, it is created based on the MAC address of the computer, which is the unique GUID value
of the network adapter in that computer.
It can be difficult for malicious users to reverse-engineer the MAC key based on the hash value in view state. Thus, MAC
encoding is a reasonably reliable way to determine whether view state data has been changed.
In general, the larger the MAC key that is used to generate the hash, the less likely it is that the hash value for different
strings will be the same. When the key is auto-generated, ASP.NET uses SHA-1 encoding to create a large key. However,
in a Web-farm environment, the key must be the same across all the servers. If the key is not the same, and the page is
posted back to a different server than the one that created the page, the ASP.NET page framework will raise an exception.
Therefore, in a Web farm environment, you should specify a key in the Machine.config file instead of letting ASP.NET auto-
generate one. In that case, make sure that you create a key that is long enough to offer sufficient security for the hashed
value. However, the longer the key is, the more time it takes to create a hash. Therefore, you must weigh security needs
versus performance needs.
Encrypting View State
Although MAC encoding helps prevent tampering with view state data, it does not prevent users from viewing the data.
You can prevent people from viewing this data in two ways: by transmitting the page over SSL, and by encrypting the view
state data. Requiring the page to be sent over SSL can help prevent data-packet sniffing and unauthorized data access by
people who are not the intended recipients of the page.
However, the user who requested the page can still view the view state data because SSL decrypts the page to display it in
the browser. This is fine if you are not concerned about authorized users having access to view state data. However, in
some cases, controls might use view state to store information that no users should have access to. For example, the page
might contain a data-bound control that stores item identifiers (data keys) in view state. If those identifiers contain
sensitive data, such as customer IDs, you should encrypt the view state data in addition to or instead of sending the page
over SSL.
To encrypt the data, set the page’s ViewStateEncryptionMode property to true. If you store information in view state, you
can use regular read and write techniques; the page handles all encryption and decryption for you. Encrypting view state
data can affect the performance of your application. Therefore, do not use encryption unless you need it.
Control State Encryption
Controls that use control state can require that view state be encrypted by calling
the RegisterRequiresViewStateEncryption method. If any control in the page requires that view state be encrypted, all view
state in the page will be encrypted.
Per-user View State Encoding
If a Web site authenticates users, you can set the ViewStateUserKeyproperty in the Page_Init event handler to associate
the page’s view state with a specific user. This helps prevent one-click attacks, in which a malicious user creates a valid,
pre-filled Web page with view state from a previously created page. The attacker then lures a victim into clicking a link
that sends the page to the server by using the victim’s identity.
When the ViewStateUserKey property is set, the attacker’s identity is used to create the hash of the view state of the
original page. When the victim is lured into resending the page, the hash values will be different because the user keys are
different. The page will fail verification and an exception will be thrown.
You must associate the ViewStateUserKey property with a unique value for each user, such as the user name or identifier.
Securing Configuration in Shared Hosting Environment
In a shared hosting environment, malicious users can potentially modify state-management properties that might affect
other applications on the computer. This can be done through direct modification of the Machine.config file, modification by
way of the configuration classes, and other administration and configuration tools. You can help prevent modification to
your application configuration by encrypting sections of configuration files. For more information, see Encrypting
Configuration Information Using Protected Configuration
Class Reference
ViewState Provides a dictionary object for retaining values between requests for the same
page.
PageStatePersisterProvides a means to define a custom mechanism for storing view state
information, such as in a SQL Server database.
ASP.NET Session State Overview
Use ASP.NET session state to store and retrieve values for a user.
This topic contains:

• Background
• Code Examples
• Class Reference
A Visual Studio project with source code is available to accompany this topic: Download.
Background
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web
application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an
independent request. The server retains no knowledge of variable values that were used during previous requests.
ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides
a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all
ASP.NET applications.Alternatives to session state include the following:
• Application state, which stores variables that can be accessed by all users of an ASP.NET application.
• Profile properties, which persists user values in a data store without expiring them.
• ASP.NET caching, which stores values in memory that is available to all ASP.NET applications.
• View state, which persists values in a page.
• Cookies.
• The query string and fields on an HTML form that are available from an HTTP request.
For a comparison of different state-management options, see ASP.NET State Management Recommendations.
Session Variables
Session variables are stored in a SessionStateItemCollection object that is exposed through
the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session
property of the Page object.
The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are
created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to
the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name
of a user, and set them to values retrieved from TextBox controls.
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
Session variables can be any valid .NET Framework type. The following example stores an ArrayList object in a session
variable named StockPicks. The value returned by the StockPicks session variable must be cast to the appropriate type
when you retrieve it from the SessionStateItemCollection.
// When retrieving an object from session state, cast it to
// the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;
Note
When you use a session-state mode other than InProc, the session-variable type must be either a
primitive .NET type or serializable. This is because the session-variable value is stored in an
external data store. For more information, see Session-State Modes.

Session Identifiers
Sessions are identified by a unique identifier that can be read by using theSessionID property. When session state is
enabled for an ASP.NET application, each request for a page in the application is examined for aSessionID value sent from
the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is
sent to the browser with the response.
By default, SessionID values are stored in a cookie. However, you can also configure the application to
store SessionID values in the URL for a “cookieless” session.
A session is considered active as long as requests continue to be made with the same SessionID value. If the time between
requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired.
Requests made with an expired SessionIDvalue result in a new session.
Security Note
SessionID values are sent in clear text, whether as a cookie or as part of the URL. A malicious
user could get access to the session of another user by obtaining the SessionID value and
including it in requests to the server. If you are storing sensitive information in session state, it is
recommended that you use SSL to encrypt any communication between the browser and server
that includes the SessionID value.

Cookieless SessionIDs
By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that
session identifiers should not be stored in a cookie by setting the cookieless attribute to true in thesessionState section of
the Web.config file.
The following example shows a Web.config file that configures an ASP.NET application to use cookieless session identifiers.
Copy
<configuration>
<system.web>
<sessionState cookieless=”true”
regenerateExpiredSessionId=”true” />
</system.web>
</configuration>
ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page’s URL. For
example, the following URL has been modified by ASP.NET to include the unique session ID lit3py55t21z5v55vlm25s55:
Copy
http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/orderform.aspx
When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by
embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as
long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied
by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session.
In that case, a new session is started for the request.
The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or
virtual directory identifier. This enables ASP.NET to resolve the application name before involving theSessionStateModule in
the request.
Note
To improve the security of your application, you should allow users to log out of your
application, at which point the application should call theAbandon method. This reduces the
potential for a malicious user to get the unique identifier in the URL and use it to retrieve private
user data stored in the session.

Regenerating Expired Session Identifiers


By default, the session ID values that are used in cookieless sessions are recycled. That is, if a request is made with a
session ID that has expired, a new session is started by using the SessionID value that is supplied with the request. This
can result in a session unintentionally being shared when a link that contains a cookieless SessionID value is used by
multiple browsers. (This can occur if the link is passed through a search engine, through an e-mail message, or through
another program.) You can reduce the chance of session data being shared by configuring the application not to recycle
session identifiers. To do this, set the regenerateExpiredSessionId attribute of the sessionState configuration element to
true. This generates a new session ID when a cookieless session request is made with an expired session ID.
Note
If the request that is made with the expired session ID is made by using the HTTP POST method,
any posted data will be lost when regenerateExpiredSessionId is true. This is because ASP.NET
performs a redirect to make sure that the browser has the new session identifier in the URL.

Custom Session Identifiers


You can implement a custom class to supply and validate SessionID values. To do so, create a class that inherits
the SessionIDManager class and override the CreateSessionID and Validate methods with your own implementations. For
an example, see the example provided for theCreateSessionID method.
You can replace the SessionIDManager class by creating a class that implements the ISessionIDManager interface. For
example, you might have a Web application that associates a unique identifier with non-ASP.NET pages (such as HTML
pages or images) by using an ISAPI filter. You can implement a custom SessionIDManager class to use this unique
identifier with ASP.NET session state. If your custom class supports cookieless session identifiers, you must implement a
solution for sending and retrieving session identifiers in the URL.
Session Modes
ASP.NET session state supports several storage options for session variables. Each option is identified as a session-
state Mode type. The default behavior is to store session variables in the memory space of the ASP.NET worker process.
However, you can also specify that session state should be stored in a separate process, in a SQL Server database, or in a
custom data source. If you do not want session state enabled for your application, you can set the session mode to Off.
For more information, see Session-State Modes.
Session Events
ASP.NET provides two events that help you manage user sessions. TheSession_OnStart event is raised when a new
session starts, and theSession_OnEnd event is raised when a session is abandoned or expires. Session events are
specified in the Global.asax file for an ASP.NET application.
The Session_OnEnd event is not supported if the session Mode property is set to a value other than InProc, which is the
default mode.
Note
If the Global.asax file or Web.config file for an ASP.NET application is modified, the
application will be restarted and any values stored in application state or session state will be
lost. Be aware that some anti-virus software can update the last-modified date and time of the
Global.asax or Web.config file for an application.
For more information, see Session-State Events.

Configuring Session State


Session state is configured by using the sessionState element of the system.web configuration section. You can also
configure session state by using the EnableSessionState value in the @ Page directive.
The sessionState element enables you to specify the following options:
• The mode in which the session will store data.
• The way in which session identifier values are sent between the client and the server.
• The session Timeout value.
• Supporting values that are based on the session Mode setting.
The following example shows a sessionState element that configures an application for SQLServer session mode. It sets
the Timeout value to 30 minutes, and specifies that session identifiers are stored in the URL.
<sessionState mode=”SQLServer”
cookieless=”true “
regenerateExpiredSessionId=”true “
timeout=”30″
sqlConnectionString=”Data Source=MySqlServer;Integrated Security=SSPI;”
stateNetworkTimeout=”30″/>
You can disable session state for an application by setting the session-state mode to Off. If you want to disable session
state for only a particular page of an application, you can set the EnableSessionState value in the @ Page directive to
false. The EnableSessionState value can also be set to ReadOnly to provide read-only access to session variables.
Concurrent Requests and Session State
Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent
requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the
same session (by using the same SessionID value), the first request gets exclusive access to the session information. The
second request executes only after the first request is finished. (The second session can also get access if the exclusive
lock on the information is freed because the first request exceeds the lock time-out.) If theEnableSessionState value in the
@ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on
the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write
request for session data to clear.
Back to top
Code Examples
How to: Save Values in Session StateHow to: Read Values from Session StateImplementing a Session-State Store
ProviderBack to topClass Reference
The following table lists key classes that relate to session state are in theSystem.Web.SessionState namespace.
Member Description
SessionIDManager Manages unique identifiers for ASP.NET session state.
SessionStateItemCollection Used to store session state variables.
ASP.NET Application State Overview
Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in
memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is
specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful
place to store small amounts of often-used data that does not change from one user to another. For information on saving
data on a per-user basis see ASP.NET Session State Overview and ASP.NET Profile Properties Overview.
Using Application State
You can access members of objects stored in application state without having to reference the Application collection. The
following code example shows how to reference a member of an object defined in the StaticObjects collection of
application state. Notice that the label identifier defined in Global.asax is used as the variable name.
protected void Page_Load(Object sender, EventArgs e)
{
Label1.Text = MyInfo.Title;
}
Application State Considerations
When using application state, you must be aware of the following important considerations:
• Resources Because it is stored in memory, application state is very fast compared to saving data to disk or a database.
However, storing large blocks of data in application state can fill up server memory, causing the server to page memory to
disk. As an alternative to using application state, you can use the ASP.NET cache mechanism for storing large amounts of
application data. The ASP.NET cache also stores data in memory and is therefore very fast; however, ASP.NET actively
manages the cache and will remove items when memory becomes scarce. For more information see ASP.NET Caching
Overview.
• Volatility Because application state is stored in server memory, it is lost whenever the application is stopped or
restarted. For example, if the Web.config file is changed, the application is restarted and all application state is lost unless
application state values have been written to a non-volatile storage medium such as a database.
• Scalability Application state is not shared among multiple servers serving the same application, as in a Web farm, or
among multiple worker processes serving the same application on the same server, as in a Web garden. Your application
therefore cannot rely on application state containing the same data for application state across different servers or
processes. If your application will run in multi-processor or multi-server environments, consider using a more scalable
option, such as a database, for data that must preserve fidelity across the application.
• Concurrency Application state is free-threaded, which means that application state data can be accessed simultaneously
by many threads. Therefore, it is important to ensure that when you update application state data, you do so in a thread-
safe manner by including built-in synchronization support. You can use the Lock and UnLock methods to ensure data
integrity by locking the data for writing by only one source at a time. You can also reduce the likelihood of concurrency
problems by initializing application state values in the Application_Start method in the Global.asax file.

ASP.NET Profile Properties Overview


In many applications, you want to store and use information that is unique to a user. When a user visits your site, you can
use the information you have stored to present the user with a personalized version of your Web application. Personalizing
an application requires a number of elements: you must store the information using a unique user identifier, be able to
recognize users when they visit again, and then fetch the user information as needed. To simplify your applications, you
can use the ASP.NET profile feature, which can perform all of these tasks for you.
The ASP.NET profile feature associates information with an individual user and stores the information in a persistent
format. Profiles allow you to manage user information without requiring you to create and maintain your own database. In
addition, the ASP.NET profile feature 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 using profiles. The profile feature provides a generic storage feature that allows you to
define and maintain almost any kind of data while still making the data available in a type-safe manner.
How ASP.NET Profiles Work
To use profiles, you first enable profiles by modifying the configuration file for your ASP.NET Web application. As part of
the configuration, you specify a profile provider, which is the underlying class that performs the low-level tasks of storing
and retrieving profile data. You can use the profile provider included with the .NET Framework, which stores profile data in
SQL Server, or you can create and use your own profile provider as described in the topic Implementing a Profile Provider.
You can specify an instance of the SqlProfileProvider that connects to a database of your choosing, or you can use the
default instance of the SqlProfileProvider that stores profile data on the local Web server.You configure the profile feature
by defining a list of properties whose values you want to maintain. For example, you might want to store the user’s postal
code so that your application can offer region-specific information, such as weather reports. In the configuration file, you
would define a profile property named PostalCode. The profile section of the configuration file might look like the
following:Copy<profile> <properties> <add /> </properties></profile>
When your application runs, ASP.NET creates a ProfileCommon class, which is a dynamically generated class that inherits
the ProfileBase class. The dynamic ProfileCommon class includes properties created from the profile property definitions
you specify in your application configuration. An instance of this dynamic ProfileCommon class is then set as the value of
theProfile property of the current HttpContext and is available to pages in your application.
In your application, you collect the value or values you want to store and assign them to the profile properties you have
defined. For example, your application’s home page might contain a text box that prompts the user to enter a postal code.
When the user enters a postal code, you set a Profileproperty to store the value for the current user, as in the following
example:
Profile.PostalCode = txtPostalCode.Text;
When you set a value for Profile.PostalCode, the value is automatically stored for the current user. You do not need to
write any code to determine who the current user is or explicitly store the value in a database���the profile feature
performs these tasks for you.
When you want to use the value, you can get it in much the same way that you set it. For example, the following code
example shows how to call an imaginary function named GetWeatherInfo, passing it the current user’s postal code as
stored in a profile:
weatherInfo = GetWeatherInfo( Profile.PostalCode );
You do not need to explicitly determine who the user is or perform any database lookups. Simply getting the property
value out of a profile causes ASP.NET to perform the necessary actions to identify the current user and look up the value in
the persistent profile store.
State Management in ASP.NetIn general,
Webapplications are stateless i.e. the objects
wont persist its state accross request to the web
application. In other words, the State or Cache
Management is nothing but the way to storing
the data in Client-Side and in Server-Side using
pretty small memory to maintain its state.There
are two major categories of the above :1.
Server-Side State Management2. Client-Side
State ManagementMoving forward, we will see
how State Management is done in ASP.Net
application.
Server-Side State ManagementSession State: Its nothing but defined as a
period of time shared between the web application and user. Every user has
individual session. Items/Objects can be placed into the Session which
would only define these objects for that user. Session contains key variables
which help to identify the related values. This can be thought of as a hash
table. Each user would represent a different key node in the hash identifying
unique values. The Session variables will be clear by the application which
can clear it, as well as through the timeout property in the web config file.
Usually the timeout is 20 minutes by default.Session Variables are stored
on the server, can hold any type of data including references, they are
similar to global variables in a windows application and use HTTP cookies
to store a key with which to locate user’s session variables.The collection of
session variables is indexed by the name of the variable or by an integer
index. Session variables are created by referring to the session variable by
name. You do not have to declare a session variable or explicitly add it to
the collection.Lets get it cleared from following
example:Session[“firstName”] = “Gaurav” //User’s first
nameSession[“lastName”] = “Arora” //User’s last name// Clear the
session variableSession[“FirstName”] = null;//Clear all Session
variablesSession.Abandon(); InProc—Stores Session state in the same
process as the ASP.NET process [aspnet_wp.exe].StateServer—Stores
Session state in a Windows NT process, which is distinct from the
ASP.NET process[aspnet_state.exe].SQLServer—Stores Session state in a
SQL Server database.Both in StateServer and SQLServer options, we need
to ensure that the objects we cache are serializable as data storages are out-
of-process systems. Both these options have impact on the application
performance as data retrieval and saving operations take more time when
compared to the InProc option. So based on our application requirement we
should choose the option that best suits our requirement.Note:By default,
ASP.NET session state is enabled for all ASP.NET applications.ASP.NET
application object
ASP.NET provides an object called Application object to store data that is accessible to all user
requests. The life span of this object is tied to the application and it is re-created every time the
application starts. Unlike ASP.NETSession object this object is accessible to all user requests.
Since this storage is created and maintained in an application domain space, this should not be
used for data storage in a web farm scenario. This option is very useful to store data like the
application metadata (CONFIG files data) that can be loaded to the Application object during
application start up and can be used during the life of the application without reloading it every
time for each user request. But if there is a requirement to invalidate the cached data whenever
there is any change to the CONFIG files while the application is running, this option should not
be used as it doesn’t provide any feature to expire the cached data. So in this case other
options like the ASP.NET Cache object should be used, which is explained below.
Types of Cache –Dependencies
When anyone add an item to cache, he/she can define the dependency relationships that can
force that item to be removed from the cache under specific activities of dependencies.
For example: If the cache is dependent on file and when the file data changes you want the
cache object to be updated.
Following are the difference dependencies:
File Dependency :
Allows invalidating a specific cache item when a disk based file or files change.
object errorData;
//Load errorData from errors.xml
CacheDependency fileDependency =
new CacheDependency(Server.MapPath(“errors.xml”));
Cache.Insert(“ERROR_INFO”, errorData, fileDependency);
Time based expiration :
Allows to invalidate a specific cache item depending on predefined time.
//Absolute Expiration
Cache.Insert(“EMP_NAME”, “Shubhabrata”, null,
DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
//Sliding Expiration
Cache.Insert(“EMP_NAME”, “Shubhabrata”, null,
Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(60));
Key dependency :
Allows to invalidate a specific cache item depending when another cache item changes.
string[] relatedKeys = new string[1];
relatedKeys[0] = “EMP_NUM”;
CacheDependency keyDependency = new CacheDependency(null, relatedKeys);
Cache["EMP_NUM"] = 5435;
Cache.Insert(“EMP_NAME”, “Shubhabrata”, keyDependency);
Cache.Insert(“EMP_ADDR”, “Bhubaneswar”, keyDependency);
Cache.Insert(“EMP_SAL”, “5555USD”, keyDependency);
.NET remoting
You might be thinking how .NET remoting can be used for data caching? The same question
came to my mind when I heard about it for the first time. As you know the .NET remoting
singleton object shares the same instance with multiple clients so singleton objects can be used
to store and share data between different client invocations. Since .NET remoting can be used
outside the process and machine, this option is very useful when we want to cache data and
share it across servers and users particularly in a web farm scenario. In this approach we can
store the data as member variables of singleton remoting object and provide methods to read
and save data. But while implementing this we need to ensure that the remoting object used as
cache is not destroyed by the garbage collector. For that we will have to set the remoting cache
object’s lease period to infinite so that the lease period never times out. We can do that by
overriding the InitializeLifetimeService method of MarshalByRefObject and return null from this
method. But the only issue with this approach is performance. As the analysis says the
performance is very poor in this approach when compared to other approaches. Anyway it is up
to the application designers/developers to analyze different options and use the best one that
suits the requirement.
Memory-mapped files
You all know what a memory-mapped file is. It is basically about mapping a file on disk to a
specific range of addresses in the application’s process address space. This option allows
different processes to use the same data by increasing the application performance. As using
memory-mapped file is not very popular among .NET developers, I would personally not suggest
this approach as implementing this involves a lot of complexities and also .NET Framework
doesn’t support this. But if anyone is very much interested in using this approach then they will
have to develop their own custom solution as per their own requirement.
Static variables
We use static variables for storing data or objects globally so that it can be accessed during the
life of the application. Similarly, in ASP.NET we can use static objects for caching data and we
can also provide methods to retrieve and save data to the cache. As static variables are stored
in the process area, performance wise it is faster. But since it is very difficult to implement
expiration policies and dependencies incase of static variables, I generally prefer ASP.NET cache
object over this option. Another problem is that the custom static cache object has to be thread-
safe which has to be implemented carefully.
Example:
public class CustomCache
{
//Synchronized to implement thread-safe
static Hashtable _myCache =
Hashtable.Synchronized(new Hashtable());
public static object GetData(object key) {
return _myCache[key];
}
public static void SetData(object key, object val)
{
_myCache[key] = val; Recent
}
}
Articles
Disable
Client-Side State ManagementCookiesCookie is a very familiar term in Public
web development environment. Cookie is a client-side storage that is sent toholidays in
the server for each request and also received as response back from the ASP.Net
server. Because of its size limitation (4096 bytes) it should be used for Calendar
storing small amount of data. Expiration policies can be set for cookies to Control Post
invalidate the items after a certain period of time. The following example ed on
shows how Cookie can be used in an ASP.NET application:if 7/30/2010 @
(this.Request.Cookies["MY_NAME"] == null) { 7:37 AM
this.Response.Cookies.Add(new By Bala
HttpCookie(“MY_NAME”, “Shubhabrata Murugan
Mohanty”));}else{ How to Pass
this.Response.Write(this.Request.Cookies["MY_NAME"].Value);}ViewSt Values from
ateASP.NET ViewState is a new concept. Here the data related to the pages One Page to
and controls are stored in ViewState which retains the values across Another in
multiple requests to the server. If you remember correctly, in VB-ASP ASP.Net? Po
applications we used to store data across multiple requests using hidden sted on
fields. ViewState is actually implemented internally as hidden fields in 7/24/2010 @
ASP.NET but here the data is hashed to improve security as against hidden 1:31 AM
fields. To see how ViewState is implemented, you can view the source of By Bala
the page in which ViewState is used in the Internet Murugan
browser. ViewState should not be used to store large amounts of data as it isUsing
passed to the server for each requestprotected void Page_Load(object ADRotator
sender, EventArgs e) { if (this.ViewState["MY_NAME"] == null) { Control in
this.ViewState["MY_NAME"] = “Shuby”; ASP.Net-
} Part
//txtName is a TextBox control 2 Posted on
this.txtName.Text = this.ViewState["MY_NAME"].ToString();
}
7/17/2010 @
Hidden fields 1:21 AM
Hidden fields are very popular among VB-ASP web developers. Hidden field is similar to any BySatheesh
other control in a page but the visible state of this control is always false. Like ViewState we Babu B
should not use it for storing large amounts of data.
Note:Similarly hidden frames can be used to cache data in the client side. But please note
Pass Values
that hidden frames are not supported by all Internet browsers. from
<!–In ASP.NET–> CodeBehind
<asp:HiddenField Value=”Shuby” runat=”server” />
<!–In HTML–>
to
<input value=”Shuby” /> JavaScript
and From
JavaScript
to
CodeBehind
in
ASP.Net Pos
ted on
7/10/2010 @
1:36 AM
BySatheesh
Babu B
Using
ADRotator
Control in
ASP.Net-
Part
1 Posted on
7/5/2010 @
1:13 AM
By Satheesh
Babu B
Insert Image & Retrive Image From Database
Default.aspx
<form id=”form1″ runat=”server”>
<div>
emp name
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<br />
<br />
emp image&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:FileUpload ID=”FileUpload1″ runat=”server” />
<br />
<br />
<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Add”
Width=”100px” />
<asp:Button ID=”Button2″ runat=”server” onclick=”Button2_Click”
Text=”Display” />
<asp:Image ID=”Image1″ runat=”server” Width=”677px” />
<br />
</div>
</form>
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader rd;
public _Default()
{
con = new SqlConnection(“initial catalog=employee;integrated security=yes”);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string fn =FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath(@”image/”) + FileUpload1.FileName);
string path=”~/image/”+fn;
cmd = new SqlCommand(“insert into emp values(‘”+TextBox1.Text+”‘,’”+path+”‘)”,con);
int t = cmd.ExecuteNonQuery();
if (t>0)
{
Response.Write(“record inserted”);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
cmd = new SqlCommand(“select empimage from emp”, con);
rd = cmd.ExecuteReader();
while (rd.Read())
{
Image1.ImageUrl = rd[0].ToString();
}
}
}
insert record throgh gridview
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ ShowFooter=”True” AutoGenerateColumns=”false”
runat=”server” BackColor=”#DEBA84″ BorderColor=”#DEBA84″ BorderStyle=”None”
BorderWidth=”1px” CellPadding=”3″ CellSpacing=”2″>
<RowStyle BackColor=”#FFF7E7″ ForeColor=”#8C4510″ />
<Columns>
<asp:TemplateField>
<HeaderTemplate>Emp Id</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblEmpId” runat=”server” Text=’<%# bind(“EmpId”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtEmpId” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Emp Name</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblEmpName” runat=”server” Text=’<%# bind(“EmpName”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtEmpName” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Emp Salary</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblEmpSalary” runat=”server” Text=’<%# bind(“EmpSalary”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtEmpSalary” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Operation</HeaderTemplate>

<FooterTemplate>
<asp:Button ID=”btnAdd” runat=”server” OnClick=”AddRecord” Text=”Add” />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor=”#F7DFB5″ ForeColor=”#8C4510″ />
<PagerStyle ForeColor=”#8C4510″ HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#738A9C” Font-Bold=”True” ForeColor=”White” />
<HeaderStyle BackColor=”#A55129″ Font-Bold=”True” ForeColor=”White” />
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader rd;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill();
}
}
void fill()
{
con.Close();
con.Open();
cmd=new SqlCommand (“select * from Employee”,con);
rd = cmd.ExecuteReader();
GridView1.DataSource = rd;
GridView1.DataBind();

rd.Close();

}
protected void AddRecord(object sender, EventArgs e)
{
TextBox txtEmpId =GridView1.FooterRow.FindControl(“txtEmpId”) as TextBox;
TextBox txtEmpName = GridView1.FooterRow.FindControl(“txtEmpName”) as TextBox;
TextBox txtEmpSalary = GridView1.FooterRow.FindControl(“txtEmpSalary”) as TextBox;
con.Close();
con.Open();
cmd = new SqlCommand(“insert into Employee values(” + Convert.ToInt32(txtEmpId.Text) + “,’” +
txtEmpName.Text + “‘,” + Convert.ToDecimal(txtEmpSalary.Text) + “)”, con);
int t=cmd.ExecuteNonQuery();
if (t>0)
{
fill();
}

}
}
Manipulation(Insert, Update, Delete) in asp.net
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
<style type=”text/css”>
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id=”form1″ runat=”server”>
<table class=”style1″>
<tr>
<td>
Emp Id</td>
<td>
<asp:TextBox ID=”txtEmpId” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Emp Name</td>
<td>
<asp:TextBox ID=”txtEmpName” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Emp Salary</td>
<td>
<asp:TextBox ID=”txtEmpSalary” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td colspan=”2″>
<br />
<br />
<asp:Button ID=”btnDisplay” runat=”server” onclick=”btnDisplay_Click”
Text=”Display” />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Button ID=”btnNext” runat=”server” onclick=”btnNext_Click” Text=”Next” />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Button ID=”btnPrev” runat=”server” onclick=”btnPrev_Click” Text=”Prev” />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Button ID=”btnInsert” runat=”server” onclick=”btnInsert_Click”
Text=”Insert” />
&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Button ID=”btnUpdate” runat=”server” onclick=”btnUpdate_Click”
Text=”Update” />
&nbsp;&nbsp;&nbsp;
<asp:Button ID=”btnDelete” runat=”server” onclick=”btnDelete_Click”
Text=”Delete” />
</td>
</tr>
</table>
<div>

</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
static int counter;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from employee”, con);
adap.Fill(ds, “employee”);
bui = new SqlCommandBuilder(adap);

}
protected void Page_Load(object sender, EventArgs e)
{

protected void btnDisplay_Click(object sender, EventArgs e)


{
txtEmpId.Text = ds.Tables["Employee"].Rows[0][0].ToString();
txtEmpName.Text = ds.Tables["Employee"].Rows[0][1].ToString();
txtEmpSalary.Text = ds.Tables["Employee"].Rows[0][2].ToString();
}
protected void btnNext_Click(object sender, EventArgs e)
{
int count = ds.Tables["Employee"].Rows.Count;
counter++;
if (counter<count)
{
txtEmpId.Text = ds.Tables["Employee"].Rows[counter][0].ToString();
txtEmpName.Text = ds.Tables["Employee"].Rows[counter][1].ToString();
txtEmpSalary.Text = ds.Tables["Employee"].Rows[counter][2].ToString();

}
else
{

Response.Write(“Record Not Found”);


}
}
protected void btnPrev_Click(object sender, EventArgs e)
{
int count = ds.Tables["Employee"].Rows.Count;
counter–;
if (counter < count)
{
txtEmpId.Text = ds.Tables["Employee"].Rows[counter][0].ToString();
txtEmpName.Text = ds.Tables["Employee"].Rows[counter][1].ToString();
txtEmpSalary.Text = ds.Tables["Employee"].Rows[counter][2].ToString();
}
else
{
Response.Write(“Record Not Found”);
}
}
protected void btnInsert_Click(object sender, EventArgs e)
{
adap.InsertCommand = bui.GetInsertCommand();
DataRow dr=ds.Tables["Employee"].NewRow();
dr[0] = Convert.ToInt32(txtEmpId.Text);
dr[1] = txtEmpName.Text;
dr[2] = Convert.ToDecimal(txtEmpSalary.Text);
ds.Tables["Employee"].Rows.Add(dr);
adap.Update(ds.Tables["Employee"]);
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
adap.UpdateCommand = bui.GetUpdateCommand();
DataRow[] dr = ds.Tables["Employee"].Select(“EmpId=”+Convert.ToInt32(txtEmpId.Text)+”");
dr[0][1] = txtEmpName.Text;
dr[0][2] = Convert.ToDecimal(txtEmpSalary.Text);
adap.Update(ds.Tables["Employee"]);
}
protected void btnDelete_Click(object sender, EventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
DataColumn[] dc = new DataColumn[1];
dc[0]=ds.Tables["Emp"].Columns["EmpId"];
ds.Tables["Emp"].PrimaryKey = dc;
DataRow dr= ds.Tables["Emp"].Rows.Find(Convert.ToInt32(txtEmpId.Text));
dr.Delete();
adap.Update(ds.Tables["Emp"]);
}
}

display Record in Repeater


.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Repeater ID=”Repeater1″ runat=”server”>
<HeaderTemplate>
<table>
<tr>
<td style=”width:100px;background-color:Gray;”>Emp Id</td>
<td style=”width:100px;background-color:Gray;”>Emp Name</td>
<td style=”width:100px;background-color:Gray;”>Emp Salary</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td style=”width:100px;background-color:Gray;”>
<asp:Label ID=”lblEmpId” runat=”server” Text=’<%# bind(“EmpId”) %>’>
</asp:Label>
</td>
<td style=”width:100px;background-color:Gray;”>
<asp:Label ID=”lblEmpName” runat=”server” Text=’<%# bind(“EmpName”) %>’>
</asp:Label>
</td>
<td style=”width:100px;background-color:Gray;”>
<asp:Label ID=”lblEmpSalary” runat=”server” Text=’<%# bind(“EmpSalary”) %>’>
</asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
}
protected void Page_Load(object sender, EventArgs e)
{
fill();
}
void fill()
{
adap = new SqlDataAdapter(“select * from employee”,con);
adap.Fill(ds,”Employee”);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
}
Deletion in Gridview
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ OnRowDeleting=”deleterecord” AutoGenerateColumns=”False” runat=”server”>
<Columns>
<asp:TemplateField HeaderText=”Emp Id”>
<ItemTemplate>
<asp:Label ID=”lblEmpId” runat=”server” Text=’<%# bind(“EmpId”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Name”>
<ItemTemplate>
<asp:Label ID=”lblEmpName” runat=”server” Text=’<%# bind(“EmpName”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Salary”>
<ItemTemplate>
<asp:Label ID=”lblEmpSalary” runat=”server” Text=’<%# bind(“EmpSalary”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Operation”>
<ItemTemplate>
<asp:Button ID=”btnDelete” runat=”server” CommandName=”Delete” Text=”Delete” />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from Employee”, con);
adap.Fill(ds, “Employee”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill();
}
}
void fill()
{
GridView1.DataSource = ds;
GridView1.DataBind();

}
protected void deleterecord(object sender, GridViewDeleteEventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
//DataColumn[] dc = new DataColumn[1];

// Label lblEmpId =GridView1.Rows[e.RowIndex].FindControl(“lblEmpId”) as Label;


// DataRow dr= ds.Tables["Employee"].Rows.Find(Convert.ToInt32(lblEmpId.Text));
// dr.Delete();
ds.Tables["Employee"].Rows[e.RowIndex].Delete();
adap.Update(ds.Tables["Employee"]);
fill();
}
}
updation in gridview
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”g1″ OnRowUpdating=”updateRecord” AutoGenerateColumns=”false”
OnRowCancelingEdit=”cancelRecord” OnRowEditing=”editRecord” runat=”server”>
<Columns>
<asp:TemplateField HeaderText=”Emp Id”>
<ItemTemplate>
<asp:Label ID=”lblEmpId” runat=”server” Text=’<%# Bind(“EmpId”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Name”>
<ItemTemplate>
<asp:Label ID=”lblEmpName” runat=”server” Text=’<%# Bind(“EmpName”) %>’></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=”txtEmpName” runat=”server” Text=’<%# Bind(“EmpName”) %>’></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Salary”>
<ItemTemplate>
<asp:Label ID=”lblEmpSalary” runat=”server” Text=’<%# Bind(“EmpSalary”) %>’></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=”txtEmpSalary” runat=”server” Text=’<%# Bind(“EmpSalary”) %>’></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Operation”>
<ItemTemplate>
<asp:Button ID=”btnEdit” runat=”server” CommandName=”Edit” Text=”Edit” />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID=”btnUpdate” CommandName=”Update” runat=”server” Text=”Update” />
<asp:Button ID=”btnCancel” runat=”server” CommandName=”Cancel” Text=”Cancel” />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from Employee”, con);
adap.Fill(ds, “Employee”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill();
}
}
void fill()
{

g1.DataSource = ds;
g1.DataBind();
}
protected void editRecord(object sender, GridViewEditEventArgs e)
{
g1.EditIndex = e.NewEditIndex;
fill();
}
protected void cancelRecord(object sender, GridViewCancelEditEventArgs e)
{
g1.EditIndex = -1;
fill();
}
protected void updateRecord(object sender, GridViewUpdateEventArgs e)
{
adap.UpdateCommand = bui.GetUpdateCommand();
Label lblEmpId =g1.Rows[e.RowIndex].FindControl(“lblEmpId”) as Label;
TextBox txtEmpName =g1.Rows[e.RowIndex].FindControl(“txtEmpName”) as TextBox;
TextBox txtEmpSalary = g1.Rows[e.RowIndex].FindControl(“txtEmpSalary”) as TextBox;
DataRow[] dr= ds.Tables["Employee"].Select(“EmpId=”+Convert.ToInt32(lblEmpId.Text)+”");
dr[0]["EmpName"] = txtEmpName.Text;
dr[0]["EmpSalary"] = Convert.ToDecimal(txtEmpSalary.Text);
int temp= adap.Update(ds.Tables["Employee"]);
if (temp>0)
{
g1.EditIndex = -1;
fill();

}
}
record show in Datalist
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:DataList ID=”d1″ runat=”server” RepeatColumns=”3″ >

<ItemTemplate>
<table>
<tr>
<td style=”width:100px;”>
<asp:Label ID=”lblEmpId” runat=”server” Text=’<%# bind(“EmpId”) %>’></asp:Label>
</td></tr>
<tr>
<td style=”width:100px;”><asp:Label ID=”Label1″ runat=”server” Text=’<%# bind(“EmpName”)
%>’></asp:Label></td></tr>
<tr> <td style=”width:100px;”><asp:Label ID=”Label2″ runat=”server” Text=’<%# bind(“EmpSalary”)
%>’></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>

</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
}
protected void Page_Load(object sender, EventArgs e)
{
fill();
}
void fill()
{
DataList d;
Repeater r1;
adap = new SqlDataAdapter(“select * from Employee”,con);
adap.Fill(ds,”Employee”);
d1.DataSource = ds;
d1.DataBind();

}
}
Difference b/w Repeater,Data List & Grid View :-
Concept Repeater Data List Grid View
Base Class Control Web Control Web Control
Default Output No No Yes
Manipulation No No Yes
Paging No no Yes
Auto Formatting No Yes Yes
Repeat Column No Yes No
Sorting No No Yes
ajax
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title></title>
<script language=”javascript” type=”text/javascript” >
function chk() {
var r = document.getElementById(“TextBox1″).value;
if (r < 60) {
alert(“enter above 60″);
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>
<asp:UpdatePanel ID=”up1″ runat=”server”>
<ContentTemplate>

<div>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

<asp:Button ID=”btnfirst” runat=”server” Text=”first” onclick=”btnfirst_Click” />


<br />
<br />
<br />
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID=”btnfirst” EventName=”Click” />
</Triggers>
</asp:UpdatePanel>
<div>
<asp:TextBox ID=”TextBox2″ runat=”server”></asp:TextBox>

<asp:Button ID=”btnsecond” runat=”server” Text=”second”


onclick=”btnsecond_Click” />
</div>

</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = System.DateTime.Now.Second.ToString();
TextBox2.Text = System.DateTime.Now.Second.ToString();

}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(“cac”);
}
protected void btnfirst_Click(object sender, EventArgs e)
{
TextBox1.Text = System.DateTime.Now.Second.ToString();

}
protected void btnsecond_Click(object sender, EventArgs e)
{

TextBox2.Text = System.DateTime.Now.Second.ToString();
}
}
check all in gridview
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ AutoGenerateColumns=”false” runat=”server”>
<Columns>
<asp:TemplateField >
<HeaderTemplate>
<asp:Button ID=”btnDelete” OnClick=”deleterecord” Text=”Delete” runat=”server” />
<asp:CheckBox ID=”chkAll” OnCheckedChanged=”checkallrows” AutoPostBack=”true” runat=”server” />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID=”chkRow” runat=”server” />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Id”>
<ItemTemplate>
<asp:Label ID=”lblEmpId” runat=”server” Text=’<%# bind(“Emp_Id”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Name”>
<ItemTemplate>
<asp:Label ID=”lblEmpName” runat=”server” Text=’<%# bind(“Emp_Name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Salary”>
<ItemTemplate>
<asp:Label ID=”lblEmpSalary” runat=”server” Text=’<%# bind(“Emp_Salary”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=abhi;integrated security=yes”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from abhinavsir”,con);
adap.Fill(ds,”Emp”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill();
}
}
void fill()
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void checkallrows(object sender, EventArgs e)
{
CheckBox chkall =GridView1.HeaderRow.FindControl(“chkall”) as CheckBox;

for (int i = 0; i < GridView1.Rows.Count; i++)


{
CheckBox chkrow = GridView1.Rows[i].FindControl(“chkrow”) as CheckBox;
if (chkall.Checked==true)
{
chkrow.Checked = true;
}
else
{
chkrow.Checked = false;
}

}
protected void deleterecord(object sender, EventArgs e)
{

for (int i = 0; i < GridView1.Rows.Count; i++)


{
CheckBox chkrow = GridView1.Rows[i].FindControl(“chkrow”) as CheckBox;
if (chkrow.Checked==true)
{
adap.DeleteCommand = bui.GetDeleteCommand();
ds.Tables["Emp"].Rows[i].Delete();

}
}
int t = adap.Update(ds.Tables["Emp"]);
fill();
}
}
Record insert & Delete in gridview though disconnected mode
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView OnRowDeleting=”DeleteRecord” AutoGenerateColumns=”False” ShowFooter=”True” ID=”GridView1″
runat=”server”>
<Columns>
<asp:TemplateField>
<HeaderTemplate>Product No</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductNo” runat=”server” Text=’<%# bind(“Product_No”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductNo” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Product Name</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductName” runat=”server” Text=’<%# bind(“Product_Name”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductName” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Product Price</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductPrice” runat=”server” Text=’<%# bind(“Product_Price”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductPrice” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Operation</HeaderTemplate>
<ItemTemplate>
<asp:Button ID=”btnDelete” runat=”server” CommandName=”Delete” Text=”Delete” />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID=”btnSave” runat=”server” OnClick=”saverecord” Text=”Save” />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=ritu;uid=sa;pwd=sa”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from Product”,con);
adap.Fill(ds,”Prod”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void saverecord(object sender, EventArgs e)
{
adap.InsertCommand = bui.GetInsertCommand();
TextBox txtProductNo =GridView1.FooterRow.FindControl(“txtProductNo”) as TextBox;
TextBox txtProductName = GridView1.FooterRow.FindControl(“txtProductName”) as TextBox;
TextBox txtProductPrice = GridView1.FooterRow.FindControl(“txtProductPrice”) as TextBox;
DataRow dr =ds.Tables["Prod"].NewRow();
dr[0] = Convert.ToInt32(txtProductNo.Text);
dr[1] = txtProductName.Text;
dr[2] =Convert.ToDecimal(txtProductPrice.Text);
ds.Tables["Prod"].Rows.Add(dr);
int t=adap.Update(ds.Tables["Prod"]);
if (t>0)
{
fillrecord();
}
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
ds.Tables["Prod"].Rows[e.RowIndex].Delete();
adap.Update(ds.Tables["Prod"]);
fillrecord();

}
}
Record insert & Delete in gridview though disconnected mode
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView OnRowDeleting=”DeleteRecord” AutoGenerateColumns=”False” ShowFooter=”True” ID=”GridView1″
runat=”server”>
<Columns>
<asp:TemplateField>
<HeaderTemplate>Product No</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductNo” runat=”server” Text=’<%# bind(“Product_No”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductNo” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Product Name</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductName” runat=”server” Text=’<%# bind(“Product_Name”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductName” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Product Price</HeaderTemplate>
<ItemTemplate>
<asp:Label ID=”lblProductPrice” runat=”server” Text=’<%# bind(“Product_Price”) %>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtProductPrice” runat=”server”></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Operation</HeaderTemplate>
<ItemTemplate>
<asp:Button ID=”btnDelete” runat=”server” CommandName=”Delete” Text=”Delete” />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID=”btnSave” runat=”server” OnClick=”saverecord” Text=”Save” />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=ritu;uid=sa;pwd=sa”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from Product”,con);
adap.Fill(ds,”Prod”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void saverecord(object sender, EventArgs e)
{
adap.InsertCommand = bui.GetInsertCommand();
TextBox txtProductNo =GridView1.FooterRow.FindControl(“txtProductNo”) as TextBox;
TextBox txtProductName = GridView1.FooterRow.FindControl(“txtProductName”) as TextBox;
TextBox txtProductPrice = GridView1.FooterRow.FindControl(“txtProductPrice”) as TextBox;
DataRow dr =ds.Tables["Prod"].NewRow();
dr[0] = Convert.ToInt32(txtProductNo.Text);
dr[1] = txtProductName.Text;
dr[2] =Convert.ToDecimal(txtProductPrice.Text);
ds.Tables["Prod"].Rows.Add(dr);
int t=adap.Update(ds.Tables["Prod"]);
if (t>0)
{
fillrecord();
}
}
protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
ds.Tables["Prod"].Rows[e.RowIndex].Delete();
adap.Update(ds.Tables["Prod"]);
fillrecord();

}
}

.updation through Gridview


.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ OnRowUpdating=”updaterecord” OnRowCancelingEdit=”cancelrecord”
OnRowEditing=”editrecord” AutoGenerateColumns=”false” runat=”server”>
<Columns>
<asp:TemplateField HeaderText=”Product No”>
<ItemTemplate>
<asp:Label ID=”lblProductNo” runat=”server” Text=’<%# bind(“Product_no”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Product Name”>
<ItemTemplate>
<asp:Label ID=”lblProductName” runat=”server” Text=’<%# bind(“Product_name”) %>’></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=”txtProductName” runat=”server” Text=’<%# bind(“Product_name”) %>’></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Product Price”>
<ItemTemplate>
<asp:Label ID=”lblProductPrice” runat=”server” Text=’<%# bind(“Product_Price”) %>’></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=”txtProductPrice” runat=”server” Text=’<%# bind(“Product_Price”) %>’></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Operation”>
<ItemTemplate>
<asp:Button ID=”btnEdit” CommandName=”Edit” runat=”server” Text=”Edit” />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID=”btnUpdate” runat=”server” Text=”Update” CommandName=”update” />
<asp:Button ID=”btnCancel” runat=”server” Text=”Cancel” CommandName=”cancel” />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=ritu;uid=sa;pwd=sa”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from product”,con);
adap.Fill(ds,”product”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
GridView1.DataSource = ds;
GridView1.DataBind();

}
protected void editrecord(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillrecord();
}
protected void cancelrecord(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillrecord();
}
protected void updaterecord(object sender, GridViewUpdateEventArgs e)
{
adap.UpdateCommand = bui.GetUpdateCommand();
Label lblProductNo = GridView1.Rows[e.RowIndex].FindControl(“lblProductNo”) as Label;
TextBox txtProductName = GridView1.Rows[e.RowIndex].FindControl(“txtProductName”) as TextBox;
TextBox txtProductPrice = GridView1.Rows[e.RowIndex].FindControl(“txtProductPrice”) as TextBox;
DataRow[] dr =ds.Tables["Product"].Select(“Product_No=”+Convert.ToInt32(lblProductNo.Text)+”");
dr[0][1] = txtProductName.Text;
dr[0][2] =Convert.ToDecimal(txtProductPrice.Text);
int t =adap.Update(ds,”Product”);
if (t>0)
{
GridView1.EditIndex = -1;
fillrecord();
}
}
}
Check All Through Gridview
.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ AutoGenerateColumns=”false” runat=”server”>
<Columns>
<asp:TemplateField >
<HeaderTemplate>
<asp:Button ID=”btnDelete” OnClick=”deleterecord” Text=”Delete” runat=”server” />
<asp:CheckBox Text=”Check All” OnCheckedChanged=”checkRows” AutoPostBack=”true” ID=”chkAll”
runat=”server” />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID=”chkRow” runat=”server” />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Product No”>
<ItemTemplate>
<asp:Label ID=”lblProductNo” runat=”server” Text=’<%# bind(“Product_no”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Product Name”>
<ItemTemplate>
<asp:Label ID=”lblProductName” runat=”server” Text=’<%# bind(“Product_name”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Product Price”>
<ItemTemplate>
<asp:Label ID=”lblProductPrice” runat=”server” Text=’<%# bind(“Product_Price”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

</Columns>

</asp:GridView>
</div>
</form>
</body>
</html>
.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder bui;
public _Default()
{
con = new SqlConnection(“initial catalog=ritu;uid=sa;pwd=sa”);
ds = new DataSet();
adap = new SqlDataAdapter(“select * from product”, con);
adap.Fill(ds, “product”);
bui = new SqlCommandBuilder(adap);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void checkRows(object sender, EventArgs e)
{
CheckBox chkall = GridView1.HeaderRow.FindControl(“chkAll”) as CheckBox;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = GridView1.Rows[i].FindControl(“chkrow”) as CheckBox;
if (chkall.Checked==true)
{
chkrow.Checked = true;
}
else
{
chkrow.Checked = false;
}
}
}
protected void deleterecord(object sender, EventArgs e)
{
adap.DeleteCommand = bui.GetDeleteCommand();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = GridView1.Rows[i].FindControl(“chkrow”) as CheckBox;
if (chkrow.Checked == true)
{
ds.Tables["Product"].Rows[i].Delete();
}

}
int t =adap.Update(ds.Tables["Product"]);
if (t>0)
{
fillrecord();
}
}
}

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Net.Mail;
using
System.Net;
public
partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
MailMessage m = newSystem.Net.Mail.MailMessage(“abhinavdotnet@gmail.com”,“abhsax1@gmail.com”,“aaa”,“asasasas”);
try
{
NetworkCredential n = new NetworkCredential(“username”, “password”);
SmtpClient s = new SmtpClient(“smtp.gmail.com”, 587);
s.EnableSsl = true;
s.UseDefaultCredentials = false;
s.Credentials = n;
s.Send(m);
Response.Write(“m s”);
}
catch (Exception)
{
throw;
}
}
}
Hyperlink in Asp.net
Default.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”g1″ AutoGenerateColumns=”false” runat=”server”>
<Columns>
<asp:HyperLinkField HeaderText=”Emp Id” DataTextField=”EmpId” DataNavigateUrlFields=”EmpId”
DataNavigateUrlFormatString=”detail.aspx?temp={0}” />
<asp:TemplateField HeaderText=”Emp Name”>
<ItemTemplate>
<asp:Label ID=”lblEmpName” runat=”server” Text=’<%# bind(“EmpName”) %>’ ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Emp Salary”>
<ItemTemplate>
<asp:Label ID=”lblEmpSalary” runat=”server” Text=’<%# bind(“EmpSalary”) %>’ ></asp:Label>
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader rd;
public _Default()
{
con = new SqlConnection(“initial catalog=Employee;integrated security=yes”);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
cmd = new SqlCommand(“select * from Emp”,con);
rd = cmd.ExecuteReader();
g1.DataSource = rd;
g1.DataBind();
}
}
Detail.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”detail.aspx.cs” Inherits=”detail” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server”>
</asp:GridView>
</div>
</form>
</body>
</html>
detail.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class detail : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader rd;
public detail()
{
con = new SqlConnection(“initial catalog=Employee;integrated security=yes”);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillrecord();
}
}
void fillrecord()
{
cmd = new SqlCommand(“select * from Empdetail where
empid=”+Convert.ToInt32(Request.QueryString["temp"].ToString())+”", con);
rd = cmd.ExecuteReader();
GridView1.DataSource = rd;
GridView1.DataBind();
}
}
Server-side options for storing page information typically have higher security than client-side options, but they can use
more Web server resources, which can lead to scalability issues when the size of the information store is large. ASP.NET
provides several options to implement server-side state management. For more information, see ASP.NET State
Management Overview.The following are the server-side state management options that ASP.NET supports:
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 StateASP.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. For more information, see ASP.NET Application State Overview.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.
Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-value dictionary of
objects.TheHttpApplicationState instance is created the first time a user accesses any URL resource in an application.
The HttpApplicationState class is most often accessed through the Application property of the HttpContext class.You can
use application state in two ways. You can add, access, or remove values from the Contents collection directly through
code. The HttpApplicationStateclass can be accessed at any time during the life of an application. However, it is often
useful to load application state data when the application starts. To do so, you can put code to load application state into
the Application_Start method in the Global.asax file.Alternatively, you can add objects to the StaticObjects collection via an
<object runat=”server”> declaration in your Web application’s Global.asax file. Application state defined in this way can
then be accessed from code anywhere in your application. The following example shows an object declaration for an
application state value:CopyYou can add objects to the StaticObjectscollection only in the Global.asax file. The collection
throws aNotSupportedException if you attempt to add objects directly through code.
1 Response to "Asp.Net"

abhinavdotnetnotes
February 14, 2011 at 5:16 am
I sended fully discription of webservice in c# .net
Reply

Leave a Reply
Top of Form

Your email address will not be published. Required fields are marked *

Name *

Email *

Website
Post Comment

Notify me of follow-up comments via email.

Subscribe to this site by email


Bottom of Form
Search
Top of Form

Bottom of Form

• Top Posts
• Latest Comments
• Tags

• Project 2011
• Asp.Net
• Have a nice day
• Ado.Net
• C# .net
• Java Script
• C# Notes
• .Net Framework

Categories
• Uncategorized (1)

Archives
• August 2010

Blog at WordPress.com.
Theme: Albeo by Design Disease.

S-ar putea să vă placă și