Invoking a Page

 

Let's start by examining in detail how the .aspx page is converted into a class and then compiled into an assembly. Generating an assembly for a particular .aspx resource is a two-step process. First, the source code of the resource file is parsed and a corresponding class is created that inherits either from Page or another class that, in turn, inherits from Page. Second, the dynamically generated class is compiled into an assembly and cached in an ASP.NET-specific temporary directory.

The compiled page remains in use as long as no changes occur to the linked .aspx source file or the whole application is restarted. Any changes to the linked .aspx file invalidates the current page-specific assembly and forces the HTTP runtime to create a new assembly on the next request for page.

Note 

Editing files such as web.config and global.asax causes the whole application to restart. In this case, all the pages will be recompiled as soon as each page is requested. The same happens if a new assembly is copied or replaced in the application's Bin folder.

The Runtime Machinery

All resources that you can access on an Internet Information Server (IIS)-based Web server are grouped by file extension. Any incoming request is then assigned to a particular runtime module for actual processing. Modules that can handle Web resources within the context of IIS are Internet Server Application Programming Interface (ISAPI) extensions that is, plain old Win32 dynamic-link libraries (DLLs) that expose, much like an interface, a bunch of API functions with predefined names and prototypes. IIS and ISAPI extensions use these DLL entries as a sort of private communication protocol. When IIS needs an ISAPI extension to accomplish a certain task, it simply loads the DLL and calls the appropriate function with valid arguments. Although the ISAPI documentation doesn't mention an ISAPI extension as an interface, it is just that a module that implements a well-known programming interface.

When the request for a resource arrives, IIS first verifies the type of the resource. Static resources such as images, text files, HTML pages, and scriptless ASP pages are resolved directly by IIS without the involvement of external modules. IIS accesses the file on the local Web server and flushes its contents to the output console so that the requesting browser can get it. Resources that require server-side elaboration are passed on to the registered module. For example, ASP pages are processed by an ISAPI extension named asp.dll. In general, when the resource is associated with executable code, IIS hands the request to that executable for further processing. Files with an .aspx extension are assigned to an ISAPI extension named aspnet_isapi.dll, as shown in Figure 3-1.

image from book
Figure 3-1: The IIS application mappings for resources with an .aspx extension.

Resource mappings are stored in the IIS metabase. Upon installation, ASP.NET modifies the IIS metabase to make sure that aspnet_isapi.dll can handle some typical ASP.NET resources. Table 3-1 lists some of these resources.

Table 3-1: IIS Application Mappings for aspnet_isapi.dll

Extension

Resource Type

.asax

ASP.NET application files. The typical example is global.asax.

.ascx

ASP.NET user control files.

.ashx

HTTP handlers, namely managed modules that interact with the low-level request and response services of IIS.

.asmx

Files that implement .NET Web services.

.aspx

Files that represent ASP.NET pages.

.axd

Extension that identifies internal HTTP handlers used to implement system features such as application-level tracing (trace.axd) or script injection (webresource.axd).

In addition, the aspnet_isapi.dll extension handles other typical Microsoft Visual Studio .NET extensions such as .cs, .csproj, .vb, .vbproj, .config, .resx.

As mentioned in Chapter 1, the exact behavior of the ASP.NET ISAPI extension depends on the process model selected for the application.

IIS 5.0 Process Model

The IIS 5.0 process model is the only option you have if you host your ASP.NET application on any version of Microsoft Windows prior to Windows 2003 Server. According to this processing model, aspnet_isapi.dll doesn't process the .aspx file, but instead acts as a dispatcher. It collects all the information available about the invoked URL and the underlying resource, and then it routes the request toward another distinct process the ASP.NET worker process named aspnet_wp.exe. The communication between the ISAPI extension and worker process takes place through named pipes.

The whole diagram is illustrated in Figure 3-2.

image from book
Figure 3-2: The ASP.NET runtime environment according to the IIS 5.0 process model.

A single copy of the worker process runs all the time and hosts all the active Web applications. The only exception to this situation is when you have a Web server with multiple CPUs. In this case, you can configure the ASP.NET runtime so that multiple worker processes run, one per each available CPU. For example, you might want to do this if you have multiple CPUs and need to run code that is thread safe, but not so safe as to assume it works well in a multiprocessor environment. A model in which multiple processes run on multiple CPUs in a single-server machine is known as a Web garden and is controlled by attributes on the <processModel> section in the machine.config file.

