Configuring Profiles and Personalization


The profiles and personalization features in ASP.NET are closely allied to the membership and roles management features you saw in the previous chapter. They use the same database as the membership and roles features to store personalized data for each user. They also build on a provider model that allows you to extend or replace the underlying profiles or personalization system if you wish.

Specifying the Profiles and Personalization Providers

ASP.NET supplies default profile and personalization providers called Sql ProfileProvider (from the System.Web.Profile namespace) and Sql PersonalizationProvider (from the System.Web.UI.WebControls.WebParts namespace). The default contents of the machine.config file specify SqlProfileProvider as the default provider for profiles, using SQL Server Express Edition as the database system and the aspnetdb database generated in the previous chapter.

You can see this provider declaration in Listing 12.1, together with a second declaration that uses the same provider but specifies a remote SQL Server database system with a pre-attached copy of the aspnetdb database. The type attribute for each provider refers to the .NET class that implements the providerwe have removed the long version information string from the listing so that you can see the structure of the file more easily.

Listing 12.1. The <profile> Section of machine.config

<system.web>   ...   <profile>     <providers>       <add name="AspNetSqlProfileProvider"            connectionStringName="LocalSqlServer"            applicationName="/"            type="System.Web.Profile.SqlProfileProvider, ..." />       <!-- following added to use SQL Server attached database -->       <add name="Sql2005RemoteProfile"            connectionStringName="Sql2005Remote"            applicationName="/"            type="System.Web.Profile.SqlProfileProvider, ..." />     </providers>   </profile>   ... </system.web>

The default provider for the personalization system is specified in the root web.config file, located in the same folder as machine.config. The web.config file contains only settings that are specific to ASP.NET, whereas the machine.config file contains settings for all parts of the .NET Framework. The <webParts> section of web.config contains several settings, but Listing 12.2 shows those that are of interest when configuring personalization.

As with the membership and roles providers, the connectionStringName attribute refers to a connection string declared in the <connectionStrings> section of machine.config. Listing 12.3 shows the two entries that relate to the provider declarations in Listing 12.1 and Listing 12.2.

Listing 12.2. The <personalization> Section of the Root web.config File

<system.web>   ...   <webParts>     <personalization>       <providers>         <add name="AspNetSqlPersonalizationProvider"              connectionStringName="LocalSqlServer"              type="System.Web...WebParts.SqlPersonalizationProvider,              ... />         <!-- following added to use SQL Server attached database -->         <add name="Sql2005RemotePersonalization"              connectionStringName="Sql2005Remote"              applicationName="/"              type="System.Web.Profile.SqlPersonalizationProvider,              ..." />       </providers>     </personalization>   </webParts>   ... </system.web>

For details about building custom providers, including a custom profile provider, see http://msdn.microsoft.com/library/enus/dnaspp/html/ASPNETProvMod_Prt8.asp.


Listing 12.3. The <connectionStrings> Section of machine.config

<connectionStrings>   <add name="LocalSqlServer"        connectionString="data source=.\SQLEXPRESS;                         Integrated Security=SSPI;                         AttachDBFilename=|DataDirectory|aspnetdb.mdf;                         User Instance=true"        providerName="System.Data.SqlClient" />   <!-- following added to use remote SQL Server attached database -->   <add name="Sql2005Remote"        connectionString="data source=myremoteserver;                         Initial Catalog=aspnetdb;                         User ID=myusername;                         Password=secret"        providerName="System.Data.SqlClient" /> </connectionStrings>

Creating and Modifying the ASP.NET Application Database

Once you have specified the providers for the profiles and personalization systems, or if you are happy to use the defaults, you must create or configure the aspnetdb database to store and manipulate the data. If you used the ASP.NET SQL Server Setup Wizard described in the previous chapter to configure the database for membership and roles, it will also have created the tables and procedures required in the database for the profiles and personalization system (see Figure 12.1).

Figure 12.1. The ASP.NET SQL Server Setup Wizard


For more information about using the ASP.NET SQL Server Setup Wizard, see the section Creating the ASP.NET Application Database in the previous chapter.


Alternatively, you can use the aspnet_regsql.exe utility to add (or remove) the profiles and personalization features from aspnetdb. The utility, which you run in a Command window, is located at:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe


You must specify the database connection details using the server name (-S) and either the user name (-U) and password (-P), or integrated authentication using your current Windows credentials (-E). You also specify the feature you want to add (-A) or remove (-R). The feature identifiers are the following:

  • all: All features

  • m: Membership

  • r: Role manager

  • p: Profiles

  • c: Personalization

  • w: SQLWeb event provider

Optionally, you can specify the name of the database using the -d argument. If omitted, the utility assumes the default name aspnetdb. As an example, to connect to the local SQL Server Express Edition database using Windows authentication and add profiles and personalization features to aspnetdb, you would enter:

aspnet_regsql -S.\SQLExpress -E -Apc


To connect to a remote server and remove all the features, you would use:

aspnet_regsql -Sservername -Uuserid -Ppassword -Rall


You can connect to your aspnetdb database in the Server Explorer (Visual Studio 2005) or Database Explorer (Visual Web Developer) window to see what tables are in place, giving you a good indication of the features actually installed.

Enabling Profiles and Declaring Profile Properties

After specifying the profiles provider(s), or accepting the default provider settings, and creating or reconfiguring the ASP.NET application database, you are ready to enable profiles for your Web site or Web application. In the local web.config file in the root folder of the site, turn on profiles using the <profile> element, and specify any profile properties that you require to be available to your visitors and application code.

Note

In the early beta releases of ASP.NET 2.0, the Web Site Administration Tool provided features to enable and configure profiles and profile properties. This feature is not available in the release version, and you must perform all configuration and management by editing the machine.config and web.config files directly.


Listing 12.4 shows the syntax and structure of the <profile> element. The attributes allow you to enable or disable this profile, specify the provider to use by default, optionally enable or disable automatic saving of profile values, and optionally specify the name of a custom class you want to use to manage the profile data.

Listing 12.4. Enabling Profiles and Specifying Profile Properties in web.config

<system.web>   ...   <profile enabled="true|false"            defaultProvider="provider-identifier"            automaticSaveEnabled="true|false"            inherits="class-name">      <properties>        <clear />        <add name="property-name"             type="data-type-name"             defaultValue="value"             serializeAs="String|Binary|Xml|ProviderSpecific"             readOnly="true|false"             provider="provider-identifier"             customProviderData="string-value"             allowAnonymous="true|false"        <remove name="property-name" />        <group name="group-name">          <add name="property-name" ... />          <remove name="property-name" />        </group>      </properties>    </profile>    ...  </system.web>

Usually, when using the ASP.NET SqlProfileProvider class, you will just include the enabled and defaultProvider attributes. The default value for the automaticSaveEnabled attribute, if omitted, is true, so that the profile system saves any changes to profile properties back to the database when page execution ends. The system does not save the values of profile properties that have not changed, which reduces the processing overhead required.

The list of profile properties in the <properties> section defines the values available in your pages and stored in the database. You can clear the list (removing any properties added by web.config files in parent folders), remove individual properties, and add new ones. You specify the behavior and type of each property using the following series of attributes:

  • name. Required The name of the property.

  • type. Optional The .NET data type name, such as String (the default), Int32, Boolean, and so on.

  • defaultValue. Optional The value of the property until another value is assigned to it.

  • serializeAs. Optional The serialization format. The default is String, though you can specify other types depending on the way that the class implementing the property can serialize its value(s).

  • readOnly. Optional Specifies if this property can only be read and not updated. Usually you will provide a default value in this case.

  • provider. Optional The name of the provider to handle this property if it does not use the default provider specified in the <profile> element.

  • customProviderData. Optional A string value placed in the property's Attributes collection under the key "CustomProviderData".

  • allowAnonymous. Optional Specifies if this property is accessible to users that have not logged in to the site or application.

Profile Property Groups

You can define groups of properties that you will access in code as subsets of the profile for each user. This provides a more structured set of profile data and can make it easier to manage the information in your code.

Listing 12.5 shows an example profile for a Web site; the profile includes several properties that are String and Int32 types, a read-only profile property with a default value, and a profile property group named "Address". Remember that the default type for a profile property, if not specified, is String.

Listing 12.5. A Simple Profile Configuration Example in web.config

<system.web>   ...   <profile enabled="true" defaultProvider="AspNetSqlProfileProvider">     <properties>       <add name="FirstName" type="String" />       <add name="LastName" type="String" />       <add name="Age" type="Int32" />       <group name="Address">         <add name="Street" />         <add name="City" />         <add name="ZipCode" />         <add name="Country" />       </group>       <add name="TextSize" type="String" allowAnonymous="true"            defaultValue="small" />       <add name="SiteName" type="String" allowAnonymous="true"            defaultValue="Demo" readOnly="true" />     </properties>   </profile>   ... </system.web>

Custom Profile Property Types

It is also possible to store profile properties that are more complex data types. For example, Listing 12.6 shows a class that implements a simple shopping cart. It exposes three properties; the UserID property is a String, the CartItems property is a System.Data.DataTable instance that contains a row for each item in the cart, and the TotalValue property is the total value of all the items in the cart as a Double.

There are also two public methods; the AddItem method takes the name, quantity, and value of an item to add, and the Clear method empties the cart. Obviously, a "real-world" cart would require extra features, such as a method to remove individual items, but this example will suffice to demonstrate the use of the profiles in ASP.NET.

