public void AddProduct(CartProduct cartProduct) { var cartList = new List <CartProduct>(); var stringObject = _session.GetString(CartKey); // Get cart and deserialize the object if (!string.IsNullOrEmpty(stringObject)) // if cart isn't null { cartList = JsonConvert.DeserializeObject <List <CartProduct> >(stringObject); // set cart to what it is currently is } // if cart list has stock, if (cartList.Any(x => x.StockId == cartProduct.StockId)) { cartList.Find(x => x.StockId == cartProduct.StockId).Qty += cartProduct.Qty; // FInd stock item and append Qty } else { // Otherwise add CartProduct to cartList cartList.Add(cartProduct); } // convert the object to string stringObject = JsonConvert.SerializeObject(cartList); _session.SetString("cart", stringObject); }
async Task RemoveItem(CartProduct product) { cartStateProvider.ShoppingCart.Items.Remove(product); // Update the cart - save to localstorage await cartStateProvider.SaveChangesAsync(); }
public static int CreateCart(Int64 AppUserId, Int64 TempAppUserId, Int64 supplierId, decimal totalPrice, Dictionary <Int64, int> LstProduct) { var cart = new Cart { UserId = AppUserId > 0 ? AppUserId : (long?)null, CartTotalPrice = totalPrice, SupplierId = supplierId, CreatedDate = DateTime.Now, TempUserId = TempAppUserId > 0 ? TempAppUserId : (long?)null }; using (ConnectorBase conn = ConnectorBase.NewInstance()) { cart.Save(conn); } foreach (KeyValuePair <Int64, int> item in LstProduct) { CartProduct cartProduct = new CartProduct(); cartProduct.CartId = cart.CartId; cartProduct.ProductAmount = item.Value; cartProduct.ProductId = item.Key; cartProduct.Save(); } return(cart.CartId); }
public JsonResult AddToCartTourPackege(int id, int qty) { var ProductById = db.TourPackeges.Where(m => m.Id == id).FirstOrDefault(); CartProduct cartProduct = new CartProduct(); cartProduct.Id = 0; cartProduct.Name = ProductById.Name; cartProduct.Qty = qty; cartProduct.Image = ProductById.Image; cartProduct.Price = ProductById.Cost; cartProduct.UserInfo = null; cartProduct.UserInfoId = 0; cartProducts.Add(cartProduct); if (cartProducts != null && cartProducts.Count > 0) { status = true; } if (status == true) { return(Json(1)); } return(Json(0)); }
public void AddItemToCart(int Cart_given_id, int Given_ProductId) { var find_cart = (from carts in _context.CartProducts where carts.CartId == Cart_given_id select carts).ToArray(); var search_product = find_cart.FirstOrDefault(existing_cart_product => existing_cart_product.ProductId == Given_ProductId); if (search_product == null) { var cartproduct = new CartProduct { CartId = Cart_given_id, ProductId = Given_ProductId, CartQuantity = 1, CartDateAdded = DateTime.Now }; _context.Add(cartproduct); _context.SaveChanges(); } else { search_product.CartQuantity++; } ProductStock_GoDown(Given_ProductId); _context.SaveChanges(); }
public ActionResult ViewCart() { List <CartProduct> productsInCart = new List <CartProduct>(); using (ShoppingEntities se = new ShoppingEntities()) { var ProductDetails = (from cartTbl in se.carts where cartTbl.userid == CurrentUserID select cartTbl).ToList(); if (ProductDetails == null) { ViewBag.NoProductsFound = "Your Cart Is Empty!"; } else { foreach (var product in ProductDetails) { var ProductInCart = (from prodTbl in se.products where prodTbl.productid == product.productid select prodTbl).First(); CartProduct cp = new CartProduct(); cp.Quantity = (int)product.quantity; cp.Product = ProductInCart; productsInCart.Add(cp); } } ViewBag.ProductList = productsInCart; } return(View()); }
public void AddToCart(string cartId, int productId) { using (var ecomContext = new EcomContext()) { if (ecomContext.ShoppingCarts.FirstOrDefault(p => p.Id == cartId) == null) { return; } var cartProduct = CartItem_GetByKeys(cartId, productId); bool isExist = cartProduct != null; if (isExist == true) { return; } cartProduct = new CartProduct() { Id = Guid.NewGuid().ToString(), CartId = cartId, ProductId = productId, Quantity = 1 }; ecomContext.CartProducts.Add(cartProduct); ecomContext.SaveChanges(); } }
public async Task <IActionResult> Edit(Guid id, [Bind("CartProductID,CartId,ProductID,ProductQuantityOrdered,ProductPrice,AddressId,TotalAmount,LastModifiedDateTime")] CartProduct cartProduct) { if (id != cartProduct.CartProductID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(cartProduct); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CartProductExists(cartProduct.CartProductID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(cartProduct)); }
public async Task <bool> Do(Request request) { if (!_stockManager.EnoughStock(request.StockId, request.Qty)) { return(false); //notEnough stock } await _stockManager.PutStockOnHold(request.StockId, request.Qty, _sessionManager.GetId()); var stock = _stockManager.GetStockProduct(request.StockId); var cartProduct = new CartProduct() { ProductName = stock.Product.Name, ProductId = stock.ProductId, StockId = stock.Id, Qty = request.Qty, TheValue = stock.Product.Value, ImgUrl = stock.Product.ImgUrl }; _sessionManager.AddProduct(cartProduct); return(true); }
public void AddToCart(int id) { ShoppingCartId = GetCartId(); var cartItem = _db.ShoppingCartProducts.SingleOrDefault( c => c.CartId == ShoppingCartId && c.ProductId == id); if (cartItem == null) { cartItem = new CartProduct { ItemId = Guid.NewGuid().ToString(), ProductId = id, CartId = ShoppingCartId, Product = _db.Products.SingleOrDefault( p => p.ProductID == id), Quantity = 1, DateCreated = DateTime.Now }; _db.ShoppingCartProducts.Add(cartItem); } else { cartItem.Quantity++; } _db.SaveChanges(); }
public async Task <CartProduct> AddProductAsync(int productId, string userId) { var cartProduct = await GetCartProductAsync(productId, userId); if (cartProduct != null) { cartProduct.Count++; } else { var user = await _context.Users.FindAsync(userId); var product = await _context.Products.FindAsync(productId); cartProduct = new CartProduct() { User = user, Product = product, Count = 1 }; _context.CartProducts.Add(cartProduct); } await _context.SaveChangesAsync(); return(cartProduct); }
public IActionResult AddCart(CartProduct cartproduct) { try { cartproduct.UserId = GetCookie("UserId"); CartProduct product = _context.CartProduct.Where(c => c.ProductId == cartproduct.ProductId).FirstOrDefault(); if (product != null) { product.Quantity += cartproduct.Quantity; _context.CartProduct.Update(product); } else { _context.CartProduct.Add(cartproduct); } int success = _context.SaveChanges(); if (success == 0) { ViewBag.Message = "Failed to Add Cart"; } else { ViewBag.Message = "Add to Cart"; } }catch (Exception e) { ViewBag.Message = "Login To Add Item"; return(RedirectToAction("Login", "Home")); } return(RedirectToAction("ProductDetails", "Home", new { id = cartproduct.ProductId })); }
public CartDto Add(Guid customerId, CartProductDto productDto) { CartDto cartDto = null; Customer customer = this.customerRepository.FindById(customerId); if (customer == null) { throw new Exception(String.Format("Customer was not found with this Id: {0}", customerId)); } Cart cart = this.cartRepository.FindOne(new CustomerCartSpec(customerId)); if (cart == null) { cart = Cart.Create(customer); this.cartRepository.Add(cart); } Product product = this.productRepository.FindById(productDto.ProductId); this.validateProduct(product.Id, product); //Double Dispatch Pattern cart.Add(CartProduct.Create(customer, cart, product, productDto.Quantity, taxDomainService)); cartDto = Mapper.Map <Cart, CartDto>(cart); this.unitOfWork.Commit(); return(cartDto); }
public int AddProductInCart(int ID) { DataContext db = new DataContext(); if (ID != 0) { CartProduct cartproduct = new CartProduct() { ProductID = ID, }; Product prod = db.Products.Where(x => x.ID == ID).FirstOrDefault(); if (prod.Product_On_Stock > 0) { prod.Product_On_Stock = prod.Product_On_Stock - 1; db.CartProducts.Add(cartproduct); db.SaveChanges(); } return(db.CartProducts.Count()); } else { return(db.CartProducts.Count()); } }
public void AddProductInCart(string productId, string username, int?quntity = null) { var product = this._productService.GetProductById(productId); var user = this._userService.GetUserByUsername(username); if (product == null || user == null) { return; } var cartProduct = GetCartProduct(productId, user.CartId); if (cartProduct != null) { return; } cartProduct = new CartProduct { Product = product, Quantity = quntity == null ? DEFAULT_QUANTITY : quntity.Value, CartId = user.CartId }; this._db.CartProducts.Add(cartProduct); this._db.SaveChanges(); }
public ActionResult Cart() { List <CartProduct> cpList = new List <CartProduct>(); if (Session["cart"] != null) { var prodList = (List <saleproduct>)Session["cart"]; var groupedProds = prodList.GroupBy(info => info.ID).Select(g => new { ID = g.Key, Count = g.Count() }); foreach (var line in groupedProds) { CartProduct cp = new CartProduct(); var prodduct = prodList.Where(x => x.ID == line.ID).FirstOrDefault(); cp.productID = prodduct.ID; cp.name = prodduct.Name; cp.imagePath = prodduct.ImagePath; cp.price = (double)prodduct.Price; cp.quantity = line.Count; cpList.Add(cp); } } return(View(cpList)); }
public void Delete(CartProduct cartProduct) { OnlineStoreContexts db = new OnlineStoreContexts(); db.CartProducts.Remove(cartProduct); db.SaveChanges(); }
public IEnumerable <CartProduct> MyOrders(string id) { System.Console.WriteLine("0000000000000000000000 id cart " + id); Cart cart = _context.Carts.Single(a => a.IdUser == id); System.Console.WriteLine("1111111111111111111111 id cart" + cart.IdCart); if (cart == null) { return(null); } System.Console.WriteLine("22222222222222222222"); var Orders = _context.CartProducts.Where(a => a.idCart == cart.IdCart); var Orders1 = Orders.ToList(); var Orders2 = new List <CartProduct>(); for (var i = 0; i < Orders1.Count(); i++) { var cc = new CartProduct() { IdOrder = Orders1[i].IdOrder, idCart = Orders1[i].idCart, idProduct = Orders1[i].idProduct, Quantity = Orders1[i].Quantity, OrederDate = Orders1[i].OrederDate, Product = _context.Products.Single(a => a.idProduit == Orders1[i].idProduct) }; Orders2.Add(cc); } System.Console.WriteLine("666666666666666666666 orders"); return(Orders2); }
public void Create(CartProduct productCart) { OnlineStoreContexts db = new OnlineStoreContexts(); db.CartProducts.Add(productCart); db.SaveChanges(); }
public void Update(CartProduct cartProduct) { OnlineStoreContexts db = new OnlineStoreContexts(); db.Entry(cartProduct).State = EntityState.Modified; db.SaveChanges(); }
protected NewCartItem BuildNewCartItem(string productId, int quantity, decimal productPrice) { var catalogProductId = _fixture.Create <string>(); var catalogProduct = new CatalogProduct { Id = catalogProductId }; var cartProduct = new CartProduct(catalogProduct); cartProduct.ApplyPrices(new List <Price>() { new Price { ProductId = catalogProductId, PricelistId = _fixture.Create <string>(), List = _fixture.Create <decimal>(), MinQuantity = _fixture.Create <int>(), } }, GetCurrency()); var newCartItem = new NewCartItem(productId, quantity) { Price = productPrice, CartProduct = cartProduct }; return(newCartItem); }
public ActionResult Details(int id) { Product p = ctx.Products.Find(id); Cart c = ctx.Carts.Where(crt => crt.SessionId == HttpContext.Session.SessionID).FirstOrDefault(); ProductViewModel pvm = new ProductViewModel(); pvm.Product = p; CartItemRequest cir = new CartItemRequest(); cir.CartId = c.Id; cir.ProductId = p.ProductId; cir.Count = 0; CartProduct cp = c.CartItems.Where(ci => ci.ProductId == p.ProductId).FirstOrDefault(); if (cp != null) { cir.Count = cp.Count; } pvm.ItemRequest = cir; return(View(pvm)); }
// GET: ShowProduct public ViewResult Add(int id) { Product product = productRepository.Find(id); if (product == null) { return(View("Index")); } List <CartProduct> products = (List <CartProduct>)Session["cart"]; if (products == null) { products = new List <CartProduct>(); } CartProduct carProduct = new CartProduct(product); carProduct.Quan = 1; products.Add(carProduct); decimal total = 0; foreach (CartProduct cp in products) { decimal t = (decimal)cp.prouduct.UnitPrice * cp.Quan; total += t; } ViewBag.Total = total; ViewBag.Gst = total * 15 / 100; Session["cart"] = products; return(View("Index", products)); }
public ActionResult AddToBasket(AddToBasketButtonAddToBasketViewModel viewModel) { var cartServiceProvider = new CartServiceProvider(); var contactFactory = new ContactFactory(); string userId = contactFactory.GetContact(); var createCartRequest = new CreateOrResumeCartRequest(Context.GetSiteName(), userId); var cart = cartServiceProvider.CreateOrResumeCart(createCartRequest).Cart; var cartProduct = new CartProduct { ProductId = viewModel.ProductSku, Price = new Price(Convert.ToDecimal(viewModel.Price), cart.CurrencyCode) }; cartProduct.Properties.Add("VariantSku", viewModel.VariantSku); var cartLines = new ReadOnlyCollection <CartLine>( new Collection <CartLine> { new CartLine { Product = cartProduct, Quantity = (uint)viewModel.Quantity } } ); var request = new AddCartLinesRequest(cart, cartLines); cartServiceProvider.AddCartLines(request); return(Json(_miniBasketService.Refresh(), JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult <CartProduct> > PostCartProduct(CartProduct cartProduct) { _context.CartProducts.Add(cartProduct); await _context.SaveChangesAsync(); return(CreatedAtAction("GetCartProduct", new { id = cartProduct.Id }, cartProduct)); }
async Task AddToBasket(MouseEventArgs e) { var item = new CartProduct { Product = prod, Quantity = Convert.ToInt32(1) }; var items = CartStateProvider.ShoppingCart.Items; var itemInCart = items.FindIndex(x => x.Product.Equals(item.Product)); Console.WriteLine("Is the item already in the cart?" + itemInCart.ToString()); if (itemInCart >= 0) { CartStateProvider.ShoppingCart.Items[itemInCart].Quantity++; } else { CartStateProvider.ShoppingCart.Items.Add(item); } Console.WriteLine(CartStateProvider.ToString()); await CartStateProvider.SaveChangesAsync(); }
public async Task <IActionResult> PutCartProduct(int id, CartProduct cartProduct) { if (id != cartProduct.Id) { return(BadRequest()); } _context.Entry(cartProduct).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CartProductExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public void ShouldClearShoppingCartTemporaryProducts() { // Arrange var cartProduct = new CartProduct(); var shoppingCart = new ShoppingCart() { TemporaryProducts = new List <CartProduct> { cartProduct, cartProduct } }; var mockedUnitOfWork = new Mock <IUnitOfWork>(); var mockedCartProductFactory = new Mock <ICartProductFactory>(); var mockedCartProductRepository = new Mock <IGenericRepository <CartProduct> >(); var mockedShoppingCartRepository = new Mock <IGenericRepository <ShoppingCart> >(); var shoppingCartsService = new ShoppingCartsService(mockedUnitOfWork.Object, mockedCartProductFactory.Object, mockedShoppingCartRepository.Object, mockedCartProductRepository.Object); // Act shoppingCartsService.Clear(shoppingCart); // Assert Assert.AreEqual(0, shoppingCart.TemporaryProducts.Count); }
/// <summary> /// Updates CartProduct based on CartID. /// </summary> /// <param name="updateCartProduct">Represents CartProduct details like CartID.</param> /// <returns>Determinates whether the existing CartProduct is updated.</returns> public override bool UpdateCartProductDAL(CartProduct updateCartProduct) { bool cartProductUpdated = false; try { //Find SystemUser based on SystemUserID CartProduct matchingCartProduct = GetCartProductByCartIDDAL(updateCartProduct.CartId); if (matchingCartProduct != null) { //Update systemUser details ReflectionHelpers.CopyProperties(updateCartProduct, matchingCartProduct, new List <string>() { "ProductId", "ProductQuantityOrdered", "AddressId", "TotalAmount" }); matchingCartProduct.LastModifiedDateTime = DateTime.Now; cartProductUpdated = true; } } catch (System.Exception) { throw; } return(cartProductUpdated); }
public async Task <bool> Do(Request request) { //service responsibility if (!_stockManager.EnoughStock(request.StockId, request.Quantity)) { return(false); } await _stockManager .PutSockOnHold(request.StockId, request.Quantity, _sessionManager.GetId()); var stock = _stockManager.GetStockWithProduct(request.StockId); var cartProduct = new CartProduct() { ProductId = stock.Product.Id, ProductName = stock.Product.Name, StockId = stock.Id, Quantity = request.Quantity, Price = stock.Product.Price, PhotoUrl = stock.Product.PhotoUrl }; _sessionManager.AddProduct(cartProduct); return(true); }
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e) { var commandName = e.CommandName; //If no command Name found if (string.IsNullOrEmpty(commandName)) return; switch (commandName.ToLower()) { //Add to Cart case "add": //Check if is a button if (!(e.CommandSource is Button)) return; var button = e.CommandSource as Button; //Check if is DataControlFieldCell if (!(button.Parent is DataControlFieldCell)) return; var cell = button.Parent as DataControlFieldCell; //Declare variables; string title = string.Empty; string image = string.Empty; decimal price = 0; //Get Id from GridViewRow object control = cell.FindControl("hf_Id"); //If id not found, no point adding to the cart if (!(control is HiddenField)) return; object objId = TextHelper.ToInteger(((HiddenField)control).Value); //If id not found, no point adding to cart if (objId == null) return; //Set id var id = (int)objId; var isExist = false; //Check if current item exist in the array foreach (var item in ShoppingCart.Where(item => item.ProductId == id)) { //If item exist, add quantity item.Quantity += 1; isExist = true; break; } //If item does not exist, add to cart as new if (!isExist) { //Get Title control = cell.FindControl("lbl_title"); if (control is Label) { title = ((Label)control).Text; } //Get Price control = cell.FindControl("lbl_price"); if (control is Label) { object objPrice = TextHelper.ToDecimal(((Label)control).Text); if (objPrice != null) price = (decimal)objPrice; } //Get Image control = cell.FindControl("img_product"); if(control is Image) { image = ((Image)control).ImageUrl; } var product = new CartProduct { ProductId = id, Title = title, Price = price, Image = image, Quantity = 1 }; ShoppingCart.Add(product); } SetShoppingCart(); break; } }