When a single worker process is used by all CPUs and controls all Web applications, it doesn't necessarily mean that no process isolation is achieved. Each Web application is, in fact, identified with its virtual directory and belongs to a distinct application domain, commonly referred to as an AppDomain. A new AppDomain is created within the ASP.NET worker process whenever a client addresses a virtual directory for the first time. After creating the new AppDomain, the ASP.NET runtime loads all the needed assemblies and passes control to the hosted HTTP pipeline to actually service the request.

If a client requests a page from an already running Web application, the ASP.NET runtime simply forwards the request to the existing AppDomain associated with that virtual directory. If the assembly needed to process the page is not loaded in the AppDomain, it will be created on the fly; otherwise, if it was already created upon the first call, it will be simply used.

IIS 6.0 Process Model

The IIS 6.0 process model is the default option for ASP.NET when the Web server operating system is Windows 2003 Server. As the name of the process model clearly suggests, this model requires IIS 6.0. However, on a Windows 2003 Server machine you can still have ASP.NET play by the rules of the IIS 5.0 process model. If this is what you want, explicitly enable the model by tweaking the <processModel> section of the machine.config file.

<processModel enable="true"> 

Be aware that switching back to the old IIS 5.0 process model is not a recommended practice, although it is perfectly legal. The main reason lies in the fact that IIS 6.0 employs a different pipeline of internal modules to process an inbound request and can mimic the behavior of IIS 5.0 only if running in emulation mode. The IIS 6.0 pipeline is centered around a generic worker process named w3wp.exe. A copy of this executable is shared by all Web applications assigned to the same application pool. In the IIS 6.0 jargon, an application pool is a group of Web applications that share the same copy of the worker process. IIS 6.0 lets you customize the application pools to achieve the degree of isolation that you need for the various applications hosted on a Web server.

The w3wp.exe worker process loads aspnet_isapi.dll; the ISAPI extension, in turn, loads the common language runtime (CLR) and starts the ASP.NET runtime pipeline to process the request. When the IIS 6.0 process model is in use, the built-in ASP.NET worker process is disabled.

Note 

Only ASP.NET 1.1 fully takes advantage of the IIS 6.0 process model. If you install ASP.NET 1.0 on a Windows 2003 Server machine, the process model will default to the IIS 5.0 process model. This happens because only the version of aspnet_isapi.dll that ships with ASP.NET 1.1 is smart enough to recognize its host and load the CLR if needed. The aspnet_isapi.dll included in ASP.NET 1.0 is limited to forwarding requests to the ASP.NET worker process and never loads the CLR.

Figure 3-3 shows how ASP.NET applications and other Web applications are processed in IIS 6.0.

image from book
Figure 3-3: How ASP.NET and Web applications are processed in IIS 6.0.

IIS 6.0 implements its HTTP listener as a kernel-level module. As a result, all incoming requests are first managed by such a driver http.sys and in kernel mode. No third-party code ever interacts with the listener, and no user-mode crashes will ever affect the stability of IIS. The http.sys driver listens for requests and posts them to the request queue of the appropriate application pool. A module called the Web Administration Service (WAS) reads from the IIS metabase and instructs the http.sys driver to create as many request queues as there are application pools registered in the metabase.

In summary, in the IIS 6.0 process model, ASP.NET runs even faster because no interprocess communication between inetinfo.exe (the IIS executable) and the worker process is required. The HTTP request is delivered directly at the worker process that hosts the CLR. Furthermore, the ASP.NET worker process is not a special process but simply a copy of the IIS worker process. This fact shifts to IIS the burden of process recycling, page output caching, and health checks.

In the IIS 6.0 process model, ASP.NET ignores most of the contents of the <processModel> section from the machine.config file. Only thread and deadlock settings are read from that section of machine.config. Everything else goes through the metabase and can be configured only by using the IIS Manager. (Other configuration information continues being read from .config files.)

Representing the Requested Page

Each incoming request that refers to an .aspx resource is mapped to, and served through, a Pagederived class. The ASP.NET HTTP runtime environment first determines the name of the class that will be used to serve the request. A particular naming convention links the URL of the page to the name of the class. If the requested page is, say, default.aspx, the associated class turns out to be ASP.default_aspx. If no class exists with that name in any of the assemblies currently loaded in the AppDomain, the HTTP runtime orders that the class be created and compiled. The source code for the class is created by parsing the source code of the .aspx resource, and it's temporarily saved in the ASP.NET temporary folder. Next, the class is compiled and loaded in memory to serve the request. When a new request for the same page arrives, the class is ready and no compile step will ever take place. (The class will be re-created and recompiled only if the timestamp of the .aspx source changes.)

