The Page Class

 

The Page Class

In the .NET Framework, the Page class provides the basic behavior for all objects that an ASP.NET application builds by starting from .aspx files. Defined in the System.Web.UI namespace, the class derives from TemplateControl and implements the IHttpHandler interface:

public class Page : TemplateControl, IHttpHandler 

In particular, TemplateControl is the abstract class that provides both ASP.NET pages and user controls with a base set of functionality. At the upper level of the hierarchy, we find the Control class. It defines the properties, methods, and events shared by all ASP.NET server-side elements pages, controls, and user controls.

Derived from a class TemplateControl that implements INamingContainer, Page also serves as the naming container for all its constituent controls. In the .NET Framework, the naming container for a control is the first parent control that implements the INamingContainer interface. For any class that implements the naming container interface, ASP.NET creates a new virtual namespace in which all child controls are guaranteed to have unique names in the overall tree of controls. (This is also a very important feature for iterative data-bound controls, such as DataGrid, and for user controls.)

The Page class also implements the methods of the IHttpHandler interface, thus qualifying as the handler of a particular type of HTTP requests those for .aspx files. The key element of the IHttpHandler interface is the ProcessRequest method, which is the method the ASP.NET runtime calls to start the page processing that will actually serve the request.

Note 

INamingContainer is a marker interface that has no methods. Its presence alone, though, forces the ASP.NET runtime to create an additional namespace for naming the child controls of the page (or the control) that implements it. The Page class is the naming container of all the page's controls, with the clear exception of those controls that implement the INamingContainer interface themselves or are children of controls that implement the interface.

Properties of the Page Class

The properties of the Page object can be classified in three distinct groups: intrinsic objects, worker properties, and page-specific properties. The tables in the following sections enumerate and describe them.

Intrinsic Objects

Table 3-9 lists all properties that return a helper object that is intrinsic to the page. In other words, objects listed here are all essential parts of the infrastructure that allows for the page execution.

Table 3-9: ASP.NET Intrinsic Objects in the Page Class

Property

Description

Application

Instance of the HttpApplicationState class; represents the state of the application. It is functionally equivalent to the ASP intrinsic Application object.

Cache

Instance of the Cache class; implements the cache for an ASP.NET application. More efficient and powerful than Application, it supports item priority and expiration.

Request

Instance of the HttpRequest class; represents the current HTTP request. It is functionally equivalent to the ASP intrinsic Request object.

Response

Instance of the HttpResponse class; sends HTTP response data to the client. It is functionally equivalent to the ASP intrinsic Response object.

Server

Instance of the HttpServerUtility class; provides helper methods for processing Web requests. It is functionally equivalent to the ASP intrinsic Server object.

Session

Instance of the HttpSessionState class; manages user-specific data. It is functionally equivalent to the ASP intrinsic Session object.

Trace

Instance of the TraceContext class; performs tracing on the page.

User

An IPrincipal object that represents the user making the request.

We'll cover Request, Response, and Server in Chapter 12; Application and Session in Chapter 13; Cache will be the subject of Chapter 14. Finally, User and security will be the subject of Chapter 15.

Worker Properties

Table 3-10 details page properties that are both informative and provide the ground for functional capabilities. You can hardly write code in the page without most of these properties.

Table 3-10: Worker Properties of the Page Class

Property

Description

ClientScript

Gets a ClientScriptManager object that contains the client script used on the page. Not available with ASP.NET 1.x.

Controls

Returns the collection of all the child controls contained in the current page.

ErrorPage

Gets or sets the error page to which the requesting browser is redirected in case of an unhandled page exception.

Form

Returns the current HtmlForm object for the page. Not available with ASP.NET 1.x.

Header

Returns a reference to the object that represents the page's header. The object implements IPageHeader. Not available with ASP.NET 1.x.

IsAsync

Indicates whether the page is being invoked through an asynchronous handler. Not available with ASP.NET 1.x.

IsCallback

Indicates whether the page is being loaded in response to a client script callback. Not available with ASP.NET 1.x.

IsCrossPagePostBack

Indicates whether the page is being loaded in response to a postback made from within another page. Not available with ASP.NET 1.x.

IsPostBack

Indicates whether the page is being loaded in response to a client postback or whether it is being loaded for the first time.

IsValid

Indicates whether page validation succeeded.

Master

Instance of the MasterPage class; represents the master page that determines the appearance of the current page. Not available with ASP.NET 1.x.

MasterPageFile

Gets and sets the master file for the current page. Not available with ASP.NET 1.x.

