Friday, January 9, 2009

Understanding the ASP.NET Architecture Part - 3

The Page Class


A Page object is instanced every time an *.aspx page is requested. The Page object is responsible for processing a client request and rendering HTML in response. The Page object provides programmatic access to a Web form, plus access to the HTTP intrinsic objects such as HttpRequest and HttpResponse.
Every *.aspx page is associated with an instance of the Page class.

Specifically, the Web page inherits from a code-behind class, which in turn inherits from the Page class.
For example, the login.aspx page contains the following directive at the top of the file:

<%@ Page Language="C#" Codebehind="login.aspx.cs" Inherits="login" %>

Then, when you switch to the code-behind file, you see the following:

public class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Note that the Codebehind attribute simply indicates the location of the code-behind file. The Inherits attribute is what actually binds the Web form to a specific class. The @ Page directive supports a long list of attributes that control the Web form's behavior at runtime.

Several of these attributes override application-level settings in the Web.config file. For example, if the Web application has session state enabled, you can prevent an individual page from participating by setting its EnableSessionState directive to "False."

The @ Page Directive


The @ Page directive provides the three required attributes shown in the previous listing: Language, Codebehind, and Inherits. In addition, many others are set to "True" by default, which means they apply to the page even if they are missing from the @ Page directive. So, the @ Page directive is as much about disabling what you do not want as it is about enabling what you need.

You should always explicitly set three attributes:

  • AutoEventWireUp: This is a Boolean attribute that indicates whether Page events are wired into specific delegate functions ("True") or whether they can be wired into user-defined functions ("False"). If the attribute value is "True" (or, by default, if the attribute is missing), then the Page_Init() and Page_Load() event handlers will always be called, and they must be declared in a standard way. If the attribute value is "False," then the events are handled only if the user chooses, and they can be delegated to any function that supports the right interface for the event. Remember, Page events will always raise, but this does not mean you have to devote code and processing time to responding to the events. We always set this attribute value to "False."
  • EnableViewState: View state allows server controls to persist their contents and selected values between postings. View state is enabled by default for an entire page, but because it can have performance implications, you should set the Boolean attribute explicitly, even if you plan to keep view state enabled ("True"). View state is convenient, but it is not always needed. Typically, it is most convenient to keep view state intact for the overall page and disable it for individual controls.
  • EnableViewStateMac: This Boolean attribute indicates whether the view state contents should be encrypted and whether the server should inspect them for evidence of tampering on the client. The Mac portion of the attribute name stands for Machine Authentication Check. Many users have run into page loading problems when this attribute is omitted (which sets the attribute to "True," by default). Many users set this attribute value to "False." Microsoft hastens to point out that MAC encryption is not a replacement for a certificate-based encryption system such as Secure Socket Layer (SSL). If tampering is an issue for you, consider implementing a certificate-based encryption system rather than relying on MAC encoding.

Page Class Members


The Page class members roughly fall into three groups. The first group includes the properties and methods that manipulate the Web form controls. The second group includes properties that access the ASP Intrinsic objects. The third group includes the Page lifecycle events . Table 1 describes important members of the Page class that fall into the first two groups.

Table 1: The Page Class Members

CLASS MEMBER
DESCRIPTION
Controls
[Property] A collection of Control objects hosted on the page. You can iterate through the collection using for-each-next syntax. For example, to print out control type details, use this code:

foreach (Control objItem in Page.Controls)
{
    Console.WriteLine(objItem.GetType.ToString());
}

FindControl
[Method] Retrieves an object reference for a specific control on the page, using its ID. For example:

TextBox MyCtl = Page.FindControl("txt1");

HasControls
[Method] Determines if a server control contains child controls. For example, a GridView control may contain embedded (child) controls, such as textboxes and buttons.
IsPostBack
[Property] A Boolean value that indicates whether the current GET or POST request results from the current page posting back to itself. This property is typically checked in the Page_Load() event. If view state is enabled, this property often indicates that the page should be processed but not re-rendered. Because view state preserves the original contents of the Page controls, you will get duplicate items in the controls if they are re-rendered without first clearing the existing items. (This generalization may not apply to your page.)
Request
[Property] Gets a reference to the current HttpRequest instance, which encapsulates the client's request details.
Response
[Property] Gets a reference to the current HttpResponse instance, which encapsulates the server response details.
Application
[Property] Gets a reference to the Application object for the current request (which wraps the HttpApplicationState class). This class enables global application information to be shared across multiple requests and sessions.
Session
[Property] Gets a reference to the Session object for the current request (which wraps the HttpSessionState class). This class provides access to session-specific settings and values. ASP.NET provides several modes for storing session state.

Page Lifecycle Events


Recall that the Page object is responsible for processing a client request and rendering HTML in response. The Page object runs through a specific set of lifecycle stages as it fulfills its responsibilities. Several of these stages are associated with events that you can capture and code behind.

The Page class itself inherits from the Control and TemplateControl classes, both of which are members of the System.Web.UI namespace. The Control class provides a common set of properties, methods, and events that are shared by all server controls.

The TemplateControl class provides additional base functionality for the Page class. Together, these two classes provide the base events that the Page class raises, as well as base methods that the Page class can override.

Table 2 summarizes the more important lifecycle stages and their associated events, or the methods that can be overridden, for adding code to specific stages.

Table 2: The Page Lifecycle Stages
STAGE
DESCRIPTION
EVENT OR METHOD?
Initialize
Initializes settings.
The Page_Init event
Load Performs actions for all requests, including initializing server controls and restoring theirstate. The Page object provides an .Is PostBack property that will fire for posts (value is "False") and reposts (value is "True"). The .IsPostBack property allows you to set up conditional logic in the Load() event handler for handling the first post vs. subsequent reposts. You can check for postback data and can view state information for the Page's child controls. The Page_Load() event
Pre-Render The stage where remaining updates are performed prior to saving view state and rendering the form. You can add custom values to view state at this stage. The Page_PreRender() event
Save View State The stage where view state information is persisted to a hidden field on the form. The SaveStateComplete() method
Dispose
Releases resources and performs final cleanup, prior to unloading the Page object.
The Page_Disposed() event
Unload This stage is where the Page object is unloaded from server memory. You can perform cleanupand release resources in this stage, butdevelopers generally perform these tasks in the Page_Disposed() event.
The Page_Unload() event

The descriptions in Table 2 are specific to the Page object, but many of the events and methods apply equally to any server control. This should be of no surprise, given that the Page class inherits from the Control class, which is common to all server controls.

In addition, the Page object acts as a container for a collection of server controls, all of which run through their own processing stages. There is a complicated interplay between the controls' execution orders and the Page execution order.

This sequencing is of particular concern when you are developing a custom server control that handles postbacks and participates in view state.

Quoted.

No comments:

Post a Comment