Você está na página 1de 24

Feature Changes in ASP.NET 2.0 Understanding ASP.NET Dynamic Compilation By default, ASP.

NET Web pages and code files are compiled dynamically when users first request a resource, such as an ASP.NET page (.aspx file), from a Web site. After pages and code files have been compiled the first time, the compiled resources are cached, so that subsequent requests to the same page are extremely efficient. ASP.NET supports the dynamic compilation of ASP.NET pages (.aspx files), ASP.NET Web services (.asmx files), ASP.NET HTTP handlers (.ashx files) and ASP.NET application files (Global.asax), as well as other files, such as source code and class files. Any changes to a dynamically compiled file will automatically invalidate the file's cached compiled assembly and trigger recompilation of all affected resources. The next time a request to the code is made, ASP.NET recognizes that the code has changed and recompiles the affected resources of the Web application. This system enables you to quickly develop applications with a minimum of compilation processing overhead. When the first request is made to an application, ASP.NET compiles files in a specific order. The first items to be compiled are referred to as the top-level items. After the first request, the top-level items are recompiled only if a dependency changes. Top-level items include the App_GlobalResources folder, the App_WebResources folder, profile properties, the App_Code folder, and the Global.asax file. After the top-level items are compiled, ASP.NET compiles additional items. These items include the App_LocalResources folder, individual ASP.NET pages (.aspx files), ASP.NET user controls (.ascx files), ASP.NET HTTP Handlers (.ashx files), and ASP.NET HTTP modules (.asmx files), as well as themes, master pages, and other source files. By default, when you compile a Web application the compiled code is placed in the Temporary ASP.NET Files folder: %SystemRoot%\Microsoft.NET\Framework\versionNumber\Temporary ASP.NET Files Changes in Architecture ASP.NET 1.X Compilation Model <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="SampleWeb.WebForm1" %> Visual Studio pre-compiles all the code-behind pages into a project assembly and places it in the bin directory. Because my Web project is named SampleWeb, the DLL is named SampleWeb.DLL. The Inherits attribute tells the compiler the class in the project assembly from which the ASPX page inherits. In the previous code snippet, it tells the compiler to look for a class called WebForm1 in the SampleWeb.DLL. <%@ Page language="c#" Src="WebForm2.cs" AutoEventWireup="false" Inherits="WebForm2 " %> If we want each page as a separate assembly (instead of the code-behind pages being precompiled into a project file), the framework supports a slightly different model for ASP.NET. In this case there is no code-behind attribute in the page directive. The link between the ASPX file and its corresponding code-behind page is managed by the Src attribute. The Src attribute points to the code-behind page as shown above. The code runs exactly the same way in both the models: ASP.NET compiles the ASPX page the first time the user requests it and then stores it into its cache. Next time around ASP.NET checks the cache to see if the copy of the page exists. In case it cannot find one, it creates a temporary source code file that represents the Page class. It puts it in the temporary ASP.NET files folder that exists inside the Windows\Microsoft.Net\Framework\Version\TemporaryASP.NETFiles\<Website> folder. In ASP.NET 1.X, the two modes of compilation available were either compilation on first request of each page or batch compilation where in many temporary ASPX pages were compiled into a single assembly. Batch compilation is preferred in some scenarios to reduce the delay on the first page request. ASP.NET 2.0 Compilation Model

The code-behind file is much cleaner than the ones in ASP.NET 1.X. The code-behind page just contains the user-defined code. It no longer contains all the control declarations that are needed to synchronize the ASPX file and the code-behind page in ASP.NET 1.X. In ASP.NET 2.0, the association between the ASPX and the code-behind page is specified with a new directive called Compilewith shown in the following code snippet: <%@ Page Language="C#" CompileWith="Default.aspx.cs" ClassName="Default_aspx" %> A new directive called ClassName, here specified as Default_aspx. This is the name of the class that the page would be given when it is compiled. ASP.NET 2.0 has simplified the batch compilation process and all that is needed is a single URL request: http://localhost/myapp/precompile.axd This mode of compilation is known as in-place compilation. The advantage of using in-place compilation is that it helps eliminate the time delay in batch compilation on the first request. It also helps to identify the compilation errors before the users find them. Full deployment pre-compilation All the code-behind, ASPX, and HTML files are compiled into one or more assemblies or executables. This type of compilation helps to protect the intellectual property in the code because the ASPX and code-behind files no longer have to be deployed as such on the production server. The compiled executable can then be copied to its destination via Xcopy or FTP. This model of compilation provides the greatest performance and security. However, it comes at a cost because we will not be able to modify the Web site once it's deployed. For full deployment pre-compilation, we use a command line tool called aspnet_compiler. The result of pre-compiling is a site with a bin directory that contains assemblies and a number of stub files with the same name as the original pages. However, when you open them you will notice that the files contain no code or HTML markup inside, although the user will not notice any difference when browsing the Web site. The code below shows the command line option to precompile the Web site. aspnet_compiler /v /<websitename> -p <source path> <destination> <websitename> is the name of the Web site <source path> is the location of the Web site to compile, and <destination> is the file path where the compiled assemblies have to be deployed. Now that compilation into assemblies can happen in one of three places (either explicitly by the developer, using aspnet_compiler.exe, or during request processing), understanding the mapping of files into assemblies becomes even more important. In fact, depending on how you write your pages, you can actually end up with an application that works fine when deployed as all source or all binary, but which fails to compile when deployed using the updatable switch. Figure 1 Syntax in ASP.NET 2.0 Default.aspx <%@ Page Language="C#" AutoEventWireup="true" Default.aspx.cs namespace MsdnMag { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } } Figure 2 Implicit Server-Side Control Access Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MsdnMag.Default" %> CodeFile="Default.aspx.cs" Inherits="MsdnMag.Default" %>

<!DOCTYPE html PUBLIC "..." "..."> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Enter your name: <asp:TextBox ID="_nameTextBox" runat="server" /><br /> <asp:Button ID="_enterButton" runat="server" Text="Enter" OnClick="_enterButton_Click"/> <br /> <asp:Label ID="_messageLabel" runat="server" /> </div> </form> </body> </html> Default.aspx.cs namespace MsdnMag { public partial class Default : System.Web.UI.Page { protected void _enterButton_Click(object sender, EventArgs e) { _messageLabel.Text = "Hello there " + _nameTextBox.Text + "!"; } } } Figure 3 Class Generation with Codebehind Class for ASPX file generated by ASP.NET namespace ASP { { ... } public class default_aspx : MsdnMag.Default

} Sibling partial class generated by ASP.NET namespace MsdnMag { public partial class Default : IRequiresSessionState { protected TextBox private } } Codebehind partial class that you write namespace MsdnMag { public partial class Default : Page { void _enterButton_Click(object sender, EventArgs e) { _messageLabel.Text = "Hello there " + _nameTextBox.Text + "!"; } } } Figure 6 Assembly Generation Deployment Mode All Source What compiles into a unique assembly App_Code directory global.asax .ascx and associated codebehind file (separate assembly for each user control) .master and associated codebehind file (separate assembly for each master page) All .aspx files and their codebehind files in a given directory (separate assembly per directory) Request time All Binary App_Code directory global.asax .ascx and .master files and their associated codebehind files All .aspx files and their codebehind files in a given directory (separate assembly per directory) Updatable (mixed) App_Code directory (D) global.asax (R) .ascx and .master files codebehind files for .ascx and .master files (D) All .aspx files in a given directory (separate assembly per directory) (R) All codebehind files associated with .aspx files in a given directory (separate assembly per directory) (D) (R) = Compiled at request time (D) = Compiled at deployment time _nameTextBox; protected Button _enterButton; protected Label _messageLabel;

HtmlForm form1;

When it's compiled

Deployment time

The Provider Model Many of the new features in ASP.NET 2.0 depend on communication between the Web application and a data store. In order to provide this access in a consistent fashion, ASP.NET 2.0 uses the provider factory model. A provider is both a pattern and a point where developers can extend the ASP.NET 2.0 framework to meet specific data store needs. For example, a

developer can create a new provider to support the user identification system, or to store personalization data in an alternate data store. Most custom providers will interact with database backend systems. However, the programmer is free to implement the required provider methods and classes using any medium or algorithm so long as it meets the models required interface specification. ASP.NET 2.0 Providers The provider model defines a set of interfaces and hooks into the data persistence layer that provides storage and retrieval for specified requests. In this way the provider model acts as a programming specification that allows ASP.NET 2.0 to service unique client concerns. ASP.NET 2.0 uses a wide variety of providers, including:

MembershipThe membership provider manages supports user authentication and user management. ProfileThe profile provider supports storage and retrieval of user specific data linked to a profile. PersonalizationThe personalization provider supports persistence of Web Part configurations and layouts for each user. Site NavigationThe site navigation provider maps the physical storage locations of ASP.NET pages with a logical model that can be used for in-site navigation and linked to the various new navigation controls Data providersADO.NET has always used a provider model to facilitate the connection between a database and the ADO.NET API. ASP.NET 2.0 builds upon the data provider by encapsulating many of the ADO.NET data calls in a new object called a data source.

Each type of provider acts independently of the other providers. You can therefore replace the profile provider without causing problems with the membership provider. In the second section of this paper, you will find specific examples of how providers are used with several of the new ASP.NET 2.0 features. The ASP.NET 2.0 Coding Model In ASP.NET 1.x, you could develop an ASP.NET page in one of two ways. First, you could put your code directly inline with your ASP.NET tags. The code inline model is very similar to the coding model that was prevalent with classical ASP and other scripting languages. However, the code inline model has several problems such as the intermixing of code and HTML. ASP.NET 1.0 introduced the code behind model as a replacement. The code behind model used an external class to house the code, while the ASPX page contained the HTML and ASP.NET tags. The code behind model thus successfully separated code from content; however it created some interesting inheritance issues and forced the developer to keep track of two files for each Web page. Although ASP.NET 2.0 still support both of these models, several significant changes have been made to both. For a more detailed review of these concepts, please see ASP.NET 2.0 Internals. Code Behind As in ASP.NET 1.x, the default code model is the code behind model. If you want to work with a separate code file, you have to create the file when you create the ASPX page. Fortunately, creating a code behind file is as simple as clicking a checkbox when you decide to create a new page.

Figure 1. Creating a Code Behind file The primary difference between a code behind file in ASP.NET 1.x and ASP.NET 2.0 is that a code behind file is now a partial class rather than a full class that inherits from the ASPX page. A partial class is a new .NET construct that allows you to define a single class in multiple source files. In ASP.NET 2.0, a partial class is particularly useful for code behind files as it removes the inheritance relationship that is present with the older code behind model.

