10、使用用户配置文件

使用用户配置文件

Asp.net Framework提供了一种可选的不同于cookie和Session状态的方式存储用户信息:Profile对象。
Profile对象提供强类型、可持久化的Session状态表单。

web.config
	<system.web>
    <profile>
      <properties>
        <add name="firstName"/>
        <add name="lastName"/>
        <add name ="numberOfVisits" type="Int32" defaultValue="0"/>
      </properties>      
    </profile>  
...


Profile属性
name
type
defaultValue
readOnly
serializeAs
allowAnonymous
provider
customProviderData

2011-5-16 16:34 danny




web.config
<?xml version="1.0"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
	<system.web>
		<compilation debug="true" targetFramework="4.0"/>
		<profile>
			<properties>
				<add name="firstName"/>
				<add name="lastName"/>
				<add name="numberOfVisits" type="Int32" defaultValue="0"/>
			</properties>
		</profile>
	</system.web>
</configuration>


显示:ShowProfile.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_PreRender(object sender, EventArgs e)
    {
        lblFirstName.Text = Profile.firstName;
        lblLastName.Text = Profile.lastName;
        Profile.numberOfVisits++;
        lblNumberOfVisits.Text = Profile.numberOfVisits.ToString();
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        Profile.firstName = txtNewFirstName.Text;
        Profile.lastName = txtNewLastName.Text;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        First Name:
        <asp:Label ID="lblFirstName" runat="server" />
        <br />
        <br />
        Last Name:
        <asp:Label ID="lblLastName" runat="server" />
        <br />
        <br />
        Number of Visits:
        <asp:Label ID="lblNumberOfVisits" runat="server" />
        <hr />
        <asp:Label ID="lblNewFirstName" Text="New First Name:" AssociatedControlID="txtNewFirstName"
            runat="server" />
        <asp:TextBox ID="txtNewFirstName" runat="server" />
        <br />
        <br />
        <asp:Label ID="lblNewLastName" Text="New Last Name:" AssociatedControlID="txtNewLastName"
            runat="server" />
        <asp:TextBox ID="txtNewLastName" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnUpdate" Text="Update Profile" runat="server" OnClick="btnUpdate_Click" />
    </div>
    </form>
</body>
</html>

1、创建用户配置文件组
通过用户分组来进行更多配置
web.config
<?xml version="1.0"?>

<configuration>
	<system.web>
		<compilation debug="true" targetFramework="4.0"/>
		<profile>
			<properties>
				<group name="Preferences">
					<add name="BackColor" defaultValue="lightblue"/>
					<add name="Font" defaultValue="Arial"/>
				</group>
				<group name="ContactInfo">
					<add name="Email" defaultValue="Your Email"/>
					<add name="Phone" defaultValue="Your Phone"/>
				</group>
			</properties>
		</profile>
	</system.web>
</configuration>


显示应用Profile组
ShowProfileGroups.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Drawing" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        lblEmail.Text = Profile.ContactInfo.Email;
        lblPhone.Text = Profile.ContactInfo.Phone;
        Style pageStyle = new Style();
        pageStyle.BackColor = ColorTranslator.FromHtml(Profile.Preferences.BackColor);
        pageStyle.Font.Name = Profile.Preferences.Font;

        Header.StyleSheet.CreateStyleRule(pageStyle, null, "html");
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Email:
        <asp:Label ID="lblEmail" runat="server" />
        <br />
        <br />
        Phone:
        <asp:Label ID="lblPhone" runat="server" />
    </div>
    </form>
</body>
</html>

显示结果:


2、支持匿名用户
web.config
<?xml version="1.0"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
	<system.web>
		<compilation debug="true" targetFramework="4.0"/>
		<authentication mode="Forms"/>
		<anonymousIdentification enabled="true"/>
		<profile>
			<properties>
				<add name="numberOfVisits" type="Int32" defaultValue="0" allowAnonymous="true"/>
			</properties>
		</profile>
	</system.web>
</configuration>


ShowAnonymousIdentification.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_PreRender(object sender, EventArgs e)
    {
        lblUserName.Text = Profile.UserName;
        lblIsAnonymous.Text = Profile.IsAnonymous.ToString();
        Profile.numberOfVisits++;
        lblNumberOfVisits.Text = Profile.numberOfVisits.ToString();
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SetAuthCookie("Danny", false);
        Response.Redirect(Request.Path);
    }

    protected void btnLogout_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Response.Redirect(Request.Path);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        User Name:
        <asp:Label ID="lblUserName" runat="server" />
        <br />
        Is Anonymous:
        <asp:Label ID="lblIsAnonymous" runat="server" />
        <br />
        Number Of Visits:
        <asp:Label ID="lblNumberOfVisits" runat="server" />
        <hr />
        <asp:Button ID="btnReload" Text="Reload" runat="server" />
        <asp:Button ID="btnLogin" Text="Login" runat="server" OnClick="btnLogin_Click" />
        <asp:Button ID="btnLogout" Text="Logout" runat="server" OnClick="btnLogout_Click" />
    </div>
    </form>
</body>
</html>


显示结果:
匿名

登录

匿名和登录显示次数是不一样的。

2011-5-16 21:15 danny


3、合并匿名用户配置文件
前面例子可知道匿名和登录显示次数是不一样的。
当用户从匿名切换到验证状态时,所有的用户配置信息会丢失。
如果在Profile对象中存储了购物车,登录后则所有的购物车项目会丢失。
可以在用户从匿名切换到验证状态时,处理Global.asax文件中的MigrateAnonymous事件,预存Profile属性的值。
该事件在拥有用户配置的用户登录时触发。

只需在Global.asax中加入以下代码:
 public void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs args)
    { 
      //Get anonymous profile
        ProfileCommon annoProfile = Profile.GetProfile(args.AnonymousID);
        
        //Copy anonymous properties to authenticated
        foreach (SettingsProperty prop in ProfileBase.Properties)
        {
            Profile[prop.Name] = annoProfile[prop.Name];
        }
        
        
        //kill the anonymous profile
        ProfileManager.DeleteProfile(args.AnonymousID);
        AnonymousIdentificationModule.ClearAnonymousIdentifier();
            
    }



