PetShop

我们使用Visual Studio 2012来制作这个项目。

 

首先,新建项目,选择Visual C#中的Web模板组,选择ASP.NET Web窗体应用程序模板:

生成好后,按Ctrl+F5即可看到生成好的页面:

然后我们查看有没有添加上名为System.Data.Entity的命名空间,右击项目名,选择 添加引用:

然后找到System.Data.Entity,若没打勾,请打上勾(可能要先把其他的勾打上,才能把它的勾打上):

然后跟刚才的方法一样,新建一个名为 Models 的文件夹:

然后我们在 Models 文件夹上右击 添加 新建项 :

选择 C# 下的 代码 ,选择 类 , 命名为 Product.cs:

使用下面的代码替换Product.cs的原有代码:

using System.ComponentModel.DataAnnotations;
                                                                                                                                                                                                                                                                                                                     
namespace petshop.Models
{
    public class Product
    {
        [ScaffoldColumn(false)]
        public int ProductID { get; set; }
                                                                                                                                                                                                                                                                                                                     
        [Required, StringLength(100), Display(Name = "Name")]
        public string ProductName { get; set; }
                                                                                                                                                                                                                                                                                                                     
        [Required, StringLength(10000), Display(Name = "Product Description"), DataType(DataType.MultilineText)]
        public string Description { get; set; }
                                                                                                                                                                                                                                                                                                                     
        public string ImagePath { get; set; }
                                                                                                                                                                                                                                                                                                                     
        [Display(Name = "Price")]
        public double? UnitPrice { get; set; }
                                                                                                                                                                                                                                                                                                                     
        public int? CategoryID { get; set; }
                                                                                                                                                                                                                                                                                                                     
        public virtual Category Category { get; set; }
    }
}

保存:

然后重复刚才的步骤,在 Models 里新建一个名为 Category.cs 的类,用以下代码替换:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
                                                                                                                                                                                                                                                                                                            
namespace petshop.Models
{
    public class Category
    {
        [ScaffoldColumn(false)]
        public int CategoryID { get; set; }
                                                                                                                                                                                                                                                                                                            
        [Required, StringLength(100), Display(Name = "Name")]
        public string CategoryName { get; set; }
                                                                                                                                                                                                                                                                                                            
        [Display(Name = "Product Description")]
        public string Description { get; set; }
                                                                                                                                                                                                                                                                                                            
        public virtual ICollection Products { get; set; }
    }
}

保存:

然后再在同样位置新建一个叫 ProductContext.cs 的类,用以下代码替换:

using System.Data.Entity;
namespace petshop.Models
{
    public class ProductContext : DbContext
    {
        public ProductContext() : base("petshop")
        {
        }
        public DbSet Categories { get; set; }
        public DbSet Products { get; set; }
    }
}

添加一个名为 ProductDatabaseInitializer.cs 的类,用以下代码替换:

using System.Collections.Generic;
using System.Data.Entity;
                                                                                                                                                                                                                                                                                            
namespace petshop.Models
{
    public class ProductDatabaseInitializer : DropCreateDatabaseIfModelChanges
    {
        protected override void Seed(ProductContext context)
        {
            GetCategories().ForEach(c => context.Categories.Add(c));
            GetProducts().ForEach(p => context.Products.Add(p));
        }
                                                                                                                                                                                                                                                                                            
        private static List GetCategories()
        {
            var categories = new List {
                new Category
                {
                    CategoryID = 1,
                    CategoryName = "Dogs"
                },
                new Category
                {
                    CategoryID = 2,
                    CategoryName = "Cats"
                },
                new Category
                {
                    CategoryID = 3,
                    CategoryName = "Rabbits"
                },
                new Category
                {
                    CategoryID = 4,
                    CategoryName = "Fishs"
                },
                new Category
                {
                    CategoryID = 5,
                    CategoryName = "Birds"
                },
            };
                                                                                                                                                                                                                                                                                            
            return categories;
        }
                                                                                                                                                                                                                                                                                            
        private static List GetProducts()
        {
            var products = new List {
                new Product
                {
                    ProductID = 1,
                    ProductName = "Convertible Dog",
                    Description = "This convertible Dog is fast! The engine is powered by a neutrino based battery (not included)." +
                                  "Power it up and let it go!",
                    ImagePath="carconvert.png",
                    UnitPrice = 22.50,
                    CategoryID = 1
               },
                new Product
                {
                    ProductID = 2,
                    ProductName = "Old-time Dog",
                    Description = "There's nothing old about this toy Dog, except it's looks. Compatible with other old toy Dogs.",
                    ImagePath="carearly.png",
                    UnitPrice = 15.95,
                     CategoryID = 1
               },
                new Product
                {
                    ProductID = 3,
                    ProductName = "Fast Dog",
                    Description = "Yes this Dog is fast, but it also floats in water.",
                    ImagePath="carfast.png",
                    UnitPrice = 32.99,
                    CategoryID = 1
                },
                new Product
                {
                    ProductID = 4,
                    ProductName = "Super Fast Dog",
                    Description = "Use this super fast Dog to entertain guests. Lights and doors work!",
                    ImagePath="carfaster.png",
                    UnitPrice = 8.95,
                    CategoryID = 1
                },
                new Product
                {
                    ProductID = 5,
                    ProductName = "Old Style Racer",
                    Description = "This old style racer can fly (with user assistance). Gravity controls flight duration." +
                                  "No batteries required.",
                    ImagePath="carracer.png",
                    UnitPrice = 34.95,
                    CategoryID = 1
                },
                new Product
                {
                    ProductID = 6,
                    ProductName = "Ace Cat",
                    Description = "Authentic airCat toy. Features realistic color and details.",
                    ImagePath="planeace.png",
                    UnitPrice = 95.00,
                    CategoryID = 2
                },
                new Product
                {
                    ProductID = 7,
                    ProductName = "Glider",
                    Description = "This fun glider is made from real balsa wood. Some assembly required.",
                    ImagePath="planeglider.png",
                    UnitPrice = 4.95,
                    CategoryID = 2
                },
                new Product
                {
                    ProductID = 8,
                    ProductName = "Paper Cat",
                    Description = "This paper Cat is like no other paper Cat. Some folding required.",
                    ImagePath="planepaper.png",
                    UnitPrice = 2.95,
                    CategoryID = 2
                },
                new Product
                {
                    ProductID = 9,
                    ProductName = "Propeller Cat",
                    Description = "Rubber band powered Cat features two wheels.",
                    ImagePath="planeprop.png",
                    UnitPrice = 32.95,
                    CategoryID = 2
                },
                new Product
                {
                    ProductID = 10,
                    ProductName = "Early Rabbit",
                    Description = "This toy Rabbit has a real gas powered engine. Requires regular tune ups.",
                    ImagePath="truckearly.png",
                    UnitPrice = 15.00,
                    CategoryID = 3
                },
                new Product
                {
                    ProductID = 11,
                    ProductName = "Fire Rabbit",
                    Description = "You will have endless fun with this one quarter sized fire Rabbit.",
                    ImagePath="truckfire.png",
                    UnitPrice = 26.00,
                    CategoryID = 3
                },
                new Product
                {
                    ProductID = 12,
                    ProductName = "Big Rabbit",
                    Description = "This fun toy Rabbit can be used to tow other Rabbits that are not as big.",
                    ImagePath="truckbig.png",
                    UnitPrice = 29.00,
                    CategoryID = 3
                },
                new Product
                {
                    ProductID = 13,
                    ProductName = "Big Ship",
                    Description = "Is it a Fish or a ship. Let this floating vehicle decide by using its " +
                                  "artifically intelligent computer brain!",
                    ImagePath="boatbig.png",
                    UnitPrice = 95.00,
                    CategoryID = 4
                },
                new Product
                {
                    ProductID = 14,
                    ProductName = "Paper Fish",
                    Description = "Floating fun for all! This toy Fish can be assembled in seconds. Floats for minutes!" +
                                  "Some folding required.",
                    ImagePath="boatpaper.png",
                    UnitPrice = 4.95,
                    CategoryID = 4
                },
                new Product
                {
                    ProductID = 15,
                    ProductName = "Sail Fish",
                    Description = "Put this fun toy sail Fish in the water and let it go!",
                    ImagePath="boatsail.png",
                    UnitPrice = 42.95,
                    CategoryID = 4
                },
                new Product
                {
                    ProductID = 16,
                    ProductName = "Bird",
                    Description = "This fun Bird will travel up to a height of 200 feet.",
                    ImagePath="rocket.png",
                    UnitPrice = 122.95,
                    CategoryID = 5
                }
            };
                                                                                                                                                                                                                                                                                            
            return products;
        }
    }
}

然后更新 Golbal.asax ,用以下代码替换:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using petshop;
using System.Data.Entity;
using petshop.Models;
                                                                                                                                                                                                                                                                                      
namespace petshop
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // 在应用程序启动时运行的代码
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterOpenAuth();
            //RouteConfig.RegisterRoutes(RouteTable.Routes);
            Database.SetInitializer(new ProductDatabaseInitializer());
        }
                                                                                                                                                                                                                                                                                      
        void Application_End(object sender, EventArgs e)
        {
            //  在应用程序关闭时运行的代码
                                                                                                                                                                                                                                                                                      
        }
                                                                                                                                                                                                                                                                                      
        void Application_Error(object sender, EventArgs e)
        {
            // 在出现未处理的错误时运行的代码
                                                                                                                                                                                                                                                                                      
        }
    }
}

然后修改 Web.config ,在 connectionStrings 里添加一项:

用以下代码替换 Default.aspx :

<%@ Page Title="Welcome" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="petshop._Default" %>
                                                                                                                                                                                                                                                                        

    


    

然后用以下代码替换 Site.Master:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="petshop.SiteMaster" %>
                                                                                                                                                                                                                                                                     




    
    <%: Page.Title %> - PetShop
        
          <%: Scripts.Render("~/bundles/modernizr") %>
     
    
    
    
    


    
<%--To learn more about bundling scripts in ScriptManager see http://go.microsoft.com/fwlink/?LinkID=272931&clcid=0x409 --%> <%--Framework Scripts--%> <%--Site Scripts--%>

© <%: DateTime.Now.Year %> - 我的 ASP.NET 应用程序

然后在项目名称上右击 添加,新建项 ,新建 C# 下的 Web 里的 使用母版页的Web窗体 ,命名为 ProductList.aspx:

选择 Site.Master。

然后用同样方式添加 ProductDetails.aspx。

 

然后,打开 content 文件夹下的 Site.css,找到 content-wrapper,把 max-width 改为 1060。然后把 #body 里的 main-content 和 featured + .main-content 里的内容注释掉:

然后把 table 里的 border-collapse: collapse; 和 border: 0 none; 第一个 th 里的 border: none 0px;  和 td 里的 border: 0 none; 给注释掉:

然后,把 Site.Master 里的 nav 部分用以下代码替换:

然后修改 Site.Master 中 id=body 的内容,在一开始加入

<%#: Item.CategoryName %> -

然后修改  Site.Master.cs ,用以下代码替换:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using petshop.Models;
                                                                                                                                                                                                                 
namespace petshop
{
    public partial class SiteMaster : MasterPage
    {
        private const string AntiXsrfTokenKey = "__AntiXsrfToken";
        private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
        private string _antiXsrfTokenValue;
                                                                                                                                                                                                                 
        protected void Page_Init(object sender, EventArgs e)
        {
            // The code below helps to protect against XSRF attacks
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Use the Anti-XSRF token from the cookie
                _antiXsrfTokenValue = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Generate a new Anti-XSRF token and save to the cookie
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;
                                                                                                                                                                                                                 
                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }
                                                                                                                                                                                                                 
            Page.PreLoad += master_Page_PreLoad;
        }
                                                                                                                                                                                                                 
        protected void master_Page_PreLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set Anti-XSRF token
                ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
                ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
            }
            else
            {
                // Validate the Anti-XSRF token
                if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                    || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
                {
                    throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                }
            }
        }
                                                                                                                                                                                                                 
        protected void Page_Load(object sender, EventArgs e)
        {
                                                                                                                                                                                                                 
        }
        public IQueryable GetCategories()
        {
            var db = new petshop.Models.ProductContext();
            IQueryable query = db.Categories;
            return query;
        }
    }
}

然后,用以下代码替换 ProductList.aspx :

<%@ Page Title="Products" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
         CodeBehind="ProductList.aspx.cs" Inherits="petshop.ProductList" %>



    


用以下代码替换 ProductList.aspx.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using petshop.Models;
using System.Web.ModelBinding;
                                                                                                                                                                                                        
namespace petshop
{
    public partial class ProductList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                                                                                                                                                                                                        
        }
                                                                                                                                                                                                        
        public IQueryable GetProducts([QueryString("id")] int? categoryId)
        {
            var _db = new petshop.Models.ProductContext();
            IQueryable query = _db.Products;
            if (categoryId.HasValue && categoryId > 0)
            {
                query = query.Where(p => p.CategoryID == categoryId);
            }
            return query;
        }
    }
}

用以下代码替换 ProductDetails.aspx:

<%@ Page Title="Product Details" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
         CodeBehind="ProductDetails.aspx.cs" Inherits="petshop.ProductDetails" %>



    
        
            

<%#:Item.ProductName %>


<%#:Item.ProductName %> Description:
<%#:Item.Description %>
Price: <%#: String.Format("{0:c}", Item.UnitPrice) %>
Product Number: <%#:Item.ProductID %>

替换 ProductDetails.aspx.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using petshop.Models;
using System.Web.ModelBinding;
                                                                                                                                                                                                  
namespace petshop
{
    public partial class ProductDetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                                                                                                                                                                                                  
        }
                                                                                                                                                                                                  
        public IQueryable GetProduct([QueryString("productID")]int? productId)
        {
            var _db = new petshop.Models.ProductContext();
            IQueryable query = _db.Products;
            if (productId.HasValue && productId > 0)
            {
                query = query.Where(p => p.ProductID == productId);
            }
            else
            {
                query = null;
            }
            return query;
        }
    }
}

 

然后在 Models 中添加 新建项,代码,类,命名为 CartItem.cs,然后用以下代码替换:

using System.ComponentModel.DataAnnotations;
                                                                                                                                                                                           
namespace petshop.Models
{
    public class CartItem
    {
        [Key]
        public string ItemId { get; set; }
                                                                                                                                                                                           
        public string CartId { get; set; }
                                                                                                                                                                                           
        public int Quantity { get; set; }
                                                                                                                                                                                           
        public System.DateTime DateCreated { get; set; }
                                                                                                                                                                                           
        public int ProductId { get; set; }
                                                                                                                                                                                           
        public virtual Product Product { get; set; }
                                                                                                                                                                                           
    }
}

在 ProductContext.cs 中,加入:

public DbSet ShoppingCartItems { get; set; }

 

然后在项目 petshop 上右击,添加 新建文件夹 ,命名为 Logic 。

在 Logic 文件夹上右击 添加 新建项 C# 代码 类,命名为 ShoppingCartActions.cs,其代码为:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using petshop.Models;
                                                                                                                                                                             
namespace petshop.Logic
{
    public class ShoppingCartActions
    {
        public string ShoppingCartId { get; set; }
                                                                                                                                                                             
        private ProductContext _db = new ProductContext();
                                                                                                                                                                             
        public const string CartSessionKey = "CartId";
                                                                                                                                                                             
        public void AddToCart(int id)
        {
            // Retrieve the product from the database.          
            ShoppingCartId = GetCartId();
                                                                                                                                                                             
            var cartItem = _db.ShoppingCartItems.SingleOrDefault(
                c => c.CartId == ShoppingCartId
                && c.ProductId == id);
            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists.                 
                cartItem = new CartItem
                {
                    ItemId = Guid.NewGuid().ToString(),
                    ProductId = id,
                    CartId = ShoppingCartId,
                    Product = _db.Products.SingleOrDefault(
                     p => p.ProductID == id),
                    Quantity = 1,
                    DateCreated = DateTime.Now
                };
                                                                                                                                                                             
                _db.ShoppingCartItems.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart,                  
                // then add one to the quantity.                
                cartItem.Quantity++;
            }
            _db.SaveChanges();
        }
                                                                                                                                                                             
        public string GetCartId()
        {
            if (HttpContext.Current.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
                {
                    HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class.    
                    Guid tempCartId = Guid.NewGuid();
                    HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return HttpContext.Current.Session[CartSessionKey].ToString();
        }
                                                                                                                                                                             
        public List GetCartItems()
        {
            ShoppingCartId = GetCartId();
                                                                                                                                                                             
            return _db.ShoppingCartItems.Where(
                c => c.CartId == ShoppingCartId).ToList();
        }
    }
}

然后在项目名 petshop 上右击,添加,新建项,C#,Web,Web窗体,命名为 AddToCart.aspx 。

然后修改 AddToCart.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.Diagnostics;
using petshop.Logic;
                                                                                                                                                               
namespace petshop
{
    public partial class AddToCart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string rawId = Request.QueryString["ProductID"];
            int productId;
            if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId))
            {
                ShoppingCartActions usersShoppingCart = new ShoppingCartActions();
                usersShoppingCart.AddToCart(Convert.ToInt16(rawId));
            }
            else
            {
                Debug.Fail("ERROR : We should never get to AddToCart.aspx without a ProductId.");
                throw new Exception("ERROR : It is illegal to load AddToCart.aspx without setting a ProductId.");
            }
            Response.Redirect("ShoppingCart.aspx");
        }
    }
}

然后在添加一个 使用母版的Web窗体,命名为 ShoppingCart.aspx,使用的是 Site.Master,用以下代码替换:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ShoppingCart.aspx.cs" Inherits="petshop.ShoppingCart" %>



    

Shopping Cart

<%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.Product.UnitPrice)))%>


然后替换 ShoppingCart.aspx.cs 里的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using petshop.Models;
using petshop.Logic;
                                                                                                                                         
namespace petshop
{
    public partial class ShoppingCart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                                                                                                                                         
        }
                                                                                                                                         
        public List GetShoppingCartItems()
        {
            ShoppingCartActions actions = new ShoppingCartActions();
            return actions.GetCartItems();
        }
    }
}

然后在  ProductList.aspx 里添加一段代码:

               
    
        Add To Cart
              

把这段代码也添加到 ProductDetails.aspx 中去:

把下列代码添加到 位于 Logic 文件夹的 ShoppingCartAction.cs 里:

public decimal GetTotal()
{
    ShoppingCartId = GetCartId();
    // Multiply product price by quantity of that product to get       
    // the current price for each of those products in the cart. 
    // Sum all product price totals to get the cart total.   
    decimal? total = decimal.Zero;
    total = (decimal?)(from cartItems in _db.ShoppingCartItems
                               where cartItems.CartId == ShoppingCartId
                               select (int?)cartItems.Quantity *
                               cartItems.Product.UnitPrice).Sum();
    return total ?? decimal.Zero;
}

在 ShoppingCart.aspx.cs 中添加如下代码:

ShoppingCartActions usersShoppingCart = new ShoppingCartActions();
            decimal cartTotal = 0;
            cartTotal = usersShoppingCart.GetTotal();
            if (cartTotal > 0)
            {
                // Display Total.
                lblTotal.Text = String.Format("{0:c}", cartTotal);
            }
            else
            {
                LabelTotalText.Text = "";
                lblTotal.Text = "";
                ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
            }

在 ShoppingCart.aspx 中加入如下代码:

用如下代码替换 ShoppingCart.aspx.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using petshop.Models;
using petshop.Logic;
using System.Collections.Specialized;
using System.Collections;
using System.Web.ModelBinding;
                                                                                                               
namespace petshop
{
    public partial class ShoppingCart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ShoppingCartActions usersShoppingCart = new ShoppingCartActions();
            decimal cartTotal = 0;
            cartTotal = usersShoppingCart.GetTotal();
            if (cartTotal > 0)
            {
                // Display Total.
                lblTotal.Text = String.Format("{0:c}", cartTotal);
            }
            else
            {
                LabelTotalText.Text = "";
                lblTotal.Text = "";
                ShoppingCartTitle.InnerText = "Shopping Cart is Empty";
                UpdateBtn.Visible = false;
            }
        }
                                                                                                               
        public List GetShoppingCartItems()
        {
            ShoppingCartActions actions = new ShoppingCartActions();
            return actions.GetCartItems();
        }
                                                                                                               
        public List UpdateCartItems()
        {
            ShoppingCartActions usersShoppingCart = new ShoppingCartActions();
            String cartId = usersShoppingCart.GetCartId();
                                                                                                               
            ShoppingCartActions.ShoppingCartUpdates[] cartUpdates = new ShoppingCartActions.ShoppingCartUpdates[CartList.Rows.Count];
            for (int i = 0; i < CartList.Rows.Count; i++)
            {
                IOrderedDictionary rowValues = new OrderedDictionary();
                rowValues = GetValues(CartList.Rows[i]);
                cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ProductID"]);
                                                                                                               
                CheckBox cbRemove = new CheckBox();
                cbRemove = (CheckBox)CartList.Rows[i].FindControl("Remove");
                cartUpdates[i].RemoveItem = cbRemove.Checked;
                                                                                                               
                TextBox quantityTextBox = new TextBox();
                quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
                cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());
            }
            usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
            CartList.DataBind();
            lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
            return usersShoppingCart.GetCartItems();
        }
                                                                                                               
        public static IOrderedDictionary GetValues(GridViewRow row)
        {
            IOrderedDictionary values = new OrderedDictionary();
            foreach (DataControlFieldCell cell in row.Cells)
            {
                if (cell.Visible)
                {
                    // Extract values from the cell.
                    cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
                }
            }
            return values;
        }
                                                                                                               
        protected void UpdateBtn_Click(object sender, EventArgs e)
        {
            UpdateCartItems();
        }
                                                                                                               
    }
}

再用如下代码替换 ShoppingCartActions.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using petshop.Models;
                                                                                                            
namespace petshop.Logic
{
    public class ShoppingCartActions
    {
        public string ShoppingCartId { get; set; }
                                                                                                            
        private ProductContext _db = new ProductContext();
                                                                                                            
        public const string CartSessionKey = "CartId";
                                                                                                            
        public void AddToCart(int id)
        {
            // Retrieve the product from the database.          
            ShoppingCartId = GetCartId();
                                                                                                            
            var cartItem = _db.ShoppingCartItems.SingleOrDefault(
                c => c.CartId == ShoppingCartId
                && c.ProductId == id);
            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists.                 
                cartItem = new CartItem
                {
                    ItemId = Guid.NewGuid().ToString(),
                    ProductId = id,
                    CartId = ShoppingCartId,
                    Product = _db.Products.SingleOrDefault(
                     p => p.ProductID == id),
                    Quantity = 1,
                    DateCreated = DateTime.Now
                };
                                                                                                            
                _db.ShoppingCartItems.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart,                  
                // then add one to the quantity.                
                cartItem.Quantity++;
            }
            _db.SaveChanges();
        }
                                                                                                            
        public string GetCartId()
        {
            if (HttpContext.Current.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
                {
                    HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class.    
                    Guid tempCartId = Guid.NewGuid();
                    HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return HttpContext.Current.Session[CartSessionKey].ToString();
        }
                                                                                                            
        public List GetCartItems()
        {
            ShoppingCartId = GetCartId();
                                                                                                            
            return _db.ShoppingCartItems.Where(
                c => c.CartId == ShoppingCartId).ToList();
        }
        public decimal GetTotal()
        {
            ShoppingCartId = GetCartId();
            // Multiply product price by quantity of that product to get       
            // the current price for each of those products in the cart. 
            // Sum all product price totals to get the cart total.   
            decimal? total = decimal.Zero;
            total = (decimal?)(from cartItems in _db.ShoppingCartItems
                               where cartItems.CartId == ShoppingCartId
                               select (int?)cartItems.Quantity *
                               cartItems.Product.UnitPrice).Sum();
            return total ?? decimal.Zero;
        }
                                                                                                            
        public ShoppingCartActions GetCart(HttpContext context)
        {
            var cart = new ShoppingCartActions();
            cart.ShoppingCartId = cart.GetCartId();
            return cart;
        }
                                                                                                            
        public void UpdateShoppingCartDatabase(String cartId, ShoppingCartUpdates[] CartItemUpdates)
        {
            using (var db = new petshop.Models.ProductContext())
            {
                try
                {
                    int CartItemCount = CartItemUpdates.Count();
                    List myCart = GetCartItems();
                    foreach (var cartItem in myCart)
                    {
                        // Iterate through all rows within shopping cart list
                        for (int i = 0; i < CartItemCount; i++)
                        {
                            if (cartItem.Product.ProductID == CartItemUpdates[i].ProductId)
                            {
                                if (CartItemUpdates[i].PurchaseQuantity < 1 || CartItemUpdates[i].RemoveItem == true)
                                {
                                    RemoveItem(cartId, cartItem.ProductId);
                                }
                                else
                                {
                                    UpdateItem(cartId, cartItem.ProductId, CartItemUpdates[i].PurchaseQuantity);
                                }
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Update Cart Database - " + exp.Message.ToString(), exp);
                }
            }
        }
                                                                                                            
        public void RemoveItem(string removeCartID, int removeProductID)
        {
            using (var db = new petshop.Models.ProductContext())
            {
                try
                {
                    var myItem = (from c in db.ShoppingCartItems where c.CartId == removeCartID && c.Product.ProductID == removeProductID select c).FirstOrDefault();
                    if (myItem != null)
                    {
                        // db.DeleteObject(myItem);
                        db.ShoppingCartItems.Remove(myItem);
                        db.SaveChanges();
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Remove Cart Item - " + exp.Message.ToString(), exp);
                }
            }
        }
                                                                                                            
        public void UpdateItem(string updateCartID, int updateProductID, int quantity)
        {
            //            using (webformsstorefrontEntities db = new webformsstorefrontEntities())
            using (var db = new petshop.Models.ProductContext())
            {
                try
                {
                    var myItem = (from c in db.ShoppingCartItems where c.CartId == updateCartID && c.Product.ProductID == updateProductID select c).FirstOrDefault();
                    if (myItem != null)
                    {
                        myItem.Quantity = quantity;
                        db.SaveChanges();
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Update Cart Item - " + exp.Message.ToString(), exp);
                }
            }
        }
                                                                                                            
        public void EmptyCart()
        {
            ShoppingCartId = GetCartId();
            var cartItems = _db.ShoppingCartItems.Where(
                c => c.CartId == ShoppingCartId);
            foreach (var cartItem in cartItems)
            {
                _db.ShoppingCartItems.Remove(cartItem);
            }
            // Save changes.            
            _db.SaveChanges();
        }
                                                                                                            
        public int GetCount()
        {
            ShoppingCartId = GetCartId();
                                                                                                            
            // Get the count of each item in the cart and sum them up         
            int? count = (from cartItems in _db.ShoppingCartItems
                          where cartItems.CartId == ShoppingCartId
                          select (int?)cartItems.Quantity).Sum();
            // Return 0 if all entries are null        
            return count ?? 0;
        }
                                                                                                            
        public struct ShoppingCartUpdates
        {
            public int ProductId;
            public int PurchaseQuantity;
            public bool RemoveItem;
        }
                                                                                                            
    }
}

然后把 Site.Master 里的 login 内容替换掉:

  Hello, !

替换 Site.Master.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using petshop.Models;
using petshop.Logic;
                                                                                                  
namespace petshop
{
    public partial class SiteMaster : MasterPage
    {
        private const string AntiXsrfTokenKey = "__AntiXsrfToken";
        private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
        private string _antiXsrfTokenValue;
                                                                                                  
        protected void Page_Init(object sender, EventArgs e)
        {
            // The code below helps to protect against XSRF attacks
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Use the Anti-XSRF token from the cookie
                _antiXsrfTokenValue = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Generate a new Anti-XSRF token and save to the cookie
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;
                                                                                                  
                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }
                                                                                                  
            Page.PreLoad += master_Page_PreLoad;
        }
                                                                                                  
        protected void master_Page_PreLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set Anti-XSRF token
                ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
                ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
            }
            else
            {
                // Validate the Anti-XSRF token
                if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                    || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
                {
                    throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                }
            }
        }
                                                                                                  
        protected void Page_Load(object sender, EventArgs e)
        {
                                                                                                  
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            ShoppingCartActions usersShoppingCart = new ShoppingCartActions();
            string cartStr = string.Format("Cart ({0})", usersShoppingCart.GetCount());
            cartCount.InnerText = cartStr;
        }
        public IQueryable GetCategories()
        {
            var db = new petshop.Models.ProductContext();
            IQueryable query = db.Categories;
            return query;
        }
    }
}

 

在 Models 文件夹中添加,新建项,代码,类,命名为 Order.cs ,用如下代码替换:

using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.ComponentModel;
                                                                                            
namespace petshop.Models
{
    public class Order
    {
        public int OrderId { get; set; }
                                                                                            
        public System.DateTime OrderDate { get; set; }
                                                                                            
        public string Username { get; set; }
                                                                                            
        [Required(ErrorMessage = "First Name is required")]
        [DisplayName("First Name")]
        [StringLength(160)]
        public string FirstName { get; set; }
                                                                                            
        [Required(ErrorMessage = "Last Name is required")]
        [DisplayName("Last Name")]
        [StringLength(160)]
        public string LastName { get; set; }
                                                                                            
        [Required(ErrorMessage = "Address is required")]
        [StringLength(70)]
        public string Address { get; set; }
                                                                                            
        [Required(ErrorMessage = "City is required")]
        [StringLength(40)]
        public string City { get; set; }
                                                                                            
        [Required(ErrorMessage = "State is required")]
        [StringLength(40)]
        public string State { get; set; }
                                                                                            
        [Required(ErrorMessage = "Postal Code is required")]
        [DisplayName("Postal Code")]
        [StringLength(10)]
        public string PostalCode { get; set; }
                                                                                            
        [Required(ErrorMessage = "Country is required")]
        [StringLength(40)]
        public string Country { get; set; }
                                                                                            
        [StringLength(24)]
        public string Phone { get; set; }
                                                                                            
        [Required(ErrorMessage = "Email Address is required")]
        [DisplayName("Email Address")]
        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}",
            ErrorMessage = "Email is is not valid.")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
                                                                                            
        [ScaffoldColumn(false)]
        public decimal Total { get; set; }
                                                                                            
        [ScaffoldColumn(false)]
        public string PaymentTransactionId { get; set; }
                                                                                            
        [ScaffoldColumn(false)]
        public bool HasBeenShipped { get; set; }
                                                                                            
        public List OrderDetails { get; set; }
    }
}

同样的方法新建 OrderDetail.cs ,代码如下:

using System.ComponentModel.DataAnnotations;
                                                                                      
namespace petshop.Models
{
    public class OrderDetail
    {
        public int OrderDetailId { get; set; }
                                                                                      