Figure 2. Code Behind model for ASP.NET 2.0 The two partial classes (ASPX and code behind) are merged into a single class during compilation. The code behind file is therefore free of all of the control declarations and inheritance issues associated with the old code behind model. The most striking difference can be seen in the actual code behind file, which no longer contains all of the auto-generated code that used to be necessary to maintain the inheritance relationship. An old code behind file contained an initialization region, as well as initialization code for every control placed on the page. Copy Code

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 code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion void Page_Load(object sender, EventArgs e) { Label1.Text = "Hello ASP.NET 2.0"; } } } Listing 1. An old code behind file (C#) A new file removes all of this code since the controls are declared in the ASPX page (the other half of the partial class) Copy Code namespace ASP { public partial class Webform1_aspx : System.Web.UI.Page { void Page_Load(object sender, EventArgs e) { Label1.Text = "Hello ASP.NET 2.0"; } } } Listing 2. A new code behind file As you can see, the new code behind file is much cleaner and easier to read. The code behind file has automatic access to any controls added to the ASP.NET page, and Visual Studio 2005 will provide automatic IntelliSense support and synchronization. Visual Studio also recognized when you are using a code behind file and opens the file rather than the source view when you double click on a control to access its events. Code Inline When you use the code-behind model in Visual Studio 2005, any code you add to the page will automatically be added to a <script> block within the ASPX file instead of to a code behind class. However, Visual Studio 2005 still displays the code in the code view. In other words, you can keep using Visual Studio like you always have, except that code will be placed directly in the ASPX page instead of a separate class.

Figure 3. Switching views

Note that the code is still separated from the content through <script> blocks and placement in the file. However, as a developer, you only have to worry about one file now instead of synchronizing two separate files. The /app_Code directory The final major change to the coding model is a direct response to a common problem in ASP.NET. Most Web applications require one or more support classes. In ASP.NET, the preferred method was to create a separate project for support classes and then add a reference to the support project within your Web application. Even if you didn't create a separate project, you still had to create a reference to whatever namespace you used within your own application. Although having a separate project made sense for larger and more complicated applications, it was often painful for developers who only needed one or two simple classes. ASP.NET 2.0 introduces a new way of adding support code. The /app_code directory is a special directory that is automatically compiled and referenced by your ASP.NET application. That is, any classes you place inside the /app_code directory are automatically accessible from any ASPX page in your application. Visual Studio 2005 and the ASP.NET compiler both automatically create an assembly from these classes and place a reference to the assembly in your Web application. In total, ASP.NET implements seven protected application directories to organize and maintain the contents and data for each of your applications: New Directory /Bin /app_code /app_globalresources /app_localresources /app_webreferences /app_data /app_browsers /app_themes Table 1. Application Directories Contents Referenced assemblies Shared application code Common resource files Localized resource files Links to web services Local databases for membership, web parts, etc. Browser specific settings Theme settings

Most of these directories are protected against web access at the ISAPI layer linking ASP.NET to IIS. That is, users can't navigate into a special directory unless it is absolutely necessary for them to do so (e.g. app_themes is open because it contains html layout files). Configuration and Site Maintenance One of the more difficult challenges as an ASP.NET developer was properly configuring the Web.config file. In ASP.NET 2.0 and Visual Studio 2005, you now have several new features to help you with this task. IntelliSense in Web.config First, Visual Studio's IntelliSense feature has now been extended to any XML file that has a valid schema. In the case of the Web.config file, this means that you get full IntelliSense support whenever you edit the Web.config file from within Visual Studio.

Figure 4. IntelliSense on Web.config IntelliSense helps reduce the chance of mis-configured files. However, ASP.NET 2.0 also includes a new administrative Website and a Microsoft Management Console to make things even easier. Administrative Website To simplify the process of managing users, ASP.NET 2.0 provides a built in Website configuration tool. The Web Site Administration Tool is a simple Website that can only be accessed on the localhost through Visual Studio 2005. Through this tool, an administrator can manage the application by configuring services such as user management, the personalization providers, security, and profiles. The tool also allows you to easily configure debugging and tracing information for your application.

Figure 5. Web site administration tool Although the tool is limited to local applications, you can easily access all of the same configuration features through the improved configuration and administration API. Microsoft Management Console Snap-In ASP.NET 2.0 deploys a special Microsoft Management Console (MMC) snap in for IIS that lets you decide which applications should use which versions of the .NET Framework.

Figure 6. MMC display of ASP.NET applications The MMC IIS tab lets you to choose which version of ASP.NET your application uses and displays the Web.config location. In addition to managing the framework version, the console has an "Edit configuration" button which lets you visually edit most of the Web.config settings without having to directly manipulate the Web.config XML file. As an administrator, you will find that this MMC snap-in provides an incredibly useful tool for configuring and managing multiple ASP.NET applications on a single server. Enhanced Configuration APIs You can also retrieve and edit configuration information using the System.Configuration.Configuration class. These API's let you programmatically access XML configuration files. This lets you to develop custom administration tools. The following code displays the type of authentication enabled for an application on your local machine: Copy Code Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); AuthenticationSection authSection = config.GetSection("system.web/authentication") as AuthenticationSection; Response.Write("Authentication mode is: " + authSection.Mode); Listing 3. Displaying the authentication type on an application The following code enables Forms based authentication for a local Web application: Copy Code Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); AuthenticationSection authSection = config.GetSection("system.web/authentication") as AuthenticationSection; authSection.Mode = AuthenticationMode.Forms; config.Save(); Listing 4. Enabling Forms authentication for an application All four of these features (IntelliSense, administrative Website, MMC snap-in and configuration API's) help reduce the amount of time and effort you will have to spend configuring your ASP.NET applications. Compilation Options

