PageRenderTime 11ms CodeModel.GetById 1ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/MvcMusicStore/Models/ShoppingCart.cs

#
C# | 200 lines | 140 code | 36 blank | 24 comment | 19 complexity | 55de6e607a285780de41a0e2aad4efd1 MD5 | raw file
  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Web;
  5using System.Web.Mvc;
  6
  7namespace MvcMusicStore.Models
  8{
  9    public partial class ShoppingCart
 10    {
 11        MusicStoreEntities storeDB = new MusicStoreEntities();
 12
 13        string ShoppingCartId { get; set; }
 14
 15        public const string CartSessionKey = "CartId";
 16
 17        public static ShoppingCart GetCart(HttpContextBase context)
 18        {
 19            var cart = new ShoppingCart();
 20            cart.ShoppingCartId = cart.GetCartId(context);
 21            return cart;
 22        }
 23
 24        // Helper method to simplify shopping cart calls
 25        public static ShoppingCart GetCart(Controller controller)
 26        {
 27            return GetCart(controller.HttpContext);
 28        }
 29
 30        public void AddToCart(Album album)
 31        {
 32            // Get the matching cart and album instances
 33            var cartItem = storeDB.Carts.SingleOrDefault(
 34c => c.CartId == ShoppingCartId
 35&& c.AlbumId == album.AlbumId);
 36
 37            if (cartItem == null)
 38            {
 39                // Create a new cart item if no cart item exists
 40                cartItem = new Cart
 41                {
 42                    AlbumId = album.AlbumId,
 43                    CartId = ShoppingCartId,
 44                    Count = 1,
 45                    DateCreated = DateTime.Now
 46                };
 47
 48                storeDB.Carts.Add(cartItem);
 49            }
 50            else
 51            {
 52                // If the item does exist in the cart, then add one to the quantity
 53                cartItem.Count++;
 54            }
 55
 56            // Save changes
 57            storeDB.SaveChanges();
 58        }
 59
 60        public int RemoveFromCart(int id)
 61        {
 62            // Get the cart
 63            var cartItem = storeDB.Carts.Single(
 64cart => cart.CartId == ShoppingCartId
 65&& cart.RecordId == id);
 66
 67            int itemCount = 0;
 68
 69            if (cartItem != null)
 70            {
 71                if (cartItem.Count > 1)
 72                {
 73                    cartItem.Count--;
 74                    itemCount = cartItem.Count;
 75                }
 76                else
 77                {
 78                    storeDB.Carts.Remove(cartItem);
 79                }
 80
 81                // Save changes
 82                storeDB.SaveChanges();
 83            }
 84
 85            return itemCount;
 86        }
 87
 88        public void EmptyCart()
 89        {
 90            var cartItems = storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId);
 91
 92            foreach (var cartItem in cartItems)
 93            {
 94                storeDB.Carts.Remove(cartItem);
 95            }
 96
 97            // Save changes
 98            storeDB.SaveChanges();
 99        }
100
101        public List<Cart> GetCartItems()
102        {
103            return storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();
104        }
105
106        public int GetCount()
107        {
108            // Get the count of each item in the cart and sum them up
109            int? count = (from cartItems in storeDB.Carts
110                          where cartItems.CartId == ShoppingCartId
111                          select (int?)cartItems.Count).Sum();
112
113            // Return 0 if all entries are null
114            return count ?? 0;
115        }
116
117        public decimal GetTotal()
118        {
119            // Multiply album price by count of that album to get 
120            // the current price for each of those albums in the cart
121            // sum all album price totals to get the cart total
122            decimal? total = (from cartItems in storeDB.Carts
123                              where cartItems.CartId == ShoppingCartId
124                              select (int?)cartItems.Count * cartItems.Album.Price).Sum();
125            return total ?? decimal.Zero;
126        }
127
128        public int CreateOrder(Order order)
129        {
130            decimal orderTotal = 0;
131
132            var cartItems = GetCartItems();
133
134            // Iterate over the items in the cart, adding the order details for each
135            foreach (var item in cartItems)
136            {
137                var orderDetail = new OrderDetail
138                {
139                    AlbumId = item.AlbumId,
140                    OrderId = order.OrderId,
141                    UnitPrice = item.Album.Price,
142                    Quantity = item.Count
143                };
144
145                // Set the order total of the shopping cart
146                orderTotal += (item.Count * item.Album.Price);
147
148                storeDB.OrderDetails.Add(orderDetail);
149
150            }
151
152            // Set the order's total to the orderTotal count
153            order.Total = orderTotal;
154
155            // Save the order
156            storeDB.SaveChanges();
157
158            // Empty the shopping cart
159            EmptyCart();
160
161            // Return the OrderId as the confirmation number
162            return order.OrderId;
163        }
164
165        // We're using HttpContextBase to allow access to cookies.
166        public string GetCartId(HttpContextBase context)
167        {
168            if (context.Session[CartSessionKey] == null)
169            {
170                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
171                {
172                    context.Session[CartSessionKey] = context.User.Identity.Name;
173                }
174                else
175                {
176                    // Generate a new random GUID using System.Guid class
177                    Guid tempCartId = Guid.NewGuid();
178
179                    // Send tempCartId back to client as a cookie
180                    context.Session[CartSessionKey] = tempCartId.ToString();
181                }
182            }
183
184            return context.Session[CartSessionKey].ToString();
185        }
186
187        // When a user has logged in, migrate their shopping cart to
188        // be associated with their username
189        public void MigrateCart(string userName)
190        {
191            var shoppingCart = storeDB.Carts.Where(c => c.CartId == ShoppingCartId);
192
193            foreach (Cart item in shoppingCart)
194            {
195                item.CartId = userName;
196            }
197            storeDB.SaveChanges();
198        }
199    }
200}