public void AddToCart(Product product)
        {
            var cartItem = db.CartItems.SingleOrDefault(c => c.CartId == ShoppingCartId &&
                                                        c.ProductId == product.ProductId);

            if (cartItem == null)
            {
                //create new cart item
                cartItem = new CartItem
                {
                    CartItemId = db.CartItems.Count() + 1,
                    CartId     = ShoppingCartId,
                    ProductId  = product.ProductId,
                    //Product = product,
                    Count       = 1,
                    DateCreated = DateTime.Now,
                };
                db.CartItems.Add(cartItem);
                db.SaveChanges();
            }
            else
            {
                //item exists in cart, so add one to quantity
                cartItem.Count++;
            }
        }
Exemplo n.º 2
0
        public IHttpActionResult PutCategory(int id, Category category)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != category.CategoryID)
            {
                return(BadRequest());
            }

            db.Entry(category).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 3
0
        public Cart RemoveFromCart(int id)
        {
            using (var context = new ShoppingCartContext())
            {
                // Get the cart
                var cartItem = context.Carts.Single(
                    cart => cart.Code == ShoppingCartId &&
                    cart.Id == id);

                if (cartItem != null)
                {
                    if (cartItem.Quantity > 1)
                    {
                        cartItem.Quantity--;
                        // Save changes
                        context.SaveChanges();
                        UpdateCart();
                    }
                    else
                    {
                        context.Carts.Remove(cartItem);
                        // Save changes
                        context.SaveChanges();
                        UpdateCart();
                        return(null);
                    }
                }
                return(context.Carts.Single(c => c.Code == ShoppingCartId && c.Id == id));
            }
        }
Exemplo n.º 4
0
        public IHttpActionResult PutProduct(int id, Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != product.ProductID)
            {
                return(BadRequest());
            }

            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public ActionResult Create(int cartId, Item item)
        {
            item.Id = 0; // Simple fix to avoid problems with users trying to set it themselfs. Should use DTOs instead
            var cart = _context.Carts.Include(c => c.Items).SingleOrDefault(c => c.Id == cartId);

            if (cart == null)
            {
                return(BadRequest(new { error = "Cart not found" }));
            }

            if (cart.Items.Any(i => i.Id == item.Id))
            {
                return(BadRequest(new { error = "Item with that id exsists in cart" }));
            }

            cart.Items.Add(item);

            _context.SaveChanges();

            _context.ItemEvents.Add(new ItemEvent()
            {
                CartId    = cartId,
                ItemId    = item.Id,
                EventType = "Added"
            });

            _context.SaveChanges();

            return(Ok(cart));
        }
Exemplo n.º 6
0
 public void Create(ShoppingCart cart)
 {
     if (cart != null)
     {
         _context.ShoppingCarts.Add(cart);
         _context.SaveChanges();
     }
 }
        public void CreateNewCategory(string categoryTitle)
        {
            Category newCategory = new Category
            {
                CategoryId = db.Categories.Count() + 1,
                Title      = categoryTitle,
            };

            db.Categories.Add(newCategory);
            db.SaveChanges();
        }
Exemplo n.º 8
0
        public CommodityItem AddToShoppingCart(CommodityItem item)
        {
            CommodityItem existingItem = GetByShoppingCartIdAndBookId(item.ShoppingCartId, item.BookId);

            if (existingItem == null)
            {
                _db.Entry(item).State = EntityState.Added;
                existingItem          = item;
            }
            else
            {
                existingItem.Quantity += item.Quantity;
            }
            _db.SaveChanges();
            return(existingItem);
        }
Exemplo n.º 9
0
        //public Cart GetCartLine(string cartId, int id)
        //{
        //    using (var context = new ShoppingCartContext())
        //    {
        //        return context.Carts.Single(c => c.Code == cartId && c.Id == id);
        //    }
        //}

        public Cart AddOneItemToCart(int id)
        {
            using (var context = new ShoppingCartContext())
            {
                // Get the matching cart and product instances
                // Get the cart
                var cartItem = context.Carts.Single(
                    cart => cart.Code == ShoppingCartId &&
                    cart.Id == id);

                if (cartItem != null)
                {
                    //Add 1 more item
                    cartItem.Quantity++;
                    // Save changes
                    context.SaveChanges();

                    UpdateCart();
                }
                var ret = context.Carts.Single(
                    cart => cart.Code == ShoppingCartId &&
                    cart.Id == id);
                return(ret);
            }
        }
