Monday, February 3, 2014

The ASP.NET Application Life Cycle, Page Life Cycle and Control Life Cycle

On a ASP.NET application running on IIS 7.5 the life cycle of your application looks like the following list.
  1. A user first makes a request for a page in you site.
  2. The request is routed to the processing pipeline, which forwards it to the ASP.NET runtime.
  3. The ASP.NET runtime creates an instance of the ApplicationManager class. The ApplicationManager instance represents the Microsoft .NET Framework domain that will be used to execute requests for you application. An application domain isolates global variables from other applications and allows each applications to load and unload separately as required.
  4. After the application domain has been created, an instance of the HostingEncironment class Is created. This class provides access to items inside the hosting environment, such as directory folders.
  5. ASP.NET creates instances of the core objects that will be used to process the request. This includes HttpContext, HttpRequest and HttpResponse objects.
  6. ASP.NET creates an instance of the HttpApplication class (or an instance is reused). This class is also the base class for a site’s Global.asax file. You can use this class to trap events that happen when your application starts or stops. When ASP.NET creates an instance of HttpApplication, it also creates the modules configured for the application, such as the SessionStateModule.
  7. Finally, ASP.NET processes requests through the HttpApplication pipeline. This pipeline also includes a set of events for validating requests, mapping URLs, accessing the cache, and more. These events are of interests to developers who want to extend the Application class.

Responding to Application Events

As said in the last item in the previous list, the HttpApplication class provides a several events you can handle to perform actions when ASP.NET raises certain events on the application level, the events wont work on a per-user level.
The following is some the most common events used by developers.
              • Application_Start  The Start event is raised when you application is started by IIS (usually as the result of a user request). This event is useful for initializing variables that are scoped at the application level.
              • Application_End  The End event is raised when your application stops or shuts down. This event is useful if you need to free application-level resources or perform some sort of logging.
              • Application_Error  The Error event is raised when an unhandled error occurs and rises up to the application scope. You should use this event to perform worst-case, catch-all error logging.
              • Application_LogRequest  The LogRequest event is raised when a request has been made to the application. You can use this event to write custom information regarding a request.
              • Application_PostLogRequest  The PostLogRequest event is raised after the logging of a request has completed.
              Other events include Application_BeginRequest, Application_EndRequest, ResolveRequestCahce, and many others.
              You can respond to these events by adding event handling methods in your Global.asax file.
              image
              The previous code tracks the number of requests made to the website, and store it in the global Application object.

              The Page Life Cycle

              Besides from the Applications life cycle there is also the Page life cycle for each page in a website. The following is a list of the page life cycle.
              1. The user makes a request to for a page.
              2. On the webserver, the ASP.NET compile the page (if necessary), or pull from cache (if available).
              3. (Start) Set request and response objects. Determine IsPostBack.
              4. (Init) Initialize page controls (but not their properties). Apply page theme.
              5. (Load) If PostBack, load control properties from view state.
              6. (Validation) Validate page and validator controls
              7. Call control event handlers (for PostBack request).
              8. (Rendering) Save view state. Render controls and display the page.
              9. (Unload) Unload request and response objects. Perform cleanup. Page is ready to be discarded. Return response to user.

              Responding to Page Events

              As with the Application events, the page raises various events through its stages. This events can be handled by the developer. It is important to know the order in which events are called, so that your code runs in the proper sequence. The following table shows a order list of the most common events of a page.
              EventDescrition
              PreIntThis is the first real event you might handle for a page. You usually use this event only if you need to set values such as master page or theme.
              This event is also useful when you are working with dynamically created controls for a page without a master page. You should create controls inside this event. If you have a master page or theme, create controls in the Init event.
              InitThis event fires after each control has been initialized. You can use this event to change initialization values for controls.
              If you need dynamically added controls to a content page, use this event.
              InitCompleteThis event is raised after all initializations of a page and its controls have been completed.
              PreLoadThis event fires before view state has been loaded for the page and its controls and before postback processing. This event is useful when you need to write code after the page is initialized but before the control view state has been re-established.
              LoadThe page is table at this time; it has been initialized and its state has been reconstructed. Code inside the page load event usually checks for postback and then sets control properties appropriately.
              The page’s load event is called first. Then the load event for each child control is called in turn (and then the load events for their child controls, if any).
              Control (postback) eventsASP.NET now calls any events on the page or its controls that caused the postback to occur. This might be a button’s click event, or a drop down list’s SelectedIndexChanged event.
              LoadCompleteAt this point all controls are loaded. If you need to do additional processing at this time, you can do so here.
              PreRenderThis event allows final changes to the page or its control. It takes place after all regular postback events have taken place. This event takes place before ViewState is saved, so any changes made here are saved.
              SaveStateCompletePrior to this event, the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored. This event is useful if you need to write processing that requires the view state to be set.
              RenderThis is a method of the page object and its controls (not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output.
              The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and scripts that are necessary to properly display a control on the browser.
              This method is useful if you are writing your own custom control. You override this method to control output for the control.
              UnloadThis event is used for cleanup code. You can use it to manually release resources, a process that is rarely necessary.

              Dynamically add controls to a page

              To dynamically add controls to a page you do this in the Page.PreInit event (when not using themes or master pages) or in Page.Init when using themes or master pages. The following example adds a textbox and a button and also handle the button Click event.
              image
              And the result looks like this.
              image
              After submit!
              image

              Control Life Cycles Events

              Controls such as Button and Textbox share a common life cycle with the Page class. Each server control, including Init, Load, Render, and Unload, goes through the same life cycle as a page.
              A control’s event is raised during the same event for its parent, so when a page executes the load event, all controls load event is also executed. And their child control executes the load event and so on.
              Controls in ASP.NET have default events that are usually handled by the developer. For example, the Page object’s default event is Load, and the Button object’s default event is the Click event.
              To handle a Page or Control event all you need to do is crate a Event Handle Method in the code behind file (C#). To do this you write a new method and set the method signature to comply to the event signature of the event. Like the following method to handle the Unload event for a button.
              image
              To programmatically add this event handler to the button you add a new EventHandler object to the Unload property of the button.
              image
              You can also set the event handler in the ASP.NET markup code like the following example.
              image

              Controlling the Automatic Postback

              A control like the Button always cause a postback to the server when clicked, but a control like DropDownList do not cause a postback when a user select a choise.
              To make a control do a postback on certain events you need to add the AutoPostBack=”true”
              image
              Now you need to add a event handler for the SelectedIndexChange event caused by the drop down list.
              image
              Then add a event handler to the SelecteIndexChanged property for the drop down list.
              image
              Now you can automatically handle selections on the drop down list in a method.

              No comments:

              Post a Comment