4、从自定义类继承Profile
自定义的Profile
App_Code/SiteProfile.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;

 
public class SiteProfile : ProfileBase
{

    private string _firstName = "Your First Name";
    private string _lastName = "Your Last Name";
    [SettingsAllowAnonymous(true)]
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }

    }
    [SettingsAllowAnonymous(true)]
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

}


相应的配置文件
web.config
<?xml version="1.0"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
	<system.web>
		<compilation debug="true" targetFramework="4.0"/>
		<anonymousIdentification enabled="true"/>
		<profile inherits="SiteProfile"/>
	</system.web>
</configuration>


显示ShowProfile.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_PreRender(object sender, EventArgs e)
    {
        lblFirstName.Text = Profile.FirstName.ToString();
        lblLastName.Text = Profile.LastName.ToString();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        First Name:
        <asp:Label ID="lblFirstName" runat="server" />
        <br />
        Last Name:
        <asp:Label ID="lblLastName" runat="server" />
    </div>
    </form>
</body>
</html>


显示结果:

当在一个类中定义Profile属性时,可以使用下面的特性修饰那些属性
SettingAllowAnonymouse   --用于允许匿名用户读写特性
ProfileProvider                   --用于关联属性到一个特定的Profile提供程序
CustomProviderData       --用于传递自定义数据到Profile提供程序

5、创建复杂Profile属性
Profile属性表示复杂的类
App_code\ShoppingCart.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;

namespace DannyExample
{
    public class ShoppingCart
    {
        private List<CartItem> _items = new List<CartItem>();

        public List<CartItem> Items
        {
            get { return _items; }
        }

    }
    public class CartItem
    {
        private string _name;
        private decimal _price;
        private string _description;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        public decimal Price
        {
            get { return _price; }
            set { _price = value; }
        }
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
        public CartItem() { }
        public CartItem(string name, decimal price, string description)
        {
            _name = name;
            _price = price;
            _description = description;
        }
    }
}


Web.config
<?xml version="1.0"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <profile>
      <properties>
        <add name="ShoppingCart" type="DannyExample.ShoppingCart"/>
      </properties>
    </profile>
  </system.web>
</configuration>


显示及操作界面:ShowShoppingCart.aspx
<%@ Page Language="C#" %>

<%@ Import Namespace="DannyExample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_PreRender(object sender, EventArgs e)
    {
        grdShoppingCart.DataSource = Profile.ShoppingCart.Items;
        grdShoppingCart.DataBind();

    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        CartItem item = new CartItem(txtName.Text, decimal.Parse(txtPrice.Text), txtDescription.Text);
        Profile.ShoppingCart.Items.Add(item);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdShoppingCart" EmptyDataText="There are no items in your shopping cart"
            runat="server">
        </asp:GridView>
        <br />
        <fieldset>
            <legend>Add Product</legend>
            <asp:Label ID="lblName" Text="Name:" AssociatedControlID="txtName" runat="server" />
            <br />
            <asp:TextBox ID="txtName" runat="server" />
            <br />
            <br />
            <asp:Label ID="lblPrice" Text="Price:" AssociatedControlID="txtPrice" runat="server" />
            <br />
            <asp:TextBox ID="txtPrice" runat="server" />
            <br />
            <br />
            <asp:Label ID="lblDescription" Text="Description:" AssociatedControlID="txtDescription"
                runat="server" />
            <br />
            <asp:TextBox ID="txtDescription" runat="server" />
            <br />
            <br />
            <asp:Button ID="btnAdd" Text="Add To Cart" runat="server" OnClick="btnAdd_Click" />
        </fieldset>
    </div>
    </form>
</body>
</html>


显示结果:
开始没有数据

添加数据

其中的奥秘在于App_Data\ASPNETDB.MDF(如果没有选择网站,单击右键,选中添加ASP.NET文件夹,然后选中App_Data,选中App_Data刷新即可)
打开数据库,其中有一张表:aspnet_Profile,查看数据:
UserID     用户的ID
PropertyNames  属性名称
PropertyValuesString 属性值
PropertyValuesBinary  Image 应该是保存图片
LastUpdateDate  最后更新时间

UserID :154cf3d3-70de-472c-8004-8931b29c48b6  不知道按什么算法算出来的。
PropertyNames:ShoppingCart:S:0:562:   ShoppingCart为属性名,: 为分隔符,0:表示分段位置,562为长度,当有多个值时0的值和562值就比较明显
PropertyValuesString:
<?xml version="1.0" encoding="utf-16"?>
<ShoppingCart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Items>
    <CartItem>
      <Name>aaa</Name>
      <Price>11</Price>
      <Description>ddge</Description>
    </CartItem>
    <CartItem>
      <Name>aaad</Name>
      <Price>112</Price>
      <Description>ddgeeg</Description>
    </CartItem>
    <CartItem>
      <Name>a</Name>
      <Price>11</Price>
      <Description>ad ddge</Description>
    </CartItem>
  </Items>
</ShoppingCart>


PropertyValuesBinary :没有细细研究。
LastUpdateDate:2011-5-16 14:13:00

补充:
Profile属性关联的serializeAs特性
Binary
ProviderSpecific
String
xml

Xml Serializer比 Binary Serializer臃肿。

App_code/ShoppingCart.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;

namespace DannyExample
{
    [Serializable]
    public class ShoppingCart
    {
        private List<CartItem> _items = new List<CartItem>();

        public List<CartItem> Items
        {
            get { return _items; }
        }

    }
    [Serializable]
    public class CartItem
    {
        private string _name;
        private decimal _price;
        private string _description;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        public decimal Price
        {
            get { return _price; }
            set { _price = value; }
        }
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
        public CartItem() { }
        public CartItem(string name, decimal price, string description)
        {
            _name = name;
            _price = price;
            _description = description;
        }
    }
}


Web.config
<?xml version="1.0"?>

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <profile>
      <properties>
        <add name="ShoppingCart" type="DannyExample.ShoppingCart" serializeAs="Binary"/>
      </properties>
    </profile>
  </system.web>
</configuration>


可能就保存在PropertyValuesBinary中。
查看数据库,发现PropertyValuesString为空。
证明了以前的想法。

2011-5-16 22:28 danny

6、自动保存用户配置
注意两点:
web.config
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <profile automaticSaveEnabled="false">
      <properties>
        <add name="ShoppingCart" type="DannyExample.ShoppingCart" serializeAs="Binary"/>
      </properties>
    </profile>
  </system.web>
</configuration>

automaticSaveEnabled="false"

Glabal.asax
 public void Profile_ProfileAutoSaveing(object s, ProfileAutoSaveEventArgs e)
    {
        if (Profile.ShoppingCart.HasChanged)
            e.ContinueWithProfileAutoSave = true;
        else
            e.ContinueWithProfileAutoSave = false;
    }    


同时要修改ShoppingCart类,具有HasChanged属性

7、从组件访问用户配置
可以在组件内引用HttpContext.Profile属性访问Profile对象。
P134

8、使用配置文件管理器
用户配置数据在用户离开应用程序时不会消失。过一段时间后,Profile对象保存的大量数据就可能变很大。如果允许匿名用户配置,情况就更糟。
ProfileManager类,用于删除旧的用户配置。
DeleteInactiveProfiles  --用于删除从某一日期后不再使用的用户配置
DeleteProfile             --用于删除与指定用户名关联的用户配置
DeleteProfiles            --用于删除和一个用户数组或ProfileInfo对象数组中的用户对象关联的用户配置
FindInactiveProfilesByUserName  --用于返回指定用户名关联的并且从某一日期之后不再活动的所有用户配置
FindProfilesByUserName     --用于获得与指定用户名关联的所有用户配置
GetAllInactiveProfiles          --用于返回某一日期之后不再活动的所有用户配置
GetAllProfiles                    --用于返回每一个用户配置
GetNumberOfInactiveProfiles  --用于返回指定的日期后不再活动的指定数量的用户配置
GetNumberOfProfiles           --用于返回指定数量的用户配置

ManagerProfiles.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    DateTime inactiveDate = DateTime.Now.AddMonths(-3);

    protected void Page_PreRender(object sender, EventArgs e)
    {
        lblProfiles.Text = ProfileManager.GetNumberOfProfiles(ProfileAuthenticationOption.All).ToString();
        lblInactiveProfiles.Text = ProfileManager.GetNumberOfInactiveProfiles(ProfileAuthenticationOption.All, inactiveDate).ToString();

    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int results = ProfileManager.DeleteInactiveProfiles(ProfileAuthenticationOption.All, inactiveDate);
        lblResults.Text = String.Format("{0} Profiles deleted!", results);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Total Profiles:
        <asp:Label ID="lblProfiles" runat="server" />
        <br />
        Inactive Profiles:
        <asp:Label ID="lblInactiveProfiles" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnDelete" Text="Delete Inactive Profiles" runat="server" OnClick="btnDelete_Click" />
        <br />
        <asp:Label ID="lblResults" EnableViewState="false" runat="server" />
    </div>
    </form>
</body>
</html>


2011-5-17 10:00 danny

9、配置用户配置提供程序
默认情况下,用户配置数据保存在应用程序的App_Data文件夹下的名叫ASPNETDB.mdf的数据库中。
P138

10、创建自定义用户配置提供程序
P138-P142

2011-5-17 10:18 danny



你可能感兴趣的:(Web,配置管理,asp.net,asp,LINQ)