ASP.NET 2.0 offers four different compilation models for a Web application: 1. Normal (ASP.NET 1.x)In a normal ASP.NET Web application, the code behind files were compiled into an assembly and stored in the /bin directory. The Web pages (ASPX) were compiled on demand. This model worked well for most Websites. However, the compilation process made the first request of any ASP.NET page slower than subsequent requests. ASP.NET 2.0 continues to support this model of compilation. 2. Batch compilationIn ASP.NET 2.0, you can batch compile any application with a single URL request. As with ASP.NET 1.x, batch compiling removes the delay on the first page request, but creates a longer cycle time on startup. In addition, batch compilation still requires that the code behind files are compiled pre-deployment. 3. Deployment pre-compilationA new feature of ASP.NET 2.0 allows for full compilation of your project prior to deployment. In the full compilation, all of the code behind files, ASPX pages, HTML, graphics resources, and other back end code are compiled into one or more executable assemblies, depending on the size of the application and the compilation settings. The assemblies contain all of the compiled code for the Website and the resource files and configuration files are copied without modification. This compilation method provides for the greatest performance and enhanced security. If you are working with highly visible or highly secure Websites, this option is the best choice for final deployment. However, if you are building a small site running on your local intranet, and the site changes frequently, full pre-compilation may be over kill. 4. Full runtime compilationAt the other extreme of deployment pre-compilation, ASP.NET 2.0 provides a new mechanism to compile the entire application at runtime. That is, you can put your un-compiled code behind files and any other associated code in the new \code directory and let ASP.NET 2.0 create and maintain references to the assembly that will be generated from these files at runtime. This option provides the greatest flexibility in terms of changing Website content at the cost of storing un-compiled code on the server. Choosing the best compilation option will depend on your exact circumstances and needs. However, the compilation model remains flexible. Even if you choose to make use of the \code directory to store your code-behind files, you may still deploy your application using the full compilation method. The ASP.NET 2.0 compilation model allows developers to pre-compile their code. As mentioned earlier, pre-compilation offers significant performance gains, but still allows developers to separate binary and markup content. Developers still have the option to fully compile both the .markup and code into binary during pre-compilation. The class-derivation model removes the issue of requiring the markup and code-behind file to be in sync. This allows developers to separate the markup file and the code-behind file. The following code demonstrates the page directives for ASP.NET 2.0 pages using both C# and Visual Basic .NET: Copy Code // C# webform1.aspx: <%@ page codefile=webform1.aspx.cs inherits=WebForm1 %> ' Visual Basic .NET webform1.aspx.cs: public partial class WebForm1 : System.Web.UI.Page {} Listing 5. Page Directives in ASP.NET 2.0 For a more detailed description about code compilation and configuration, please see ASP.NET 2.0 Internals. Changes in Development ASP.NET 2.0 and Visual Studio 2005 also change many of the day to day aspects of Web application development. In this section, we will look at several of the areas where features available in ASP.NET 1.x have been heavily modified. Development Tools The latest release of Visual Studio (Visual Studio 2005) includes several new development tools to help you build Web applications.

IntelliSense Now everywhere! IntelliSense helps you develop code faster by issuing "popup" programming hints. Every time you reference an object in your code, IntelliSense offers you a list of available methods, properties and events. You no longer have to type out complete methods, or search documentation for parameter specifications. Previous releases of Visual Studio.NET had excellent IntelliSense support, but the Visual Studio 2005 allows you to take advantage of IntelliSense in script blocks, inline CSS style attributes, configuration files and any XML file that contains a DTD or a XML schema references.

Wizards to auto-generate code for many tasks One of the major goals of ASP.NET 2.0 is to reduce development time and the number of lines of code you have to write. Visual Studio 2005 includes wizards you can use to create data source connections, and many other common tasks.

Designer support for master pages, themes and skins Classic ASP pages required you to start each page from scratch. Replicating page layout in an application was a timeconsuming process. Visual Studio 2005 provides full WYSIWYG support for ASP.NET master pages. Master pages are page templates that can be used to apply a consistent style and layout to each page in your application. After you create a master page, you can easily create new pages that leverage your master page, and let ASP.NET automatically apply the style and layout of the master page. Visual Studio 2005 lets you see how any content you add to a page will look when combined with the master page (even though the code from the master page is hidden from your development page).

Improved code editing features Editing code is not an easy task in traditional ASP applications. Visual Studio 2005 makes code editing much easier by preserving all HTML code (including white space, casing, indention, carriage returns, and word wrapping). Visual Studio 2005 allows you to set style formats for the HTML code for your application that can be imported or exported to standardize development for your whole team. Style sheets allow you to format the way your content is displayed to a user. Visual Studio.NET 2005 allows you to customize the format for how your HTML code is written. For example, you can enforce style guidelines to ensure all HTML tags are capitalized, or that all nested HTML elements are indented two spaces. These guidelines allow your entire development team to develop pages with the same formatting rules. Visual Studio 2005 also supports tag-outline and tag-navigation modes to help you edit large documents. These modes allow you to move through, expand, and collapse HTML and ASP.NET tags, and to see open and closed tag relationships clearly. You can easily add and edit tables into HTML pages using the "Insert Table" dialog box. The wizard lets you specify the style, size (table width and the number of rows and columns), and format of a table without writing any code. Visual Studio 2005 also allows you to develop your HTML code for a specific Web browser or HTML standard. For example, it you want all your HTML code to adhere to Netscape's standard, you can select Netscape HTML as your target, and any code that doesn't meet Netscape's standards will be flagged in real-time.

