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

使用Profile

尽管你仅可以为一个应用程序定义一个profile,但如果你需要让几个profile属性一起工作,把它们放在组中,会让你觉得它们更易管理。

例如,在列表3中,有一个带有两个组的profile,这两个组分别是AddressPreferences
列表3. Web.Config

<configuration>
<system.web>
      
   
<anonymousIdentification enabled="true" />
        
   
<profile>
               
<properties>
   
<group name="Address">
                  
<add 
         
name="Street"  
         allowAnonymous
="true" />
                 
<add 
         
name="City"  
         allowAnonymous
="true" />
   
</group>
   
<group name="Preferences">
      
<add 
         
name="ReceiveNewsletter" 
         type
="Boolean"
         defaultValue
="false"
         allowAnonymous
="true" />
   
</group>
              
</properties>
        
</profile>
</system.web>
</configuration>

当你用组来定义profile时,你应该使用组名来设置或读取profile属性。例如,在列表3中,你可以使用以下一些句子来完成三个profile属性的赋值。
[C#]
Profile.Address.City 
= "Modesto";
Profile.Address.Street 
= "111 King Arthur Ln";
Profile.Preferences.ReceiveNewsletter 
= false;

一个profile的定义只能包含一层组,换句话说,你不能把其他的组放在一个profile组的下面一层。

使用复杂的profile属性

到目前为止,我们已经介绍了声明包含简单类型(如string或整型)属性的profile,其实你也可以在profile中声明复杂属性。
举个例子,假设你现在需要在profile中存储一个购物篮,如果这样做的话,你就可以在每次访问网站时获得自己的购物篮。
列表4 声明了一个包含profile,这个profile包含一个名为ShoppingCart的属性,而该属性的type特性是一个叫ShoppingCart的类(我们接下来会创建该类),该类名是有效的。
我们还会注意到,该声明中包含一个serializeAs特性,该特性可以帮助ShoppingCart使用二进制序列化器(binary serializer)进行持久化,而不是使用xml序列化器。

 列表4 Web.config

<configuration>
<system.web>

  
<anonymousIdentification enabled="true" />
  
  
<profile>
    
<properties>
    
<add 
       
name="ShoppingCart"
       type
="ShoppingCart"
       serializeAs
="Binary"
       allowAnonymous
="true" />
    
</properties>
  
</profile>
</system.web>
</configuration>

列表
5 中有一个简单购物篮的实现代码,该购物篮拥有添加和删除项(item)的方法(method),同时它还拥有两个属性(property),一个是用于获得该购物篮中的所有项的,一个是用于表示所有商品的总价的。

列表5 ShoppingCart (c#)
using System;
using System.Collections;

[Serializable]
public class ShoppingCart
{
    
public Hashtable _CartItems = new Hashtable();

    
// Return all the items from the Shopping Cart
    public ICollection CartItems
    
{
        
get return _CartItems.Values; }
    }


    
// The sum total of the prices
    public decimal Total
    
{
        
get 
        
{
            
decimal sum = 0;
            
foreach (CartItem item in _CartItems.Values)
                sum 
+= item.Price * item.Quantity;
            
return sum;
        }

    }


    
// Add a new item to the shopping cart
    public void AddItem(int ID, string Name, decimal Price)
    
{
        CartItem item 
= (CartItem)_CartItems[ID];
        
if (item == null)
            _CartItems.Add(ID, 
new CartItem(ID, Name, Price));
        
else
        
{
            item.Quantity
++;
            _CartItems[ID] 
= item;
        }

    }


    
// Remove an item from the shopping cart
    public void RemoveItem(int ID)
    
{
        CartItem item 
= (CartItem)_CartItems[ID];
        
if (item == null)
            
return;
        item.Quantity
--;
        
if (item.Quantity == 0)
            _CartItems.Remove(ID);
        
else
            _CartItems[ID] 
= item;
    }


}


[Serializable]
public class CartItem
{
    
private int _ID;
    
private string _Name;
    
private decimal _Price;
    
private int _Quantity = 1;

    
public int ID
    
{
        
get return _ID; }
    }


    
public string Name
    
{
        
get return _Name; }
    }


    
public decimal Price
    
{
        
get return _Price; }
    }


    
public int Quantity
    
{
        
get return _Quantity; }
        
set { _Quantity = value; }
    }


    
public CartItem(int ID, string Name, decimal Price)
    
{
        _ID 
= ID;
        _Name 
= Name;
        _Price 
= Price;
    }

}