Exemplo n.º 10
0
        public async Task RemoveFromCart_WhenCartItemIdIsPassed_ShouldSucceed()
        {
            //arrange
            var options = new DbContextOptionsBuilder <ShoppingCartContext>()
                          .UseInMemoryDatabase(databaseName: "RemoveFromCart_WhenCartItemIdIsPassed_ShouldSucceed")
                          .Options;

            //act
            using (var context = new ShoppingCartContext(options))
            {
                var logger = new Mock <ILogger <CartItemRepository> >();
                var cir    = new CartItemRepository(new ShoppingCartContext(options), logger.Object);
                await cir.AddToCart(new CartItem { CustomerId = 1, Quantity = 5, DateCreated = DateTime.Now, ArticleId = 1 });

                await cir.AddToCart(new CartItem { CustomerId = 1, Quantity = 15, DateCreated = DateTime.Now, ArticleId = 1 });

                context.SaveChanges();
                await cir.RemoveFromCart(1);
            }

            //assert
            using (var context = new ShoppingCartContext(options))
            {
                context.CartItem.Should().HaveCount(2);
            }
        }
Exemplo n.º 11
0
        public CartItem Add2Cart(CartItem cartItem)
        {
            var existingCartItem = GetByCartIdAndBookId(cartItem.CartId, cartItem.BookId);

            if (existingCartItem == null)
            {
                _db.Entry(cartItem).State = EntityState.Added;
                existingCartItem          = cartItem;
            }
            else
            {
                existingCartItem.Quantity += cartItem.Quantity;
            }
            _db.SaveChanges();
            return(existingCartItem);
        }
Exemplo n.º 12
0
        public void CreateNewProduct(Product product)
        {
            var newProduct = new Product()
            {
                Name           = product.Name,
                Description    = product.Description,
                Quantity       = product.Quantity,
                Price          = product.Price,
                Cost           = product.Cost,
                PurchaseDate   = product.PurchaseDate,
                CategoryId     = product.CategoryId,
                StoreManagerId = product.StoreManagerId,
            };

            db.Products.Add(newProduct);
            db.SaveChanges();
        }
Exemplo n.º 13
0
        public IActionResult UpdatePassword(string email, string oldpassword, string newpassword)
        {
            string   username = HttpContext.Session.GetString("username");
            var      key      = "E546C8DF278CD5931069B522E695D4F2";
            Customer customer = dbcontext.Customers.Where(x => x.EmailAddress == email && x.Password == Utils.Crypto.Encrypt(oldpassword, key)).FirstOrDefault();

            //   var oldpasswordfromdb = Utils.Crypto.Decrypt(customer.Password,key);

            if (customer != null)
            {
                customer.Password = Utils.Crypto.Encrypt(newpassword, key);
                dbcontext.Update(customer);
                dbcontext.SaveChanges();
                Response.Cookies.Delete(".AspNetCore.Session");
                return(new JsonResult(new { success = "Success" }));
            }
            return(new JsonResult(new { success = "Fail" }));
        }
Exemplo n.º 14
0
        public ActionResult AddressAndPayment(FormCollection values)
        {
            var order = new Order();

            TryUpdateModel(order);

            order.Username = User.Identity.Name;

            // Save Order
            storeDB.Orders.Add(order);
            storeDB.SaveChanges();
            // Process the order
            var cart = ShopCart.GetCart(this.HttpContext);

            cart.CreateOrder(order);
            storeDB.SaveChanges();

            return(RedirectToAction("Complete", new { id = order.OrderID }));
        }
Exemplo n.º 15
0
 public static long Next(string seq)
 {
     using (var context = new ShoppingCartContext())
     {
         var next = context.Sequences.SingleOrDefault(s => s.Code == seq);
         next.CurrentValue++;
         context.SaveChanges();
         return(next.CurrentValue);
     }
 }
Exemplo n.º 16
0
        public IActionResult ReduceItem(string productID)
        {
            string  sessionId  = Request.Cookies["sessionId"];
            Session session    = dbcontext.Sessions.Find(sessionId);
            Product product    = dbcontext.Products.Find(productID);
            Cart    cart_check = dbcontext.Carts.Where(x => x.ProductID == productID && x.SessionID == session.SessionID).FirstOrDefault();

            if (cart_check.CartQuantity > 1)
            {
                cart_check.CartQuantity = (int)cart_check.CartQuantity - 1;
                dbcontext.Update(cart_check);
                dbcontext.SaveChanges();
            }
            else
            {
                dbcontext.Remove(cart_check);
                dbcontext.SaveChanges();
            }
            return(new JsonResult(new { success = "Success" }));
        }
Exemplo n.º 17
0
        private Cart CreateCart(string sessionId)
        {
            var cart = new Cart()
            {
                SessionId = sessionId,
                CartItems = new List<CartItem>(),
            };

            _db.Carts.Add(cart);
            _db.SaveChanges();
            return cart;
        }
