New code compilation features in ASP.net Whidbey

Source: Internet
Author: User
Tags contains file system html tags integer new features stub root directory visual studio
Asp.net| compiling new code compilation features in ASP.net Whidbey
G. Andrew Duthie
Graymad Enterprises, Inc.

October 2003

Summary: Learn how to use asp.net Whidbey to make your code more easily available. The code directory automatically compiles codes for your site, but precompilation makes deployment easier.

Download the source code for this article. (Note that in the sample file, the programmer's comment is in English, which is translated into Chinese for easy Reader's understanding.) )

Directory
Brief introduction
New Modular Code Model
\code Directory
Interest Calculator
Pre-compiling support
In-situ precompilation
Deploying precompilation
IntelliSense is everywhere!
Summary

Brief introduction
The upcoming new version of Microsoft®asp.net introduced a number of features and improvements, its code name asp.net Whidbey, is based on the new version of the Microsoft®visual studio®.net name. Some of these features take advantage of the new features in the underlying microsoft®.net Framework version (ASP.net Whidbey is built on that version). Among these features, one of the most useful feature sets is related to code compilation.

This article describes the major changes to the ASP.net Whidbey compilation model, the impact of these changes on writing asp.net applications, and how to take advantage of these changes.

The improved functionality and new compilation capabilities can be grouped into the following four basic areas:

Improvements to the modular code model.
The new Code directory.
New support for precompiled asp.net applications.
microsoft®intellisense® enhanced functionality.
New Modular Code Model
By default, sites developed using Visual Studio. NET 2002 or 2003 use a feature called "Modular Code" to separate visual elements (HTML tags, controls, and so on) from UI-related programming logic. When a developer creates a new Web form (such as foo.aspx), Visual Studio automatically creates an associated codebehind class file that has the same name as the Web form, followed by. vb or. cs (depending on the language in which the project is used). Class files are associated with Web forms through the codebehind and Inherits properties of the @ Page directive.

The class file contains the event-handling code, including the code used to bind the event handler to the corresponding event, and the detach declaration for each control (added to the. aspx file through the Visual Studio Web forms editor). When you compile (build) a Web application project, all of the codebehind classes in it are compiled into a. NET assembly that will be placed in the Web application's \ Bin directory. The Web Forms page itself is compiled dynamically at run time, and each Web form inherits from its associated codebehind class. For more information about the modular code model in Visual Studio. NET 2003 and ASP.net 1.1, refer to the MSDN Library article Web Forms Code Model (English).

Although the original modular code model is theoretically good (who doesn't want to separate UI elements from programming logic)? ), but there are some drawbacks:

A rebuild is required. In Visual Studio. NET, the runtime does not automatically compile the Codebehind class, so any changes to the Codebehind class need to regenerate the entire project to apply the changes. (Note that you can specify dynamic compilation of a modular code file by using the SRC attribute of the @ Page directive, but Visual Studio. NET does not perform this action by default.) )
Shared development issues. Because all codebehind classes in the project are compiled into an assembly, it is difficult to have multiple developers develop a project at the same time without encountering bottlenecks.
Code is easily corrupted. Controls exist in both declarations (in. aspx pages) and programmatically (in the Codebehind Class), and if the two sets of controls are not synchronized correctly, the code can easily be compromised.
Increased complexity and lack of single file support. In Visual Studio. NET, many of the features that are used to improve productivity, including IntelliSense statement completion, require the use of modular code. Unfortunately, these features typically add a large amount of relatively complex code to the Codebehind class, which causes the code to be easily compromised because changing the code that is inserted by Visual Studio. NET can easily break the page.
With these drawbacks in mind, the team responsible for developing asp.net and Visual Studio. NET Whidbey decided to reconsider the modular code model. The new modular code model leverages the new capabilities of Microsoft®visual Basic®.net and C # called local classes (called local types in C #). A local class enables you to define different parts of a class in multiple files. At compile time, the compiler combines these parts together. ASP.net Whidbey uses the new Compilewith and Classname properties in the @ Page directive to identify the Codebehind local class to be combined with an. aspx page. By taking advantage of department classes and making other changes, the ASP.net team can accomplish the following:

You do not need to write control declarations and event-binding code in the Codebehind class (binding events declaratively in a control declaration).
Allows the runtime to dynamically compile both the Web Forms page and the Codebehind class without having to regenerate the entire project for minor changes.
Reduce file contention in shared development.
The same IDE experience is available to developers who use modular code files and developers who prefer single file development (where all code and markup are contained in. aspx files).
The following are the different views before and after the changes to the modular code model. The following code is the default code created by Visual Studio when you add a new Web Form using modular code (called a code-delimited Web Form in Visual Studio. NET Whidbey):

Visual Studio. NET 2002/2003
WebForm1.aspx:

<%@ Page language= "vb" autoeventwireup= "false"
Codebehind= "WebForm1.aspx.vb" inherits= "Testwebapp_121602.webform1"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<title>WebForm1</title>
<meta name= "generator" content= "Microsoft Visual Studio. NET 7.1" >
<meta name= "Code_language" content= "Visual Basic. NET 7.1" >
<meta name=vs_defaultclientscript content= "JavaScript" >
<meta Name=vs_targetschema
Content= "HTTP://SCHEMAS.MICROSOFT.COM/INTELLISENSE/IE5" >
<body ms_positioning= "GridLayout" > <form id= "Form1" method= "POST" runat= "Server" >
</form>
</body>

WebForm1.aspx.vb:

Public Class WebForm1
Inherits System.Web.UI.Page

#Region the code generated by the Web Forms Designer

' This call is required by the Web Forms Designer.
<system.diagnostics.debuggerstepthrough () > _
Private Sub InitializeComponent ()

End Sub

' NOTE: The following placeholder declaration is
' Required by the Web Forms Designer.
' Do not delete or change its location.
Private Designerplaceholderdeclaration as System.Object

