sailing

Everything...

[Asp.net]Understand profile

Detailed introduction on asp.net 2.0 feature: profile, from how to access it in code both in anonymous and authenticated condition and sql provider for storage, also cover the report part for managibility.
Here is the URL: http://msdn.microsoft.com/asp.net/default.aspx?pull=/library/en-us/dnvs05/html/UserProfiles.asp
Enjoy! :)

A few code piece for quick reference:
1. Add your type to the web.config
<configuration>
<system.web>

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

2. Define your type
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;
    }
}

3. How to access it in your code:
<%@ 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>

4.On how to play with authenticated profile:
<%@ 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>

5. Migrating the info in the anonymous mode to authenticated mode
This magic lies in 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>

6. Config to use MSSQL provider for storage
step1: run the script comes with the .net framework: aspnet_regsql and it is located in your Windows\Microsoft.NET\Framework\[version] folder.
step 2: Update your web.config looks like this:
<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>

7. Delete inactive profile:
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" );
    }
       
}

8 Get stored profile information:
<%@ 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>

posted on 2006-07-16 17:41  乌生鱼汤  阅读(271)  评论(0编辑  收藏  举报

导航