New Features of ASP.NET 2.0


This chapter isn't an in-depth look at any specific featureinstead, we are going to give you a taste of what's to come so you can see how much easier Web development is going to be. For this overview of new features, we've broken them down into rough end-to-end scenarios.

Templates for a Consistent Look and Feel

ASP.NET 1.x provides an easy way to develop Web sites, but one thing that has become apparent is the lack of an architecture for applying a consistent look and feel. Several workaround techniques emerged:

  • Creating a custom class object that inherits from Page and having this custom page preload controls

  • Creating a templated server control, where the templates provide the layout areas for each page, and using this control on every page

  • Having User Controls for common areas of the site, such as headings, menus, and footers

Of these, the first two require knowledge of creating server controls, and while this is a topic most ASP.NET developers could master, it may not be one they've had experience with. Therefore, a solution using custom server controls tends to be avoided. The last option, though, is a simple solution, easy to create and implement. User Controls were created to provide reusable functionality, and this is a great use for them. However, to apply a consistent look and feel you need to first place the User Controls on each page and then ensure that they are placed in the same place on each page. In other words, you really need a page template, and in reality this manifests itself as an ASP.NET file that you simply copy for each new page. The danger of this approach is that it's too easy to modify a page and change the layout for that single page.

To provide a templating solution, ASP.NET 2.0 has the concept of Master Pages, which provide a template for the look and feel of a page. A Master Page is an ASP.NET page that provides a template for other pages, giving shared page-level layout and functionality. The Master Page defines place-holders for the content, which can be overridden by child pages. The resultant page is a combination of the Master Page and the child page, as shown in Figure 1.1.

Figure 1.1. Combining a Master Page and a child page


Master Pages are covered in Chapter 9.


Styles for Controls

The second major feature of ASP.NET 2.0 that deals with the look and feel of a site is that of themes. Theming, or skinning, has become very popular, allowing users to create a customized look for applications. Two of the most popular themed applications on the Windows desktop are audio players (WinAmp and Windows Media Player), and with some additional software, even Windows XP can be themed.

The popularity of theming is due to the nature of humanswe like to choose the way things look, and we like to express our individuality. This is easy on the desktop, where users generally have a single machine each. With Web sites, however, theming becomes a more difficult issue because of the number of users. Tracking which users have which themes and managing those themes becomes an overhead that site administrators don't want to get involved with.

Some Web sites provide forms of theming, but these are relatively limited in terms of customization, perhaps allowing only a choice of color scheme. Other sites provide a selection of stylesheets for users to pick from, assuming their browsers support this feature, or alternatively change the stylesheet on the server. This allows not only color schemes to be selected but also complete styles, including fonts, the style of borders, and so on.

In ASP.NET 2.0, the goals for theming are quite simple.

  • Allow customization of the appearance of a site or page using the same design tools and methods used when developing the page itself. This means there's no need to learn any special tools or techniques to add themes to a site.

  • Allow themes to be applied to controls, pages, and even entire sites. For example, this allows users to customize parts of a site while ensuring that other parts (such as corporate identity) aren't customized.

  • Allow all visual properties to be customized, thus ensuring that when themed, pages and controls can achieve a consistent style.

The implementation of this in ASP.NET 2.0 is built around two areas: skins and themes. A skin is a set of properties and templates that can be applied to controls. A theme is a set of skins and any other associated files (such as images or stylesheets). Skins are control-specific, so for a given theme there could be a separate skin for each control within that theme. Any controls without a skin inherit the default look. There are two types of themes.

  • Customization themes override control definitions, thus changing the look and feel of controls. Customization themes are applied with the Theme attribute on the Page directive.

  • Stylesheet themes don't override control definitions, thus allowing the control to use the theme properties or override them. Stylesheet themes are applied with the StylesheetTheme attribute on the Page directive.

