Get Personal

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

ITPro Today

October 30, 2009

13 Min Read
ITPro Today logo

asp:feature

LANGUAGES: VB .NET

ASP.NET VERSIONS:2.0

 

Get Personal

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

 

By G. Andrew Duthie

 

By now, you may - or may not - have gotten a taste ofASP.NET 2.0, which is being unveiled publicly at the 2003 ProfessionalDeveloper's Conference. In ASP.NET 2.0, one of the primary goals of thedevelopment team was to reduce the amount of time and code required to supportcommon application scenarios. As such, ASP.NET provides a wide array of newfeatures designed to save you time and effort, including no-code data binding,themes, new server controls, and, in particular, personalization andmembership, 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 stepis configuring the provider that you will use to store the personalization ormembership data. Though you can create the Microsoft Access or SQL Serverdatabase and add the necessary configuration elements manually, the easier wayis to use the ASP.NET Web Site Administration tool, shown in Figure 1. Notethat to configure an application successfully, you must be logged in using anaccount with administrator rights (you also can launch Visual Studio with anadministrator-level account using Run As... and launch the Web SiteAdministration tool from the button in Solution Explorer, shown in Figure 2).

 


Figure 1. The ASP.NET Web SiteAdministration tool provides the means to configure personalization andmembership features (the Membership data store is configured using the Securitytab), as well as reports and data-access features.

 


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

 

To create an Access .mdb file for storing personalizationdata, you need to open the Web Site Administration tool; the file, namedAspNetDB.mdb, will be created automatically in a folder named DATA. Althoughnot enabled in the build of Visual Studio against which this article waswritten, the Web Site Administration tool contains an entire section devoted toconfiguring personalization settings. In a later section, I'll walk you throughadding the necessary configuration sections by hand.

 

You configure the provider to use for membership servicesusing 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 SecuritySetup Wizard. I'll walk you through this process momentarily.

 


Figure 3. The Security tab of the Web Site Administration tool providesa wizard for easy setup of the membership data store as well as a set ofmanagement 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 youneed to do from here is add users to the database (which you can do using theWeb Site Administration tool, or the membership APIs), set authorizationrestrictions on pages as desired, and create a login page.

 

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

 

In addition to the built-in Microsoft Access and SQLServer providers, you can create your own custom providers and configure yourapplications to use these providers. So, if you already have a user-credentialdatabase that you're not willing to part with, ASP.NET allows you to use thatand still get the benefits that membership services provide. Note that at thetime of this writing, the actual means for creating custom providers couldundergo some changes still, so I'll save a demonstration of creating customproviders for a future article.

 

Add Personalization andMembership Support

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

 

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

 

Next, click the Security tab, ensure that the SecuritySetup Wizard radio button is selected, and click Next. Step one is simplyinformational, so once you've read it, click Next (you may need to scroll tosee the button). In step two, ensure that the "From the Internet" radio buttonis selected and then click Next. Note that the "From the Internet" setting willconfigure the application to use ASP.NET forms authentication, and the "From alocal area network" setting will configure the application to use Windowsauthentication (which means that users will not need to log in to yourapplication explicitly). In step three, click Next to use the AspNetDB.mdb filethat is created automatically by the Web Site Administration tool. Then skipstep four by clicking Next again. In step five, add at least one user fortesting purposes. If you want to add more than one user, check the Add AnotherUser 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 thewizard allows you to create access rules to allow or deny access to all or partof your application based on user or role names. For now, just click Next. Youcan always add rules later. Finally, click Finish to exit the Wizard. Thedatabase has been created, and a Web.config file with the necessary elementshas been added to your Web Site. The resulting Web.config file is shown inFigure 4.

 

             connectionString=      "c:inetpubwwwrootaspnetPRO_PMDATAAspNetDB.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 providerelements for membership and role management. These elements are addedautomatically by the Security Setup Wizard, when the membership data store iscreated.   Add Personalization Properties To demonstrate personalization, next I'll show you how toadd some property definitions and store and retrieve them from a page. One ofthe properties will allow the user to choose a page theme that will be usedwhenever the user visits. Themes are a new feature of ASP.NET 2.0 that allowyou to modify the look and feel of an entire site with a simple configurationsetting 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 inorder to allow anonymous access to any personalization properties. Thepersonalization section contains two properties, both of which use theallowAnonymous attribute to enable the properties to be tracked for users whoare not logged in. The first property, Theme, does not specify a type, so itwill be treated as a string. The second property, FavoriteColors, specifies theStringCollection class as its type. Any attempt to store data that is notcompatible with the StringCollection class in this property will result in anexception being thrown. The serializeAs attribute allows the StringCollectionto 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 asspecified, 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 tothe controls added in the preceding example step.   When finished, the page shouldlook similar to Figure 6.  
