[转]ASP.NET 2.0个性化配置(profile)系列(3)

迁移匿名Profile设置
Profile
对象既可用于匿名用户也可以用于已认证用户。然而,当用户从匿名用户状态转换为已认证用户状态时,Profile对象能够以一种令人难以理解的方式完成任务。
当匿名用户使用Profile对象时,用户profile是与一个随机生成的号码相关联的,该号码是根据每个用户唯一生成的,它保存在浏览器的cookie中,无论何时该用户返回应用程序,该用户的Profile设置会被自动加载。
如果匿名用户通过认证的话,所有与该用户相关的profile就会丢失,同时系统会生成一个新的profile。这时该Profile信息将与用户名相关联,而非唯一识别号。
要想理解所有这些工作,最好的方法就是看看下面的例子。列表9中的web.config定义了一个profile,该profile只有一个FavoriteColor属性。

列表 9 Web.config

<configuration>
<system.web>
   
<authentication mode="Forms" />     
           
<anonymousIdentification enabled="true" />        
   
<profile>
   
<properties>
                  
<add 
         
name="FavoriteColor"
         allowAnonymous
="true" 
         defaultValue
="Red" />
               
</properties>
           
</profile>
</system.web>
</configuration>

列表10中有一个包含两个按钮的页面,分别是loginlogout按钮,其中还有一个用于更新FavoriteColor属性的表单。