Listing 12.6. A Simple ShoppingCart Class

using System; using System.Data; namespace DemoShoppingCart {   public class ShoppingCart   {     // internal member variables     private String user;     private DataTable items;     private Double total;     // public properties     public String UserID     {       get { return user; }       set { user = value; }     }     public DataTable CartItems     {       get { return items; }       set { items = value; }     }     public Double TotalValue     {       get { return total; }       set { total = value; }     }     // default constructor     public ShoppingCart()     {       // create an empty shopping cart       user = String.Empty;       // create an empty DataTable to hold the cart items       items = new DataTable("Items");       items.Columns.Add(new DataColumn("ItemName",                         Type.GetType("System.String")));       items.Columns.Add(new DataColumn("Qty",                         Type.GetType("System.Int32")));       items.Columns.Add(new DataColumn("Value",                         Type.GetType("System.Double")));       // set total value of the new cart to zero       total = 0;     }     // add an item to the cart     public void AddItem(String ItemName, Int32 ItemQty,                         Double ItemValue)     {       // create new DataTable row and populate with values       DataRow row = items.NewRow();       row["ItemName"] = ItemName;       row["Qty"] = ItemQty;       row["Value"] = ItemValue;       // add row to DataTable and update total value       items.Rows.Add(row);       total += (ItemQty * ItemValue);     }     // empty the cart by clearing the DataTable     public void Clear()     {       items.Rows.Clear();       total = 0;     }   } }

You can obtain a useful starter kit for building e-commerce applications from the ASP.NET Web site. Called the PayPal-enabled eCommerce Starter Kit, you can download it from http://www.asp.net/default.aspx?tabindex=5&tabid=41.


You simply place the code file shown in Listing 12.6 that implements the class in the App_Code subfolder of your Web site and ASP.NET will compile it at runtime. You then add a using directive to the page to make it available to code in that page:

using DemoShoppingCart;


It is now possible to use this custom type as a profile property. In the web.config file for the site, you add it to the <properties> section; specifying the type as the namespace.classname for the classas shown in Listing 12.7. You will see how to access instances of this class, along with the other profile properties, in the section Storing and Using Dynamic Profile Data, later in this chapter.

Listing 12.7. Adding the ShoppingCart Class as a Profile Property to web.config

<system.web>   <profile enabled="true" defaultProvider="AspNetSqlProfileProvider">     <properties>       ...       <add name="Cart" type="DemoShoppingCart.ShoppingCart"            allowAnonymous="true" />     </properties>   </profile> </system.web>

Anonymous Profiles

Several of the examples in the code listings earlier in this chapter include the allowAnonymous="true" attribute in the <properties> section of the <profile> element in the web.config files. This is a useful feature of the profiles system, and means that you can store information for users who have not logged into the site. However, you should use it with care, because it does mean that you can end up storing many rows of profile data in your application database as anonymous visitors browse the site, and ASP.NET does not remove these rows at the end of their useful life.

Anonymous profiles depend on a cookie stored on the user's machine, which ASP.NET generates when you enable anonymous profiles. When they visit the site again, the anonymous user ID stored in this cookie allows ASP.NET to reconnect visitors to their stored profile data. However, users may delete cookies, or just never visit your site again, and so the profile data rows remain in the aspnet_Profile table of the application database.

Therefore, if you use anonymous profiles, you should consider creating a stored procedure or other code routine that purges old rows from the database, based on the LastUpdated value that is stored in each row.

For this reason, anonymous profiles are not enabled by default. To enable them, you add the <anonymousIdentification> element to the <system.web> section of your web.config file, with the attribute enabled="true":

<anonymousIdentification enabled="true" />


In fact, several features of ASP.NET use anonymous identification, not just profiles. You can use several attributes in this element to control how the anonymous identification process works, as shown in Listing 12.8.

Listing 12.8. The <anonymousIdentification> Element Syntax and Structure

<anonymousIdentification enabled="true|false"    cookieName="cookie-name"    cookiePath="path"    domain="validity-domain-path"    cookieTimeout="minutes"    cookieSlidingExpiration="true|false"    cookieProtection="All|None|Encryption|Validation"    cookieRequireSSL="true|false"    cookieless="UseCookie|UseUri|UseDeviceProfile|AutoDetect" />

The cookiePath, domain, cookieTimeout, cookieSlidingExpiration, cookieProtection, cookieRequiresSSL, and cookieless attributes all work in the same way as the equivalents in the <forms> element of the <authentication> element that you saw in the section ASP.NET Authentication and Authorization, in the previous chapter. All these attributes are optional. If they are omitted, the cookie name is ".ASPXANONYMOUS" with a timeout of 100000 minutes (around 69 days). It uses only Validation protection without SSL, and it applies to the whole site.



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