Feature Changes in ASP.NET 2.0

 

July 2006

Jayesh Patel, Bryan Acker, Robert McGovern
Infusion Development

Summary: If you are considering migrating from ASP or ASP.NET 1.x, you should definitely consider the advantages provided by the new features in ASP.NET 2.0. This article provides a feature-based overview of ASP.NET 2.0 for developers familiar with ASP or ASP.NET 1.1. (29 printed pages)

Contents

Introduction
Changes in Architecture
Changes in Development
New Features in ASP.NET 2.0
Defining a Theme
Using a Theme
Applying a Skin to a Control
Summary

Introduction

Computer languages and frameworks evolve as the needs of the development community evolve. ASP.NET is certainly no exception. ASP.NET 2.0 is the first major update to the ASP.NET framework and includes solutions to common problems encountered with ASP.NET 1.x as well as new features that greatly increase the flexibility and functionality of Web development on the .NET platform. If you are still working with ASP applications, then ASP.NET 2.0 offers even more incentive to upgrade.

This white paper covers major architectural changes and modifications in the way one develops ASP.NET applications, and also examines several of the important new features offered in ASP.NET 2.0. Most of the topics in this paper assume a background with ASP.NET 1.x. If you have never developed ASP.NET applications before, you may want to start with the MSDN migration guide at https://msdn.microsoft.com/asp.net/reference/migration/aspmig/default.aspx.

If you are migrating from ASP.NET 1.x, you might also be interested in reading Common ASP.NET 2.0 Conversion Issues and Solutions. The Conversion Issues and Solutions paper gives you practical implementation details of performing a migration. It also fully explains how to use the Visual Studio Conversion Wizard to upgrade your ASP.NET 1.x application to ASP.NET 2.0.

Goals of ASP.NET 2.0

Building on ASP.NET 1.1, the developers of ASP.NET 2.0 chose to focus on four goals:

  1. Improve the reliability and usability of Web applications

    Currently, many ASP.NET 1.x applications run on Microsoft IIS 5.0. ASP.NET 2.0 leverages new IIS 6.0 features for improved performance and scalability. Specifically, IIS 6.0 provides a new process model which greatly enhances the ability of a server to host multiple applications in a truly independent fashion. Each ASP.NET application resides in its own isolated process and cannot accidentally interact with other applications. Quite simply put, applications can no longer break each other. Each application runs completely separated from every other application. If one application crashes, it doesn't affect other applications.

    In terms of usability, new features such as master pages and themes allow you to develop large Web applications using a consistent structure that is manageable and configurable.

  2. Reduce the number of lines of code you have to write in common scenarios

    ASP.NET 2.0 includes wizards and controls that allow you to perform frequent tasks (e.g. data access) without having to write a single line of code. Visual Studio 2005 includes designers to layout and configure complex pages with data bound tables. As a developer, you can use the wizards to work faster and smarter.

    ASP.NET 2.0 also leverages changes in the .NET Framework. In particular, the partial class concept is particularly useful for ASP.NET developers. A partial class lets you write part of the code and lets the ASP.NET compiler write the rest when necessary. You no longer have to see boilerplate code, nor do you have to write any of it.

  3. Offer user features to personalize Web applications

    ASP.NET 2.0 includes built-in controls to help you manage user accounts and personalize the content and layout of pages in your application. First, the membership service lets you track users. The new login controls integrate with the membership service to allow you to automate account creation and user login without writing any code. The new Web Parts feature allows you to create Web applications that contain controls that can be edited and personalized by users. Users can select and customize the parts that are displayed on a Web page as they see fit. Finally, the Profile service provides long-term persistence of user preferences and data through declarative XML configuration.

  4. Provide enhanced design features to generate consistent layouts and design

    ASP.NET 2.0 supports master pages, themes and skins to build applications with a consistent page layout and design. These new features are easy to implement and modify, and greatly enhance the manageability and maintainability of large applications.

    Many of the new features in ASP.NET 2.0 are aimed specifically at addressing these goals. Throughout the rest of the paper, we will look at individual technologies and see how ASP.NET 2.0 builds on ASP.NET 1.x to provide a powerful Web application development platform.

What Does ASP.NET 2.0 Mean To ASP Developers?

For ASP developers, the impact of the many new features in ASP.NET 2.0 is largely dependant on your development background. Classical ASP required considerable HTML knowledge and manual coding even for relatively simple tasks like generating a table or a form. ASP.NET abstracts most of these idiosyncrasies and encapsulates them in auto-generated code or core class libraries. You no longer have to worry about HTML tags, POST, GET, and query strings. You can focus on developing code that implements business logic.

Classical ASP development intermixed HTML code with scripting code. This spaghetti code made readability very difficult. Scripting code could be inserted anywhere, which also made it hard to build well-designed applications that shared code properly and in an extensible fashion. ASP.NET applications implement an object-oriented paradigm that allows for faster development and reduces the complexity of building upon existing code.