Private Sub Page_Init (ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles Mybase.init
' CodeGen: This method invocation is required by the Web Forms Designer.
' Do not modify it using the Code Editor.
InitializeComponent ()
End Sub

#End Region

Private Sub Page_Load (ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles MyBase.Load
' Place the user code here to initialize the page
End Sub

End Class

Visual Studio. NET Whidbey
Default.aspx:

<%@ page language= "VB" compilewith= "Default.aspx.vb"
Classname= "ASP. Default_aspx "%>

<title> Untitled Page </title>
<body>
<form runat= "Server" >

</form>
</body>

Default.aspx.vb:

Imports Microsoft.VisualBasic

Namespace ASP

Expands Class default_aspx

End Class

End Namespace

It is clear from the example above that the code generated by Visual Studio. NET Whidbey is clearer and easier to read. You do not need to sacrifice drag-and-drop functionality or IntelliSense to accomplish this.

\code Directory
Another cool and useful new feature in ASP.net Whidbey is the addition of the \code directory. The \code directory, similar to the \ Bin directory, is a special directory used by ASP.net, but it differs from the \ Bin directory: the \ Bin directory is used to store precompiled assemblies used by the application, and the \code directory is used to store class files to be dynamically compiled at run time. This allows you to store classes of business logic components, data access components, and other components in a location in your application and use them from any page. Because these classes are compiled dynamically at run time and are automatically referenced by an application that contains the \code directory, you do not need to build the project before you deploy the project, nor do you need to explicitly add a class reference. You can make changes to your components with confidence, and then deploy using a simple XCOPY or drag-and-drop operation. In addition to simplifying the deployment and referencing of components, the \code directory greatly simplifies the process of creating and accessing resource files (. resx) used during localization, as well as automating the generation and compilation of proxy classes for WSDL files (. wsdl).

To better illustrate the implementation of the above actions, let's look at a few examples first. In the first example, we'll see how to create a simple business component and how to access it from a Web forms page.

Interest Calculator
First, we open Visual Studio. NET Whidbey and create a new Web site called compilation. After you create a Web site, the IDE should resemble figure 1.



Figure 1:visual Studio. NET Whidbey Web site

Then, we add the \code folder to the Web site, add the method to right-click the item, and then select New Folder (the new folders). This folder must be named Code, but the name is not case-sensitive. After you add a folder, we can add a new class file: Right-click the \code folder, clicking Add New Item ... (Add New Item ... , and then select the Class (Class) item in the Templates pane of the Add New Item dialog box. Name the class Calculateinterest.vb. Then add the code to calculate the interest (add it to the class and End Class statements):

Public Function calcbalance (ByVal prncpl as Integer, _
ByVal Rate as Double, _
ByVal Years as Integer, _
ByVal Period as Integer) as String
Dim Basenum as Double = (1 + rate/period)
Calcbalance = _
Format (Prncpl * System.Math.Pow (Basenum, _
(Years * Period)), "#,###,# #0.00"). Tostring
End Function

After creating the component class, we need to modify the Default.aspx page to provide the fields to enter the data and to invoke the Calcbalance method of the component. For the sake of simplicity, the complete list of Default.aspx is shown below (note that Default.aspx uses the single file code model).

Default.aspx:

<%@ page language= "VB"%>

<script runat= "Server" >
Sub Button1_Click (ByVal sender as Object, _
ByVal e as System.EventArgs)
Dim Calc as New calculateinterest
Label6.text = "$" & _
Calc.calcbalance (Convert.ToInt32 (TextBox1.Text), _
(Convert.ToInt32 (TextBox2.Text)/100), _
Convert.ToInt32 (TextBox3.Text), _
Convert.ToInt16 (Dropdownlist1.selectedvalue))
Label6.visible = True
End Sub
</script>

<title> Interest Calculator </title>
<body>
<form runat= "Server" >
<asp:label id= "Label1"
runat= "Server" >p Principal ($):</asp:label>
<asp:textbox id= "TextBox1" runat= "Server" >
</asp:textbox>
<br/>
<asp:label id= "Label2"
runat= "Server" > rate (%):</asp:label>
<asp:textbox id= "TextBox2" runat= "Server" >
</asp:textbox>
<br/>
<asp:label id= "Label3" runat= "Server" > Number of years:</asp:label>
<asp:textbox id= "TextBox3" runat= "Server" >
</asp:textbox>
<br/>
<asp:label id= "Label4"
runat= "Server" > Compounding frequency:</asp:label>
<asp:dropdownlist id= "Dropdownlist1" runat= "Server" >
<asp:listitem value= "1" > Annual </asp:ListItem>
<asp:listitem value= "4" > Quarterly </asp:ListItem>
<asp:listitem value= "A" > Monthly </asp:ListItem>
<asp:listitem value= "365" > Daily </asp:ListItem>
</asp:dropdownlist>
<br/>
<asp:label id= "Label5"
runat= "Server" > Balance: </asp:label>
<asp:label id= "Label6"
Visible= "false" runat= "Server" ></asp:label>
<br/>
<asp:button id= "Button1"
runat= "Server" text= "Compute" onclick= "Button1_Click"/>
</form>
</body>

In Design view, the modified default.aspx should resemble figure 2.



Figure 2: Default.aspx in Design view

Note that when you type code in the < script > block that is used to invoke the component class, you get the complete IntelliSense statement completion (including the Component Class), as shown in Figure 3. This is a major improvement on the basis of Visual Studio. NET 2003, and Visual Studio. NET 2003 does not support IntelliSense in server-side < script > blocks.



Figure 3: IntelliSense in the Source view

Browsing Default.aspx produces the output shown in Figure 4. Fill in the principal, interest rate, and number of years, then click Calculate (Calculated), and the output should look like Figure 5.



Figure 4:default.aspx's initial output



Figure 5: The computed output

Resource file
If you have previously used Web applications in Visual Studio. NET 2002 or 2003, you must have noticed that each time you create a new Web Forms page, in addition to the. aspx page and the. vb or. cs Modular file, Visual Studio Creates a matching file (that is, WebForm1.aspx.resx) with a. resx extension. Like most WEB developers, you may also ignore or attempt to delete these files because their use and/or usage is not straightforward. In short, these. resx files are called resource files and are primarily used to store individual versions of resources, such as text strings for different languages used for localization.

In Visual Studio. NET 2002 and 2003, resource files need to be added to the project assembly as part of the build project process, and you need to import two namespaces, create a ResourceManager object, and call its GetString method to access the The source string.

With the help of the \code directory, the resource access process in Visual Studio. NET Whidbey becomes very simple, as shown in the following example.

Let's start with creating a resource file, or using the project in the previous example. First, right-click the compilation Web site you just created, and then click Add New Item ... (Add New Item ... )。 In the Add New Item dialog box, select Assembly Resource file (assembly resource file) template, name the resource file Strings.resx, and then click Open. The default view of the Strings.resx file should resemble Figure 6.



Figure 6: Editing a resource file in the XML editor

Add the following items to the datasheet (you can leave the "comment" (note), type (type), and mimetype (MIME type) columns blank):

Name value
Txtcolorprompt Please choose a color:
Txtcolorresponsered you have chosen red!
Txtcolorresponsegreen you chose the green!
Txtcolorresponseblue you have chosen blue!

Now repeat the procedure above, add a new resource file named Strings.en-gb.resx, add the following items to its datasheet, and then save the file (because we did not add the txtcolorresponse* entry, all clients will use the Values for these items in the Strings.resx):

Name value
Txtcolorprompt Please choose a color:

Now, to take advantage of the magic of the Code directory, we need to drag these two. resx files from the root directory of the Web site to the code directory. When you do this, you will get a result similar to Figure 7.



Figure 7:code. resx files in the directory

To illustrate how simple it is to use the created resource file now, we add a Web form to the project by right-clicking the Web site node and then clicking Add New Item .... (Add New Item ... )。 In the Add New Item dialog box, select the Web form, name the page colorpicker.aspx, and then click Open. Modify this page so that it matches the following list.

Colorpicker.aspx:

<%@ page uiculture= "EN-GB" language= "VB"%>

<script runat= "Server" >


Sub Page_Load (ByVal sender as Object, ByVal e as System.EventArgs)
Label1.Text = Resources.strings.txtColorPrompt
End Sub

Sub Submit_click (ByVal sender as Object, _
ByVal e as System.EventArgs)
Label1.forecolor = _
System.Drawing.Color.FromName (Dropdownlist1.selectedvalue)
Select Case Dropdownlist1.selectedvalue
Case "Red"
Label1.Text = Resources.strings.txtColorResponseRed
Case "Green"
Label1.Text = Resources.strings.txtColorResponseGreen
Case "Blue"
Label1.Text = Resources.strings.txtColorResponseBlue
End Select
Dropdownlist1.visible = False
Submit.visible = False
End Sub
</script>

<title> Color Selector </title>
<body>
<form runat= "Server" >
<asp:label id= "Label1" runat= "Server" >Label</asp:label>
<asp:dropdownlist id= "Dropdownlist1" runat= "Server" >
<asp:listitem value= "Red" > Red </asp:listitem>
<asp:listitem value= "Green" > </asp:listitem>
<asp:listitem value= "Blue" > Blue </asp:listitem>
</asp:dropdownlist>
<asp:button id= "Submit"
text= "Submit" runat= "Server" onclick= "Submit_click"/>
</form>
</body>

When browsing colorpicker.aspx from a browser, the default output is similar to Figure 8. If you browse this page from a system set up for UK users (you can simulate this by setting the page's UICulture property to "EN-GB" and saving the page), the output is similar to Figure 9 (note that we have added u in "colour").



Figure 8:colorpicker.aspx Default output



Figure 9: Colorpicker.aspx output of the British system

Note that only one line of code is required to access a resource file in ASP.net Whidbey. Because the resource file is automatically embedded and referenced after it is placed in the Code directory, you do not need to reference any namespaces or assemblies, and you do not need to create objects for accessing resource strings. And ASP.net can also determine which resource file should be used (based on user browser settings), so we don't need to judge this at run time and respond accordingly. ASP.net can help us accomplish all this.

Pre-compiling support
One of the advantages of ASP.net Web forms is that after you add dynamic compilation, you can easily change the. aspx page, and the page will update dynamically when you save the changes without recompiling (as long as you don't use modular code). However, dynamic compilation is not appropriate for every application, and when you first access an application, dynamic compilation causes the browser's initial performance to degrade. Also, many times you may want to deploy an application that has no source code.

If you experience this, you'll be more than happy to learn that asp.net Whidbey has the ability to support precompiled Web sites. asp.net Whidbey supports two precompilation modes: in-place precompilation and deployment precompilation.

In-situ precompilation
In-place precompilation allows you to manually batch-compile all pages in a Web site. This is what happens when a user clicks a page for the first time in your application (except in the latter case mentioned above), and the user simply sits down to wait for the batch compilation to complete.

There are two main reasons to use in-place precompilation: First, it avoids the performance degradation of the batch compilation when the page is first requested, and secondly, it allows you to discover compilation errors "before" the user.

In-situ precompilation is also easy to implement by simply browsing to the root of the Web site and adding a specific handler name Precompile.axd (a user familiar with the ASP.net trace feature will find the name similar to the Trace.axd handler):

Http://localhost/mywebsitename/precompile.axd

Where Mywebsitename is the name of your Web site. Once the site is precompiled, requests for pages within the site should be completed without any compile latency.

Deploying precompilation
The second precompilation mode allows you to create an executable version of the entire Web site that does not require any source code (including HTML and other static files) to deploy this version. Therefore, deployment precompilation prevents others from randomly accessing intellectual property information that is represented by code. The generated assemblies and Stub file sets can be deployed to the production server through XCOPY, FTP, Windows Explorer, and so on.

To precompile a site for deployment, ASP.net Whidbey provides a command-line utility named Aspnet_compiler.exe. To invoke the ASP.net preprocessor on the file system Web site, you need to open a command window to browse to the installation location of the. NET Framework (<Windows>\Microsoft.NET\Framework\< version >) , and then enter the following command:

aspnet_compiler/v/<websitename>-P <source> <destination>

Where <websitename> is the name of the Web site (that is, the name entered in the browser),<source> and <destination> to two file system paths. Point to the location where you want to compile the site and where the compiled version should be exported. As an example of our Web site, the commands you enter are as follows (note that the following is a command):

Aspnet_compiler/v/compilation
-P c:\WebSites\Compilation c:\WebSites\Compilation_Compiled
If you want to view all available options for the ASP.net preprocessor, simply enter the following command:

Aspnet_compiler/?

Note that some command-line options require that the WEB site must be a valid Microsoft®internet information Service (IIS) application to function correctly.

If you browse to the target directory in Microsoft®windows Explorer, you will see that the precompiled Web site will generate a site containing the bin directory containing assemblies and descriptive files, as well as a large number of Stub files with the same name as the original page. But does not contain code (including HTML and executable code). If you browse this site, the output is the same as the output from the original site. Note that you cannot use in-place precompilation on a site that has been precompiled for deployment because it has been precompiled.

IntelliSense is everywhere!
For Visual Studio. NET 2002 and 2003, one of the most vexing issues (I believe many developers agree) is inconsistent with IntelliSense and other features used to improve productivity. Do you want to drag controls from the toolbox to the page in HTML view? I can't do that. In fact, the Toolbox's Web forms panel is not visible in HTML view at all! Do you want to write inline code on the. aspx page instead of using modular code? You can do this, but you must discard IntelliSense, drag-and-drop functionality, and more. Finally, as I mentioned in my recent article in MSDN asp.net Developer Center, the design-time support for customizing controls in Visual Studio. NET 2002 or 2003 needs to span layers of barriers, including a somewhat coarse but effective XSL Modify.

Happily, the unification of the compilation model was implemented in ASP.net Whidbey, and all these problems were solved. In Visual Studio. NET Whidbey, you can write inline code or use a new modular code model, as well as control drag-and-drop, IntelliSense-statement completion, and all of the functionality that you would like to use to increase productivity that you would otherwise be unable to use because of coding limitations. In addition, the design-time support for custom server controls and Web controls has been greatly improved, including adding IntelliSense statements to the custom controls in the Source view (HTML view in the equivalent view in Visual Studio. NET Whidbey).

Summary
Changes to the compilation model in ASP.net Whidbey, as well as improvements to the corresponding features in Visual Studio. NET Whidbey, are undoubtedly a huge leap forward, not only to provide developers with the required flexibility, but also to enable them to take full advantage of the IDE Provides the ability to increase productivity. The dramatically simplified modular code model makes the feature more useful and straightforward, and the new full support for inline code is clearly welcomed by developers who want all the code to be in an. aspx file.

It is believed that the \code directory will greatly increase productivity, especially for developers who are engaged in fast-growing small and medium projects, as well as for developers who are unable to complete their work because of the complexity of the compilation process. It also provides a more straightforward and straightforward way to access business logic components, resource files, WSDL files, and other resources: by automatically compiling, embedding, or creating proxies for these resources and automatically referencing them, you can access these resources with little code.

The precompilation feature allows developers to easily improve the initial performance of their site and, if necessary, add protection to important intellectual property information by providing full-featured WEB applications that do not contain source code or HTML.

Finally, a set of all functional Visual Studio. NET Whidbey will undoubtedly give developers extraordinary experience, not only from the embedded code model and the modular code model to obtain full IntelliSense support, but also to see all the views of a given page, Development work will no longer be limited to a certain style by tool limitations.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.