Visual Studio 2005 includes a light weight Web server Visual Studio 2005 includes a light-weight Web server for developing ASP.NET applications. The Web server services local requests only and is perfect for development. By adding this Web server, you no longer need to use IIS on a development machine. You can use the built-in server, and get full debugging support. Another important advantage is

any user can build and test an application. You no longer need to be an administrator on the computer. It should be noted that you must still deploy your final applications on IIS.

Improved debugging environment Debugging applications in ASP is an arduous process, as code is interpreted on the fly. Syntax errors aren't exposed until you run applications. The debugging support is improved in Visual Studio 2005. Visual Studio .NET 2003 provided limited support for edit-and-continue debugging. Visual Studio 2005 improves edit-and-continue debugging and provides more information during the debugging process. For example, an improved implementation of DataTips provides information about variables and expressions as mouse popup windows during the debugging process. Visual Studio 2005 also provides additional features, like advanced debugging with breakpoints on disassembly, registers, addresses (when applicable), and "Just My Code Stepping".

For a more detailed description of the development tools provided by Visual Studio 2005, please visit http://msdn.microsoft.com/vstudio/. Connecting to the Server In ASP.NET 1.x and older versions of Visual Studio .NET, you had to connect to an IIS instance through Front Page Server Extensions. As a developer, you also had to have administrative access to an IIS instance in order to create new websites. Many companies were leery of the administrative burden of creating, monitoring, updating and maintaining extra Web servers running inside the corporate network. In ASP.NET 2.0, connecting to the server has changed. The Development Server First, for development, Visual Studio 2005 now comes with a built in development-only Web server. This lightweight Web server can only respond to local requests and is therefore not a security threat. The server does, however, support full debugging features and can be used as a development tool for new Web applications. When you are ready to test out scalability and performance or deploy for production, simply move the application to IIS. The Production Server When you are connecting to an IIS instance, you now have several choices. When you open a Web application project in Visual Studio .NET, you are asked to select a connection method.

Figure 7. Connecting to a Web Application via FTP

You can use Front Page Server Extensions, FTP, Share Point or several other mechanisms to transfer files to the server and synchronize code. Compiling ASP.NET 2.0 Applications Another major change to traditional ASP.NET 1.x involves the ways in which Web applications can be compiled. In ASP.NET 1.x, applications were either compiled on first request, or in a batch mode on start up. Both methods had advantages and disadvantages. The most notable shared disadvantage was that you generally had to deploy uncompiled code to a production server. This code could be manipulated directly on the production server, which was either an advantage or a disadvantage depending on your security needs. ASP.NET 2.0 offers a new compilation method that pre-compiles your proprietary source code into binary assemblies for deployment. The pre-compiled application consists of assemblies that can be strongly named and signed, and various resource files such as images which have no significant value to an attacker. The pre-compiled application is therefore much more secure than a normal ASP.NET application. For more information on compilation options, please see ASP.NET 2.0 Internals. Site Navigation Web sites require consistent navigation to provide a pleasant user experience. Traditional ASP applications rely on adding hyperlinks, or user controls that encapsulate hyperlinks. Creating these hyperlinks is a very time consuming process and often causes problems when pages are moved to new locations within the application. ASP.NET 1.x did not have a really useful solution to this problem. You still had to encode links in HTML tags or within ASP.NET control properties. ASP.NET 2.0 offers many new features to improve site navigation and reduce the maintenance tasks of changing the physical locations of Web pages. ASP.NET 2.0 allows you to define your application's navigation based on a logical structure. Using a logical structure for navigation allows you to create a navigation path for your application by logically relating Web pages to one another, instead of depending on the physical location of each page on the server. By organizing the navigation logically, you can reorganize your application's navigation without modifying any code. You can also use the logical structure to create navigational aids such as tree views, menus, and "bread crumb" trails. The web.sitemap file The ASP.NET 2.0 SiteMap class exposes the logical structure of your Website. You can define the underlying structure using XML with the site navigation provider included in ASP.NET 2.0, or you can use any other data format with a custom provider. Once you have defined the layout, you can use the navigational structure in many different ways. A logical structure can be created in two easy steps: 1. Create an XML file named web.sitemap that lays out the pages of the site in a hierarchical fashion. Visual Studio 2005 allows you to create new .sitemap files ("Add New Item" and select the sitemap template), and also provides IntelliSense support when editing sitemap files. Copy Code <?xml version="1.0" encoding="utf-8" ?> <siteMap> <siteMapNode title="Home" url="default.aspx"> <siteMapNode title="Article 1" url="~/articles/demoarticle1.aspx" /> <siteMapNode title="Article 2" url="~/articles/demoarticle2.aspx" /> <siteMapNode title="Article 3" url="~/articles/demoarticle3.aspx" /> </siteMapNode> <siteMapNode title="Picture Gallery" url="~/PhotoAlbum/PhotoAlbums.aspx"> <siteMapNode title="Meetings" url="~/PhotoAlbum/PictureAlbum.aspx?albumid=1"/> <siteMapNode title="Activities"

url="~/PhotoAlbum/PictureAlbum.aspx?albumid=2"/> <siteMapNode title="Training" url="~/PhotoAlbum/PictureAlbum.aspx?albumid=3"/> </siteMapNode> </siteMap> Listing 6. Sample XML web.sitemap

2.

Drag a SiteMapDataSource control from the Toolbox and drop it on a page. The SiteMapDataSource control will automatically bind to the logical site structure contained in the web.sitemap file.

Once the SiteMapDataSource control is on a page, you can easily bind it to other controls such as the treeview control or the menu control. Copy Code <%@ page language="VB" masterpagefile="~/Mysite.master" %> <asp:content id="Content1" contentplaceholderid="LeftSideContent"> <H2>Navigation </H2> <asp:treeview id="Navigation tree" runat="server" datasourceid="NavSource"/> </asp:content> Listing7. Implementing a Treeview control The tree view will display site navigation using a hierarchical view based on the definitions in the web.sitemap file. Navigation Controls ASP.NET 2.0 also introduces a set of navigation controls that can be used with the site navigation service. By using the <asp:TreeView> or <asp:Menu> controls, you can create a visual navigation structure for your application. The new <asp:SiteMapPath> control can be used to generate a "bread crumb trail" navigation structure.

Figure 8. Bread crumb trail for the Home / Articles / Article 2 page For a more detailed description about site navigation and navigation controls, consult the following power point presentation: http://www.asp.net/whidbey/downloads/WSV315_Sanabria_slide.zip. URL Mapping Another new navigation-related feature in ASP.NET 2.0 is URL Mapping. Websites often require long, complicated and convoluted URLs (think of an MSDN reference!). If you wanted to hide your URLs in a classical ASP application you had to write a custom ISAPI handler to pre-process requests. ASP.NET 2.0 adds the URLMapping configuration section to the Web.config file. A developer can define a mapping that hides the real URL by mapping it to a more user friendly URL. Copy Code <urlMappings enabled="true"> <add url="~/Home.aspx" mappedUrl="~/Default.aspx?tabid=0" /> </urlMappings> Listing 8.URLMapping configuration section The configuration shown above would map (and redirect) all requests for Home.aspx to Default.aspx?tabid=0. Users can bookmark the short link, and the short link will be displayed on their browser. Data Access and Data Sources ASP.NET 1.x data access leveraged ADO.NET connections and commands to provide data that could be bound to various ASP.NET controls. ASP.NET 2.0 improves on the relationship with ADO.NET by providing data sources which encapsulate the

code to create both connections and commands in a single XML tag within the Web.config file. As with ASP.NET 1.x, you can use a wizard inside of Visual Studio 2005 to create these data sources. ASP.NET 2.0 ships with data sources for:

Microsoft AccessThe access data source can automatically connect to and query an Access database. ObjectsThe OjbectDataSource control is a data layer abstraction on top of a middle tier or other set of objects. You can use the Object Data Source when you want to treat one or more sets of objects as data that can be linked to data bound controls.

XMLThe XmlDataSource links to hierarchical data in an XML file. Site MapThe SiteMapDataSource provides a data source for the site navigation controls including bread crumbs.

New Data Bound Controls ASP.NET 2.0 also includes two new data bound controls. The first control, GridView, expands on the DataGrid by providing configurable code for editing cells, displaying rows on multiple pages, sorting, deletion, selection, and other common behaviors.

Figure 9. GridView control The second control, DetailsView, provides a detail view that complements both GridView and DataGrid.

Figure 10. DetailsView control The DetailsView control displays one record at a time, giving you much greater control over how a record is displayed, edited, deleted or created. New Features in ASP.NET 2.0

Almost every major update to an API or framework involves both changes to existing features and new features and enhancements. In this section, we will look at several of the new features available in ASP.NET 2.0. Master Pages Master pages are a new feature introduced in ASP.NET 2.0 to help you reduce development time for Web applications by defining a single location to maintain a consistent look and feel in a site. Master pages allow you to design a template that can be used to generate a common layout for many pages in the application. The primary goal of master pages is to avoid creating each page from scratch and having to repeat the layout code. Another benefit of using master pages is that, if you want to change the layout of the pages in the application, you only have to update the master page rather than each individual page. This feature is somewhat similar to the Windows Form technique of Visual Inheritance, which was available with the original version of the .NET Framework and is used for desktop application development. A master page looks like any ordinary ASP.NET Web page except for the extension (.master instead of .aspx) and some special controls and header fields. Master pages must contain one or more <asp:ContentPlaceHolder> controls. These controls represent areas of replaceable content. Basically, anything that is not in a ContentPlaceHolder will appear on any page that uses the master page. Visual Studio 2005 automatically creates most of this code for you, so you don't have to write complex HTML code for your page layout. A master page must also include the following default source code: Copy Code <%@ master language="C#" CodeFile="site.master.cs" Inherits ="ASP.site_master" %> <html> <head runat="server"><title>Untitled Page</title></head> <body> <form runat="server"> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> </form> </body> </html> Listing 9. Source code added to each master page Other than these key changes, a master page can contain any HTML or control that can be found on a normal ASP.NET page. Although master pages and frames serve a similar purpose, master pages offer much more functionality. Unlike with frames, using master pages allow you to:

Bookmark a page and recall all the information on the specific page, not just the default frame page. A master page isn't really a frame. It's a single page that contains collated content from the master page and the content page that builds on the master. Therefore it looks and acts like a single Web page rather than a frame.

Work by means of controls and tags rather than HTML. Thanks to Visual Studio, you don't have to worry about opening and closing frame tags or modifying countless html attributes to ensure that each frame displays in the correct fashion. You can simply create the place holder and modify its properties through Visual Studio.

Leverage Visual Studio 2005 code creation to visually design the layout, manage the frames and provide all of the plumbing to link the content pages into the master page. You can add new content without having to worry that the overall HTML layout of the page will be affected.