The implementation is simple because a skin uses the same definition as the server control it is skinning, and themes are just a set of files in a directory under the application root. For example, consider this sample directory structure.

default.aspx \Themes   \MyTheme     MySkin.skin   \YourTheme     YourSkin.skin


Each theme consists of a directory under the Themes directory. Within each theme there is a file with a .skin suffix, which contains the skin details for that theme. For example, MySkin.skin might contain:

<asp:Label Skin runat="server"   Font-Bold="True" BackColor="#FFC080" /> <asp:Label Skin runat="server"   Font-Italic="True" Font-Names="Comic Sans MS" />


This defines two skins for the Label control, each having different visual properties. The theme can be chosen by setting the appropriate page-level property, and the skin is chosen by setting a control-level property, as demonstrated in the following code snippets:

<%@ Page Theme="MyTheme" %> <form runat="server">   <asp:Label Skin Text="A Label" /> </form>


or

<%@ Page StylesheetTheme="MyTheme" %> <form runat="server">   <asp:Label Skin Text="A Label" /> </form>


Both of these can be set at runtime as well as design time, so this provides an extremely powerful solution, especially when connected with the new Personalization features.

Personalization and themes are covered in Chapter 12.


Securing Your Site

With the large amount of business being done on the Web, security is vitally important for protecting not only confidential information such as credit card numbers but also users' personal details and preferences. Thus, you have to build into your site features to authenticate users. This was easy to do in ASP.NET 1.x, although you still had to write code. Security was created by picking your preferred security mechanism (most often Forms Authentication) and then adding controls to your page to provide the login detailsusername, password, "remember me" checkbox, and so on. There was no built-in mechanism for storing personal details, so this was a roll-it-yourself affair.

With ASP.NET 2.0, the pain has been taken out of both areas. For login functionality, there is now:

  • A Login control, providing complete functionality for logging into a site

  • A LoginStatus control, which indicates the login status and can be configured to provide automatic links to login and logout pages

  • A LoginName control to display the current (or anonymous) name

  • A LoginView control, providing templated views depending on the login status

  • A CreateUser wizard, to allow simple creation of user accounts

  • A PasswordRecovery control, encompassing the "I forgot my password" functionality

For example, to add login features to your page all you need to do is add the following code:

<form runat="server">   <asp:Login runat="server" /> </form>


This gives us the simple interface shown in Figure 1.2.

Figure 1.2. The Login control


This could be achieved easily in previous versions of ASP.NET, but not with such simplicity. You needed labels, text entry boxes, buttons, and validation, whereas now it's all rolled into one control. Sure it looks plain, but this is the basic unformatted version. Using Visual Studio 2005, you can auto-format this for a better look. You can also skin the interface, as shown in Figure 1.3, or even template it to provide your own customized look. Along with the other login controls, you get a complete solution for handling user logins.

Figure 1.3. A skinned Login control


The user interface isn't the only part of logging into a site; there's also the code needed to validate the user against a data store. With ASP.NET 1.x this required not only code to be written but also knowledge of what that data store was and how it stored data. ASP.NET 2.0 introduces a new Membership API, whose aim is to abstract the required membership functionality from the storage of the member information. For example, validation of user credentials can now be replaced with the code shown in Listing 1.1.

Listing 1.1. Validating User Credentials

If Membership.ValidateUser(Email.Text, Password.Text) Then   ' user is valid Else   ' user is not valid End If

What's better is that when using the Login control you don't even have to do thisthe control handles it for you.

The great strength of the Membership API is that it is built on the idea of Membership Providers, with support for Microsoft SQL Server and Active Directory supplied by default. To integrate custom membership stores, you simply need to provide a component that inherits from the Membership interface and add the new provider details to the configuration file.

The Membership API has some simple goals.

  • Offer an easy solution for authenticating and managing users, requiring no knowledge of the underlying storage mechanism.

  • Provide support for multiple data providers, allowing data stored about users to come from different data stores.

  • Provide comprehensive user management in a simple-to-use API, giving an easy way for developers to store and access user details.

  • Give users a unique identity, allowing integration with other services such as the Personalization and Role Manager features.