NamingContainer

Returns null.

Page

Returns the current Page object.

PageAdapter

Returns the adapter object for the current Page object.

Parent

Returns null.

PreviousPage

Returns the reference to the caller page in case of a cross-page postback. Not available with ASP.NET 1.x.

TemplateSourceDirectory

Gets the virtual directory of the page.

Validators

Returns the collection of all validation controls contained in the page.

ViewStateUserKey

String property that represents a user-specific identifier used to hash the view-state contents. This trick is a line of defense against one-click attacks. Not available with ASP.NET 1.0.

In the context of an ASP.NET application, the Page object is the root of the hierarchy. For this reason, inherited properties such as NamingContainer and Parent always return null. The Page property, on the other hand, returns an instance of the same object (this in C# and Me in Visual Basic .NET).

The ViewStateUserKey property that has been added with version 1.1 of the .NET Framework deserves a special mention. A common use for the user key would be to stuff user-specific information that would then be used to hash the contents of the view state along with other information. (See Chapter 13.) A typical value for the ViewStateUserKey property is the name of the authenticated user or the user's session ID. This contrivance reinforces the security level for the view state information and further lowers the likelihood of attacks. If you employ a user-specific key, an attacker can't construct a valid view state for your user account unless the attacker can also authenticate as you. With this configuration, you have another barrier against one-click attacks. This technique, though, might not be effective for Web sites that allow anonymous access, unless you have some other unique tracking device running.

Note that if you plan to set the ViewStateUserKey property, you must do that during the Page_Init event. If you attempt to do it later (for example, when Page_Load fires), an exception will be thrown.

Context Properties

Table 3-11 lists properties that represent visual and nonvisual attributes of the page, such as the URL's query string, the client target, the title, and the applied style sheet.

Table 3-11: Page-Specific Properties of the Page Class

Property

Description

ClientID

Always returns the empty string.

ClientQueryString

Gets the query string portion of the requested URL. Not available with ASP.NET 1.x.

ClientTarget

Set to the empty string by default; allows you to specify the type of the browser the HTML should comply with. Setting this property disables automatic detection of browser capabilities.

EnableViewState

Indicates whether the page has to manage view-state data. You can also enable or disable the view-state feature through the EnableViewState attribute of the @Page directive.

EnableViewStateMac

Indicates whether ASP.NET should calculate a machine-specific authentication code and append it to the page view state.

EnableTheming

Indicates whether the page supports themes. Not available with ASP.NET 1.x.

ID

Always returns the empty string.

MaintainScrollPositionOnPostback

Indicates whether to return the user to the same position in the client browser after postback. Not available with ASP.NET 1.x.

SmartNavigation

Indicates whether smart navigation is enabled. Smart navigation exploits a bunch of browser-specific capabilities to enhance the user's experience with the page. The feature requires Internet Explorer 5.5 or newer.

StyleSheetTheme

Gets or sets the name of the style sheet applied to this page. Not available with ASP.NET 1.x.

Theme

Gets and sets the theme for the page. Note that themes can be programmatically set only in the PreInit event. Not available with ASP.NET 1.x.

Title

Gets or sets the title for the page. Not available with ASP.NET 1.x.

TraceEnabled

Toggles page tracing on and off. Not available with ASP.NET 1.x.

TraceModeValue

Gets or sets the trace mode. Not available with ASP.NET 1.x.

UniqueID

Always returns the empty string.

ViewStateEncryptionMode

Indicates if and how the view state should be encrypted.

Visible

Indicates whether ASP.NET has to render the page. If you set Visible to false, ASP.NET doesn't generate any HTML code for the page. When Visible is false, only the text explicitly written using Response.Write hits the client.

The three ID properties (ID, ClientID, and UniqueID) always return the empty string from a Page object. They make sense only for server controls.

Methods of the Page Class

The whole range of Page methods can be classified in a few categories based on the tasks each method accomplishes. A few methods are involved with the generation of the markup for the page; others are helper methods to build the page and manage the constituent controls. Finally, a third group collects all the methods that have to do with client-side scripting.

Rendering Methods

Table 3-12 details the methods that are directly or indirectly involved with the generation of the markup code.

Table 3-12: Methods for Markup Generation

Method

Description

DataBind

Binds all the data-bound controls contained in the page to their data sources. The DataBind method doesn't generate code itself but prepares the ground for the forthcoming rendering.

RenderControl

Outputs the HTML text for the page, including tracing information if tracing is enabled.

VerifyRenderingInServerForm

Controls call this method when they render to ensure that they are included in the body of a server form. The method does not return a value, but it throws an exception in case of error.

In an ASP.NET page, no control can be placed outside a <form> tag with the runat attribute set to server. The VerifyRenderingInServerForm method is used by Web and HTML controls to ensure that they are rendered correctly. In theory, custom controls should call this method during the rendering phase. In many situations, the custom control embeds or derives an existing Web or HTML control that will make the check itself.

Not directly exposed by the Page class, but strictly related to it, is the GetWebResourceUrl method on the ClientScriptManager class in ASP.NET 2.0. The method provides a long-awaited feature to control developers. When you develop a control, you typically need to embed static resources such as images or client script files. You can make these files be separate downloads but, even though it's effective, the solution looks poor and inelegant. Visual Studio .NET 2003 and newer versions allow you to embed resources in the control assembly, but how would you retrieve these resources programmatically and bind them to the control? For example, to bind an assembly-stored image to an <IMG> tag, you need a URL for the image. The GetWebResourceUrl method returns a URL for the specified resource. The URL refers to a new Web Resource service (webresource.axd) that retrieves and returns the requested resource from an assembly.

// Bind the <IMG> tag to the given GIF image in the control's assembly img.ImageUrl = Page.GetWebResourceUrl (typeof(TheControl), GifName)); 

GetWebResourceUrl requires a Type object, which will be used to locate the assembly that contains the resource. The assembly is identified with the assembly that contains the definition of the specified type in the current AppDomain. If you're writing a custom control, the type will likely be the control's type. As its second argument, the GetWebResourceUrl method requires the name of the embedded resource. The returned URL takes the following form:

WebResource.axd?a=assembly&r=resourceName&t=timestamp 

The timestamp value is the current timestamp of the assembly, and it is added to make the browser download resources again should the assembly be modified.

Controls-Related Methods

Table 3-13 details a bunch of helper methods on the Page class architected to let you manage and validate child controls and resolve URLs.

Table 3-13: Helper Methods of the Page Object

Method

Description

DesignerInitialize

Initializes the instance of the Page class at design time, when the page is being hosted by RAD designers such as Visual Studio.

FindControl

Takes a control's ID and searches for it in the page's naming container. The search doesn't dig out child controls that are naming containers themselves.

GetTypeHashCode

Retrieves the hash code generated by ASP.xxx_aspx page objects at run time. In the base Page class, the method implementation simply returns 0; significant numbers are returned by classes used for actual pages.

GetValidators

Returns a collection of control validators for a specified validation group. Not available with ASP.NET 1.x.

HasControls

Determines whether the page contains any child controls.

LoadControl

Compiles and loads a user control from an .ascx file, and returns a Control object. If the user control supports caching, the object returned is PartialCachingControl.

LoadTemplate

Compiles and loads a user control from an .ascx file, and returns it wrapped in an instance of an internal class that implements the ITemplate interface. The internal class is named SimpleTemplate.

MapPath

Retrieves the physical, fully qualified path that an absolute or relative virtual path maps to.

ParseControl

Parses a well-formed input string, and returns an instance of the control that corresponds to the specified markup text. If the string contains more controls, only the first is taken into account. The runat attribute can be omitted. The method returns an object of type Control and must be cast to a more specific type.

RegisterRequiresControlState

Registers a control as one that requires control state. Not available with ASP.NET 1.x.

RegisterRequiresPostBack

Registers the specified control to receive a postback handling notice, even if its ID doesn't match any ID in the collection of posted data. The control must implement the IPostBackData-Handler interface.

RegisterRequiresRaiseEvent

Registers the specified control to handle an incoming postback event. The control must implement the IPostBackEventHandler interface.

RegisterViewStateHandler

Mostly for internal use, the method sets an internal flag causing the page view state to be persisted. If this method is not called in the prerendering phase, no view state will ever be written. Typically, only the HtmlForm server control for the page calls this method. There's no need to call it from within user applications.

ResolveUrl

Resolves a relative URL into an absolute URL based on the value of the TemplateSourceDirectory property.

Validate

Instructs any validation controls included on the page to validate their assigned information. ASP.NET 2.0 supports validation groups.

The methods LoadControl and LoadTemplate share a common code infrastructure but return different objects, as the following pseudocode shows:

public Control LoadControl(string virtualPath) {     Control ascx = GetCompiledUserControlType(virtualPath);     ascx.InitializeAsUserControl();     return ascx; } public ITemplate LoadTemplate(string virtualPath) {     Control ascx = GetCompiledUserControlType(virtualPath);     return new SimpleTemplate(ascx); } 

Both methods differ from ParseControl in that the latter never causes compilation but simply parses the string and infers control information. The information is then used to create and initialize a new instance of the control class. As mentioned, the runat attribute is unnecessary in this context. In ASP.NET, the runat attribute is key, but in practice, it has no other role than marking the surrounding markup text for parsing and instantiation. It does not contain information useful to instantiate a control, and for this reason it can be omitted from the strings you pass directly to ParseControl.

Script-Related Methods

Table 3-14 enumerates all the methods in the Page class that have to do with HTML and script code to be inserted in the client page.

Table 3-14: Script-Related Methods

Method

Description

GetCallbackEventReference

Obtains a reference to a client-side function that, when invoked, initiates a client call back to server-side events. Not available with ASP.NET 1.x.

GetPostBackClientEvent

Calls into GetCallbackEventReference.

GetPostBackClientHyperlink

Appends javascript: to the beginning of the return string received from GetPostBackEventReference.

javascript:__doPostBack('CtlID','')

GetPostBackEventReference

Returns the prototype of the client-side script function that causes, when invoked, a postback. It takes a Control and an argument, and it returns a string like this:

__doPostBack('CtlID','')

IsClientScriptBlockRegistered

Determines whether the specified client script is registered with the page. Marked as obsolete.

IsStartupScriptRegistered

Determines whether the specified client startup script is registered with the page. Marked as obsolete.

RegisterArrayDeclaration

Use this method to add an ECMAScript array to the client page. This method accepts the name of the array and a string that will be used verbatim as the body of the array. For example, if you call the method with arguments such as theArray and "'a', 'b'", you get the following JavaScript code:

var theArray = new Array('a', 'b');

Marked as obsolete.

RegisterClientScriptBlock

An ASP.NET page uses this method to emit client-side script blocks in the client page just after the opening tag of the HTML <form> element. Marked as obsolete.

RegisterHiddenField

Use this method to automatically register a hidden field on the page. Marked as obsolete.

RegisterOnSubmitStatement

Use this method to emit client script code that handles the client OnSubmit event. The script should be a JavaScript function call to client code registered elsewhere. Marked as obsolete.

RegisterStartupScript

An ASP.NET page uses this method to emit client-side script blocks in the client page just before closing the HTML <form> element. Marked as obsolete.

SetFocus

Sets the browser focus to the specified control. Not available with ASP.NET 1.x.

As you can see, some methods in Table 3-14, which are defined and usable in ASP.NET 1.x, have been marked as obsolete. In ASP.NET 2.0 applications, you should avoid calling them and resort to methods with the same name exposed out of the ClientScript property. (See Table 3-10.)

// Avoid this in ASP.NET 2.0 Page.RegisterArrayDeclaration( ); // Use this in ASP.NET 2.0 Page.ClientScript.RegisterArrayDeclaration( ); 

Methods listed in Table 3-14 let you emit script in the client page either JavaScript or VBScript. When you use any of these methods, you actually tell the page to insert that script code when the page is rendered. So when any of these methods execute, the script-related information is simply cached in internal structures and used later when the page object generates its HTML text.

Note 

JavaScript is the script language that virtually any available browser supports. For this reason, some of the methods in Table 3-14 default to JavaScript. However, when you register a script block, nothing really prevents you from using VBScript as long as you set the language attribute of the <script> tag accordingly. On the other hand, methods such as RegisterOnSubmitStatement and RegisterArrayDeclaration can be used only with JavaScript code.

Events of the Page Class

The Page class fires a few events that are notified during the page life cycle. As Table 3-15 shows, some events are orthogonal to the typical life cycle of a page (initialization, postback, rendering phases) and are fired as extra-page situations evolve. Let's briefly review the events and then attack the topic with an in-depth discussion on the page life cycle.

Table 3-15: Events That a Page Can Fire

Event

Description

AbortTransaction

Occurs for ASP.NET pages marked to participate in an automatic transaction when a transaction aborts.

CommitTransaction

Occurs for ASP.NET pages marked to participate in an automatic transaction when a transaction commits.

DataBinding

Occurs when the DataBind method is called on the page to bind all the child controls to their respective data sources.

Disposed

Occurs when the page is released from memory, which is the last stage of the page life cycle.

Error

Occurs when an unhandled exception is thrown.

Init

Occurs when the page is initialized, which is the first step in the page life cycle.

InitComplete

Occurs when all child controls and the page have been initialized. Not available in ASP.NET 1.x.

Load

Occurs when the page loads up, after being initialized.

LoadComplete

Occurs when the loading of the page is completed and server events have been raised. Not available in ASP.NET 1.x.

PreInit

Occurs just before the initialization phase of the page begins. Not available in ASP.NET 1.x.

PreLoad

Occurs just before the loading phase of the page begins. Not available in ASP.NET 1.x.

PreRender

Occurs when the page is about to render.

PreRenderComplete

Occurs just before the pre-rendering phase begins. Not available in ASP.NET 1.x.

SaveStateComplete

Occurs when the view state of the page has been saved to the persistence medium. Not available in ASP.NET 1.x.

Unload

Occurs when the page is unloaded from memory but not yet disposed.

The Eventing Model

When a page is requested, its class and the server controls it contains are responsible for executing the request and rendering HTML back to the client. The communication between the client and the server is stateless and disconnected because of the HTTP protocol. Real-world applications, though, need some state to be maintained between successive calls made to the same page. With ASP, and with other server-side development platforms such as Java Server Pages and LAMP, the programmer is entirely responsible for persisting the state. In contrast, ASP.NET provides a built-in infrastructure that saves and restores the state of a page in a transparent manner. In this way, and in spite of the underlying stateless protocol, the client experience appears to be that of a continuously executing process. It's just an illusion, though.

Introducing the View State

The illusion of continuity is created by the view state feature of ASP.NET pages and is based on some assumptions about how the page is designed and works. Also, server-side Web controls play a remarkable role. In brief, before rendering its contents to HTML, the page encodes and stuffs into a persistence medium (typically, a hidden field) all the state information that the page itself and its constituent controls want to save. When the page posts back, the state information is deserialized from the hidden field and used to initialize instances of the server controls declared in the page layout.

The view state is specific to each instance of the page because it is embedded in the HTML. The net effect of this is that controls are initialized with the same values they had the last time the view state was created that is, the last time the page was rendered to the client. Furthermore, an additional step in the page life cycle merges the persisted state with any updates introduced by client-side actions. When the page executes after a postback, it finds a stateful and up-to-date context just as it is working over a continuous point-to-point connection.

Two basic assumptions are made. The first assumption is that the page always posts to itself and carries its state back and forth. The second assumption is that the server-side controls have to be declared with the runat=server attribute to spring to life once the page posts back.

The Single Form Model

Admittedly, for programmers whose experience is with ASP, the single form model of ASP.NET can be difficult to understand. These programmers frequently ask questions on forums and newsgroups such as, "Where's the Action property of the form?" and "Why can't I redirect to a particular page when a form is submitted?"

ASP.NET pages are built to support exactly one server-side <form> tag. The form must include all the controls you want to interact with on the server. Both the form and the controls must be marked with the runat attribute; otherwise, they will be considered as plain text to be output verbatim. A server-side form is an instance of the HtmlForm class. The HtmlForm class does not expose any property equivalent to the Action property of the HTML <form> tag. The reason is that an ASP.NET page always posts to itself. Unlike the Action property, other common form properties such as Method and Target are fully supported.

Valid ASP.NET pages are also those that have no server-side forms and those that run HTML forms a <form> tag without the runat attribute. In an ASP.NET page, you can also have both HTML and server forms. In no case, though, can you have more than one <form> tag with the runat attribute set to server. HTML forms work as usual and let you post to any page in the application. The drawback is that in this case no state will be automatically restored. In other words, the ASP.NET Web Forms model works only if you use exactly one server <form> element. We'll return to this topic in Chapter 5.

Note 

ASP.NET pages are served by a HTTP handler like an instance of the Page class. Each request takes up a thread in the ASP.NET thread pool and releases it only when the request completes. What if a frequently requested page starts an external and particularly lengthy task? The risk is that the ASP.NET process is idle but has no free threads in the pool to serve incoming requests for other pages. This is mostly due to the fact that HTTP handlers, including page classes, work synchronously. To alleviate this issue, ASP.NET supports asynchronous handlers since version 1.0 through the IHttpAsyncHandler interface. In ASP.NET 2.0, creating asynchronous pages is even easier thanks to a specific support from the framework. We'll cover this topic in great detail in Programming Microsoft ASP.NET 2.0 Applications: Advanced Topics (Microsoft Press, 2005).

 


Programming Microsoft ASP. Net 2.0 Core Reference
Programming Microsoft ASP.NET 2.0 Core Reference
ISBN: 0735621764
EAN: 2147483647
Year: 2004
Pages: 112
Authors: Dino Esposito
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net