列表10. Anonymous.aspx (C#)

<%@ Page Language="C#" %>

<script runat="server">

    
void Login(Object s, EventArgs e)
    
{
        FormsAuthentication.SetAuthCookie(
"Bill"false);
        Response.Redirect(Request.Path);
    }


    
void Logout(Object s, EventArgs e)
    
{
        FormsAuthentication.SignOut();
        Response.Redirect(Request.Path);
    }


    
void UpdateProfile(Object s, EventArgs e)
    
{
        Profile.FavoriteColor 
= txtFavoriteColor.Text;
    }

    
    
void Page_PreRender()
    
{
        lblUsername.Text 
= Profile.UserName;
        lblFavoriteColor.Text 
= Profile.FavoriteColor;
    }

        
</script>

<html>
<head>
    
<title>Anonymous</title>
</head>
<body>
    
<form id="form1" runat="server">

    
<asp:Button
        
Text="Login"
        OnClick
="Login"
        Runat
="Server" />
    
<asp:Button ID="Button1"
        Text
="Logout"
        OnClick
="Logout"
        Runat
="Server" />
    
<hr />
    
<asp:TextBox    
        
id="txtFavoriteColor"
        Runat
="Server" />
    
<asp:Button
        
Text="Update Profile"
        OnClick
="UpdateProfile"
        Runat
="Server" />
    
<hr />
    
<b>Username:</b>
    
<asp:Label  
        
id="lblUsername"
        Runat
="Server" />
    
<br />
    
<b>Favorite Color:</b>
    
<asp:Label
        
id="lblFavoriteColor"
        Runat
="Server" />    
        
    
</form>
</body>
</html>

当你打开第一个页面时,UserName的值是一个随机生成的唯一识别号。当你按下Login按钮后,你就完成了身份认证,它是通过用户票据(User Bill)完成的。

列表10的页面中包含一个用于更新FavoriteColor的表单,要注意的是,在你登录登出的时候,会分别生成两个不同的profile。例如当你先登录,后登出的话,那么系统会生成一个随机的唯一识别号。

在很多情况下,你需要把匿名profile迁移到认证profile状态,如果你需要迁移profile属性值的话,你可以利用 ProfileModule类的MigrateAnonymous事件完成该任务,该事件只能在Global.asax文件中进行处理。列表11中的 Global.asax演示了你如何才能实现FavoriteColor属性的迁移。

列表 11. Global.asax (C#)
<%@ Application Language="C#" %>
<script runat="server">

    
void Profile_MigrateAnonymous(Object s, 
      ProfileMigrateEventArgs e)
    
{
        ProfileCommon anonProfile 
= 
          Profile.GetProfile(e.AnonymousId);
        Profile.FavoriteColor 
= anonProfile.FavoriteColor;
    }
   
</script>

通过Profile类的GetProfile()方法你可以获得匿名profile,该方法接收一个唯一识别号,并且返回与唯一识别号对应的profileProfileMigrateEventArgs对象包含一个匿名识别号。

配置Profile Provider
默认情况下,profile被保存在sqlserver 2005 express数据库,它位于App_Data目录中,这或许在你开发一些普通的asp.net应用程序时是没有问题的,但很有可能,你需要把你的应用程序的profile保存在另一个数据库中,比如一个完整版的SqlServer 2005的实例中,而该数据库又位于你局域网的某个位置。

Profile
使用Provider模式,通过修改web.configmachine.config的设置来告诉系统把信息存储在哪里。
ASP.NET
本身配了一个profile provider,叫SqlProfileProvider。如果你感到困惑,你可以通过继承ProfileProvider基类来创建一个自己的 provider。例如,你可以创建一个基于Oracle数据库或MySql数据库的Provider。在这里,我们将只讨论最简单的方法,即通过SqlServer数据库来保存profile信息。

要使用Microsoft SQL Server存储profile信息,必须完成两个步骤。首先,你必须安装SQL Server数据库,然后你必须重新设置配置文件。

ASP.NET 2.0
框架提供了一个用于配置SQL Server来存储Profile信息的工具,该工具叫做aspnet_regsql,它位于Windows\Microsoft.NET\ Framework\[.NET版本号],执行该工具。

SQL Server
安装向导会指导你完成必要的步骤,完成这些步骤后,向导会自动创建用于存储profile信息的存储过程和表结构。

在你完成SQL Server数据库的配置后,你需要修改web.configmachine.config中的数据库连接设置来指向服务器上的SQL Server数据库,本例中该数据库的实例名为MyServer,列表12列出了该配置文件。

列表 12. Web.Config

<configuration>
<connectionStrings>
<add
name="myConnectionString"
connectionString
=
"Server=MyServer;Trusted_Connection=true;database=MyDatabase"
 />
</connectionStrings>
<system.web>
<anonymousIdentification enabled="true" />
<profile defaultProvider="MyProfileProvider">
<providers>
<add
name="MyProfileProvider"
type
="System.Web.Profile.SqlProfileProvider"
connectionStringName
="myConnectionString" />
</providers>
<properties>
<add
name="FirstName"
allowAnonymous
="true" />
<add
name="LastName"
allowAnonymous
="true" />
</properties>
</profile>
</system.web>
</configuration>

在列表12中的profile配置中,包含了一个defaultProvider特性,这个特性指向一个叫MyProfileProvider profile provider,而这个provider定义是在profile标记的<providers>节中完成的。 MyProfileProvider则使用一个叫MyConnectionString的连接字符串完成数据库连接,并保存profile信息到数据库中。MyConnectionString可以在位于web.config开头的<connectionStrings>节中找到。

管理profile并生成profile报告
Profile
会对象自动保存用户profile信息,这既是好事业是坏事。说它是好事,是因为你不需要写存储信息的所有逻辑代码,说它是坏事,是因为这样可能造成一大堆无用的信息被保存在数据库中。

幸运的是,ASP.NET 2.0框架包含一个叫做ProfileManager的类,你可以使用它来管理profile信息。它包含了相当多的方法使你能够有效地管理profile并且生成profile报表,下面列出了一些该类的重要方法:

·    DeleteInactiveProfiles. 删除一个特定日期之前的所有profile

·    DeleteProfile. 删除特定用户的profile

·    DeleteProfiles. 删除一个profile集合

·    FindInactiveProfilesByUserName. 返回一个ProfileInfo对象的集合,该集合表示的profile是匹配一个某个名字,并且是从某个特定日期开始一直未被使用

·    FindProfilesByUserName. 返回一个ProfileInfo对象集合,该集合与某个用户名相关联

·    GetAllInactiveProfiles. 返回一个ProfileInfo对象集合,该集合表示的profile是从某个特定日期开始一直未被使用的profile

·    GetAllProfiles. 返回一个ProfileInfo对象集合,该集合表示所有的profile

·    GetNumberOfInactiveProfiles. 返回从某个特定日期开始一直未被使用的profile的数量

·    GetNumberOfProfiles. 返回profile总数

这些方法中,虽然所有的方法都返回一个ProfileInfo对象集合,但没有一个返回一个真正的profileProfileInfo对象包含以下profile属性

·    IsAnonymous. 表示该profile是否为匿名profile

·    LastActivityDate. 最后一次profile被访问的时间和日期

·    LastUpdatedDate. 最后一次profile被升级的时间和日期

·    Size. 表示profile的大小,这是在profile provider存储profile信息时记录的

·    UserName. profile关联的用户名

ProfileManager有几个方法提供了额外的参数用于支持分页。例如,GetAllProfiles方法的一个重载版本就提供了专门用于设置页面索引、页面大小、总共的记录数的参数,这些参数在需要分页的页面中十分有用。

ProfileManager
既可以在asp.net页面下使用,也可以在其它程序中使用。例如,你可能需要做一个控制台程序用于每天清除长时间未使用的 profile。列表14的控制台程序会删除七天未使用的profile,你可以使用Windows计划任务(Windows Scheduled Tasks)来安排该程序的执行时间。

列表 14. DeleteInactiveProfiles (C#)

using System;
using System.Web.Profile;

public class DeleteInactiveProfiles
{    
    
public static void Main()
    
{
      
int deleted = 0;
      deleted 
= 
        ProfileManager.DeleteInactiveProfiles(
        ProfileAuthenticationOption.All, 
        DateTime.Now.AddDays(
-7));
      Console.WriteLine(
"Deleted " + 
        deleted.ToString() 
+ " profiles" );
    }
      
}


你可以通过一下的命令行指令对列表14进行编译

[Visual Basic .NET]
C:\WINDOWS\Microsoft.NET\Framework\v2.0.40607\vbc 
  /r:System.Web.dll DeleteInactiveProfiles.vb

[C#]
C:\WINDOWS\Microsoft.NET\Framework\v2.0.40607\csc 
  DeleteInactiveProfiles.cs


你还可以使用ProfileManager类生成profile信息报表。例如,如果你打算生成一个用户调查的报表,你可以把用户调查保存在profile中,这样就可以轻易的使用ProfileManager生成你需要的报表。

列表15中的web.config中有三个属性:SurveyCompletedFavoriteLanguage FavoriteEnvironment

列表 15. Web.Config

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    
   
<system.web>

      
              
<anonymousIdentification enabled="true" />

      
<profile>
      
<properties>
                      
<add 
            
name="SurveyCompleted"
            type
="Boolean"
            allowAnonymous
="true" />
                      
<add 
            
name="FavoriteLanguage"
            allowAnonymous
="true" />
                     
<add 
            
name="FavoriteEnvironment"
            allowAnonymous
="true" />
      
</properties>
              
</profile>
 
</system.web>
</configuration>

列表16中的页面演示了一个简单的用户调查。该页面包含两个Panel控件,第一个控件中有两个调查问题,当用户完成调查后,第一个控件会自动隐藏,而第二个会显示出来,第二个Panel有一段表示感谢的文字。

列表 16. Survey.aspx (C#)

<%@ Page Language="C#" %>
<script runat="server">

    
void SaveSurvey(Object s, EventArgs e)
    
{    
        Profile.FavoriteLanguage 
= rdlLanguage.SelectedItem.Text;
        Profile.FavoriteEnvironment 
= rdlEnvironment.SelectedItem.Text;
        Profile.SurveyCompleted 
= true;
    }

    
    
void Page_PreRender()
    
{    
        
if (Profile.SurveyCompleted) 
        
{
            pnlSurvey.Visible 
= false;
            pnlSurveyCompleted.Visible 
= true;
        }

        
else
        
{
            pnlSurvey.Visible 
= true;
            pnlSurveyCompleted.Visible 
= false;
        }

    }

    
</script>

<html>
<head>
    
<title>Survey</title>
</head>
<body>
    
<form id="form1" runat="server">
    
    
<asp:Panel ID="pnlSurvey" Runat="Server">
    What is your favorite programming language?
    
<br />
    
<asp:RadioButtonList 
        
id="rdlLanguage"
        runat
="Server">
        
<asp:ListItem Text="VB.NET" Selected="True" />    
        
<asp:ListItem Text="C#" />
        
<asp:ListItem Text="J#" />    
    
</asp:RadioButtonList>
    
<p>&nbsp;</p>
    What is your favorite development environment?
    
<br />
    
<asp:RadioButtonList 
        
id="rdlEnvironment"
        runat
="Server">
        
<asp:ListItem Text="VS.NET" Selected="True" />    
        
<asp:ListItem Text="Web Matrix" />
        
<asp:ListItem Text="Notepad" />    
    
</asp:RadioButtonList>
    
<p>&nbsp;</p>    
    
<asp:Button ID="Button1"
        Text
="Submit Survey"
        Onclick
="SaveSurvey"
        Runat
="Server" />
    
</asp:Panel>
    
<asp:Panel ID="pnlSurveyCompleted" Runat="Server">
    Thank you for completing the survey!
    
</asp:Panel>
    
</form>
</body>
</html>

列表17中显示调查的结果,该页面中有一个显示ProfileInfo对象集合的GridView控件,该ProfileInfo对象集合是由 ProfileManagerGetAllProfiles方法获得的。当你点击GridView中的任意一行的Select链接时,你将会看到对这个问题的调查结果,该调查结果是由Profile类的GetProfile方法获得的。

列表 17. SurveyResults.aspx (C#)

<%@ Page Language="C#" %>
<script runat="server">

    
void Page_Load()
    
{    
        ResultsGrid.DataSource 
= 
ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
        ResultsGrid.DataBind();
    }

    
    
void DisplayProfileDetails(Object s, EventArgs e)
    
{
        ProfileCommon SelectedProfile 
= 
            Profile.GetProfile(ResultsGrid.SelectedValue.ToString());
        lblLanguage.Text 
= SelectedProfile.FavoriteLanguage;
        lblEnvironment.Text 
= SelectedProfile.FavoriteEnvironment;
    }

    
</script>

<html>
<head>
    
<title>Survey Results</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<h2>Survey Results</h2>
    
<asp:GridView 
        
id="ResultsGrid"
        DataKeyNames
="UserName"
        AutoGenerateSelectButton
="true"
        OnSelectedIndexChanged
="DisplayProfileDetails"
        SelectedRowStyle-BackColor
="LightYellow"
        Runat
="Server" />
    
<p>&nbsp;</p>
    
<h2>Survey Details</h2>
    
<b>Favorite Language:</b>
    
<asp:Label  
        
id="lblLanguage"
        Runat
="Server" />
    
<br />
    
<b>Favorite Environment:</b>
    
<asp:Label  
        
id="lblEnvironment"
        Runat
="Server" />
    
</form>
</body>
</html>
posted on 2008-02-28 16:05  北漂浪子  阅读(446)  评论(0)    收藏  举报