In short, master pages greatly simplify the task of making a Web application look consistent, regardless of how many pages are involved. Content Pages Content pages are attached to a master-page and define content for any ContentPlaceHolder controls in the master page. The content page contains <asp:content> controls which reference the <asp:contentPlaceHolder> controls in the master page through the ContentPlaceHolder id. The content pages and the master page combine to form a single response.

Copy Code <%@ page language="VB" MasterPageFile="~/Mysite.master" %> <asp:content id="Content1" contentplaceholderid="LeftSideContent"> <H2>Navigation </H2> <asp:treeview id="Navigation tree" runat="server" datasourceid="NavSource"/> </asp:content> <asp:content id="Content1" contentplaceholderid="RightSideContent"> <asp:label runat="server">Support section</asp:label> </asp:content> Listing 10. Content page placeholders in a master page Once again, the user actually makes a request for the content page. ASP.NET notices the reference to the master page and renders the master page content in combination with the content page. Nested Master Pages In certain instances, master pages must be nested to achieve increased control over site layout and style. For example, your company may have a website that has a constant header and footer for every page, but your accounting department has a slightly different template than your IT department.

Figure 11. Nested Master Pages By nesting individual department master pages within the top-level company master page, you can implement high levels of consistency for each department while controlling what can be overridden by content and master pages. The key point to remember is that the end user requests one page and receives one page, even though the application may be compiling content from multiple master pages and content pages! Overriding Master Pages Despite the best planning and requirements review, situations will arise where a new feature has to be added to one particular web page. If you are considering abandoning your master page to add or remove functionality from a specific content page, you can override your master page. Consider, for example, a case where you don't want a specific content page to display the standard navigation bar that you have built into your master page. If you add a configurable property to your master page, you can decide to turn the navigation bar on or off for each of your content pages. Themes and Skins Currently ASP developers must use Cascading Style Sheets (CSS) and inline styles to enforce a look and feel on a Web site. Although these technologies help, consistency is still primarily a function of developer discipline in using the correct styles.

ASP.NET 2.0 rectifies this issue through the use of themes and skins, which are applied uniformly across every page and control in a website. A theme is a set of skin files grouped together to make a specific look for a set of controls. Themes Themes are similar to CSS style sheets in that both themes and style sheets define a set of common attributes that apply to any page where the theme or style sheet is applied. However, themes differ from style sheets in the following ways Themes can define many properties of a control or page, not just a specific set of style properties. Themes can include auxiliary files (e.g. graphics) that can't be included in a CSS style sheet. Themes do not cascade the way style sheets do (e.g. theme property values always override local property values). Themes can include style sheet references. Each application has a themes directory. Each specific theme has its own subdirectory that contains skin files and any other files that apply to the style. Defining a Theme You can define skins and deploy them in subdirectories stemming from the App_Themes directory. Each subdirectory constitutes a theme, which can contain multiple skin files. An App_themes subdirectory contains .skin files as well as any other resources used by the theme (i.e. image files and style sheets).

Figure 12. App_themes sub directory The actual skin definitions are contained in the .skin files and look very much like the tags used to declare control instances in ASPX files. For example, in the app_themes directory, create a subdirectory named Pink. To create a .skin file for your theme, simply add the following code and save it in the Pink directory: Copy Code <asp:DropDownList runat="server" BackColor="hotpink" ForeColor="white" /> <asp:GridView runat="server" BackColor="#CCCCCC" BorderWidth="2pt" BorderStyle="Solid" BorderColor="#CCCCCC" GridLines="Vertical" HorizontalAlign="Left"> <HeaderStyle ForeColor="white" BackColor="hotpink" /> <ItemStyle ForeColor="black" BackColor="white" /> <AlternatingItemStyle BackColor="pink" ForeColor="black" /> </asp:GridView> Listing 11. A typical .skin file for a custom theme This theme can then be applied to pages in your application. Of course, it will turn the background of your data grid hot pink, which may not be a desirable effect.

Using a Theme Themes can be applied: At page level using a single tag: <%@ page language="VB" theme="pink" %> Site-wide using a configuration element inside of the Web.config file: <pages theme="Pink" />. The Web.config file is the master configuration file for each ASP.NET application. The effects of a theme can be seen if you examine the common calendar control in Figure 13:

Figure 13. Calendar with blue theme This version of the calendar uses a simple blue theme. By simply changing the theme attribute, you can completely change the look of the calendar, as shown in Figure 14:

Figure 14. Calendar with a grey theme Skins A skin is a set of properties and templates that can be used to standardize the size, font, and other characteristics of controls on a page. You can use skins to create pre-defined display settings for a control and apply the appropriate skin at runtime. You might, for example, select a skin based on a user preference, or determine the appropriate skin based on the browser used to access the page. Optional skins can be applied to pre-defined controls by setting the SkinId property Copy Code <!- Default Skin -->!> <asp: label runat="server" Font-names="verdana, arial" font-size="10pt" ForeColor= "#000066" BackColor="transparent" /> <!- Title Skin -->!> <asp: label runat="server" id="foo" skinid="Title" Font-names="verdana, arial" font size="18pt" ForeColor= "#000066" BackColor="transparent" font-bold="true" font-underline="true" /> Listing 12. Creating a skin Once a skin has been defined, you can apply it to all the controls on a page or to a specific control using themes and the SkinID property. Applying a Skin to a Control