Exemplo n.º 18
0
        // PUT api/Todo/5
        public HttpResponseMessage PutTodo(int id, Todo todo)
        {
            if (ModelState.IsValid && id == todo.Id)
            {
                db.Entry(todo).State = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
        public void addImageDBRecord(string imagePath, string imageName, bool imageThumbnail, int productId)
        {
            var imageUploader = new ImageUploadLogic();
            var newImage      = new Image
            {
                ImageID          = db.Images.Count() + 1,
                ImageTitle       = imageName,
                ImagePath        = imagePath,
                IsImageThumbnail = imageThumbnail,
                ProductId        = productId,
            };

            db.Images.Add(newImage);
            db.SaveChanges();

            if (imageThumbnail)
            {
                var product = db.Products.Find(productId);
                product.ThumbnailImagePath = imagePath;
                db.SaveChanges();
            }
        }
Exemplo n.º 20
0
        public IActionResult AddToCart(string productID)
        {
            string browseSessionId = Request.Cookies["sessionId"];
            string loginSessionId  = HttpContext.Session.GetString("SessionId");
            string isUserLogin     = HttpContext.Session.GetString("username");

            Session browsesession = dbcontext.Sessions.Find(browseSessionId);
            Session loginsession  = dbcontext.Sessions.Find(loginSessionId);
            Product product       = dbcontext.Products.Find(productID);

            Cart cart_check = new Cart();

            cart_check = dbcontext.Carts.Where(x => x.ProductID == productID && x.SessionID == browsesession.SessionID).FirstOrDefault();

            if (cart_check != null)
            {
                cart_check.CartQuantity = (int)cart_check.CartQuantity + 1;
                dbcontext.Update(cart_check);
                dbcontext.SaveChanges();
            }
            else
            {
                Cart cart = new Cart()
                {
                    ProductID = product.ProductID,
                };
                if (isUserLogin != null)
                {
                    cart.CustomerID = isUserLogin;
                }
                cart.SessionID    = browseSessionId;
                cart.CartQuantity = 1;
                dbcontext.Add(cart);
                dbcontext.SaveChanges();
            }

            return(Content("This is a GET result, your productId is " + productID));
        }
Exemplo n.º 21
0
 public void Save(Product Product)
 {
     try
     {
         using (_context = new ShoppingCartContext())
         {
             _context.Product.Add(Product);
             _context.SaveChanges();
         }
     }
     catch (Exception ex)
     {
     }
 }
Exemplo n.º 22
0
 private Cart CreateCartIfItDoesntExist(string sessionId, Cart cart)
 {
     if (cart == null)
     {
         cart = new Cart
         {
             SessionId = sessionId,
             CartItems = new List <CartItem>()
         };
         _shoppingCartContext.Carts.Add(cart);
         _shoppingCartContext.SaveChanges();
     }
     return(cart);
 }
Exemplo n.º 23
0
        public void AddToCart(Product product)
        {
            using (var context = new ShoppingCartContext())
            {
                // Get the matching cart and product instances
                var cartItem = context.Carts.SingleOrDefault(
                    c => c.Code == ShoppingCartId &&
                    c.ProductId == product.Id);

                if (cartItem == null)
                {
                    // Create a new cart item if no cart item exists
                    cartItem = new Cart
                    {
                        ProductId   = product.Id,
                        Code        = ShoppingCartId,
                        Quantity    = 1,
                        DateCreated = DateTime.Now,
                        PriceType   = "R",
                        Categories  = new List <string>()
                        {
                            "1001", "1002"
                        },
                        AddOnItem      = false,
                        ShippingCost   = 0m,
                        DiscountAmount = 0m,
                        OriginalPrice  = context.Products.Where(p => p.Id == product.Id).SelectMany(x => x.ProductOffers).ToList().Single(o => o.ProductId == product.Id && o.PriceTypeId == 1).Price,
                        //OriginalPrice = context.Products.Single(p => p.Id == product.Id).Price,
                        Product = context.Products.Single(p => p.Id == product.Id),
                        //DiscountedPrice = 0m,
                        DiscountApplied = false,
                        ProductWeight   = product.Weight
                    };
                    context.Carts.Add(cartItem);
                }
                else
                {
                    // If the item does exist in the cart,
                    // then add one to the quantity
                    cartItem.Quantity++;
                }
                // Save changes
                context.SaveChanges();


                //update the cart (promotion)
                UpdateCart();
            }
        }
Exemplo n.º 24
0
        private Cart CreateCartIfItDoesntExist(string sessionId, Cart cart)
        {
            if (null == cart)
            {
                cart = new Cart
                {
                    SessionId = sessionId,
                    CartItems = new List <CartItem>()
                };
                _db.Carts.Add(cart);
                _db.SaveChanges();
            }

            return(cart);
        }
Exemplo n.º 25
0
 /// <summary>
 /// 根据sessionId创建Cart对象,并返回
 /// </summary>
 /// <param name="sessionId"></param>
 /// <param name="cart"></param>
 /// <returns></returns>
 public Cart CreateCartIfItDoesntExist(string sessionId, Cart cart)
 {
     //此时cart不使用ref与out的原因
     if (null == cart)
     {
         //注意此处创建的购物车中保存了SessionId(可使用memcache单独保存缓存)
         cart = new Cart
         {
             SessionId = sessionId,
             CartItems = new List <CartItem>()
         };
         _db.Carts.Add(cart);
         _db.SaveChanges();
     }
     return(cart);
 }
Exemplo n.º 26
0
        public ShoppingCart GetBySessionId(string sessionId)
        {
            ShoppingCart shoppingCart = _db.ShoppingCarts.Include("CommodityItems").Where(c => c.SessionId == sessionId).SingleOrDefault();

            if (shoppingCart == null)
            {
                shoppingCart = new ShoppingCart
                {
                    SessionId      = sessionId,
                    CommodityItems = new List <CommodityItem>()
                };
                _db.ShoppingCarts.Add(shoppingCart);
                _db.SaveChanges();
            }
            return(shoppingCart);
        }
Exemplo n.º 27
0
        public void EmptyCart()
        {
            using (var context = new ShoppingCartContext())
            {
                var cartItems = context.Carts.Where(
                    cart => cart.Code == ShoppingCartId);

                foreach (var cartItem in cartItems)
                {
                    context.Carts.Remove(cartItem);
                }
                // Save changes
                context.SaveChanges();

                UpdateCart();
            }
        }
Exemplo n.º 28
0
 public void Save(Cart Cart)
 {
     try
     {
         using (_context = new ShoppingCartContext())
         {
             _context.Cart.Add(Cart);
             if (Cart.ID > 0)
             {
                 _context.Entry(Cart).State = EntityState.Modified;
             }
             _context.SaveChanges();
         }
     }
     catch (Exception ex)
     {
     }
 }
Exemplo n.º 29
0
        public void UpdateCart()
        {
            using (var context = new ShoppingCartContext())
            {
                var shippingRateObj = context.AppSettings.Single(a => a.Code == "ShippingRate");
                var shippingRate    = 0m;
                if (shippingRateObj.ValueType == "decimal")
                {
                    shippingRate = Convert.ToDecimal(shippingRateObj.Value);
                }

                var cartItems = context.Carts.Where(cart => cart.Code == ShoppingCartId).ToList();

                foreach (var c in cartItems)
                {
                    c.Categories = context.Products.Where(p => p.Id == c.ProductId).SelectMany(x => x.Categories).Select(y => y.Code).ToList();
                }

                var newCarts = CartProcessor.Process(context.Promotions.Single(p => p.Code == "Christmas discount").PromotionLineItems.ToList(), cartItems);

                foreach (var cart in context.Carts)
                {
                    foreach (var nCart in newCarts)
                    {
                        if (cart.Code == nCart.Code && cart.ProductId == nCart.ProductId)
                        {
                            cart.Quantity       = nCart.Quantity;
                            cart.DiscountAmount = nCart.DiscountAmount;
                            cart.ShippingCost   = nCart.ProductWeight * nCart.Quantity * shippingRate; //fixed rate shipping
                            cart.DiscountAmount = nCart.DiscountAmount;
                            cart.OriginalPrice  = nCart.OriginalPrice;
                            cart.AddOnItem      = nCart.AddOnItem;
                            //cart.DiscountedPrice = nCart.DiscountedPrice;
                            cart.NetBeforeDiscount = nCart.NetBeforeDiscount;
                            cart.Sum = nCart.Sum + (nCart.ProductWeight * nCart.Quantity * shippingRate);
                            cart.TotalDiscountAmount = nCart.TotalDiscountAmount;

                            //context.Entry(cart).State = EntityState.Modified;
                        }
                    }
                }
                context.SaveChanges();
            }
        }
Exemplo n.º 30
0
        public ActionResult Create(Cart cart)
        {
            if (cart.UserId == 0)
            {
                return(BadRequest(new { error = "user required" }));
            }

            if (_context.Carts.Any(c => c.UserId == cart.UserId))
            {
                return(BadRequest(new { error = "User already have cart" }));
            }

            cart.Id = 0; // Workaround of no DTOs

            _context.Carts.Add(cart);
            _context.SaveChanges();

            return(Created($"/{cart.Id}", cart));
        }