Internal changes in ASP.NET 2.0
Release Date: 11/2/2004
| Update Date: 11/2/2004
Jayesh Patel, Bryan Acker and Robert McGOvern
Infusion developments
Scope of application:
Microsoft ASP.NET 2.0
Abstract: Although ASP.NET 2.0 is compatible with ASP.NET 1.1, it is still a large number of internal changes to ASP.NET, including changes in code model, compilation, page lifecycle, and the like. This article will summarize these changes.
This page
Introduction Code model compiles full runtime compilation (code directory) page lifecycle scalability advanced cache technical performance conclusion
introduction
For professional ASP.NET developers, important issues related to ASP.NET 2.0 are what changes have occurred inside. Although new features are very interesting and practical, it is very interesting to truly want to master this technology, the changes in ASP.NET core structures are the most attractive place. In this white paper, we will introduce from the version 1.x, what changes have occurred within the ASP.NET 2.0 internal structure.
The subject of this white paper introduction is very useful for developers who focus on performance and how to optimize applications. Specifically, we will introduce the main issues related to code model, compilation, page lifecycle, scalability, performance, and cache.
Many examples in this article require you to have a considerable understanding of ASP.NET, Visual Basic .NET, and / or C # syntax. This article also provides a reference document in place to discuss in-depth discussions on certain specific topics.
Back to top
Code model
Perhaps ASP.NET 2.0 The most obvious change in internal working methods is the change in the creation of the ASP.NET web page. This section describes the changes in the inclination of the code model and these changes on the development of ASP.NET.
Code model in ASP.NET 1.x
In ASP.NET 1.x, there are two main options for developers to develop web forms. First, developers can refer to the traditional ASP model and write code directly in the ASPX page. This process is called "embedded code", which is very suitable for simple commands. However, for more complex code, the writing embedded code will be difficult to read a mixed web page that mixes (HTML) and function (code). In ASP.NET, in order to help solve this problem, the default encoding method has been changed. You can write business logic and event processing code in separate, only code-containing files (called "in-code" files). The inheid code model will only contain a file containing the code with the ASPX file containing the indicator mark. By separating the code with the representation, the development team can let the designer process the demo file, and let the developer handle the code file, thereby increasing the work efficiency of the development team.
Figure 1: ASP.NET 1.x code model
The main difficulty in which the code model is facing is how to keep the content file with the ASPX page synchronization. Although the ASPX page is inherited from the content file from the programming, it is actually associated with more complex relationships.
For more information on the intrinsic code models in ASP.NET 1.x, see MSDN Library Articles Web Forms Code Model.
Inheritance complexity
The ASP.NET design mode is to let developers drag and drop the control to the ASPX page using Microsoft Visual Studio .NET. Visual Studio will then automatically generate the appropriate support code in the included code file. If the control has been added to the ASPX page, you must add a new code to the code file. In other words, although the ASPX page inherits the code file in the anly, but actually the ASPX page pushes the design of the code file. Compile complexity
The second synchronization problem is how to compile files. All included code files and all support classes are compiled into a program set and stored in the / bin directory of the web application. The compilation of the application is performed before the deployment work. On the other hand, the ASPX page is also compiled at runtime during the first request. The ASP.NET runtime actually compiles the ASPX page to the page yourself.
The problem with this process is that the ASPX page can be changed without the need to update the code assembly. That is, the developer can change a certain attribute or change the type of a control on the ASPX page, without updating the code file, and does not need to recompile the app. When this happens, the application may encounter an unexpected error due to the inner code file does not match the associated ASPX page.
Code model in ASP.NET 2.0
ASP.NET 2.0 continues to provide embedded code and an intrinsic code model. From the perspective of the embedded code model, there is basically no change in the way Microsoft Visual Studio 2005 supports single file development. For more information on Visual Studio 2005 and how it handles the embedded code, see this article (English).
ASP.NET 2.0 solves the inheritance and compilation of the code model by changing the essence of the code file. In ASP.NET 2.0, the content files are no longer the complete implementation of the System.Web.ui.page class. Instead, the content file is a new constructor called "local class". The partial class contains all user-defined code, but does not contain any lines and connection code that automatically generated in ASP.NET 1.x in ASP.NET 1.x. When requesting the ASPX page of the new intrinsic code file, the ASP.NET 2.0 runtime will actually merge the ASPX page and the local class into a class, rather than two separate classes.
Figure 2: Introduction Code Model in ASP.NET 2.0
Local class uses a new keyword (in Visual Basic, which is expands in C #, which is the code in the class in the runtime, and the code in the class in another class. Similarly, the ASPX page uses a new instruction (called CompileWith) to indicate the association between the page and the content file.
Compare code files
If you are familiar with the traditional ASP.NET 1.x containing code files, you should know that Visual Studio will insert the auto-generated control declaration and initialization code. This automatically generated code is a direct result of bidirectional synchronization between code files and ASPX files. A typical ASPX page with labels has a corresponding intrinsic code file, which is composed of many automatically generated text lines.
Listing 1: Introduction Code File in ASP.NET 1.x
Namespace WebApplication1
{
Public class Webform1: System.Web.ui.page
{
protected system.web.ui.webcontrols.label label1;
Private void Page_load (Object Sender,
System.eventargs e) {}
#Region Web Form Designer Generated CodeOverride Protected Void OnInit (Eventargs E)
{
InitializationComponent ();
Base.onit (E);
}
Private vidinitiRizeComponent ()
{
This.Load = New System.EventHandler (this.page_load);
}
#ndregion
}
}
Automatically generated code not only defines labels (lines in bold), but also declares new events (page load) and automatically bind the event to the automatically generated method package (Page_Load ()).
In contrast, the same ASP.NET page is more concise in an in-code file generated in ASP.NET 2.0.
Listing 2: Introduction Code File in ASP.NET 2.0.x
Namespace ASP {
Public Partial Class Webform1_ASPX
{
}
}
Developers can automatically access Label1 and add events as needed. For example, you can add a PAGE_LOAD event to initialize the label.
Listing 3: Add events in new intrinsic code files
Namespace ASP {
Public Partial Class Webform1_ASPX
{
Void Page_Load (Object Sender, Eventargs E)
{
Label1.text = "Hello ASP.NET 2.0";
}
}
}
The event syntax can be generated via Visual Studio .NET. The generated content contains shorter code files, and does not contain any automatically generated code. The ASP.NET run library automatically binds the events in the code file to the controls on the ASPX page. In other words, the ASP.NET runtime can now automatically perform code generation, which is originally performed by Visual Studio.
Inheritance complexity
The new intrinsic code model greatly reduces the complexity of inheritance. Since the ASPX page is not directly inherited from the inside the code file, the content files are no longer need to define and support all controls defined on the ASPX page. Similarly, the content file can automatically access any controls on the ASPX page without requiring code (declaration code is required in ASP.NET 1.x). All of this can be implemented because the ASP.NET runtime can automatically insert the required declaration code and event binding code into the final compilation file. Because these work is done by the running library, the code developers and Web developers don't have to worry about this problem.
During the design, the link will be maintained by Visual Studio 2005. The Visual Studio environment will use the ASP.NET runtime compilation segment to ensure that the code developers and web developers can work synchronously.
Compile complexity
Since the new intrinsic code file is linked together with the ASPX page and compiled into a complete class while running, the complexity of compilation does not exist. That is, the content file will be automatically synchronized with the ASPX page. Even if the new compilation model may contain uncapacity, it is very clear because of the abnormality generated, so you can quickly find the root source of the problem.
Back to top
Compile
Since the introduction of the page model in ASP.NET 1.x, the compilation process of the ASP.NET web page has been divided into two phases. First, compile the content file and other support classes to a program set, then compile each ASPX file at runtime. Although this model has many advantages, it also has several shortcomings. ASP.NET 2.0 provides several alternatives for basic models, enlarged compilation selection, and you can choose according to specific needs.
Compilation in ASP.NET 1.x
The main compilation model in ASP.NET 1.x generates an application assembly (including all compiled interposed files and other source code) and a temporary assembly (created specifically for each ASPX page for the request) . In some cases, compiler optimization (eg, batch) may cause the temporary ASPX page to be compiled into the same program. In any case, each ASPX page is compiled into a temporary program set, so the page can be loaded into the ASP.NET running library.
Figure 3: Compilation in ASP.NET 1.x
Although this model has a lot of advantages, it has two main disadvantages. First, you must deploy the ASPX page to the Web site in the format that users can read. If the developer uses the "embedded code" model, you also need to deploy some or all business logic to the production server. Although IIS and ASP.NET are configured to not display the original ASPX page, the embassy attacker can still access these files through any entry open to the web server. Second, when anyone first requested the web page, the response will be slower than normal, because the ASP.NET runtime must compile the ASPX page.
In this process, the only developer can control whether the ASPX page is batch. In ASP.NET 1.x, you can configure batch compilation by modifying the
Listing 4: Configuring batch compilation
BATCH = "True | FALSE" BatchTimeout = "Number of Seconds" MaxbatchSize = "Maximum Number of Pages Per Batch CompiLation" MaxbatchGeneratedFileSize = "Maximum Combined size (in kb) of the Generated Source File Per Batch CompiLation compilation> When requesting the web page for the first time, batch compilation will shorten the load time by extending the startup time. Another advantage of batch compilation is to compile all ASPX files into a temporary program, rather than compile each page into a temporary program. Compilation in ASP.NET 2.0 ASP.NET 2.0 provides four different compilation models for web applications: • Ordinary (ASP.NET 1.x) - In a normal ASP.NET Web application, the content file is compiled into a program set and stored in the / bin directory. Web page (ASPX) is compiled on demand. This model applies to most Web sites. However, the compilation process will cause the response speed than the next request ASP.NET page to slow down. ASP.NET 2.0 continues to support this compilation model. • Batch Compilation - In ASP.NET 2.0, you can use a URL request to compile any applications. Just like in ASP.NET 1.x, batch compilation eliminates the latency of the first request page, but extended startup time. In addition, batch compilation still requires compilation of code files before deployment. • Deploy Precipure - This is a new feature provided by ASP.NET 2.0 that allows you to compile items before deployment. In full compilation, based on the size and compilation settings of the application, you can compile all the code files, ASPX pages, HTML, graphics resources, and other backend code to one or more executable program sets. These assessments contain all the compiled code in the Web site, and copy the resource files and configuration files. This compilation method provides the best performance and security, but the price is not to modify the Web site after deployment. If you are deploying a highly visible or highly secure Web site, this option is the best choice for the final deployment. However, if you are building a small site running on the local intranet, and the site changes frequently, then complete precompiled translation may be redundant. • Complete runtime compilation - Another extreme situation that is opposite to deployment is that ASP.NET 2.0 provides a new mechanism for compiling the entire application at runtime. That is, you can put the uncharacted code file and other associated code in the new code directory, generate an assembly based on these files at runtime and make ASP.NET 2.0 created and maintained for these assemblies. Quote. This option provides maximum flexibility to change the content of the Web site, but the cost is stored on the server. You can choose the best compilation option based on the actual situation, but the compilation model is still flexible. Even if you choose to use the code directory to store the content file, you can still use the complete compilation of this method to deploy the application. Batch compilation Web.config batches are still valid in ASP.NET 2.0. The advantage of batch compilation is that the page can be displayed immediately to the first user and can detect any errors in the ASPX page during batch compilation. However, batch compilation does extend the startup time of the application, and must be built into the web.config file. Deployment preparatory Deployment Precorpore Allows you to create one or more assemblies as an executable version of the Web site. The generated assembly contains the compiled code of the Web site. HTML page, resource, configuration file, and ASPX page will be copied separately. Deploying Pre-compilation requires the use of an ASPNET_COMPILER.EXE command line utility, which creates the target deployment directory, which contains the / bin directory for the storage assembly and the Stub files of the various ASPX pages. You can also use this utility to perform in the bit pre-compile, similar to the behavior called "Magic". The Stub file uses the name of the ASPX page, but contains a simple code that calls the compiled assembly. In other words, the ASPX page is a simple empty case, not a perfect page. By precompiling the Web site before deployment, security will greatly improve, because if the assembly is not completed, no code will be accessed. To enhance protection, you can chaos the generated assembly to make your web application safer. The main disadvantage of deploying pre-compilation is that you must do these operations before deploying, and you cannot change the Web site after deployment. If you want to make changes, you must recompile the Web site and redeploy it. For most major web applications, the deployment pre-compilation option is the preferred mechanism for deployment because it can reduce the number of original code deployed on the web server and provide the highest security. The increased process can be built into the usual development / test / deployment cycle without severe productivity. Back to top Completely compiled (code directory) In the above three compilation methods, you must compile all code files before deployment (including code and support classes). The code directory is provided in ASP.NET 2.0. The code directory is a special directory for storing uncompiled classes. At runtime, the ASP.NET Run library compiles the contents of this directory into a program set, which will automatically reference the ASPX page in the application. In other words, use the code directory, there is no need to create and reference separate assemblies for support code. The advantage of the code directory is that you can deploy it without a complete compilation project, thereby reducing the possibility of mismatch. But the disadvantage is that you may need to store unparacted code on the server. This option is especially suitable for ASP.NET applications that do not require a large number of support code (regardless of the format of code files or external objects). For simple applications, the ability to quickly deploy and test systems is more advantageous than a more robust compilation method. Back to top Page life cycle ASP.NET 2.0 has two major changes in the life cycle of the ASP.NET page. First, ASP.NET 2.0 provides new events to support new features, including master page, personalized, and integrated mobile device support. Second, ASP.NET 2.0 introduces technology from page-transmitting web forms. New event Compared to ASP.NET 1.x, ASP.NET 2.0 provides a more accurate page lifecycle stack. These new methods provide a higher level of control for web developers. These events can be accessed through the "Page" object on any ASP.NET page. Table 1 shows a comprehensive list of methods. "Method" column shows the actual event method name, the "Active" column indicator is always active or only during the postback operation. For example, you can use the new method TestDeviceFilter to determine which device filter is available and use this information to determine how to display the page. In other words, the new method loadControlState is only called during the rapid process. This method can be replaced (used in conjunction with SaveControlState) to create a replacement sequence scheme for saving and recovering control status during flexion. Table 1: page lifecycle methods activities Constructor always Construct always TestDeviceFilter always AddParsedSubObject always DeterminePostBackMode always OnPreInit always LoadPersonalizationData always InitializeThemes always OnInit always ApplyControlSkin always ApplyPersonalization always OnInitComplete always LoadPageStateFromPersistenceMedium PostBack LoadControlState PostBack LoadViewState PostBack ProcessPostData1 PostBack OnPreLoad always OnLoad always ProcessPostData2 PostBack RaiseChangedEvents PostBack RaisePostBackEvent PostBack onLoadComplete always OnPreRender always OnPreRenderComplete always SavePersonalizationData SaveControlState always always always SavePageStateToPersistenceMedium SaveViewState Render always always always OnUnload by viewing the page life cycle of a lower level of detail, we can see where can naturally achieve many of the features in ASP.NET 2.0, for example, Subject and personalization. For example, a topic can be processed in the Intializethemes event, and load personalized data in LoadPersonalizationData and applied to the ApplyPersonalization method later. Note that the order of the method is extremely important for the UI elements that determine the final appearance of the web application. Transplitude Other major changes in the page life cycle include events and web forms. In ASP.NET 1.x, the web form is automatically returned to its host page. That is, when the user submits the form, the form data will always be submitted back to the page containing the original form. This design can easily store control status, but limit the capabilities of developers to perform more complex operations. In ASP.NET 2.0, the Web Form Control has a new attribute that allows developers to send form data to where the form data can be determined when the submission is performed. In most cases, the return mechanism is required, so the mechanism is still the default setting. However, if the developer wants to send data to different forms, this is now achievable. Figure 4: Return and cross-page transmission For example, you can create a multi-page pair, which contain several different forms. Each form is submitted in order to the next page until the user arrives at the summary page that can perform the final verification. The data on the previous page can be accessed through the Previouspage object in the current context. The PreviOUSGE object is used to store data on the previous page and available on the current page. It is because there is this object, and the cross-page transmission will not sacrifice the persistence of the control. If the user needs to back up a form in order, you can access these page data immediately without having to re-enter all data. Back to top Scalability ASP.NET was originally designed to an open frame. That is, many modules and components constituting ASP.NET can be extended, modified, or replaced to meet your specific needs. In ASP.NET 2.0, the scalable essence of the framework is clearly illustrated by new HTTPHANDLERS and HTTPMODULES. Request pipeline In ASP.NET, requests from the web server from the web server via the Internet Server Application Programming Interface (ISAPI) filter and passed to the actual ASP.NET runtime. Figure 5: Request pipe When IIS receives a request, map the extension to the ISAPI filter according to IIS settings. .aspx, .asmx, .asd and other extensions are mapped to ASPNET_ISAPI.dll, which is just an ISAPI filter for starting the ASP.NET runtime. When the request is encountered an ASP.NET running library, it will start on the HTTPApplication object (as the host of the ASP.NET web application). HTTPApplication object: 1. Read configuration files for your computer and application level. 2. Pass the request to one or more HttpModule instances. Each httpmodule provides a service such as session maintenance, verification, or profile maintenance. These modules deliver the request back to HTTPApplication. 3. Pass the request to httphandler based on the verbs and paths. The verb refers to the HTTP verb (GET, POST, FTP, etc.) used in the request, and the path refers to the URL in the application. Depending on the configuration of the handler, the request may be processed as an ASP.NET page (System.web.ui.page is the IHTTPHANDLER implementation), or other operations may also be triggered, such as batching all web pages (PrecomiPlation. ASD will trigger precomphandler). In ASP.NET 2.0, this model does not change, but several new modules and handles have been added to provide more services. Just like in ASP.NET 1.x, you can extend, replace, or reconfigure any modules or handle classes to provide custom features. New module Obviously, new HTTPModules is used to support new services available in ASP.NET 2.0. Specifically, ASP.NET applications with default module settings include new modules added to the following purposes: • The sessionID - The session identification mechanism has been split from the ASP.NET 1.x session module, the purpose is to better control the cookie, URL rewriting, and other forms of generating the session ID. • Role Management - This is a new module that provides role-based services to support new user identification mechanisms. This module helps to link the ASP.NET application link to the role-based security of the .NET Framework. • Anonymous ID - Supports new personalization features for anonymous users. This module can help track the features that anonymous users can access, as well as tracking the way these features are maintained between requests. • Profile-Profile Module links to new configuration file services to help provide user-specific persistent data storage. • Page Counter - A new module added in ASP.NET 2.0, is used to link page counters and improve the statistical analysis of web communications. In addition to these new modules, some old modules have also changed: For example, the output cache module now supports new cache technologies described later later in this white paper. New processor In addition to new modules, ASP.NET 2.0 also introduces new handlers to support application configuration tools and other new features, such as batch compilation requests. The most important new process includes the ".axd" series used to process the Web site management request. These handlers will start to allow developers to configure internal management tools for ASP.NET users and other settings. These management handles include: • Web Management - WebAdminHandler is the home page for managing the Web site. This handler provides a starting point for managing ASP.NET 2.0 web applications. • Track - ASP.NET 1.x TraceHandler has been improved, and is the only "AXD" processor in ASP.NET 1.x. • Web Resources - With new management tools and WebResourceShandler, you can now configure the web resource to deploy. • Cached Image - CachedimageServiceHandler supports cache graphics components. • Counters - SiteCountersHandler uses the page counter module to provide access statistics for ASP.NET 2.0 applications. • Precatch - As described earnes, you can use Precomphandler to batch compilation of all ASPX pages in the ASP.NET application. • Web Parts Export - WebPartExportHandler supports storage and transfer web part layout. The web part is a new mechanism for the look and content of the web application for personalized portal style. As before, HTTPFORBIDENHANDLER is linked to any file type that should not be returned. In ASP.NET 2.0, the list of files prohibited has been extended, and now includes master page, external files, and other new developer components. Back to top Advanced cache technology One way to improve the performance of web applications is to cache static content in memory. The content returned to the cache is always compared to the new rendering of the new rendering. However, the disadvantage is that the content of the cache may expire. ASP.NET 1.x supports several caches, including: • Page Level - Each page can be cached as a whole, or cache based on parameters to access the page. The cached page will expire after the specified time. • Page Footage - If you build a page using a User Control (.ascx file), you can individually cache user controls separately on the rest of the page content. • Programming Cache - Due to the cache API, developers can also cache objects. The cache API has a significant advantage that makes developers to create different types of dependencies when they refreshed cache. In ASP.NET 2.0, the cache mechanism of the page level has been expanded to support database dependencies. With database cache dependencies, the cache can be bound to a specific table in the SQL Server database. If the table changes, the cache will automatically expire. In addition, developers can now use the cached replacement function to replace the cached part of the cache with the refresh content. The replacement function after the cache allows the application to use the page level cache, even if some of the contents of the page should be generated. Database caokes expired For most data-driven Web sites, the cache is a complex topic, especially if the cache is needed and must update the data. In ASP.NET 1.x, the page can be cached for a while and organize by entering parameters (query string or post parameters): Listing 5: ASP.NET 1.x Output Cache Instruction <% @ outputcache duration = "3600" VarybyParam = "prodid"%> For example, the code in the list 5 is based on the variable PRODID to cache the page in memory. The problem in the above example is that what should I do if the relevant business data is updated elsewhere? For example, suppose to cache a product catalog page according to the product ID. If you update this product from the management site (such as stock quantity or price), the cached data will be incorrect, and the data to the customer is not correct. In previous versions of ASP.NET, you want to resolve this issue, you need to use the response.removeoutputCacheItem manually to remove this page from the cache, or wait until the Duration time has expired to automatically update the page. ASP.NET 2.0 solves this problem by supporting database buffering dependencies. You can use the table level notification when using SQL Server 7 and 200, and Microsoft SQL Server 2005 will provide a more accurate level notification. For example, the following code can cache the product page for an hour, but add a second layer dependency on the database table. Listing 6: ASP.NET 2.0 Database Coke Example <% @ OutputCache Duration = "3600" VarybyParam = "product" Sqldependency = "MyDatabase: Products"%> When using the new SQLDependency property, just change the "Products" table, the cached page will expire. The SQLDependency property must reference the DataSource configured in the web.config file. DataSource is used to identify the database connection and the parameters necessary to issue a dependency notification. Custom cache dependency ASP.NET 2.0 comes with a Cachedependency implementation, the SQLCachedependenceCy, which supports Microsoft SQL Server. Realizing new cache dependencies is a complex process, but because ASP.NET 2.0 has scalable, this process can be implemented. In other words, you can create your own CacheDependency class to provide similar features for other database systems such as Oracle or Sybase. Replacement function after cache For several page elements to maintain dynamic updates, most of the contents of the page are suitable for cache, and the replacement of the cache provided by ASP.NET 2.0 can be used. The replacement function after the cache is used to notify the ASP.NET runtime to re-evaluate a particular element on this page before displaying a cached page. There are two ways to use this feature: • Call the new response.writesubstitution method to pass references to replace the callback function. • Add the Replacement after cache You can create a control that supports replacement after the cache is created to take full advantage of this feature. One example of such controls is Adrotator. Listing 7 shows this page: • Retrieve data from the "Authors" table of the "PUBS" database. • Bind the data to the GridView control. • Display ads from Adrotator. • Display the time of the creation page on the label control. The <% @ Page language = "c #" codebehind = "postcache.aspx.cs" Autoeventwireup = "true" inherits = "WebApplication1.postcache"%> <% @ outputcache duration = "30" VarybyParam = "none"%>
HEAD>