ASP.NET 2.0 also takes care of many of the redundant details you had to implement manually in ASP. For example, you can use object-oriented features to easily re-use code between pages. You can also leverage master pages to quickly create a coherent design for your application, or apply skins and themes to programmatically set the look and feel of your Web pages. Thanks to the intuitive design environment, rich set of debugging tools and strongly typed compiled languages, ASP.NET 2.0 helps you develop better applications faster.

Migrating from ASP.NET 1.x

If you have ASP.NET 1.x applications in production, you will be relieved to know that ASP.NET was created to be backwards compatible. For the most part, ASP.NET 1.x applications will run as normal on ASP.NET 2.0 without any changes. More information can be found in the article Step-By-Step Guide to Converting Web Projects from Visual Studio .NET 2002/2003 to Visual Studio 2005.

You will notice many changes when you upgrade to Visual Studio 2005. In particular, the default development model for ASP.NET pages has changed. In addition, with ASP.NET 2.0, you will have a variety of new compilation and deployment options. All of these changes will be discussed in detail in the following sections.

You can also learn more about the migration process in Common ASP.NET 2.0 Conversion Issues and Solutions.

Changes in Architecture

The fundamental architecture of ASP.NET has always been designed for flexibility and extensibility. ASP.NET 2.0 continues this tradition by incorporating a new provider model to support many of the new features. New utilities and API's have been added to improve site maintenance and improve configuration. All of these changes are designed to make developing ASP.NET 2.0 applications a faster and more streamlined process while still providing the flexibility and extensibility that developers were used to with ASP.NET 1.x.

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:

  • Membership—The membership provider manages supports user authentication and user management.
  • Profile—The profile provider supports storage and retrieval of user specific data linked to a profile.
  • Personalization—The personalization provider supports persistence of Web Part configurations and layouts for each user.
  • Site Navigation—The 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 providers—ADO.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 supports 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.

  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)

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.

Aa479401.migrateasp203b(en-us,MSDN.10).gif

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 Contents
/Bin Referenced assemblies
/app_code Shared application code
/app_globalresources Common resource files
/app_localresources Localized resource files
/app_webreferences Links to web services
/app_data Local databases for membership, web parts, etc.
/app_browsers Browser specific settings
/app_themes Theme settings

Table 1. Application Directories

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.

Aa479401.migrateasp204(en-us,MSDN.10).gif

Figure 4. IntelliSense on Web.config

IntelliSense helps reduce the chance of misconfigured 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.

Aa479401.migrateasp205(en-us,MSDN.10).gif

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.

Aa479401.migrateasp206(en-us,MSDN.10).gif

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:

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:

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 compilation—In 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-compilation—A 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 compilation—At 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:

// 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 time-consuming 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 https://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.

Aa479401.migrateasp207(en-us,MSDN.10).gif

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.

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.

    <?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.

<%@ 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.

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.

Aa479401.migrateasp208(en-us,MSDN.10).gif

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: https://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.

<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 Access—The access data source can automatically connect to and query an Access database.
  • Objects—The 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.
  • XML—The XmlDataSource links to hierarchical data in an XML file.
  • Site Map—The 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.

Aa479401.migrateasp209(en-us,MSDN.10).gif

Figure 9. GridView control

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

Aa479401.migrateasp210(en-us,MSDN.10).gif

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:

<%@ 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.

<%@ 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.

Aa479401.migrateasp211(en-us,MSDN.10).gif

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).

Aa479401.migrateasp212(en-us,MSDN.10).gif

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:

<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:

Aa479401.migrateasp213(en-us,MSDN.10).gif

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:

Aa479401.migrateasp214(en-us,MSDN.10).gif

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

<!- 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.

<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.

<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 Profiles

Once you have defined a profile, Visual Studio 2005 automatically exposes the profile properties through the Profile object.

Aa479401.migrateasp215(en-us,MSDN.10).gif

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:

Aa479401.migrateasp216(en-us,MSDN.10).gif

Figure 16. A Web Parts Catalog

The user can then drag and drop the controls into an arrangement that makes the most sense for his or her particular needs.

Aa479401.migrateasp217(en-us,MSDN.10).gif

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.

 

About the authors

Jayesh Patel—Jay Patel is a developer in both .NET and Java Technologies. Jay's research focuses on pattern-based programming and agile methodologies.

Bryan Acker—Bryan Acker is a technical writer for Infusion Development. Bryan has a strong background in ASP and ASP.NET Web development and Web hosting.

Robert McGovern—Rob McGovern is a senior writer, developer, and project manager for Infusion Development. Rob has worked on several different ASP.NET projects, including CodeNotes for ASP.NET and the JSP to ASP.NET migration guide. Rob is also a Microsoft MVP for Virtual Earth.

Infusion Development Corporation is a Microsoft-Certified Solutions Provider offering customized software-development, training, and consulting services for Fortune 1000 Corporations, with an emphasis on the financial-services industry. With offices in New York and Toronto, Infusion Development has established an international client base, including some of the world's largest companies in the financial service, securities brokerage, and software development industries.

© Microsoft Corporation. All rights reserved.