daqingshu
西双版纳

G. Andrew Duthie
Graymad Enterprises Inc.

October 2003

Applies to:
Microsoft® ASP.NET Whidbey
Microsoft Visual Basic® .NET

Summary: Learn how to reduce development time and how to code with personalization and membership in the upcoming version of ASP.NET, code name ASP.NET "Whidbey" (after the code name for the upcoming release of Microsoft® Visual Studio® .NET).

Configure the Provider

With both personalization and membership, the first step is configuring the provider that you will use to store the personalization or membership data. Though you can create the Microsoft Access or Microsoft SQL Server™ database and add the necessary configuration elements manually, the easier way is to use the ASP.NET Web Site Administration tool, shown in Figure 1. Note that to configure an application successfully, you must be logged in using an account with administrator rights (you also can launch Microsoft Visual Studio® .NET with an administrator-level account using Run As... and launch the Web Site Administration tool from the button in Solution Explorer).

The ASP.NET Web Site Administration tool provides the means to configure personalization and membership features (the Membership data store is configured using the Security tab), as well as reports and data-access features.

To create an Access .mdb file for storing personalization data, you need to open the Web Site Administration tool; the file, named AspNetDB.mdb, will be created automatically in a folder named DATA. Although not enabled in the build of Visual Studio against which this article was written, the Web Site Administration tool contains an entire section devoted to configuring personalization settings. In a later section, I'll walk you through adding the necessary configuration sections by hand.

You configure the provider to use for membership services using the Security tab of the Web Site Administration tool, shown in Figure 3. The easiest way to configure the membership provider is to select the Security Setup Wizard. I'll walk you through this process momentarily.

At this point, the membership database will be created, and the necessary configuration elements will be added to the web.config file. All you need to do from here is add users to the database (which you can do using the Web Site Administration tool, or the membership APIs), set authorization restrictions on pages as desired, and create a login page.

