使用ASP.NET 2.0 Profile存储用户信息_2[翻译] Level 200

继承一个profile
你也可以通过从一个已经存在的profile类中继承一个profile来完成对profile的定义,这种特性能够帮助你在多个应用程序中使用相同的profile。
例如,列表7中列出了一个拥有多个用户属性的类,该类是从ProfileBase类继承而来的(你可以在System.Web.Profile中找到) 

在列表8中的Web.config包含一个从UserInfo类继承而来的profile,通过该声明,新的profile可以获得UserInfo类的所有属性。

列表  7 . UserInfo (C#) 

using  System;
using  System.Web.Profile;

public   class  UserInfo : ProfileBase
{
    
private string _FirstName;
    
private string _LastName;

    
public string FirstName 
    
{
        
get return _FirstName; }
        
set { _FirstName = value; }
    }

    
public string LastName
    
{
        
get return _LastName; }
        
set { _LastName = value; }
    }

}
列表 8. Web.Config

< configuration >
    
< system .web >
           
< anonymousIdentification  enabled ="true"   />
   
< profile  inherits ="UserInfo"   />
    
</ system.web >
</ configuration >
迁移匿名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中有一个包含两个按钮的页面,分别是login和logout按钮,其中还有一个用于更新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的值是一个随机生成的唯一识别号(见图3)。当你按下Login按钮后,你就完成了身份认证,它是通过用户票据(User Bill)完成的。


图3 使用匿名和认证profile

列表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,该方法接收一个唯一识别号,并且返回与唯一识别号对应的profile。ProfileMigrateEventArgs对象包含一个匿名识别号。

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

Profile使用Provider模式,通过修改web.config或machine.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版本号]。执行该工具后,你会看到图4中的ASP.NET SQL Server安装向导。

图4 使用ASP.NET SQL Server安装程序

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

在你完成SQL Server数据库的配置后,你需要修改web.config或machine.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对象集合,但没有一个返回一个真正的profile。ProfileInfo对象包含以下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进行编译

[C#]
C:WINDOWSMicrosoft.NETFrameworkv2.
0.40607 csc 
  DeleteInactiveProfiles.cs

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

列表15中的web.config中有三个属性:SurveyCompleted、FavoriteLanguageFavoriteEnvironment

Listing 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有一段表示感谢的文字。
列表 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 >

总结
    当建立Web应用程序时,我依旧花费了大量的时间和精力用于做一些大伤脑筋的事情。其中的一个任务就是写一些用于从数据库存储和获得用户信息的代码。虽然 Profile对象引入的都是asp.net 1.0中可以实现的功能,但是这个新特性帮助我们从乏味的编码工作中解脱出来,这样也能让我们在写Web应用程序的过程中,把更多的精力放在我们更感兴趣的事情上。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值