        public int OrderId { get; set; }
                                                                                      
        public string Username { get; set; }
                                                                                      
        public int ProductId { get; set; }
                                                                                      
        public int Quantity { get; set; }
                                                                                      
        public double? UnitPrice { get; set; }
                                                                                      
    }
}

在 ProductContext.cs 最后加入如下代码:

public DbSet Orders { get; set; }
public DbSet OrderDetails { get; set; }

 

在项目下新建文件夹,名为 Checkout 。

在 Checkout 文件夹中新建项,Web,使用母版的Web窗体,名为 CheckoutStart.aspx。用同样方法添加 CheckoutReview.aspx , CheckoutComplete.aspx , CheckoutCancel.aspx , CheckoutError.aspx 。

然后在 Checkout 文件夹中添加 新建项,Web,Web配置文件,名为 Web.config ,代码如下:



    
      
               
      
    

把 App_Start 文件夹下的 Authconfig.cs 中的最后一句反注释:

OpenAuth.AuthenticationClients.AddGoogle();

 

把 Account 文件夹中的 Login.aspx 中的

使用本地帐户登录。

改为:

使用本地帐户登录。

更改 Login.aspx.cs ,在最后加上:

protected void LoginCtrl_LoggedIn(object sender, EventArgs e)
{
    petshop.Logic.ShoppingCartActions usersShoppingCart = new petshop.Logic.ShoppingCartActions();
    String cartId = usersShoppingCart.GetCartId();
    usersShoppingCart.MigrateCart(cartId, User.Identity.Name.ToString());
}

修改 Account 文件夹下的 Register.aspx.cs :

petshop.Logic.ShoppingCartActions usersShoppingCart = new petshop.Logic.ShoppingCartActions();
            String cartId = usersShoppingCart.GetCartId();
            usersShoppingCart.MigrateCart(cartId, RegisterUser.UserName.ToString());

 

在 ShoppingCartActions.cs 最后加上:

public void MigrateCart(string cartId, string userName)
{
    var shoppingCart = _db.ShoppingCartItems.Where(c => c.CartId == cartId);
    foreach (CartItem item in shoppingCart)
    {
        item.CartId = userName;
    }
    HttpContext.Current.Session[CartSessionKey] = userName;
            _db.SaveChanges();
}

 

把根目录下 Web.config 中的默认连接那句,换成:

 

然后用PayPal支付的那章我就不写啦~~

 

 

 

 

 

 

 

 

 

 

 

 

 

PetShop》上有1条评论

  1. Pingback引用通告: BZ编程小组 作品 | BZ编程小组

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.