This topic outlines the application life cycle, listing important life-cycle events and describing how code that you write can fit into the application life cycle. Within ASP.NET, several processing steps must occur for an ASP.NET application to be initialized and process requests. Additionally, ASP.NET is only one piece of the Web server architecture that services requests made by browsers. It is important for you to understand the application life cycle so that you can write code at the appropriate life cycle stage for the effect you intend. Application Life Cycle in General The following table describes the stages of the ASP.NET application life cycle. Stage Description User requests an application resource from the Web server. The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx. Note If a file name extension has not been mapped to ASP.NET, then ASP.NET will not receive the request. This is important to understand for applications that use ASP.NET authentication. For example, because .htm files are typically not mapped to ASP.NET, ASP.NET will not perform authentication or authorization checks on requests for .htm files. Therefore, even if a file contains only static content, if you want ASP.NET to check authentication, create the file using a file name extension mapped to ASP.NET, such as .aspx. 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
This topic outlines the application life cycle, listing important life-cycle events and describing how code that you write can fit into the application life cycle. Within ASP.NET, several processing steps must occur for an ASP.NET application to be initialized and process requests. Additionally, ASP.NET is only one piece of the Web server architecture that services requests made by browsers. It is important for you to understand the application life cycle so that you can write code at the appropriate life cycle stage for the effect you intend.
Application Life Cycle in General
The following table describes the stages of the ASP.NET application life cycle.
Stage Description
User requests an application resource from the Web server.
The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.
Note
If a file name extension has not been mapped to ASP.NET, then ASP.NET will not receive the request. This is important to understand for applications that use ASP.NET authentication. For example, because .htm files are typically not mapped to ASP.NET, ASP.NET will not perform authentication or authorization checks on requests for .htm files. Therefore, even if a file contains only static content, if you want ASP.NET to check authentication, create the file using a file name extension mapped to ASP.NET, such as .aspx.
Note
If you create a custom handler to service a particular file name extension, you must map the extension to ASP.NET in IIS and also register the handler in your application's Web.config file. For more information, see Introduction to HTTP Handlers.
ASP.NET receives the first request for the application.
When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provides access to information about the application such as the name of the folder where the application is stored.
The following diagram illustrates this relationship:
ASP.NET also compiles the top-level items in the application if required, including application code in the App_Code folder.
ASP.NET core objects are created for each request.
After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, including cookies and browser information. The HttpResponse object contains the response that is sent to the client, including all rendered output and cookies.
An HttpApplication object is assigned to the request
After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application.
Note
The first time an ASP.NET page or process is requested in an application, a new instance of HttpApplication is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.
When an instance of HttpApplication is created, any configured modules are also created. For instance, if the application is configured to do so, ASP.NET creates a SessionStateModule module. After all configured modules are created, the HttpApplication class's Init method is called.
2
The following diagram illustrates this relationship:
The request is processed by the HttpApplication pipeline.
The following events are executed by the HttpApplication class while the request is processed. The events are of particular interest to developers who want to extend the HttpApplication class.
1. Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequest and Script Exploits Overview.
2. Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.
3. Raise the BeginRequest event.
4. Raise the AuthenticateRequest event.
5. Raise the PostAuthenticateRequest event.
6. Raise the AuthorizeRequest event.
7. Raise the PostAuthorizeRequest event.
8. Raise the ResolveRequestCache event.
9. Raise the PostResolveRequestCache event.
10. Based on the file name extension of the requested resource (mapped in
the application's configuration file), select a class that implements IHttpHandler to process the request. If the request is for an object (page) derived from the Page class and the page needs to be compiled, ASP.NET compiles the page before creating an instance of it.
11. Raise the PostMapRequestHandler event.
12. Raise the AcquireRequestState event.
13. Raise the PostAcquireRequestState event.
14. Raise the PreRequestHandlerExecute event.
15. Call the ProcessRequest method (or the asynchronous version BeginProcessRequest) of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance handles the request.
16. Raise the PostRequestHandlerExecute event.
17. Raise the ReleaseRequestState event.
18. Raise the PostReleaseRequestState event.
19. Perform response filtering if the Filter property is defined.
20. Raise the UpdateRequestCache event.
21. Raise the PostUpdateRequestCache event.
22. Raise the EndRequest event.
Life Cycle Events and the Global.asax file
During the application life cycle, the application raises events that you can handle and calls particular methods that you can override. To handle application events or methods, you can create a file named Global.asax in the root directory of your application.
If you create a Global.asax file, ASP.NET compiles it into a class derived from the HttpApplication class, and then uses the derived class to represent the application.
An instance of HttpApplication processes only one request at a time. This simplifies application event handling because you do not need to lock non-static members in the application class when you access them. This also allows you to store request-specific data in non-static members of the application class. For example, you can define a property in the Global.asax file and assign it a request-specific value.
ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as Application_BeginRequest. This is similar to the way that ASP.NET page methods are automatically bound to events, such as the page's Page_Load event. For details, see ASP.NET Page Life Cycle Overview.
The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.
The following table lists some of the events and methods that are used during the application life cycle. There are many more events than those listed, but they are not commonly used.
Event or method Description
Application_Start Called when the first resource (such as a page) in an ASP.NET application is
requested. The Application_Start method is called only one time during the life cycle of an application. You can use this method to perform startup tasks such as loading data into the cache and initializing static values.
You should set only static data during application start. Do not set any instance data because it will be available only to the first instance of the HttpApplication class that is created.
Application_event Raised at the appropriate time in the application life cycle, as listed in the application life cycle table earlier in this topic.
Application_Error can be raised at any phase in the application life cycle.
Application_EndRequest is the only event that is guaranteed to be raised in every request, because a request can be short-circuited. For example, if two modules handle the Application_BeginRequest event and the first one throws an exception, the Application_BeginRequest event will not be called for the second module. However, the Application_EndRequest method is always called to allow the application to clean up resources.
HttpApplication.Init
Called once for every instance of the HttpApplication class after all modules have been created.
Dispose Called before the application instance is destroyed. You can use this method to manually release any unmanaged resources. For more information, see Cleaning Up Unmanaged Resources.
Application_End Called once per lifetime of the application before the application is unloaded.
HTTP Modules
The ASP.NET application life cycle is extensible through IHttpModule classes. ASP.NET includes several classes that implement IHttpModule, such as the SessionStateModule class. You can also create your own classes that implement IHttpModule.
If you add modules to your application, the modules themselves can raise events. The application can subscribe to in these events in the Global.asax file by using the convention modulename_eventname. For example, to handle the Authenticate event raised by a FormsAuthenticationModule object, you can create a handler named FormsAuthentication_Authenticate.
The SessionStateModule class is enabled by default in ASP.NET. All session events are automatically wired up as Session_event, such as Session_Start. The Start event is raised each time a new session is created. For more information, see Session State Overview.
What’s the sequence in which ASP.NET events are processed ?
1) What’s the sequence in which ASP.NET events are processed? 1) Initialize: Initialize settings needed during the lifetime of the incoming Web request.2) Load view state: At the end of this phase, the ViewState property of a control is automatically populated3) Process postback data: Process incoming form data and update properties accordingly.4) Load: Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect
client-side data.5) Send postback change notifications: Raise change events in response to state changes between the current and previous postbacks.6) Handle postback events: Handle the client-side event that caused the postback and raise appropriate events on the server.7) Prerender: Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost.8) Save state: The ViewState property of a control is automatically persisted to a string object after this stage. This string object is sent to the client and back as a hidden variable. For improving efficiency, a control can override the SaveViewState method to modify the ViewState property.9 Render: Generate output to be rendered to the client.10) Dispose: Perform any final cleanup before the control is torn down. References to expensive resources such as database connections must be released in this phase.11) Unload: Perform any final cleanup before the control is torn down. Control authors generally perform cleanup in Dispose and do not handle this event.Initialization, Page Load, PreRendor, Page unload
In which event are the controls fully loaded ?Read Page Life cycle and write the answer here
ASP.NET Page Life Cycle Overview
When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of
processing steps. These include initialization, instantiating controls, restoring and maintaining state,
running event handler code, and rendering. It is important for you to understand the page life cycle so
that you can write code at the appropriate life-cycle stage for the effect you intend. Additionally, if you
develop custom controls, you must be familiar with the page life cycle in order to correctly initialize
controls, populate control properties with view-state data, and run any control behavior code. (The life
cycle of a control is based on the page life cycle, but the page raises more events for a control than are
available for an ASP.NET page alone.)
General Page Life-cycle Stages
In general terms, the page goes through the stages outlined in the following table. In addition to the
page life-cycle stages, there are application stages that occur before and after a request but are not
specific to a page. For more information, see ASP.NET Application Life Cycle Overview.
Stage Description
Page request The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.(Query: When a page requires compilation?)
Start In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.
Page initialization
During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
Load During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.Query: If not postback then what happens?
Validation During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.(Query: Why you require validate the control?)
Postback event handling
If the request is a postback, any event handlers are called.
Rendering Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.
Unload Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.
Life-cycle Events
Within each stage of the life cycle of a page, the page raises events that you can handle to run your own
code. For control events, you bind the event handler to the event, either declaratively using attributes
such as onclick, or in code.
Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular
names and automatically runs those methods when certain events are raised. If the AutoEventWireup
attribute of the @ Page directive is set to true (or if it is not defined, since by default it is true), page
events are automatically bound to methods that use the naming convention of Page_event, such as
Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web
Server Control Event Model.
The following table lists the page life-cycle events that you will use most frequently. There are more
events than those listed; however, they are not used for most page processing scenarios. Instead, they
are primarily used by server controls on the ASP.NET Web page to initialize and render themselves. If
you want to write your own ASP.NET server controls, you need to understand more about these stages.
For information about creating custom controls, see Developing Custom ASP.NET Server Controls.
PreInit Use this event for the following: Check the IsPostBack property to determine whether this is the first
time the page is being processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
Note
If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
InitComplete Raised by the Page object. Use this event for processing tasks that require all initialization be complete.
PreLoad Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
Load The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.Use the OnLoad event method to set properties in controls and establish database connections.
Control events Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
Note
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
LoadComplete Use this event for tasks that require that all other controls on the page be loaded.
PreRender Before this event occurs: The Page object calls EnsureChildControls for each control and for the
Each data bound control whose DataSourceID property is set calls its
DataBind method. For more information, see Data Binding Events for Data-
Bound Controls below.
The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.
SaveStateComplete
Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.
Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Unload This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
Note
During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.
Additional Page Life Cycle Considerations
Individual ASP.NET server controls have their own life cycle that is similar to the page life cycle. For
example, a control's Init and Load events occur during the corresponding page events.
Although both Init and Load recursively occur on each control, they happen in reverse order. The Init
event (and also the Unload event) for each child control occur before the corresponding event is raised
for its container (bottom-up). However the Load event for a container occurs before the Load events
bound before the containing control (the GridView control) is bound, so their data-binding stages are
out of sync.
To avoid this condition, put the data source control for the ListBox control in the same template item as
the ListBox control itself, and do not set the data binding properties of the ListBox declaratively.
Instead, set them programmatically at run time during the RowDataBound event, so that the ListBox
control does not bind to its data until the CompanyID information is available.
For more information, see Binding to Data Using a Data Source Control.
Data Binding Events for Data-Bound Controls
To help you understand the relationship between the page life cycle and data binding events, the
following table lists data-related events in data-bound controls such as the GridView, DetailsView, and
FormView controls.
Control Event Typical Use
DataBinding This event is raised by data-bound controls before the PreRender event of the containing control (or of the Page object) and marks the beginning of binding the control to the data.Use this event to manually open database connections, if required. (The data source controls often make this unnecessary.)
RowCreated (GridView only) or ItemCreated (DataList, DetailsView, SiteMapPath, DataGrid, FormView, and Repeater controls)
Use this event to manipulate content that is not dependent on data binding. For example, at run time, you might programmatically add formatting to a header or footer row in a GridView control.
RowDataBound (GridView only) or ItemDataBound (DataList, SiteMapPath, DataGrid, and Repeater controls)
When this event occurs, data is available in the row or item, so you can format data or set the FilterExpression property on child data source controls for displaying related data within the row or item.
DataBound This event marks the end of data-binding operations in a data-bound control. In a GridView control, data binding is complete for all rows and any child controls.Use this event to format data bound content or to initiate data binding in other controls that depend on values from the current control's content. (For details, see "Catch-up Events for Added Controls" earlier in this topic.)
The Login control can use settings in the Web.config file to manage membership authentication
automatically. However, if your application requires you to customize how the control works, or if you
want to understand how Login control events relate to the page life cycle, you can use the events
listed in the following table.
Control Event Typical Use
LoggingIn This event is raised during a postback, after the page's LoadComplete event has occurred. It marks the beginning of the login process. Use this event for tasks that must occur prior to beginning the authentication process.
Authenticate This event is raised after the LoggingIn event. Use this event to override or enhance the default authentication behavior of a Login control.
LoggedIn This event is raised after the user name and password have been authenticated. Use this event to redirect to another page or to dynamically set the text in the control. This event does not occur if there is an error or if authentication fails.
LoginError This event is raised if authentication was not successful. Use this event to set text in the control that explains the problem or to direct the user to a different page.
How can we identify that the Page is PostBack ?
When an event is triggered, for instance, a button is clicked, or an item in a gridis selected, the page is submitted back to the server for processing, along withinformation about the event and any preexisting data on the page (via view state).We say the page “posts back” to the server. This is a powerful concept to graspbecause it is postback that lets us run code on the server rather than on the client’sbrowser, and it is postback that lets our server code know which items within adrop-down list were selected, or what information a user typed into a text box.But what would happen if you had multiple DropDownList controls that werepopulated with database data? Users could interact with those DropDownListcontrols and, in turn, we could set certain options within the page based on whatthey selected from the drop-down menus. Although this seems like a commontask, with traditional ASP it incurred considerable overhead. The problem is thatwhile the data that’s bound to the drop-down menu from the database neverchanges, every time the user selects an item from the drop-down menu and apostback has to be done, the database must be accessed again to rebuild thecontents of each drop-down list on the page. However, this is not a problem inASP.NET.In ASP.NET we can check for postback with the IsPostBack property, and thusavoid performing any time consuming tasks unnecessarily. IsPostBack is a pagelevelproperty—meaning that it’s a property of the page itself—and we’d mostcommonly use it in the Page_Load() event handler to execute code only whenthe page is first loaded.
How does ASP.NET maintain state in between subsequent request ?
A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.
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 State
The 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 details, see How to: Save Values in View State. For recommendations about when you should use view state, see ASP.NET State Management Recommendations.
Control State
Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips.
The ViewState property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.
The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState 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, see ASP.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.
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
ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client. With server-based state management, you can decrease the amount of information sent to the client in order to preserve state, however it can use costly resources on the server. The following sections describe three server-based state management features: application state, session state, and profile properties.
Application State
ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages. 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.
Once you add your application-specific information to application state, the server manages it. For usage recommendations, see ASP.NET State Management Recommendations.
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 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 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.
Event Bubbling is nothing but events raised by child controls is handled by the parent control. Example: Suppose consider datagrid as parent control in which there are several child controls.There can be a column of link buttons right.Each link button has click event.Instead of writing event routine for each link button write one routine for parent which will handlde the click events of the child link button events.Parent can know which child actaully triggered the event.That thru arguments passed to event routine. " Happy programming"
Bubbling an Event
The ASP.NET page framework provides a technique called event bubbling that allows a child control to
propagate events up its containment hierarchy. Event bubbling enables events to be raised from a more
convenient location in the controls hierarchy and allows event handlers to be attached to the original
control as well as to the control that exposes the bubbled event.
Event bubbling is used by the data-bound controls (Repeater, DataList, and DataGrid) to expose
command events raised by child controls (within item templates) as top-level events. While ASP.NET
server controls in the .NET Framework use event bubbling for command events (events whose event
data class derives from CommandEventArgs), any event defined on a server control can be bubbled.
A control can participate in event bubbling through two methods that it inherits from the base class
System.Web.UI.Control. These methods are OnBubbleEvent and RaiseBubbleEvent. The following
missing, the ASP.NET parser assumes that there is source code in the App_Code folder of the application. If you have source code for a control that you want to register on a page without having to compile it, place the source code in the App_Code folder. ASP.NET dynamically compiles source files in the App_Code folder at run time.
namespace
The namespace of the custom control that is being registered.
src
The location (relative or absolute) of the declarative ASP.NET User Controls file to associate
with the tagprefix:tagname pair.
tagname
An arbitrary alias to associate with a class. This attribute is only used for user controls.
tagprefix
An arbitrary alias that provides a shorthand reference to the namespace of the markup being
used in the file that contains the directive.
Remarks
Including the @ Register directive in a page or user control allows you to lay out custom server
controls or user controls using declarative Custom Server Control Syntax.
Note
You can also register custom controls on all the pages of an application by using the controls Element for pages (ASP.NET Settings Schema) in the Web.config file.
Use the @ Register directive in the following situations:
To add a custom server control declaratively to a Web page, a user control, a master page, or
a skin file (see ASP.NET Themes and Skins Overview).
To add a user control declaratively to a Web page, a user control, a master page, or a
skin file.
Note
The tagprefix value "mobile" is used by ASP.NET to identify the mobile Web controls in the System.Web.UI.MobileControls namespace. You should avoid using this prefix for your controls.
When you use the @ Register directive to reference a control, you can place the code for the control in
If your user control is in the same directory as the page that contains it, the src attribute value should be the name and extension of the .ascx file.
When including custom server controls that you have compiled into a .dll file for use with your
application, use the tagprefix attribute with the assembly and namespace attributes. If you do not
include the namespace attribute, or if you assign an empty string ("") to it, a parser error will
occur.
Caution
When you develop a custom server control, you must include it in a namespace. If you do not, it will not be accessible from an ASP.NET page. For more information about developing custom ASP.NET server controls, see Developing Custom ASP.NET Server Controls.
Example
The following code example uses @ Register directives to declare tagprefix and tagname aliases,
along with assigning a src attribute, to reference a user control within a Web page. The first part of the
code is a simple user control consisting of an ASP.NET Calendar control. The second portion of the
code is a page that hosts the control. Note that the tagprefix attribute assigns an arbitrary prefix value
to use with the tag. The tagname attribute uses the value of the class name assigned to the user control
(although the value of this attribute is arbitrary and any string value can be used--you do not have to use
the class name of the control being referenced). The src attribute points to the source file for the user
control, relative to the application root folder. The user control is referenced within the body of the page
by using the prefix, a colon, and the name of the tag, in this form: <uc1:CalendarUserControl
runat="server" />.
Copy Code
<%@ Control ClassName="CalendarUserControl" %> <asp:calendar id="Calendar1"