如果你把列表5中的代码添加到应用程序的App_Code目录中,购物篮会自动被编译。

 在列表5中有一点值得注意,那就是ShoppingCartCartItem类都加上了可序列化的特性,这一点对于他们能否被序列化十分重要,只有这样才能保存在Profile对象中。

最后,列表6的页面显示了可以被添加到购物篮中的产品。购物篮是通过BindShoppingCart方法从Profile对象中载入,该方法把购物篮中的对象绑定到一个GridView对象上,这些对象可以通过ShoppingCart类的CartItems属性获得。

AddCartItem方法用于在购物篮中添加一个产品,该方法中包含了检测Profile是否存在ShoppingCart的代码。对于Profile中存储的对象,你必须自己实例化这些对象,他们不会自动实例化。

RemoveCartItem方法用于从购物篮中移除一个产品,该方法只是简单地通过调用Profile中的ShoppingCart对象的RemoveItem方法。

列表
6. Products.aspx (C#)

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<script runat="server">

    
void Page_Load() {
        
if (!IsPostBack)
            BindShoppingCart();
    }

        
    
void BindShoppingCart() 
    
{
        
if (Profile.ShoppingCart != null
        
{
            CartGrid.DataSource 
= Profile.ShoppingCart.CartItems;
            CartGrid.DataBind();
            lblTotal.Text 
= Profile.ShoppingCart.Total.ToString("c");
        }

    }

   
    
void AddCartItem(Object s, EventArgs e) 
    
{
        GridViewRow row 
= ProductGrid.SelectedRow;

        
int ID = (int)ProductGrid.SelectedDataKey.Value;
        String Name 
= row.Cells[1].Text;
        decimal Price 
= Decimal.Parse(row.Cells[2].Text, 
          NumberStyles.Currency);
        
        
if (Profile.ShoppingCart == null)
            Profile.ShoppingCart 
= new ShoppingCart();
       
        Profile.ShoppingCart.AddItem(ID, Name, Price);
        BindShoppingCart();
    }

    
    
void RemoveCartItem(Object s, EventArgs e) 
    
{
        
int ID = (int)CartGrid.SelectedDataKey.Value;
        Profile.ShoppingCart.RemoveItem(ID);
        BindShoppingCart();
    }

</script>

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

    
<table width="100%">
    
<tr>
        
<td valign="top">
    
<h2>Products</h2>    
    
<asp:GridView
        
ID="ProductGrid"
        DataSourceID
="ProductSource"
        DataKeyNames
="ProductID"
        AutoGenerateColumns
="false"
        OnSelectedIndexChanged
="AddCartItem"
        ShowHeader
="false"
        CellPadding
="5"
        Runat
="Server">
        
<Columns>
            
<asp:ButtonField 
                
CommandName="select"
                Text
="Buy" />
            
<asp:BoundField
                
DataField="ProductName" />
            
<asp:BoundField
                
DataField="UnitPrice" 
                DataFormatString
="{0:c}" />
        
</Columns>
    
</asp:GridView>

    
<asp:SqlDataSource
        
ID="ProductSource"
        ConnectionString
=
"Server=localhost;Database=Northwind;Trusted_Connection=true;"

        SelectCommand
=
          "SELECT ProductID,ProductName,UnitPrice FROM Products"

        Runat
="Server" />
        
</td>
        
<td valign="top">
        
<h2>Shopping Cart</h2>
        
<asp:GridView
            
ID="CartGrid"
            AutoGenerateColumns
="false"
            DataKeyNames
="ID"
            OnSelectedIndexChanged
="RemoveCartItem"
            CellPadding
="5" 
            Width
="300"
            Runat
="Server">
            
<Columns>
            
<asp:ButtonField
                
CommandName="select"
                Text
="Remove" />
            
<asp:BoundField
                
DataField="Name" 
                HeaderText
="Name" />
            
<asp:BoundField
                
DataField="Price" 
                HeaderText
="Price" 
                DataFormatString
="{0:c}" />
            
<asp:BoundField
                
DataField="Quantity" 
                HeaderText
="Quantity" />
            
</Columns>
        
</asp:GridView>
        
<b>Total:</b> 
        
<asp:Label ID="lblTotal" Runat="Server" />
        
</td>
     
</tr>
     
</table>
    
</form>
</body>
</html>
继承一个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; }
    }

}



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>

posted on 2008-02-28 15:53  北漂浪子  阅读(256)  评论(0)    收藏  举报