It is important to note that the database structure that is created for both personalization and membership is the same, so you can (and for efficiency's sake, should) use the same provider for both personalization and membership. That said, it is possible to use a different provider for personalization than for membership, and vice-versa, if you prefer.

In addition to the built-in Access and SQL Server providers, you can create your own custom providers and configure your applications to use these providers. So, if you already have a user-credential database that you're not willing to part with, ASP.NET allows you to use that and still get the benefits that membership services provide. Note that at the time of this writing, the actual means for creating custom providers could undergo some changes still, so I'll save a demonstration of creating custom providers for a future article.

How's the Data Stored?

Use Server Explorer to see how data is stored in AspNetDB.mdb. Just create a database connection to AspNetDB.mdb and drag tables from the connection to a page in your site. Visual Studio will create a GridView control and bind it to an AccessDataSource control (note that the ASP.NET worker process must have read-write permissions on the folder containing the database for this to work). If you have difficulty browsing pages in the application, close the connection in Server Explorer before browsing the pages.

Add Personalization and Membership Support

Enough with the theory; let's get to an example already. I'll walk you through configuring personalization and membership to use the Access provider; adding a user to the membership database; adding personalization properties; and using those properties from a page, both for anonymous and logged-in users.

Fire up your copy of Visual Studio and create a new Web site. Once you have the site created and loaded into the IDE, click the Web Site Administration tool button in the Solution Explorer window (again, see Figure 2).

Next, click the Security tab, ensure that the Security Setup Wizard radio button is selected, and click Next. Step one is simply informational, so once you've read it, click Next (you may need to scroll to see the button). In step two, ensure that the From the Internet radio button is selected and then click Next. Note that the "From the Internet" setting will configure the application to use ASP.NET forms authentication, and the "From a local area network" setting will configure the application to use Windows authentication (which means that users will not need to log in to your application explicitly). In step three, click Next to use the AspNetDB.mdb file that is created automatically by the Web Site Administration tool. Then skip step four by clicking Next again. In step five, add at least one user for testing purposes. If you want to add more than one user, check the Add Another User check box once you've filled in all required fields, and then click Next. Otherwise, just fill in the required fields and click Next. Step six of the wizard allows you to create access rules to allow or deny access to all or part of your application based on user or role names. For now, just click Next. You can always add rules later. Finally, click Finish to exit the Wizard. The database has been created, and a web.config file with the necessary elements has been added to your Web Site. This web.config file contains provider elements for membership and role management. These elements are added automatically by the Security Setup wizard, when the membership data store is created.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  
<connectionStrings>
    
<add name="webAdminConnection631974613823397072"
      connectionString
=
      "c:\inetpub\wwwroot\aspnetPRO_PM\DATA\AspNetDB.mdb"

    
/>
  
</connectionStrings>
  
<system.web>
    
<membership defaultProvider="AspNetDB">
      
<providers>
        
<add name="AspNetDB" 
          type
="System.Web.Security.AccessMembershipProvider,
          System.Web, Version=1.1.3300.0, Culture=neutral, 
          PublicKeyToken=b03f5f7f11d50a3a"

          connectionStringName
=
           "webAdminConnection631974613823397072"

          applicationName
="/aspnetPRO_PM" 
          enablePasswordRetrieval
="true"
          enablePasswordReset
="true" 
          requiresQuestionAndAnswer
="true"
          passwordFormat
="Encrypted" />
      
</providers>
    
</membership>
    
<roleManager defaultProvider="AspNetDB">
      
<providers>
        
<add name="AspNetDB" 
         type
="System.Web.Security.AccessRoleProvider, 
         System.Web, Version=1.1.3300.0, Culture=neutral,
         PublicKeyToken=b03f5f7f11d50a3a"

         connectionStringName
=
          "webAdminConnection631974613823397072"

         applicationName
="/aspnetPRO_PM" />
      
</providers>
    
</roleManager>
    
<authentication mode="Forms" />
  
</system.web>
</configuration>

Personalization and Membership: What do they mean?

Personalization and membership enable you to control access to your application, as well as to store and retrieve information about users of your application, including anonymous users. You can customize the appearance and behavior of your application based on this information, and you even can allow users to store profile information, such as a shopping cart, while browsing anonymously, and later easily migrate that information to their personal profiles when they log in.

Personalization allows you to store profile information about users of your application in a persistent data store. Personalization supports a pluggable data-provider layer and a set of APIs for storing and retrieving profile information in a strongly typed fashion. Personalization allows you to specify one or more arbitrary properties to be stored in a user's profile. You can specify the type of each property (which can be a system type or a user-defined type or custom class), as well as whether the property is tracked for anonymous users, whether the property is read-only or read-write, and more.

Personalization also can be integrated with membership services to provide a unified solution for user management, login, and profile-information storage. By default, the ASP.NET personalization system associates profile information with the identity with which the user authenticates, accessible through HttpContext.Current.User.Identity.Name. If you are using ASP.NET membership services for user-credential management, then any time a user logs into your application, his or her membership identity automatically will be stored in HttpContext.Current.User.Identity.Name, and all profile information associated with that identity will be available to the application. Support for storing profile information for anonymous users is not enabled by default and requires adding an element to the Web.config file for the application, as well as specifically making each desired property available for anonymous users.

Membership describes the set of technologies, including (as with personalization) a back-end provider for storing data; a set of APIs for managing users and logins, and so on; and controls that allow you to add user-credential storage and related functionality to your application with no lines of code.

User credentials are stored in a back-end membership database specified by the data provider you configure in Web.config. ASP.NET Whidbey ships with Access, and SQL Server providers are available out of the box. Once membership is configured, and users are added to the membership data store, adding login functionality to the application can be as simple as dragging a single control to a page in the application. The ASP.NET login controls (Login, LoginView, LoginStatus, LoginName, and PasswordRecovery) contain all of the logic necessary to validate credentials and perform any necessary redirection, and so on, and are designed to integrate with membership.

Add Personalization Properties

To demonstrate personalization, next I'll show you how to add some property definitions and store and retrieve them from a page. One of the properties will allow the user to choose a page theme that will be used whenever the user visits. Themes are a new feature of ASP.NET Whidbey that allow you to modify the look and feel of an entire site with a simple configuration setting or a few lines of code.

Open Web.config and add the following, directly after the <system.web> element:

<anonymousIdentification enabled="true"/>
<personalization>
  <profile>
    <property name="Theme" allowAnonymous="true" />
      <property name="FavoriteColors"
       type=
        "System.Collections.Specialized.StringCollection"
       allowAnonymous="true" 
       serializeAs="Xml" />
  </profile>
</personalization>


 

The <anonymousIdentification> element is required in order to allow anonymous access to any personalization properties. The personalization section contains two properties, both of which use the allowAnonymous attribute to enable the properties to be tracked for users who are not logged in. The first property, Theme, does not specify a type, so it will be treated as a string. The second property, FavoriteColors, specifies the StringCollection class as its type. Any attempt to store data that is not compatible with the StringCollection class in this property will result in an exception being thrown. The serializeAs attribute allows the StringCollection to be stored in the database as an XML string.

Create a new Web Form in the project called Default.aspx. Then, switch to Design view and add the controls, with their properties set as specified, shown in Figure 5.

Table 1. Properties to be assigned to the controls added in the preceding example step

Control

Properties

DropDownList

ID = Themes

Button

ID = SetTheme

Text = Set Theme

TextBox

ID = textFavColor

Button

ID = AddColor

Text = Add Color

ListBox

ID = listFavColors

Select the DropDownList control and in the Properties window, scroll down to and select the Items
property. Click the ellipsis button to open the Collection Editor. Add two items, one with the text and value
set to BasicBlue and one set to SmokeAndGlass, and then click OK. Double-click the Set Theme button and
add the following code to the event handler:

Profile.Theme = Themes.SelectedValue

Add the following event handler to the Server Code window:

Sub Page_PreInit(ByVal sender As Object, _
   ByVal e As System.EventArgs)
   If Profile.Theme = "" Then
      If Request.Form("Themes") <> "" Then
         Page.Theme = Request.Form("Themes")
      End If
   Else
      Page.Theme = Profile.Theme
   End If
End Sub

This code is required to set the page's theme, which must be set in the Page_PreInit event or earlier.
The code checks to see whether a theme is already set for the user's personalization profile and uses that theme.
If no theme exists, the code checks to see if the user has submitted the page with a new theme choice and, if so,
uses the new theme. Otherwise, no theme will be applied.

Switch back to Design view and double-click the Add Color button. Add the following code to the event handler:

Dim FaveColor As String = _
   Server.HtmlEncode(textFavColor.Text)
Dim FaveColors As New _
   System.Collections.Specialized.StringCollection
Profile.FavoriteColors.Add(FaveColor)
DisplayFavoriteColors()

Add the following subroutine just below the AddColor_Click handler:

Sub DisplayFavoriteColors()
   listFavColors.DataSource = Profile.FavoriteColors
   listFavColors.DataBind()
End Sub

Add the following line to the Page_Load event handler (if necessary, switch to Design view and double-click
an empty area of the page to add the Page_Load handler):

DisplayFavoriteColors()

Now, save the page.

Test the Personalization Settings

Browse the page, select a theme from the DropDownList control and click Set Theme. You should see
the theme applied to the controls. Next, type the name of a color in the text box and click Add Color. The color will be added to the list box, which is populated from the profile. After applying a theme and adding a couple of colors, the page should look similar to Figure 5.

Up to this point, the personalization information is being stored exclusively for anonymous users. But what
if you want to take the information that's already been saved for an anonymous user and migrate it to a specific profile for a user when he or she logs in? Here's how: Add a Global.asax file to the Web site by right-clicking the site in Solution Explorer, selecting Add New Item, and choosing the Global Application Class template. Then, add the following code to Global.asax:

Sub Personalization_MigrateAnonymous (sender As Object, _
   e As PersonalizationMigrateEventArgs)
   Profile.Theme = _
      Profile.GetProfile(e.AnonymousId).Theme
   Profile.FavoriteColors = _
      Profile.GetProfile(e.AnonymousId).FavoriteColors
End Sub

In Design view, add a Login control and a LoginName control (found on the Security tab of the toolbox) to
Default.aspx, below the other controls, then save and browse the page. When the page is first displayed, no user name
will be displayed by the LoginName control, and the page will display any properties you previously had set while
browsing anonymously. Log in using the account credentials you added when configuring the membership database.
The LoginName control will display your user ID now, and the Theme and FavoriteColors properties have been
migrated to the profile for your logged-in account. Note that if you log in and then log out again, a new anonymous
identity is created, and any personalization for the previous anonymous identity is no longer displayed.

Summary

In this article, I've demonstrated how the new personalization and membership features of ASP.NET Whidbey
provide powerful functionality to your Web applications while requiring very little effort (and even less code!) to configure
and use. In addition to the scenarios demonstrated in this article, personalization services can be used in conjunction with
the new Web-parts feature of ASP.NET Whidbey to create powerful and easily customizable portals. Using personalization
and membership, it is now possible to create rich, customized Web applications with robust security while writing little or
no plumbing code, leaving you more time to focus on the business logic that enables the features your users actually care about.



posted on 2006-02-26 01:11  Edvard  阅读(493)  评论(0)    收藏  举报