Security, membership, and role management are covered in Chapter 11.


Personalizing Your Site

One of the areas driving changes on the Internet is that of communities. People like to belong, and the Internet is a big, lonely place. Community sites give you a home, a sense of belonging. Part of that comes from being in contact with like-minded people, and part comes from the features some of these sites offer. Our houses are decorated to our style, and many of us customize our Windows desktop, so why shouldn't our favorite Web sites offer the same opportunity?

Hand in hand with the Membership API lie the Personalization features. These provide a simple programming model for storing user details (including those of anonymous users), with easy customization. Like Membership, Personalization can be configured to work with multiple data providers and provides an easy way to define custom properties for each user. This leads to a user profile with strong types, allowing easy access within ASP.NET pages. For example, you can create a profile with Name, Address, and Theme as properties and a page that allows the user to update them, as shown in Listing 1.2.

The simplicity of this method means we only have to deal with the user profile. We don't need to know how it stores the datawe just deal with the properties each profile has. This personalization also allows us to easily use the theming capabilities, changing the theme when the page is created, as demonstrated here.

Sub Page_PreInit(Sender As Object, E As EventArgs)   Me.Theme = Profile.Theme End Sub


Listing 1.2. Using the Profile Custom Properties

<script runat="server">   Sub Page_Load(Sender As Object, E As EventArgs)     Name.Text = Profile.Name     Address.Text = Profile.Address     UserTheme.Text = Profile.Theme   End Sub   Sub Update_Click(Sender As Object, E As EventArgs)     Profile.Name = Name.Text     Profile.Address = Address.Text     Profile.Theme = UserTheme.Text   End Sub </script> <form runat="server">   Name:    <asp:TextBox  runat="server" /> <br />   Address: <asp:TextBox  runat="server" /> <br />   Theme:   <asp:TextBox  runat="server" /> <br />   <asp:Button Text="Update" onClick="Update_Click" runat="server" /> </form>

To ensure that the theme customization is applied before the controls are created, we use the new PreInit event.

Personalization is covered in Chapter 12.


Creating Portals

As if customization of a site's look weren't enough, ASP.NET 2.0 also brings a way to alter the structure with its new portal framework.

The success of the ASP.NET IBuySpy portal application and its offshoots, such as DotNetNuke and Rainbow, shows that customized sites are popular. The issue has always been how to provide a consistent look while still allowing user customization, not only of the style but also of the content and placement of content. Microsoft has already implemented solutions to provide this functionality, including SharePoint Server and Outlook WebParts.

In ASP.NET 2.0, WebParts become the underlying technology for all Microsoft portal applications, providing a single easy-to-use, extensible framework. The concept revolves around two key sets of controlsa set of zone controls and a range of different WebParts controls. The zone identifies areas on the page in which the appearance or behavior of the content is consistent (e.g., the colors, styles, and layout orientation), and the WebParts identify the individual content areas or modules within each zone. There are different types of WebPart controls for different purposes, for example:

  • Generic Web Parts, which are used to reference assemblies or user controls that contain the content that is normally visible on the page

  • A range of catalog parts, which display parts that are not currently on the page but are available to be added

  • A range of editor parts such as the AppearanceEditorPart and the LayoutEditorPart, which allow customization of the visible parts

For example, consider an intranet site that needs a selection of areas of content, such as contact information, stocks, weather, and so on. Figure 1.4 shows a sample page.

Figure 1.4. Sample intranet site using the portal framework


This page has two main areas of contentthe left area containing details of employees, which is a user control, and the right area with weather details (a custom server control), and Stocks and Canteen, which are both user controls. Each of the two areas is a WebPartZone control, and the content within them is user controls or server controls within a ZoneTemplate. The code for the left WebPartZone control appears in Listing 1.3.

Listing 1.3. Sample Intranet Site Using WebParts

<asp:WebPartZone  runat="server" style="float:left;">   <ZoneTemplate>     <uc1:Contacts  runat="server" />   </ZoneTemplate>   <CloseVerb ImageUrl="~/Images/CloseVerb.gif"     Description="Removes the WebPart from the page" />   <MinimizeVerb ImageUrl="~/Images/MinimizeVerb.gif" />   <RestoreVerb ImageUrl="~/Images/RestoreVerb.gif" />   <EditVerb ImageUrl="~/Images/EditVerb.gif"     Description="Edit the properties of the WebPart" />   <ExportVerb Text="Export" />   <SelectedPartChromeStyle BorderColor="#A7B756"     BorderStyle="Dotted" BorderWidth="5px" /> </asp:WebPartZone>

At first glance, this doesn't look like much improvement over existing layout methods such as user controlsin fact, it looks more complex. However, the framework on which WebParts is built is great for developers and users alike. Developers only have to drop user controls or server controls into a ZoneTemplate to automatically receive WebParts functionality.

For example, the Personalization features allow each Web part to be moved to another location within its zone or to a different zone. Moving a WebPart is simply a matter of drag and drop, as shown in Figure 1.5, where the Stocks section is being moved to the left zone.

Figure 1.5. Dragging a WebPart to another location


Editing of WebPart controls is also part of the portal framework. You can use a control called the WebPartPageMenu to automatically provide a drop-down list where users can change the mode that the page is viewed in and then edit the properties of the individual WebParts. By default the user can alter a range of layout and appearance properties, such as the title, height, width, and orientation (see Figure 1.6).

Figure 1.6. The built-in editing features for a WebPart


The portal framework is covered in Chapter 13.


Using Images on Your Site

Using images isn't a particularly difficult area of site design, but their use has been eased with two new server controls. First, the ImageMap control provides easy support for image maps, as demonstrated in the following code sample.

<asp:ImageMap runat="server"      onClick="Map_Click"      ImageUrl="images/states.jpg">   <asp:CircleHotSpot X="100" Y="100" Radius="25"        PostBackValue="Other State" />   <asp:RectangleHotSpot Top="200" Left="150"        Right="200" Bottom="150"        PostBackValue="More State"/>   <asp:PolygonHotSpot Coordinates="3,4, 15,18, 45,18, 15,70, 3,4"        PostBackValue="State 1" /> </asp:ImageMap>


The detection of the hot spot is handled in the postback event.

Sub Map_Click(Sender As Object, E As ImageMapEventArgs)   Select Case e.PostBackValue   Case "State 1"     ' ...   Case "Other State"     ' ...   Case "More States"     ' ...   End Select End Sub


Images are covered in Chapter 11.


Using Data on Your Site

It's probably no exaggeration to say that most, if not all, Web sites use some form of data to drive them. Whether XML files, a database, or another dynamic form of storage, the data allows a site to respond to the user and to be up to date. ASP.NET 1.x provided some great data binding capabilities, but they always involved code, often the same code used over and over. One of the key goals of ASP.NET 2.0 is to reduce code and to ease the use of databases, especially for beginner programmers. To achieve this, a new set of data controls has been introduced, removing the need for in-depth knowledge of ADO.NET.

Data source controls provide a consistent and extensible method for declaratively accessing data from Web pages. There are several data source controls, including AccessDataSource, SqlDataSource, XmlDataSource, and ObjectDataSource. The use of data controls is simple, as shown here.

<asp:SqlDataSource  runat="server"   ConnectionString="server=.;database=pubs;Trusted_Connection=True"   SelectCommand="SELECT * FROM authors"/> <asp:DataGrid DataSource runat="server" />