The ASP.default_aspx class inherits from Page or from a class that in turn inherits from Page. In most cases, the base class for ASP.default_aspx will be a combination of the code-behind, partial class created through Visual Studio .NET and a second partial class dynamically arranged by the ASP.NET HTTP runtime. Figure 3-4 provides a graphical demonstration of how the source code of the dynamic page class is built.

image from book
Figure 3-4: ASP.NET generates the source code for the dynamic class that will serve a request.

Partial classes are a hot feature of the new generation of .NET compilers. When partially declared, a class has its source code split over multiple source files, each of which appears to contain an ordinary class definition from beginning to end. The new keyword partial, though, informs the compiler that the class declaration being processed is incomplete. To get full and complete source code, the compiler must look into other files specified on the command line.

Partial Classes in ASP.NET Projects

Ideal for team development, partial classes simplify coding and avoid manual file synchronization in all situations in which a mix of user-defined and tool-generated code is used. Want an illustrious example? ASP.NET projects developed with Visual Studio .NET.

Partial classes are a compiler feature specifically designed to overcome the brittleness of toolgenerated code in many Visual Studio .NET projects, including ASP.NET projects. A savvy use of partial classes allows you to eliminate all those weird, auto-generated, semi-hidden regions of code that Visual Studio .NET 2003 inserts to support page designers.

Generally, partial classes are a source-level, assembly-limited, non-object-oriented way to extend the behavior of a class. A number of advantages are derived from intensive use of partial classes. For example, you can have multiple teams at work on the same component at the same time. In addition, you have a neat and elegant way to add functionality to a class incrementally. In the end, this is just what the ASP.NET runtime does.