Figure 6. This screen capture shows the appearance of the controls inthe Visual Studio IDE.   Select the DropDownList control and in the Propertieswindow, scroll down to and select the Items property. Click the ellipsis buttonto open the Collection Editor. Add two items, one with the text and value setto BasicBlue and one set to SmokeAndGlass, and then click OK. Double-click theSet 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 AsObject, _   ByVal e AsSystem.EventArgs)    If Profile.Theme ="" Then      IfRequest.Form("Themes") <> "" Then         Page.Theme =Request.Form("Themes")       End If   Else      Page.Theme =Profile.Theme   End IfEnd Sub   This code is required to set the page's theme, which mustbe set in the Page_PreInit event or earlier. The code checks to see whether atheme is already set for the user's personalization profile and uses thattheme. If no theme exists, the code checks to see if the user has submitted thepage with a new theme choice and, if so, uses the new theme. Otherwise, notheme will be applied.   Switch back to Design view and double-click the Add Colorbutton. Add the following code to the event handler:   Dim FaveColor As String = _   Server.HtmlEncode(textFavColor.Text) Dim FaveColors As New _   System.Collections.Specialized.StringCollectionProfile.FavoriteColors.Add(FaveColor) DisplayFavoriteColors()   Add the following subroutine just below the AddColor_Clickhandler:   Sub DisplayFavoriteColors()   listFavColors.DataSource = Profile.FavoriteColors   listFavColors.DataBind()End Sub   Add the following line to the Page_Load event handler (ifnecessary, switch to Design view and double-click an empty area of the page toadd the Page_Load handler):   DisplayFavoriteColors()   Now, save the page.   Test the Personalization Settings Browse the page, select a theme from the DropDownListcontrol 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 colorwill be added to the list box, which is populated from the profile. Afterapplying a theme and adding a couple of colors, the page should look similar toFigure 7.  
Figure 7. This screen capture shows the personalization properties inaction. Note how the button borders and foreground color, as well as thetext-box borders, are affected by the theme chosen.   Up to this point, the personalization information is beingstored exclusively for anonymous users. But what if you want to take theinformation that's already been saved for an anonymous user and migrate it to aspecific profile for a user when he or she logs in? Here's how: Add aGlobal.asax file to the Web site by right-clicking the site in SolutionExplorer, selecting Add New Item, and choosing the Global Application Classtemplate. 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).FavoriteColorsEnd Sub   In Design view, add a Login control and a LoginNamecontrol (found on the Security tab of the toolbox) to Default.aspx, below theother controls, then save and browse the page. When the page is firstdisplayed, no user name will be displayed by the LoginName control, and thepage will display any properties you previously had set while browsinganonymously. Log in using the account credentials you added when configuringthe membership database. The LoginName control will display your user ID now,and the Theme and FavoriteColors properties have been migrated to the profilefor your logged-in account. Note that if you log in and then log out again, anew anonymous identity is created, and any personalization for the previousanonymous identity is no longer displayed.   In this article, I've demonstrated how the new personalizationand membership features of ASP.NET 2.0 provide powerful functionality to yourWeb applications while requiring very little effort (and even less code!) toconfigure and use. In addition to the scenarios demonstrated in this article,personalization services can be used in conjunction with the new Web-partsfeature 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 noplumbing code, leaving you more time to focus on the business logic thatenables the features your users actually care about.   The sample code in thisarticle is available for download.   G. Andrew Duthie is the founder and principal ofGraymad 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 theInternational .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 inAspNetDB.mdb. Just create a database connection to AspNetDB.mdb and drag tablesfrom the connection to a page in your site. Visual Studio will create aGridView control and bind it to an AccessDataSource control (note that the ASP.NETworker process must have read-write permissions on the folder containing thedatabase for this to work). If you have difficulty browsing pages in theapplication, close the connection in Server Explorer before browsing the pages.   Personalization and Membership: What do they mean? Personalization and membership enable you to controlaccess to your application, as well as to store and retrieve information aboutusers of your application, including anonymous users. You can customize theappearance and behavior of your application based on this information, and youeven can allow users to store profile information, such as a shopping cart,while browsing anonymously, and later easily migrate that information to theirpersonal profiles when they log in.   Personalization allows you to store profile informationabout users of your application in a persistent data store. Personalizationsupports a pluggable data-provider layer and a set of APIs for storing andretrieving profile information in a strongly typed fashion. Personalizationallows you to specify one or more arbitrary properties to be stored in a user'sprofile. You can specify the type of each property (which can be a system typeor a user-defined type or custom class), as well as whether the property istracked for anonymous users, whether the property is read-only or read-write,and more.   Personalization also can be integrated with membershipservices to provide a unified solution for user management, login, andprofile-information storage. By default, the ASP.NET personalization systemassociates profile information with the identity with which the userauthenticates, accessible through HttpContext.Current.User.Identity.Name. Ifyou are using ASP.NET membership services for user-credential management, thenany time a user logs into your application, his or her membership identityautomatically will be stored in HttpContext.Current.User.Identity.Name, and allprofile information associated with that identity will be available to theapplication. Support for storing profile information for anonymous users is notenabled by default and requires adding an element to the Web.config file forthe application, as well as specifically making each desired property availablefor anonymous users.   Membership describes the set of technologies, including(as with personalization) a back-end provider for storing data; a set of APIsfor managing users and logins, etc.; and controls that allow you to adduser-credential storage and related functionality to your application with nolines of code.   User credentials are stored in a back-end membershipdatabase specified by the dataprovider 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 isconfigured, and users are added to the membership data store, adding loginfunctionality to the application can be as simple as dragging a single controlto a page in the application. The ASP.NET login controls (Login, LoginView,LoginStatus, LoginName, and PasswordRecovery) contain all of the logicnecessary to validate credentials and perform any necessary redirection, etc.,and are designed to integrate with membership.      

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like