This just encapsulates the code everyone used to put in the Page_Load eventit connects to the database, fetches the data, and binds the grid. The contents of the SelectCommand can be a stored procedure as well as a SQL command, thus preserving the separation of data access from the page itself. There are commands for updating, inserting, and deleting.

This model is extended by use of a parameter collection, allowing parameters to be passed into the command from a variety of sources. For example, the code in Listing 1.4 automatically takes the value from the TextBox control txtState and feeds this into the parameter @state.

Listing 1.4. Using a ControlParameter

<asp:SqlDataSource  runat="server"   ConnectionString="server=.;database=pubs;Trusted_Connection=True"   SelectCommand="SELECT * FROM authors WHERE state=@state">   <SelectParameters>     <asp:ControlParameter name="@state" Control        PropertyName="Text" />   </SelectParameters> </asp:SqlDataSource> <asp:TextBox  runat="server" /> <asp:DataGrid DataSource runat="server" />

There are also other parameter types, allowing parameter information to be taken directly from Session variables, Cookies, the Request (QueryString), and the HTML Form.

Data Binding

Data binding in ASP.NET 1.x was simple, but it did cause confusion in some areas. For example, should you use early binding, for which you have to know the underlying data structure? Or should you take the development shortcut and use late binding, like this:

<%# DataBinder.Eval(Container.DataItem, "au_lname") %>


With ASP.NET 2.0, this syntax has been simplified.

<%# Eval("au_lname") %>


In addition, there is a Bind method, which provides two-way binding, allowing easy creation of pages that can update data. There is also an equivalent XPath syntax for XPath expressions when binding to XML documents.

<%# XPath("@au_lname") %>


Binding to Objects

One of the most requested features has been the ability to bind data directly to objects. Good design dictates that you separate your data access layer from your presentation layer, and this is often done as a set of classes. The new ObjectDataSource allows you to simply bind directly to existing objects, such as classes, thus allowing you to have a strongly typed data layer but still use the easy data binding that ASP.NET 2.0 brings.

Binding to Configuration Settings

A similar binding syntax is used to allow declarative access to certain configuration parameters, such as application settings, connection strings, and resources. Here is the syntax for these:

<%$ section: key %>


For example:

<%$ ConnectionStrings: pubs %>


Data source controls and data binding are covered in Chapters 3, 4, and 5.


Internationalization

Building Web sites that support multiple languages is important because Web sites are used by more and more people for whom English is a secondary language. In ASP.NET 2.0, support for multiple languages is extremely simple, based around global resources (sometimes called shared resources) and local page resources. Global resources live in the Resources folder underneath the application root and consist of XML-based resource files (.resx) containing keys and content for those keys. Global resources can be accessed by any page in the application. For example, consider a file called shared.resx, which among the meta-data might have a key like this:

<data name="SharedResource">   <value>English Label from shared resource file</value> </data>


There might also be a French language resource file, shared.fr-fr.resx.

<data name="SharedResource">   <value>French shared resource</value> </data


Binding to these resources declaratively can be done in the same way as binding to configuration resources, for example:

<asp:Label runat="server"      Text="%<$ Resources: SharedResource %> />


At page compilation time the browser language is detected and the resource selected from the appropriate file.

Another way to fetch this resource is to use a meta-attribute on the label.

<asp:Label runat="server"      meta:resourcekey="Shared:SharedResource"/>


In this case, the first part of the meta value identifies the name of the file, and the second part (after the colon) identifies the key.

Local resources are only accessible to individual pages. Like global resources, they are stored in .resx files, but this time under a Local-Resources directory, where the name of the resource file is the ASP.NET page with the .resx extension applied. Thus, for a page supporting two languages there would be two local resource files, LocalResources\UsingResources.aspx.resx and LocalResources\UsingResources. aspx.fr-fr.resx. Either of the binding formats works for local resources, but generally the meta one is used because Visual Studio 2005 can automatically process ASP.NET pages, adding the meta-attribute and building a resource file.

Resources are covered in Chapter 9.




ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net