The ASPX markup defines server controls that will be handled by the code in the code-behind class. For this model to work, the code-behind class needs to incorporate references to these server controls as internal members typically, protected members. In Visual Studio .NET 2003, these declarations are added by the integrated development environment (IDE) as you save your markup and stored in semi-hidden regions. In Visual Studio .NET 2005, the codebehind class is a partial class that just lacks members declaration. Missing declarations are incrementally added at run time via a second partial class created by the ASP.NET HTTP runtime. The compiler of choice (C#, Microsoft Visual Basic .NET, or whatever) will then merge the two partial classes to create the real parent of the dynamically created page class.

Processing the Request

To serve a request for a page named default.aspx, the ASP.NET runtime needs to get a reference to a class ASP.default_aspx. If this class doesn't exist in any of the assemblies currently loaded in the AppDomain, it will be created. Next, the HTTP runtime environment invokes the class through the methods of a well-known interface IHttpHandler. The root Page class implements this interface, which includes a couple of members the ProcessRequest method and the Boolean IsReusable property. Once the HTTP runtime has obtained an instance of the class that represents the requested resource, invoking the ProcessRequest method a public method gives birth to the process that culminates in the generation of the final response for the browser. As mentioned, the steps and events that execute and trigger out of the call to ProcessRequest are collectively known as the page life cycle.

Unlike ASP pages, ASP.NET pages are not simply parsed and served to the user. While serving pages is the ultimate goal of the ASP.NET runtime, the way in which the resultant markup code is generated is much more sophisticated than in ASP and involves many more objects. The ASP.NET worker process be it w3wp.exe or aspnet_wp.exe passes any incoming HTTP requests to the so-called HTTP pipeline. The HTTP pipeline is a fully extensible chain of managed objects that works according to the classic concept of a pipeline. All these objects form what is often referred to as the ASP.NET HTTP runtime environment.

The HttpRuntime Object

A page request passes through a pipeline of objects that process the original HTTP payload and, at the end of the chain, produce some markup code for the browser. The entry point in this pipeline is the HttpRuntime class. The ASP.NET worker process activates the HTTP pipeline by creating a new instance of the HttpRuntime class and then calling its ProcessRequest method. For the sake of clarity, note that despite the name, HttpRuntime.ProcessRequest has nothing to do with the IHttpHandler interface.

The HttpRuntime class contains a lot of private and internal methods and only three public static methods: Close, ProcessRequest, and UnloadAppDomain, as detailed in Table 3-2.

Table 3-2: Public Methods in the HttpRuntime Class

Method

Description

Close

Removes all items from the ASP.NET cache, and terminates the Web application. This method should be used only when your code implements its own hosting environment. There is no need to call this method in the course of normal ASP.NET request processing.

ProcessRequest

Drives all ASP.NET Web processing execution.

UnloadAppDomain

Terminates the current ASP.NET application. The application restarts the next time a request is received for it.

It is important to note that all the methods shown in Table 3-2 have a limited applicability in user applications. In particular, you're not supposed to use ProcessRequest in your own code, whereas Close is useful only if you're hosting ASP.NET in a custom application. Of the three methods in Table 3-2, only UnloadAppDomain can be considered for use if, under certain runtime conditions, you realize you need to restart the application. (See the sidebar "What Causes Application Restarts?" later in this chapter.)

Upon creation, the HttpRuntime object initializes a number of internal objects that will help carry out the page request. Helper objects include the cache manager and the file system monitor used to detect changes in the files that form the application. When the ProcessRequest method is called, the HttpRuntime object starts working to serve a page to the browser. It creates a new context for the request and initializes a specialized text writer object in which the markup code will be accumulated. A context is given by an instance of the HttpContext class, which encapsulates all HTTP-specific information about the request.

After that, the HttpRuntime object uses the context information to either locate or create a Web application object capable of handling the request. A Web application is searched using the virtual directory information contained in the URL. The object used to find or create a new Web application is HttpApplicationFactory an internal-use object responsible for returning a valid object capable of handling the request.

Before we get to discover more about the various components of the HTTP pipeline, a look at Figure 3-5 is in order.

image from book
Figure 3-5: The HTTP pipeline processing for a page.

The Application Factory

During the lifetime of the application, the HttpApplicationFactory object maintains a pool of HttpApplication objects to serve incoming HTTP requests. When invoked, the application factory object verifies that an AppDomain exists for the virtual folder the request targets. If the application is already running, the factory picks an HttpApplication out of the pool of available objects and passes it the request. A new HttpApplication object is created if an existing object not be available.

If the virtual folder has not yet been called for the first time, a new HttpApplication object for the virtual folder is created in a new AppDomain. In this case, the creation of an HttpApplication object entails the compilation of the global.asax application file, if one is present, and the creation of the assembly that represents the actual page requested. This event is actually equivalent to the start of the application. An HttpApplication object is used to process a single page request at a time; multiple objects are used to serve simultaneous requests.

The HttpApplication Object

HttpApplication is the base class that represents a running ASP.NET application. A running ASP.NET application is represented by a dynamically created class that inherits from HttpApplication. The source code of the dynamically generated application class is created by parsing the contents of the global.asax file, if any is present. If global.asax is available, the application class is built and named after it: ASP.global_asax. Otherwise, the base HttpApplication class is used.

An instance of an HttpApplication-derived class is responsible for managing the entire lifetime of the request it is assigned to. The same instance can be reused only after the request has been completed. The HttpApplication maintains a list of HTTP module objects that can filter and even modify the content of the request. Registered modules are called during various moments of the elaboration as the request passes through the pipeline.

The HttpApplication object determines the type of object that represents the resource being requested typically, an ASP.NET page, a Web service, or perhaps a user control. HttpApplication then uses the proper handler factory to get an object that represents the requested resource. The factory either instantiates the class for the requested resource from an existing assembly or dynamically creates the assembly and then an instance of the class. A handler factory object is a class that implements the IHttpHandlerFactory interface and is responsible for returning an instance of a managed class that can handle the HTTP request an HTTP handler. An ASP.NET page is simply a handler object that is, an instance of a class that implements the IHttpHandler interface.

The Page Factory

The HttpApplication class determines the type of object that must handle the request and delegates the type-specific handler factory to create an instance of that type. Let's see what happens when the resource requested is a page.

Once the HttpApplication object in charge of the request has figured out the proper handler, it creates an instance of the handler factory object. For a request that targets a page, the factory is a class named PageHandlerFactory. To find the appropriate handler, HttpApplication uses the information in the <httpHandlers> section of the configuration file. Table 3-3 contains a brief list of the main handlers registered.

Table 3-3: Handler Factory Classes in the .NET Framework

Handler Factory

Type

Description

HttpRemotingHandlerFactory

*.rem;

*.soap

Instantiates the object that will take care of a .NET

Remoting request routed through IIS. Instantiates an object of type HttpRemotingHandler.

PageHandlerFactory

*.aspx

Compiles and instantiates the type that represents the page. The source code for the class is built while parsing the source code of the .aspx file. Instantiates an object of a type that derives from Page.

SimpleHandlerFactory

*.ashx

Compiles and instantiates the specified HTTP handler from the source code of the .ashx file. Instantiates an object that implements the IHttpHandler interface.

WebServiceHandlerFactory

*.asmx

Compiles the source code of a Web service, and translates the SOAP payload into a method invocation. Instantiates an object of the type specified in the Web service file.

Bear in mind that handler factory objects do not compile the requested resource each time it is invoked. The compiled code is stored in an ASP.NET temporary directory on the Web server and used until the corresponding resource file is modified.

So the page handler factory creates an instance of an object that represents the particular page requested. As mentioned, this object inherits from the System.Web.UI.Page class, which in turn implements the IHttpHandler interface. The page object is returned to the application factory, which passes that back to the HttpRuntime object. The final step accomplished by the ASP.NET runtime is calling the IHttpHandler's ProcessRequest method on the page object. This call causes the page to execute the user-defined code and generate the markup for the browser.

In Chapter 12, we'll return to the initialization of an ASP.NET application, the contents of global.asax, and the information stuffed into the HTTP context a container object that, created by the HttpRuntime class, is populated and passed along the pipeline and finally bound to the page handler.

image from book
What Causes Application Restarts?

There are a few reasons why an ASP.NET application can be restarted. For the most part, restarts occur because the system reclaims server resources, cleans the working set, or in an attempt to prevent the long-term effect of latent bugs, makes the application irresponsive. Another reason is that too many dynamic changes to ASPX pages have caused too large a number of assemblies (typically, one per page) to be loaded in memory. An application that consumes more than a certain share of virtual memory is killed and restarted. The ASP.NET runtime environment implements a good deal of checks and automatically restarts an application if any the following scenarios occur:

In addition to all this, in ASP.NET 1.1 and superior an application can be restarted programmatically by calling HttpRuntime.UnloadAppDomain.

The Processing Directives of a Page

Processing directives configure the runtime environment that will execute the page. In ASP.NET, directives can be located anywhere in the page, although it's a good and common practice to place them at the beginning of the file. In addition, the name of a directive is case-insensitive and the values of directive attributes don't need to be quoted. The most important and most frequently used directive in ASP.NET is @Page. The complete list of ASP.NET directives is shown in Table 3-4.

Table 3-4: Directives Supported by ASP.NET Pages

Directive

Description

@ Assembly

Links an assembly to the current page or user control.

@ Control

Defines control-specific attributes that guide the behavior of the control compiler.

@ Implements

Indicates that the page, or the user control, implements a specified .NET Framework interface.

@ Import

Indicates a namespace to import into a page or user control.

@ Master

Identifies an ASP.NET master page. (See Chapter 6.) This directive is not available with ASP.NET 1.x.

@ OutputCache

Controls the output caching policies of a page or user control. (See Chapter 14.)

@ Page

Defines page-specific attributes that guide the behavior of the page compiler and the language parser that will preprocess the page.

@ Reference

Links a page or user control to the current page or user control.

@ Register

Creates a custom tag in the page or the control. The new tag (prefix and name) is associated with the name space and the code of a user-defined control.

With the exception of @Page, @Master, and @Control, all directives can be used both within a page and a control declaration. @Page and @Control are mutually exclusive. @Page can be used only in .aspx files, while the @Control directive can be used only in user control .ascx files. @Master, in turn, is used to define a very special type of page the master page.

The syntax of a processing directive is unique and common to all supported types of directives. Multiple attributes must be separated with blanks, and no blank can be placed around the equal sign (=) that assigns a value to an attribute, as the following line of code demonstrates:

<%@ Directive_Name attribute="value" [attribute="value"...] %> 

Each directive has its own closed set of typed attributes. Assigning a value of the wrong type to an attribute, or using a wrong attribute with a directive, results in a compilation error.

Important 

The content of directive attributes is always rendered as plain text. However, attributes are expected to contain values that can be rendered to a particular .NET Framework type. When the ASP.NET page is parsed, all the directive attributes are extracted and stored in a dictionary. The names and number of attributes must match the expected schema for the directive. The string that expresses the value of an attribute is valid as long as it can be converted into the expected type. For example, if the attribute is designed to take a Boolean value, true and false are its only feasible values.

The @Page Directive

The @Page directive can be used only in .aspx pages and generates a compile error if used with other types of ASP.NET pages such as controls and Web services. Each .aspx file is allowed to include at most one @Page directive. Although not strictly necessary from the syntax point of view, the directive is realistically required by all pages of some complexity.

@Page features about 30 attributes that can be logically grouped in three categories: compilation (defined in Table 3-5), overall page behavior (defined in Table 3-6), and page output (defined in Table 3-7). Each ASP.NET page is compiled upon first request, and the HTML actually served to the browser is generated by the methods of the dynamically generated class. Attributes listed in Table 3-5 let you fine-tune parameters for the compiler and choose the language to use.

Table 3-5: @Page Attributes for Page Compilation

Attribute

Description

ClassName

Specifies the name of the class name that will be dynamically compiled when the page is requested. Must be a class name without namespace information.

CodeFile

Indicates the path to the code-behind class for the current page. The source class file must be deployed to the Web server. Not available with ASP.NET 1.x.

CodeBehind

Attribute consumed by Visual Studio .NET 2003, indicates the path to the code-behind class for the current page. The source class file will be compiled to a deployable assembly.

CodeFileBaseClass

Allows you to specify the grandparent class for a page. ASP.NET uses the information in this attribute to determine the parent for the code file class. Not available with ASP.NET 1.x.

CompilationMode

Indicates whether the page should be compiled at run time. Not available with ASP.NET 1.x.

CompilerOptions

A sequence of compiler command-line switches used to compile the page.

Debug

A Boolean value that indicates whether the page should be compiled with debug symbols.

Explicit

A Boolean Value that determines Whether the page is compiled with the Visual Basic Option Explicit mode set to On. Option Explicit forces the programmer to explicitly declare all variables. The attribute is ignored if the page language is not Visual Basic .NET.

Inherits

Defines the base class for the page to inherit. It can be any class derived from the Page class.

Language

Indicates the language to use when compiling inline code blocks (<% %>) and all the code that appears in the page <script> section. Supported languages include Visual Basic .NET, C#, JScript .NET, J#. If not otherwise specified, the language defaults to Visual Basic .NET.

MasterPageFile

Indicates the master page for the current page. Not available with ASP.NET 1.x.

Src

Indicates the source file that contains the implementation of the base class specified with Inherits. The attribute is not used by Visual Studio .NET and other rapid application development (RAD) designers.

Strict

A Boolean value that determines whether the page is compiled with the Visual Basic Option Strict mode set to On. When enabled, Option Strict permits only type-safe conversions and prohibits implicit conversions in which loss of data is possible. (In this case, the behavior is identical to that of C#.) The attribute is ignored if the page language is not Visual Basic .NET.

Trace

A Boolean value that indicates whether tracing is enabled. If tracing is enabled, extra information is appended to the page's output. The default is false.

TraceMode

Indicates how trace messages are to be displayed for the page when tracing is enabled. Feasible values are SortByTime and SortByCategory. The default, when tracing is enabled, is SortByTime.

WarningLevel

Indicates the compiler warning level at which you want the compiler to abort compilation for the page. Possible values are 0 through 4.

Table 3-6: @Page Attributes for Page Behavior

Attribute

Description

AspCompat

A Boolean attribute that, when set to true, allows the page to be executed on a single-threaded apartment (STA) thread. The setting allows the page to call COM+ 1.0 components and components developed with Microsoft Visual Basic 6.0 that require access to the un-managed ASP built-in objects. (I'll cover this topic in Chapter 12.)

Async

If set to true, the generated page class derives from IHttpAsyncHandler rather than having IHttpHandler adding some built-in asynchronous capabilities to the page. Not available with ASP.NET 1.x.

AutoEventWireup

A Boolean attribute that indicates whether page events are automatically enabled. Set to true by default. Pages developed with Visual Studio .NET have this attribute set to false, and page events are individually tied to handlers.

Buffer

A Boolean attribute that determines whether HTTP response buffering is enabled. Set to true by default.

Description

Provides a text description of the page. The ASP.NET page parser ignores the attribute, which subsequently has only a documentation purpose.

EnableSessionState

Defines how the page should treat session data. If set to true, the session state can be read and written. If set to false, session data is not available to the application. Finally, if set to ReadOnly, the session state can be read but can not changed.

EnableViewState

A Boolean value that indicates whether the page view state is maintained across page requests. The view state is the page call context a collection of values that retain the state of the page and are carriedback and forth. View state is enabled by default. (I'll cover this topic in Chapter 13.)

EnableViewStateMac

A Boolean value that indicates ASP.NET should calculate a machine-specific authentication code and append it to the view state of the page (in addition to Base64 encoding). The Mac in the attribute name stands for machine authentication check. When the attribute is true, upon post-backs ASP.NET will check the authentication code of the view state to make sure that it hasn't been tampered with on the client.

ErrorPage

Defines the target URL to which users will be automatically redirected in case of unhandled page exceptions.

SmartNavigation

A Boolean value that indicates whether the page supports the Microsoft Internet Explorer 5 or later smart navigation feature. Smart navigation allows a page to be refreshed without losing scroll position and element focus.

Theme, StylesheetTheme

Indicates the name of the theme (or style-sheet theme) selected for the page. Not available with ASP.NET 1.x.

Transaction

Indicates whether the page supports or requires transactions. Feasible values are: Disabled, NotSupported, Supported, Required, and RequiresNew. Transaction support is disabled by default.

ValidateRequest

A Boolean value that indicates whether request validation should occur. If this value is set to true, ASP.NET checks all input data against a hard-coded list of potentially dangerous values. This functionality helps reduce the risk of cross-site scripting attacks for pages. The value is true by default. This feature is not supported in ASP.NET 1.0.

Table 3-7: @Page Directives for Page Output

Attribute

Description

ClientTarget

Indicates the target browser for which ASP.NET server controls should render content.

CodePage

Indicates the code page value for the response. Set this attribute only if you created the page using a code page other than the default code page of the Web server on which the page will run. In this case, set the attribute to the code page of your development machine. A code page is a character set that includes numbers, punctuation marks, and other glyphs. Code pages differ on a per-language basis.

ContentType

Defines the content type of the response as a standard MIME type. Supports any valid HTTP content type string.

Culture

Indicates the culture setting for the page. Culture information includes the writing and sorting system, calendar, and date and currency formats. The attribute must be set to a non-neutral culture name, which means it must contain both language and country information. For example, en-US is a valid value unlike en alone, which is considered country-neutral.

LCID

A 32-bit value that defines the locale identifier for the page. By default, ASP.NET uses the locale of the Web server.

ResponseEncoding

Indicates the character encoding of the page. The value is used to set the CharSet attribute on the content type HTTP header.

Internally, ASP.NET handles all strings as Unicode.

UICulture

Specifies the default culture name used by the Resource Manager to look up culture-specific resources at run time.

Notice that the default values of the Explicit and Strict attributes are read from the application's configuration settings. The configuration settings of an ASP.NET application are obtained by merging all machine-wide settings with application-wide and even folder-wide settings. This means you can also control what the default values for the Explicit and Strict attributes are. Unless you change the default configuration settings the .config files are created when the .NET Framework is installed both Explicit and Strict default to true. Should the related settings be removed from the configuration files, both attributes would default to false instead.

Attributes listed in Table 3-6 allow you to control to some extent the overall behavior of the page and the supported range of features. For example, you can set a custom error page, disable session state, and control the transactional behavior of the page.

Attributes listed in Table 3-7 allow you to control the format of the output being generated for the page. For example, you can set the content type of the page or localize the output to the extent possible.

As you can see, many attributes discussed in Table 3-7 concern the issue of page localization. Building multilanguage and international applications is a task that ASP.NET, and the .NET Framework in general, greatly simplify.

The @Assembly Directive

The @Assembly directive links an assembly to the current page so that its classes and interfaces are available for use on the page. When ASP.NET compiles the page, a few assemblies are linked by default. So you should resort to the directive only if you need linkage to a nondefault assembly. Table 3-8 lists the .NET assemblies that are automatically provided to the compiler.

Table 3-8: Assemblies Linked by Default

Assembly File Name

Description

Mscorlib.dll

Provides the core functionality of the .NET Framework, including types, AppDomains, and run-time services.

System.dll

Provides another bunch of system services, including regular expressions, compilation, native methods, file I/O, and networking.

System.Configuration.dll

Defines classes to read and write configuration data. Not included in ASP.NET 1.x.

System.Data.dll

Defines data container and data access classes, including the whole ADO.NET framework.

System.Drawing.dll

Implements the GDI+ features.

System.EnterpriseServices.dll

Provides the classes that allow for serviced components and COM+ interaction.

System.Web.dll

The assembly implements the core ASP.NET services, controls, and classes.

System.Web.Mobile.dll

The assembly implements the core ASP.NET mobile services, controls, and classes. Not included if version 1.0 of the .NET Framework is installed.

System.Web.Services.dll

Contains the core code that makes Web services run.

System.Xml.dll

Implements the .NET Framework XML features.

In addition to these assemblies, the ASP.NET runtime automatically links to the page all the assemblies that reside in the Web application Bin subdirectory. Note that you can modify, extend, or restrict the list of default assemblies by editing the machine-wide configuration settings set in the machine.config file. In this case, changes apply to all ASP.NET applications run on that Web server. Alternately, you can modify the assembly list on a per-application basis by editing the application's specific web.config file. To prevent all assemblies found in the Bin directory from being linked to the page, remove the following line from the root configuration file:

<add assembly="*" /> 
Warning 

For an ASP.NET application, the whole set of configuration attributes is set at the machine level. Initially, all applications hosted on a given server machine share the same settings. Then, individual applications can override some of those settings in their own web.config files. Each application can have a web.config file in the root virtual folder and other copies of it in subdirectories not necessarily subapplications. Each page is subject to settings as determined by the configuration files found in the path from the machine to the containing folder. In ASP.NET 1.x, the machine.config file contains the whole tree of default settings. In ASP.NET 2.0, the configuration data that specifically refers to Web applications has been moved to a web.config file installed in the same system folder as machine.config. The folder is named CONFIG and located below the installation path of ASP.NET that is, %WINDOWS%\Microsoft.Net\Framework\[version].

To link a needed assembly to the page, use the following syntax:

<%@ Assembly Name="AssemblyName" %> <%@ Assembly src="/books/2/370/1/html/2/assembly_code.cs" %> 

The @Assembly directive supports two mutually exclusive attributes: Name and Src. Name indicates the name of the assembly to link to the page. The name cannot include the path or the extension. Src indicates the path to a source file to dynamically compile and link against the page. The @Assembly directive can appear multiple times in the body of the page. In fact, you need a new directive for each assembly to link. Name and Src cannot be used in the same @Assembly directive, but multiple directives defined in the same page can use either.

Note 

In terms of performance, the difference between Name and Src is minimal, although Name points to an existing and ready-to-load assembly. The source file referenced by Src is compiled only the first time it is requested. The ASP.NET runtime maps a source file with a dynamically compiled assembly and keeps using the compiled code until the original file undergoes changes. This means that after the first application-level call the impact on the page performance is identical whether you use Name or Src.

The @Import Directive

The @Import directive links the specified namespace to the page so that all the types defined can be accessed from the page without specifying the fully qualified name. For example, to create a new instance of the ADO.NET DataSet class, you either import the System.Data namespace or resort to the following code:

System.Data.DataSet ds = new System.Data.DataSet(); 

Once you've imported the System.Data namespace into the page, you can use more natural coding, as shown here:

DataSet ds = new DataSet(); 

The syntax of the @Import directive is rather self-explanatory:

<%@ Import namespace="value" %> 

@Import can be used as many times as needed in the body of the page. The @Import directive is the ASP.NET counterpart of the C# using statement and the Visual Basic .NET Imports statement. Looking back at unmanaged C/C++, we could say the directive plays a role nearly identical to the #include directive.

Caution 

Notice that @Import helps the compiler only to resolve class names; it doesn't automatically link required assemblies. Using the @Import directive allows you to use shorter class names, but as long as the assembly that contains the class code is not properly linked, the compiler will generate a type error. In this case, using the fully qualified class name is of no help because the compiler lacks the type definition.

You might have noticed that, more often than not, assembly and namespace names coincide. Bear in mind it only happens by chance and that assemblies and namespaces are radically different entities, each requiring the proper directive.

For example, to be able to connect to a SQL Server database and grab some disconnected data, you need to import the following two namespaces:

<%@ Import namespace="System.Data" %> <%@ Import namespace=" System.Data.SqlClient" %> 

You need the System.Data namespace to work with the DataSet and DataTable classes, and you need the System.Data.SqlClient namespace to prepare and issue the command. In this case, you don't need to link against additional assemblies because the System.Data.dll assembly is linked by default.

The @Implements Directive

The directive indicates that the current page implements the specified .NET Framework interface. An interface is a set of signatures for a logically related group of functions. An interface is a sort of contract that shows the component's commitment to expose that group of functions. Unlike abstract classes, an interface doesn't provide code or executable functionality. When you implement an interface in an ASP.NET page, you declare any required methods and properties within the <script> section. The syntax of the @Implements directive is as follows:

<%@ Implements interface="InterfaceName" %> 

The @Implements directive can appear multiple times in the page if the page has to implement multiple interfaces. Note that if you decide to put all the page logic in a separate class file, you can't use the directive to implement interfaces. Instead, you implement the interface in the code-behind class.

The @Reference Directive

The @Reference directive is used to establish a dynamic link between the current page and the specified page or user control. This feature has significant consequences in the way in which you set up cross-page communication. It also lets you create strongly typed instances of user controls. Let's review the syntax.

The directive can appear multiple times in the page and features two mutually exclusive attributes Page and Control. Both attributes are expected to contain a path to a source file:

<%@ Reference page="source_page" %> <%@ Reference control="source_user_control" %> 

The Page attribute points to an .aspx source file, whereas the Control attribute contains the path of an .ascx user control. In both cases, the referenced source file will be dynamically compiled into an assembly, thus making the classes defined in the source programmatically available to the referencing page. When running, an ASP.NET page is an instance of a .NET Framework class with a specific interface made of methods and properties. When the referencing page executes, a referenced page becomes a class that represents the .aspx source file and can be instantiated and programmed at will. Notice that for the directive to work the referenced page must belong to the same domain as the calling page. Cross-site calls are not allowed, and both the Page and Control attributes expect to receive a relative virtual path.

Note 

In ASP.NET 2.0, you are better off using cross-page posting to enable communication between pages.

 


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