Skip navigation

Get Personal

Reduce development time and code with personalization and membership in ASP.NET 2.0.

asp:feature

LANGUAGES: VB .NET

ASP.NET VERSIONS: 2.0

 

Get Personal

Reduce development time and code with personalization and membership in ASP.NET 2.0.

 

By G. Andrew Duthie

 

By now, you may - or may not - have gotten a taste of ASP.NET 2.0, which is being unveiled publicly at the 2003 Professional Developer's Conference. In ASP.NET 2.0, one of the primary goals of the development team was to reduce the amount of time and code required to support common application scenarios. As such, ASP.NET provides a wide array of new features designed to save you time and effort, including no-code data binding, themes, new server controls, and, in particular, personalization and membership, which I'll discuss in this article. (See the sidebar, "Personalization and Membership: What do they mean?")

 

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 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 Visual Studio with an administrator-level account using Run As... and launch the Web Site Administration tool from the button in Solution Explorer, shown in Figure 2).

 


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

 


Figure 2. The Web Site Administration tool button is used to open the ASP.NET Web Site Administration tool in the Visual Studio IDE.

 

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.

 


Figure 3. The Security tab of the Web Site Administration tool provides a wizard for easy setup of the membership data store as well as a set of management tools for making modifications once the data store has been created.

 

At this point, the membership database will be created, and the necessary configuration elements will be added to Web.config. 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's 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 Microsoft 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.

 

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. The resulting Web.config file is shown in Figure 4.

 

  

    

      connectionString=

      "c:\inetpub\wwwroot\aspnetPRO_PM\DATA\AspNetDB.mdb"

    />

  

  

    

      

        

          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" />

      

    

    

      

        

         type="System.Web.Security.AccessRoleProvider,

         System.Web, Version=1.1.3300.0, Culture=neutral,

         PublicKeyToken=b03f5f7f11d50a3a"

         connectionStringName=

          "webAdminConnection631974613823397072"

         applicationName="/aspnetPRO_PM" />

      

    

    

  

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

 

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

 

  

    

      

       type=

        "System.Collections.Specialized.StringCollection"

       allowAnonymous="true"

       serializeAs="Xml" />

  

 

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

 

Control

Properties

DropDownList

ID = Themes

Button

ID = SetTheme

Text = Set Theme

TextBox

ID = textFavColor

Button

ID = AddColor

Text = Add Color

ListBox

ID = listFavColors

Figure 5. These are the properties to be assigned to the controls added in the preceding example step.

 

When finished, the page should look similar to Figure 6.

 


Figure 6. This screen capture shows the appearance of the controls in the Visual Studio IDE.

 

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

 


Figure 7. This screen capture shows the personalization properties in action. Note how the button borders and foreground color, as well as the text-box borders, are affected by the theme chosen.

 

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.

 

In this article, I've demonstrated how the new personalization and membership features of ASP.NET 2.0 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 2.0 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.

 

The sample code in this article is available for download.

 

G. Andrew Duthie is the founder and principal of Graymad Enterprises Inc. (http://www.graymad.com). He is the author of several ASP.NET books from Microsoft Press and O'Reilly & Associates, including ASP.NET in a Nutshell, 2nd ed., and is also a member of the International .NET Association (http://www.ineta.org) speaker's bureau. You can reach Andrew at mailto:[email protected].

 

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.

 

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, etc.; 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 2.0 ships with Microsoft 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, etc., and are designed to integrate with membership.

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish