WebApplication与Profile购物车

http://www.cnblogs.com/mldark/articles/1598294.html

http://bbs.langsin.com/thread-55987-1-1.html

在WebApplication中使用Profile做购物车功能。开发环境VS.NET 2008。

一Web.config文件配置

<system.web>
    <anonymousIdentification enabled="true"/>
    <profile inherits="ShoppingCartTest.UserProfile">
    </profile>
</system.web>

二UserProfile类

using System.Web.Profile;
using System.Web.Security;


namespace ShoppingCartTest
{
    public class UserProfile : ProfileBase
    {
        public static UserProfile GetUserProfile(string username)
        {
            return ((UserProfile)(ProfileBase.Create(username)));
        }
        public static UserProfile GetUserProfile()
        {
            string userName = System.Web.HttpContext.Current.User.Identity.Name;

           //HttpContext.Current.Request.AnonymousID


            return Create(userName) as UserProfile;
        }

        public virtual ProfileShoppingCart ProfileShoppingCart
        {
            get
            {
                return ((ProfileShoppingCart)(this.GetPropertyValue("ProfileShoppingCart")));
            }
            set
            {
                this.SetPropertyValue("ProfileShoppingCart", value);
            }
        }
    }
}


三ProfileShoppingCart类

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

namespace ShoppingCartTest

{

    [Serializable]

    public class ProfileShoppingCart

    {

        public DataTable _CartItems = new DataTable("CartItems");

        public ProfileShoppingCart()

        {

            CreatTable();

        }

        // 返回购物车中所有的商品

        public DataTable CartItems

        {

            get { return _CartItems; }

        }

        // 计算购物车中所有商品的总价钱

        public decimal Total

        {

            get

            {

                decimal sum = 0;

                foreach (DataRow row in _CartItems.Rows)

                   sum += Convert.ToDecimal(row["Price"].ToString()) * Convert.ToDecimal(row["Quantity"].ToString());

                return sum;

            }

        }

        // 添加商品到购物车

        public void AddItem(int ID, string Name, decimal Price)

        {

            if (_CartItems.Select("ID=" + ID).Length == 0)

            {

                DataRow row = _CartItems.NewRow();

                row["ID"] = ID;

                row["Name"] = Name;

                row["Price"] = Price;

                row["Quantity"] = 1;

                _CartItems.Rows.Add(row);

            }

            else

            {

                foreach (DataRow row in _CartItems.Select("ID=" + ID))

                {

                    row["Quantity"] = Convert.ToDecimal(row["Quantity"].ToString()) + 1;

                }

            }

        }

        // 移除购物车中的商品

        public void RemoveItem(int ID)

        {

            if (_CartItems.Select("ID=" + ID).Length == 0)

            {

                return;

            }

            else

            {

                foreach (DataRow row in _CartItems.Select("ID=" + ID))

                {

                    row["Quantity"] = Convert.ToDecimal(row["Quantity"].ToString()) - 1;

                    if (Convert.ToDecimal(row["Quantity"].ToString()) == 0)

                    {

                        _CartItems.Rows.Remove(row);

                    }

                }

            }

        }

        // 创建DataTable

        private void CreatTable()

        {

            _CartItems.Columns.Add("ID", typeof(int));

            _CartItems.Columns.Add("Name",typeof(string));

            _CartItems.Columns.Add("Price",typeof(decimal));

            _CartItems.Columns.Add("Quantity", typeof(decimal));

        }

    }

}

四shopping.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="shopping.aspx.cs" Inherits="ShoppingCartTest.shopping" %>

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></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" />
                <br />
                <b> Profile:</b><asp:Label ID="lblProfile" runat="server" Text="[lblProfile]"></asp:Label>
                <br />
                <a href="profileView.aspx" target="_blank">profileView</a>
                <br />
    <asp:Button ID="btnClearProfile" runat="server" onclick="btnClearProfile_Click" 
        Text="ClearProfile" />
                <br />
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

五shopping.aspx.cs代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Web.Profile;

namespace ShoppingCartTest
{
    public partial class shopping : System.Web.UI.Page
    {
        private static UserProfile Profile ;
        // 绑定购物车
        private void BindShoppingCart()
        {
            if (Profile.ProfileShoppingCart != null)
            {
                CartGrid.DataSource = Profile.ProfileShoppingCart.CartItems;
                CartGrid.DataBind();
                lblTotal.Text = Profile.ProfileShoppingCart.Total.ToString("c");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Profile = UserProfile.GetUserProfile("ProfileShoppingCart");
                Profile = UserProfile.GetUserProfile();
                
                BindShoppingCart();
            }

            GridView1.DataSource = ProfileManager.GetAllProfiles(System.Web.Profile.ProfileAuthenticationOption.All);
            GridView1.DataBind();
            lblProfile.Text = Profile.UserName;
        }
        // 移除购物车中的产品
        protected void RemoveCartItem(object sender, EventArgs e)
        {
            int ID = (int)CartGrid.SelectedDataKey.Value;
            Profile.ProfileShoppingCart.RemoveItem(ID);
            Profile.Save();
            BindShoppingCart();
        }
        // 添加产品到购物车
        protected void AddCartItem(object sender, 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.ProfileShoppingCart == null)
                Profile.ProfileShoppingCart = new ProfileShoppingCart();

            Profile.ProfileShoppingCart.AddItem(ID, Name, Price);
            Profile.Save();
            BindShoppingCart();
        }

        protected void btnClearProfile_Click(object sender, EventArgs e)
        {
            foreach (ProfileInfo pf in ProfileManager.GetAllProfiles(System.Web.Profile.ProfileAuthenticationOption.All))
            {
                if (DateTime.Now.Day - pf.LastUpdatedDate.Day >= 1)
                {
                    ProfileManager.DeleteProfile(pf.UserName);
                }
            }
            GridView1.DataSource = ProfileManager.GetAllProfiles(System.Web.Profile.ProfileAuthenticationOption.All);
            GridView1.DataBind();
        }
    }
}


六 Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Profile;

namespace ShoppingCartTest
{
    public class Global : System.Web.HttpApplication
    {
        protected void Profile_MigrateAnonymous(Object sender,ProfileMigrateEventArgs e)
        {
            UserProfile Profile = UserProfile.GetUserProfile("ProfileShoppingCart");
            UserProfile anonProfile = UserProfile.GetUserProfile(e.AnonymousID);
            Profile.ProfileShoppingCart = anonProfile.ProfileShoppingCart;


             HttpContext.Current.Profile.Save();

  •             //删除匿名标识
  •             System.Web.Security.AnonymousIdentificationModule.ClearAnonymousIdentifier();
  •             //删除匿名用户Profile
  •             System.Web.Profile.ProfileManager.DeleteProfile(e.AnonymousID);
  •             //删除匿名用户
  •             System.Web.Security.Membership.DeleteUser(e.AnonymousID);

      

      }  
        }
    }

  • 你可能感兴趣的:(server,object,String,System,Class,asp)