If a default skin exists and the page is defined by a theme, the default skin will automatically be applied to a control. If you define the SkinID property for the control, the default skin will be replaced by the skin referenced in the SkinID property. Membership One of the major drawbacks of ASP development is that user management schemes must be created from scratch. This process is not only complex, but very time consuming. The membership provider and login controls in ASP.NET 2.0 provide a unified way of managing user information. Any time a user logs into your application, you can automatically reference their identity as well as basic user information. The user's credentials are securely stored in a back-end user database that you can configure in the Web.config file. ASP.NET 2.0 provides both SQL Server 2005 Express Edition and SQL Server providers, but you can create custom providers for any type of backend data store. This extensibility is extremely helpful if you already have an account database that you want to use with ASP.NET's membership feature. After you configure membership for your application, you can use ASP.NET 2.0's Login Controls to automate user registration and password retrieval. Login Controls ASP.NET 2.0 offers new login controls to help create and manage user accounts without writing any code. You can simply drag a <asp:CreateUserWizard> control onto a page to create a user registration form that offers a step-by-step wizard to walk users through the registration process. The new login controls provide an intuitive interface that allows you to format the controls to match the design of your application. The properties window lets you access the label, value and error message validation elements for each property. By using the LoginName and LoginStatus controls you can now give each user a personalized greeting as well as create login/logout functionality without writing any code. The LoginView control allows you to determine which content is displayed to the user, without writing a single line of code. The content is displayed by examining the status and role of each user to determine an appropriate view. In traditional ASP applications, you had to write code to identify the current user, additional code to validate the user's status, and then even more code to display content based on the user. Users often forgot their passwords. ASP.NET 2.0 implements a secure PasswordRecovery control to simplify the process of retrieving a forgotten password. The control prompts the user for a username, and sends the password via email. It should be noted that in order to send the email, the Web.config file must be edited to point to the SMTP server that sends the email. Copy Code <smtpMail serverName="localhost"> </smtpMail> Listing 13. Configuring SMTP server in Web.config For a more detailed description of authentication controls, visit Personalization with ASP.NET 2.0. Profiles The ASP.NET 2.0 profile features allow you to define, save and retrieve information associated with any user that visits your Web site. In a traditional ASP application, you would have to develop your own code to gather the data about the user, store it in session during the user's session and save it to some persistent data store when the user leaves the website. ASP.NET 2.0 automates all of this functionality with profiles. A profile is essentially a bucket of information associated with a user, and directly accessible through the Profile object that is accessible from every ASPX page.

Defining a Profile Within machine.config or Web.config, you can define a profile with <property> values that represent information such as name, billing address and email addresses for each user. You can even create groups of logical properties. Copy Code <profile> <properties> <group name="BillingAddress"> <add name="Street" type="System.String" /> <add name="City" defaultValue="Toronto" type="System.String" /> <add name="StateProv" type="System.String" /> <add name="ZipPostal" type="System.String" /> </group> </properties> </profile> Listing 14. Defining a Profile Once you have defined the profile, ASP.NET and the profile provider automatically take care of managing this information including loading it on request and storing it when the user leaves your site. Using Profilese you have defined a profile, Visual Studio 2005 automatically exposes the profile properties through the Profile object.

Figure 15. Using Profiles Visual Studio 2005 also provides full IntelliSense support for profiles. If you ever make a change to the profile definition, Visual Studio will automatically provide the correct IntelliSense as soon as you have saved your Web.config file. Web Parts One of the major differences between a Web application and a desktop application has been the ease with which a desktop application can contain multiple configurable components. For example, consider the Visual Studio IDE itself. A user can decide which screens to display and how they are arranged. Developing similar functionality in a Web site is a daunting prospect. ASP.NET 2.0 introduces a solution to this problem in the form of Web Parts. Web Parts are modular components that can be included and arranged by the user to create a productive interface that is not cluttered with unnecessary details. The user can:

Choose which parts to display Configure the parts in any order or arrangement Save the view from one Web session to the next Customize the look of certain Web Parts.

All of these features are practically impossible to implement with ordinary Web applications.You can think of Web Parts as modular Web page blocks. Each block can be added or removed from the Web page dynamically, at runtime. Code for organizing and manipulating Web Parts is built in to ASP.NET 2.0. All of the functionality for adding, removing and configuring layout is automatically handled by the Web Parts system. The programmer simply builds Web Parts and assigns them to Web Part Zones. A user can mix and match Web Parts, display them in any order, and expect the configuration to be saved between site visits. Using Web Parts For example, a Web Part application for a hospital may let users choose from a variety of display components ranging from current patient status to alerts on drug interactions. Each user can choose which parts to display from a catalog:

Figure 16. A Web Parts CatalogThe user can then drag and drop the controls into an arrangement that makes the most sense for his or her particular needs.

Figure 17. Arranging Web Parts The layout and configuration are automatically stored for the user's next visit. For a more detailed description of Web Parts, please visit Personalization with ASP.NET 2.0. Summary ASP.NET 2.0 continues in the footsteps of ASP.NET 1.x by providing a scalable, extensible and configurable framework for Web application development. The core architecture of ASP.NET has changed to support a greater variety of options for

compilation and deployment. As a developer, you will also notice that many of your primary tasks have been made easier by new controls, new wizards and new features in Visual Studio 2005. Finally, ASP.NET 2.0 expands the palette of options even further by introducing revolutionary new controls for personalization, themes and skins, and master pages. All of these enhancements build on the ASP.NET 1.1 framework to provide an even better set of options for Web development within the .NET framework.

Você também pode gostar