public async Task<IHttpActionResult> PutCart(int id, Cart cart) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != cart.Id) { return BadRequest(); } db.Entry(cart).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CartExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public void AddToCart(Album album) { // Get the matching cart and album instances var cartItem = storeDB.Carts.SingleOrDefault( c => c.CartId == ShoppingCartId && c.AlbumId == album.AlbumId); if (cartItem == null) { // Create a new cart item if no cart item exists cartItem = new Cart { AlbumId = album.AlbumId, CartId = ShoppingCartId, Count = 1, DateCreated = DateTime.Now }; storeDB.Carts.Add(cartItem); } else { // If the item does exist in the cart, then add one to the quantity cartItem.Count++; } // Save changes storeDB.SaveChanges(); }
public Cart ReleaseCart(decimal receivedTax) { if (receivedTax < CartTax) { throw new ApplicationException("Call the police!"); } else { this.collectedTax += receivedTax; } Cart currentCart; if (this.freeCarts.Count == 0) { currentCart = new Cart(); } else { int lastCart = this.freeCarts.Count - 1; currentCart = this.freeCarts[lastCart]; this.freeCarts.RemoveAt(lastCart); } return currentCart; }
protected void Page_Load(object sender, EventArgs e) { Response.Clear(); Response.ContentType = "text/plain"; Response.Write(" "); try { this.CurrentCart = Cart.GetCartFromSession(Session);//Duncan Here it gets the Cart related to the User Session. if (this.CurrentCart.Dirty) this.CurrentCart.Clean(); if (Request.RequestType == "GET" && Request.QueryString.HasKeys()) { ProcessGet(); } else if (Request.RequestType == "POST" && Request.Form.HasKeys()) { ProcessPost(); } } catch (CartException ex) { Response.Write(this.BuildResponse(AddResponse.Failure)); } }
/// <summary> /// "放入购物车"按钮单击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ButtonAdd2Cart_Click(object sender, System.EventArgs e) { if (Session["user_id"] == null) Page.Response.Redirect("Login.aspx?in=1"); Cart cart = new Cart(); Hashtable ht = new Hashtable(); ArrayList selectedBooks = this.GetSelected(); //如果用户没有选择,就单击该按钮,则给出警告 if (selectedBooks.Count == 0) { Response.Write("<Script Language=JavaScript>alert('请选择图书!');</Script>"); return; } //循环将选择的图书加入到购物篮中 foreach (int bookId in selectedBooks) { ht.Clear(); ht.Add("UserId", Session["user_id"].ToString()); ht.Add("BookId", bookId); ht.Add("Amount", TextBoxAmount.Text.Trim()); cart.Add(ht); } Response.Redirect("CartView.aspx"); }
// Create a new checkout with the selected product. For convenience in the sample app we will hardcode the user's shipping address. // The shipping rates fetched in ShippingRateListActivity will be for this address. public void CreateCheckout(Product product, Action<Checkout, Response> success, Action<RetrofitError> failure) { var cart = new Cart(); cart.AddVariant(product.Variants[0]); Checkout = new Checkout(cart); Checkout.ShippingAddress = new Address { FirstName = "Dinosaur", LastName = "Banana", Address1 = "421 8th Ave", City = "New York", Province = "NY", Zip = "10001", CountryCode = "US" }; Checkout.Email = "*****@*****.**"; Checkout.SetWebReturnToUrl(GetString(Resource.String.web_return_to_url)); Checkout.SetWebReturnToLabel(GetString(Resource.String.web_return_to_label)); BuyClient.CreateCheckout(Checkout, (data, response) => { Checkout = data; success(data, response); }, failure); }
public void AddBattery(Battery battery, List<Cart> list) { var cart = new Cart { GoodsId = battery.Id, GoodsCategory = "Batteries", Price = battery.Price, Count = 1 }; var flg = 1; foreach (Cart item in list) { if (item.GoodsId == battery.Id && item.GoodsCategory == "Batteries") { item.Count++; flg = 0; break; } } if (flg == 1) { list.Add(cart); } }
protected void btnAdd_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(Request.QueryString["id"])) { string clientId = Context.User.Identity.GetUserId(); if (clientId != null) { int id = Convert.ToInt32(Request.QueryString["id"]); int amount = Convert.ToInt32(ddlAmount.SelectedValue); Cart cart = new Cart { Amount = amount, ClientID = clientId, DatePurchased = DateTime.Now, IsInCart = true, ProductID = id }; CartModel model = new CartModel(); lblResult.Text = model.InsertCart(cart); } else { lblResult.Text = "Please log in to order items"; } } }
public ViewResult Index(Cart cart, string returnUrl) { CartIndexViewModel model = new CartIndexViewModel(); model.Cart = cart; model.ReturnUrl = returnUrl; return View(model); }
public void GetProductRepositoryTestIsCalled() { //Arrange MainWindow windowTest = new MainWindow(); var MockNotificationSvc = new Mock<INotificationService>(); var MockPaymentProcessor = new Mock<IPaymentProcessor>(); var MockProductRepo = new Mock<IProductRepository>(); OrderItemRepository orderRepo = new OrderItemRepository(); Cart ActiveCart = new Cart(orderRepo); List<Product> catalogProducts = new List<Product>() { new Product(){Name = "cable", OnHand = 5}, new Product(){Name = "charger", OnHand = 4}, new Product() {Name = "battery", OnHand = 3} }; MockProductRepo.Setup(x => x.GetProducts()).Returns(catalogProducts); //Act windowTest.ListProductsInCatalog(MockProductRepo.Object); Assert.AreEqual(true, windowTest.lstSelection.Items.Contains("cable")); MockProductRepo.Verify(x => x.GetProducts()); }
private void UpdateSession() { if (HttpContext.Session["Cart"] == null) HttpContext.Session["Cart"] = cart; else cart = HttpContext.Session["Cart"] as Cart<Product>; }
void initCartData() { var cart = new Cart() { CreateTime = DateTime.Now, Id = 1, }; SaleItem saleItem = new SaleItem() { Cart = cart, CartId = 1, Id = 1, ProductId = 1, Quantity = 10 }; SaleItem saleItem2 = new SaleItem() { Cart = cart, CartId = 1, Id = 2, ProductId = 2, Quantity = 10 }; cart.SaleItems.Add(saleItem); cart.SaleItems.Add(saleItem2); fakeShoppingCartDbContext.Carts.Add(cart); fakeShoppingCartDbContext.SaleItems.Add(saleItem); fakeShoppingCartDbContext.SaleItems.Add(saleItem2); }
public RedirectToRouteResult AddToCart(int Id, int quantity) { cart = getCart(); Product p = db.Products.Where(x => x.Id == Id).SingleOrDefault(); cart.AddItem(p, quantity); return RedirectToAction("Index", "Shop"); }
protected void Page_Load(object sender, EventArgs e) { try { if (Session["MYCART"] == null) { Session["MYCART"] = myCart; } else { myCart = (Cart)(Session["MYCART"]); } string PID = Request["PID"]; string sql = "SELECT * FROM Products WHERE ProductId=" + PID; ds = DBFunctions.GetDataSetDB(sql); lblProdDesc.Text = ds.Tables[0].Rows[0]["ProductSDesc"].ToString(); lblPrice.Text = "$" + ds.Tables[0].Rows[0]["Price"].ToString(); Session["PRICE"] = ds.Tables[0].Rows[0]["Price"].ToString(); Session["PRODDESC"] = ds.Tables[0].Rows[0]["ProductSDesc"].ToString(); Session["PRODUCTID"] = ds.Tables[0].Rows[0]["ProductId"].ToString(); } catch (Exception ex) { lblStatus.Text = ex.Message; } }
public ViewResult Checkout(Cart cart, Address address, bool mainAddress, string shipMethod) { if(!cart.Lines.Any()) ModelState.AddModelError("","Sorry, your cart is empty!"); var user = AuthHelper.GetUser(HttpContext, new EfUserRepository()); if (mainAddress) //если основной, то перезаписываем { if (address.AddressID == 0) //на случай, если пользователь не заполнил свой адрес в профиле { address.ModifiedDate = DateTime.Now; address.rowguid = Guid.NewGuid(); _addressRepository.SaveToAddress(address); _addressCustomerRepository.SaveToCustomerAddress(_addressCustomerRepository.BindCustomerAddress( user, address)); } else { _addressRepository.SaveToAddress(address); } } else // иначе добавляем новый { address.AddressID = 0; address.ModifiedDate = DateTime.Now; address.rowguid = Guid.NewGuid(); _addressRepository.SaveToAddress(address); } if (ModelState.IsValid) { _orderProcessor.Processor(cart, user,address, shipMethod); cart.Clear(); return View("Completed"); } return View("Checkout"); }
protected void Page_Load(object sender, EventArgs e) { try { this.CurrentCart = Cart.GetCartFromSession(Session); if (this.CurrentCart == null) throw new CartException("Cannot load cart data from session"); if (this.CurrentCart.BillingLocation == null) throw new CartException("Incomplete Cart (Billing)"); if (this.CurrentCart.ShippingLocation == null) throw new CartException("Incomplete Cart (Shipping)"); if (this.CurrentCart.Payment == null) throw new CartException("Incomplete Cart (Payment)"); if (this.CurrentCart.Dirty) this.CurrentCart.Clean(); string locationsummarypath = String.Format("{0}/locationsummary.ascx", Constants.UserControls.CHECKOUT_CONTROLS_DIR); string paymentsummarypath = String.Format("{0}/paymentsummary.ascx", Constants.UserControls.CHECKOUT_CONTROLS_DIR); string shippingoptionsummarypath = String.Format("{0}/shippingoptionsummary.ascx", Constants.UserControls.CHECKOUT_CONTROLS_DIR); string itemsummarypath = String.Format("{0}/itemsummary.ascx", Constants.UserControls.CHECKOUT_CONTROLS_DIR); BillingSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, locationsummarypath, CurrentCart.BillingLocation)); ShippingSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, locationsummarypath, CurrentCart.ShippingLocation)); ShippingOptionSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, shippingoptionsummarypath, CurrentCart)); orderid = Convert.ToInt32(Request.QueryString["id"]); POrder = Convert.ToInt32(Request.QueryString["po"]); //PaymentSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, paymentsummarypath, CurrentCart.Payment)); ItemsSummaryPlaceholder.Controls.Add(Helper.LoadUserControl(Page, itemsummarypath, CurrentCart)); } catch (CartException ex) { Page.Controls.Add(new LiteralControl("There was an error loading your cart")); } }
public RedirectToRouteResult ChangeQuantity(Cart cart, int productId, string returnUrl, int quantity=0) { if (quantity < 1) quantity = 1; var product = _repository.Products.FirstOrDefault(p => p.ProductID == productId); if (product != null) cart.ChangeQuantity(product, quantity); return RedirectToAction("Index", new {returnUrl}); }
public MenuViewModel(Menu menu, Cart cart) { List<CartLine> tempLines = new List<CartLine>(); foreach (var dish in menu.Dishes) { CartLine line = new CartLine() {Dish = dish}; if (cart.Contains(dish)) { line.Quantity = cart.Get(dish).Quantity; } tempLines.Add(line); } Starters = tempLines .Where(x => x.Dish.DishType == DishType.Starter) .ToList(); MainDishes = tempLines .Where(x => x.Dish.DishType == DishType.MainDish) .ToList(); Deserts = tempLines .Where(x => x.Dish.DishType == DishType.Desert) .ToList(); }
public void AddToCart(int id) { // Retrieve the product from the database. ShoppingCartId = GetCartId(); var cartItem = db.Carts.SingleOrDefault( c => c.CartID == ShoppingCartId && c.ProductID == id); if (cartItem == null) { cartItem = new Cart { ItemID = Guid.NewGuid().ToString(), ProductID = id, CartID = ShoppingCartId, Product = db.Products.SingleOrDefault( p => p.ProductID == id), Quantity = 1, DateCreated = DateTime.Now }; db.Carts.Add(cartItem); } else { cartItem.Quantity++; } db.SaveChanges(); }
public void AddToCart(Product product) { // Get the matching cart and product instances var cartItem = _cartAppService.Find( c => c.CartId == ShoppingCartId && c.ProductId == product.ProductId).SingleOrDefault(); if (cartItem == null) { // Create a new cart item if no cart item exists cartItem = new Cart { ProductId = product.ProductId, CartId = ShoppingCartId, Count = 1, DateCreated = DateTime.Now }; _cartAppService.Create(cartItem); } else { // If the item does exist in the cart, then add one to the quantity cartItem.Count++; } }
/// <summary> /// Initializes the specified cart. /// </summary> /// <param name="cart">The cart.</param> public virtual void Initialize(Cart cart) { Assert.ArgumentNotNull(cart, "cart"); this.LineItemCount = ((CommerceCart)cart).LineItemCount; this.Total = ((CommerceTotal)cart.Total).Subtotal.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode); }
public string ChangeStatus(int id = 0, int statusID = 0) { Profile p = ViewBag.profile; Cart order = new Cart(); order = order.GetByPayment(id); order.SetStatus(statusID, p.first + " " + p.last); return "success"; }
protected void btnAdd_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(Request.QueryString["id"])) { //get the id of the current logged in user string clientId = Context.User.Identity.GetUserId(); //implement a check to make sure only logged in user can order a product if (clientId != null) { int id = Convert.ToInt32(Request.QueryString["id"]); int amount = Convert.ToInt32(ddlAmount.SelectedValue); Cart cart = new Cart { Amount = amount, ClientID = clientId, DatePurchased = DateTime.Now, IsInCart = true, ProductID = id }; CartModel cartModel = new CartModel(); lblResult.Text = cartModel.InsertCart(cart); Response.Redirect("~/Index.aspx"); } else { lblResult.Text = "Please log in to order items"; } } }
public void Cannot_Checkout_Empty_Cart() { // Arrange - create a mock order processor Mock<IOrderProcessor> mock = new Mock<IOrderProcessor>(); // Arrange - create an empty cart Cart cart = new Cart(); // Arrange - create shipping details ShippingDetails shippingDetails = new ShippingDetails(); // Arrange - create an instance of the controller CartController target = new CartController(null, mock.Object); // Act var result = target.Checkout(cart, shippingDetails); // Assert check that the order hasn't been passed on to the processor mock.Verify(m => m.ProcessOrder(It.IsAny<Cart>(), It.IsAny<ShippingDetails>()), Times.Never); // Assert - check that the method is returning the default view Assert.AreEqual("", result.ViewName); // Assert - check that we are passing an invalid model to the view Assert.AreEqual(false, result.ViewData.ModelState.IsValid); }
protected void btnAddToCart_Click(object sender, EventArgs e) { Cart cart; if (Session["Cart"] is Cart) cart = Session["Cart"] as Cart; else cart = new Cart(); short quantity = 1; try { quantity = Convert.ToInt16(txtQuantity.Text); } catch (Exception ex) { lblMessage.Text = string.Format("An error has occurred: {0}", ex.ToString()); } //TODO: Put this in try/catch as well //TODO: Feels like this is too much business logic. Should be moved to OrderDetail constructor? var productRepository = new ProductRepository(); var product = productRepository.GetProductById(_productId); var orderDetail = new OrderDetail() { Discount = 0.0F, ProductId = _productId, Quantity = quantity, Product = product, UnitPrice = product.UnitPrice }; cart.OrderDetails.Add(orderDetail); Session["Cart"] = cart; Response.Redirect("~/ViewCart.aspx"); }
public void CreateOrder(Cart cart) { int statusID = chocoPlanetDbEntities.Status.SingleOrDefault(s => s.Name == "Новий").ID; int orderItemsID = (chocoPlanetDbEntities.OrderItems.Count() != 0) ? (chocoPlanetDbEntities.OrderItems.Max(id => id.ID) + 1) : 1; Country country = new Country() { ID = (chocoPlanetDbEntities.Country.Count() != 0) ? chocoPlanetDbEntities.Country.Max(id => id.ID) + 1 : 1, Name = cart.ShippingDetails.Country }; Address address = new Address() { ID = (chocoPlanetDbEntities.Address.Count() != 0) ? chocoPlanetDbEntities.Address.Max(id => id.ID) + 1 : 1, CountryId = country.ID, Town = cart.ShippingDetails.Town, Stret = cart.ShippingDetails.Stret }; Customer customer = new Customer() { ID = (chocoPlanetDbEntities.Customer.Count() != 0) ? chocoPlanetDbEntities.Customer.Max(id => id.ID) + 1 : 1, Name = cart.ShippingDetails.Name, Telefon = cart.ShippingDetails.Telefon, AddressId = address.ID }; Order order = new Order() { ID = (chocoPlanetDbEntities.Order.Count() != 0) ? chocoPlanetDbEntities.Order.Max(id => id.ID) + 1 : 1, StatusId = statusID, CreateDate = DateTime.Now, ModifayDate = DateTime.Now, CustomerId = customer.ID }; foreach (CartLine line in cart.Lines) { OrderItems orderItems = new OrderItems(); orderItems.ID = orderItemsID; orderItems.OrderId = order.ID; orderItems.ProductId = chocoPlanetDbEntities.Product.SingleOrDefault(name => name.Name == line.Product.Name).ID; orderItems.Quantity = line.Quantity; chocoPlanetDbEntities.OrderItems.AddObject(orderItems); orderItemsID++; } chocoPlanetDbEntities.Order.AddObject(order); chocoPlanetDbEntities.Country.AddObject(country); chocoPlanetDbEntities.Customer.AddObject(customer); chocoPlanetDbEntities.Address.AddObject(address); chocoPlanetDbEntities.SaveChanges(); }
public ViewResult Index(Cart cart, string returnUrl) { return View(new CartView { ReturnUrl = returnUrl, Cart = cart }); }
public static void HandleAuthorizationAmountNotification(GCheckout.AutoGen.AuthorizationAmountNotification authnotification) { string googleOrderID = authnotification.googleordernumber; Cart order = new Cart().GetByPayment(googleOrderID); if (order.getPayment().status != "Complete") { order.UpdatePayment(authnotification.ordersummary.financialorderstate.ToString()); } }
public void FillCartWithProducts() { this.cart = new Cart(); FillCartCollectionWithItems(Items_Count); FillCartItemsAndQuantityWithData(this.cart.ItemsCollection); }
public ActionResult UpdateCart(UpdateCardModel model) { var cart = new Cart(new SessionFacade(HttpContext.Session), _storageContext); cart.UpdateCard(model.Id, model.Quantity); return RedirectToAction("Index"); }
public Customer(string name) : base(name) { // TODO: Uncomment the line above once the first Person constructor is set Cart = new Cart(); }
public CartSummaryViewComponent(Cart cart) { _cart = cart; }
public void ClearCart() { Cart.Clear(); }
public void PostCarts(Cart _cart) { repository.Create(_cart); }
public CartController(UnitOfWork unitOfWork, Cart cart) { _unitOfWork = unitOfWork; _cart = cart; }
public List <CartLine> List(Cart cart) { return(cart.CartLines); }
private void SaveCart(Cart cart) { HttpContext.Session.SetJson("Cart", cart); }
public Order ProcessOrder(Cart cart, int addressID) { Order order = new Order(); Address ad = new Address(); //DateTime now = new DateTime(); //now = DateTime.Now; order.FirstName = cart.User.FirstName; order.LastName = cart.User.LastName; order.Email = cart.User.Email; ad = cart.User.UserAddresses.FirstOrDefault(i => i.Id == addressID); if (ad != null) { order.Address1 = ad.Address1; order.Address2 = ad.Address2; order.City = ad.City; order.Country = ad.Country; order.Postal = ad.Postal; //order.OrderDate = now; // order.Status = "Shipped"; order.UserId = cart.UserId; } foreach (CartItem x in cart.CartItems) { OrderItem oi = new OrderItem(); oi.ItemId = x.ItemId; //oi.Name = x.Item.Name; oi.Name = context.Items.FirstOrDefault(i => i.Id == x.ItemId).Name; //oi.Description = x.Item.Description; oi.Description = context.Items.FirstOrDefault(i => i.Id == x.ItemId).Description; //oi.Price = x.Item.Price * x.ItemQuantity; oi.Price = context.Items.FirstOrDefault(i => i.Id == x.ItemId).Price *x.ItemQuantity; oi.Quantity = x.ItemQuantity; //oi.Weight = x.Item.Weight; // oi.Weight = context.Items.FirstOrDefault(i => i.Id == x.ItemId).Weight; //oi.ShippingCost = x.Item.ShippingCost; oi.ShippingCost = context.Items.FirstOrDefault(i => i.Id == x.ItemId).ShippingCost; //oi.Tax = x.Item.Tax; oi.Tax = context.Items.FirstOrDefault(i => i.Id == x.ItemId).Tax; //oi.TotalPrice = (x.Item.Price * x.ItemQuantity) + x.Item.ShippingCost + x.Item.Tax; oi.TotalPrice = oi.Price + oi.ShippingCost + oi.Tax; order.OrderItems.Add(oi); //order.OrderItems.Add(new OrderItem() //{ // ItemId = x.ItemId, // Name = x.Item.Name, // Description = x.Item.Description, // Price = x.Item.Price * x.ItemQuantity, // Quantity = x.ItemQuantity, // Weight = x.Item.Weight, // ShippingCost = x.Item.ShippingCost, // Tax = x.Item.Tax, // TotalPrice = (x.Item.Price * x.ItemQuantity) + x.Item.ShippingCost + x.Item.Tax //}); } if (cart.CartItems != null) { //cart.CartItems.ToList<CartItem>().ForEach(x => order.OrderItems.Add(new OrderItem() //{ // ItemId = x.ItemId, // Name = x.Item.Name, // Description = x.Item.Description, // Price = x.Item.Price * x.ItemQuantity, // Quantity = x.ItemQuantity, // Weight = x.Item.Weight, // ShippingCost = x.Item.ShippingCost, // Tax = x.Item.Tax, // TotalPrice = (x.Item.Price * x.ItemQuantity) + x.Item.ShippingCost + x.Item.Tax //})); order.OrderItems.ToList().ForEach(o => { order.SubTotal += o.Price; order.Tax += o.Tax; order.ShippingCost += o.ShippingCost; }); } return(order); }
public List <CartProduct> GetShoppingCartItems() { Cart actions = new Cart(); return(actions.GetCartItems()); }
public CartSummaryViewComponent(Cart cartService) { _cart = cartService; }
public void Execute_WithProperties( BaseCartItemSubtotalPercentOffAction action, IRuleValue <decimal> subtotal, IRuleValue <decimal> percentOff, Cart cart, CommerceContext commerceContext, IRuleExecutionContext context) { /********************************************** * Arrange **********************************************/ cart.Adjustments.Clear(); cart.Lines.ForEach(l => l.Adjustments.Clear()); var globalPricingPolicy = commerceContext.GetPolicy <GlobalPricingPolicy>(); globalPricingPolicy.ShouldRoundPriceCalc = false; cart.Lines.ForEach(l => l.Totals.SubTotal.Amount = 100); var cartline = cart.Lines[1]; cartline.Totals.SubTotal.Amount = 150; var cartTotals = new CartTotals(cart); subtotal.Yield(context).ReturnsForAnyArgs(150); percentOff.Yield(context).ReturnsForAnyArgs(25.55M); var propertiesModel = new PropertiesModel(); propertiesModel.Properties.Add("PromotionId", "id"); propertiesModel.Properties.Add("PromotionCartText", "carttext"); propertiesModel.Properties.Add("PromotionText", "text"); commerceContext.AddObject(propertiesModel); context.Fact <CommerceContext>().ReturnsForAnyArgs(commerceContext); commerceContext.AddObject(cartTotals); commerceContext.AddObject(cart); action.MatchingLines(context).ReturnsForAnyArgs(cart.Lines); action.SubtotalOperator = new DecimalGreaterThanEqualToOperator(); action.Subtotal = subtotal; action.PercentOff = percentOff; /********************************************** * Act **********************************************/ Action executeAction = () => action.Execute(context); /********************************************** * Assert **********************************************/ executeAction.Should().NotThrow <Exception>(); cart.Lines.SelectMany(l => l.Adjustments).Should().HaveCount(1); cart.Adjustments.Should().BeEmpty(); cartTotals.Lines[cartline.Id].SubTotal.Amount.Should().Be(111.6750M); cartline.Adjustments.Should().NotBeEmpty(); cartline.Adjustments.FirstOrDefault().Should().NotBeNull(); cartline.Adjustments.FirstOrDefault().Should().BeOfType <CartLineLevelAwardedAdjustment>(); cartline.Adjustments.FirstOrDefault()?.Name.Should().Be("text"); cartline.Adjustments.FirstOrDefault()?.DisplayName.Should().Be("carttext"); cartline.Adjustments.FirstOrDefault()?.AdjustmentType.Should().Be(commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount); cartline.Adjustments.FirstOrDefault()?.AwardingBlock.Should().Contain(nameof(BaseCartItemSubtotalPercentOffAction)); cartline.Adjustments.FirstOrDefault()?.IsTaxable.Should().BeFalse(); cartline.Adjustments.FirstOrDefault()?.Adjustment.CurrencyCode.Should().Be(commerceContext.CurrentCurrency()); cartline.Adjustments.FirstOrDefault()?.Adjustment.Amount.Should().Be(-38.325M); cartline.HasComponent <MessagesComponent>().Should().BeTrue(); }
public OrderController(IOrderRepository repoService, Cart cartService) { _repository = repoService; _cart = cartService; }
public void RemoveFromCart(Cart cart, int productId) { cart.CartLines.Remove(cart.CartLines.FirstOrDefault(c => c.Product.ProductId == productId)); }
private Cart GetCart() { Cart cart = HttpContext.Session.GetJson <Cart>("Cart") ?? new Cart(); return(cart); }
public OrderController(IOrderRepository rep, Cart crt) { repository = rep; cart = crt; }
public CartController(IProductRepository repo, Cart cartService) { repository = repo; cart = cartService; }
public ViewResult Summary(Cart cart) { return(View(cart)); }
public async Task <Cart> Update(Cart cart) { return(await _cartRepo.UpdateAsync(cart.Id, cart)); }
public CartController(IProductRepository repository, Cart cartService) { _repository = repository; _cartService = cartService; }
public async Task <ResponseObject> Post([FromBody] OrderDetails orderDetails) { //int cartID, int shippingAddressID,Address address=null Order order = new Order(); Cart cart = new Cart(); //cart.CartItems = new List<CartItem>(); await HttpContext.Session.LoadAsync(); int userID = HttpContext.Session.GetInt32("UserID") ?? 0; if (HttpContext.Session.GetInt32("IsLoggedIn") == 1) { cart = context.Carts .Where(c => c.UserId == userID) .Include(i => i.CartItems) .Include(u => u.User) .ThenInclude(ua => ua.UserAddresses) .SingleOrDefault(); if (cart != null || cart.CartItems != null) { order = ProcessOrder(cart, orderDetails.shippingAddressID); context.Orders.Add(order); await context.SaveChangesAsync(); List <Order> orders = new List <Order>() { order }; response.SetContent(true, "Order Placed Successfully", orders.ToList <object>()); //return response; } else { response.SetContent(false, "Could not process order"); //return response; } } else//*********ANNONYMOUS USER { await HttpContext.Session.LoadAsync(); cart = HttpContext.Session.GetObject <Cart>("AnnonymousCart") ?? null; if (cart != null && ValidateAddress(orderDetails.address)) { cart.User = new User(); cart.User.UserAddresses = new List <Address>(); cart.User.UserAddresses.Add(orderDetails.address); order = ProcessOrder(cart, orderDetails.shippingAddressID); List <Order> orders = new List <Order>() { order }; response.SetContent(true, "Order Placed Successfully", orders.ToList <object>()); //return response; } else { response.SetContent(false, "Could not process order"); //return response; } } return(response); }
/// <summary> /// A method to return the current state of the cart /// </summary> /// <param name="create">Specifies whether a cart should be created if one does not exist</param> /// <returns>Cart object</returns> public void StoreCart(Cart cart) { // Store the cart object in session state HttpContext.Current.Session[CART_KEY] = cart; }
public PartialViewResult Summary(Cart cart) { return(PartialView(cart)); }
// GET: Favorites public ActionResult Index(double?delete, double?cart) { if (Session["User_id"] == null) { return(RedirectToAction("Index", "Login")); } int User_id = Convert.ToInt32(Session["User_id"]); var list = db.Favorites.Select(s => s); string deleteISBN = delete.ToString(); string CartISBN = cart.ToString(); // VERWIJDER UIT FAVORIETEN if (deleteISBN != "" && deleteISBN != null) { using (DatabaseEntities1 db = new DatabaseEntities1()) { db.Favorites.Remove(db.Favorites.Single(x => x.ISBN == delete && x.User_id == User_id)); db.SaveChanges(); } } if (CartISBN != "" && CartISBN != null) { var listCart = db.Carts.Select(s => s); int User_idCart = Convert.ToInt32(Session["User_id"]); bool has = listCart.Any(x => x.ISBN == cart && x.User_id == User_id); if (has) { using (DatabaseEntities1 db = new DatabaseEntities1()) { db.Carts.Remove(db.Carts.Single(x => x.ISBN == cart && x.User_id == User_id)); db.SaveChanges(); } } else { // ISBN TOEVOEGEN AAN FAVORIETEN using (DatabaseEntities1 db = new DatabaseEntities1()) { var cartObj = new Cart() { User_id = User_id, ISBN = Convert.ToDouble(cart), Quantity = 1 }; db.Carts.Add(cartObj); db.SaveChanges(); } } } //VERWIJDEREN UIT WINKELWAGEN // laad favorieten var result = (from favo in db.Favorites from book in db.Books where favo.ISBN == book.ISBN && favo.User_id == User_id select book).ToList(); return(View(result)); }
public ViewResult Index(Cart cart, string returnUrl) { return(View(new CartIndexViewModel { Cart = cart, ReturnUrl = returnUrl })); }
public abstract void Handle(Cart cart);
public void Can_Load_Cart() { Product p1 = new Product { ProductID = 1, Name = "P1" }; Product p2 = new Product { ProductID = 1, Name = "P1" }; mockRepo.Setup(m => m.Products) .Returns((new Product[] { p1, p2 }) .AsQueryable <Product>()); Cart testCart = new Cart(); testCart.AddItem(p1, 2); testCart.AddItem(p2, 1); Mock <ISession> mockSession = new Mock <ISession>(); Mock <IStoreRepository> mockRepo = new Mock <IStoreRepository>(); mockRepo.Setup(m => m.Products).Returns(( new Product[] { new Product { ProductID = 1, Name = "P1" }, new Product { ProductID = 2, Name = "P2" } }).AsQueryable()); Cart testCart = new Cart(); testCart.AddItem(p1, 2); testCart.AddItem(p2, 1); CartModel cartModel = new CartModel(mockRepo.Object, testCart); cartModel.OnGet("myUrl"); Assert.Equal(2, cartModel.Cart.Lines.Count()); Assert.Equal("myurl", cartModel.ReturnUrl); // byte[] data=Encoding.UTF8.GetBytes(JsonSerializer.Serialize(testCart)); // mockSession.Setup(c => // c.TryGetValue(It.IsAny<string>(), out data)); // Mock<HttpContext> mockContext = new Mock<HttpContext>(); // mockContext.SetupGet(c => c.Session).Returns(mockSession.Object); // CartModel cartModel = new CartModel(mockRepo.Object) // { // PageContext = new PageContext( // new ActionContext{ // HttpContext = mockContext.Object, // RouteData= new Microsoft.AspNetCore.Routing.RouteData(), // ActionDescriptor = new PageActionDescriptor() // }) // }; // cartModel.OnGet("MyUrl"); // Assert.Equal(2, cartModel.Cart.Lines.Count() ); // Assert.Equal("myUrl",cartModel.ReturnUrl ); }
public void PutCarts(Cart _cart) { repository.Update(_cart); }
public void CartTest() { var cartMock = new Mock <ICartProvider>(); var cart = new Cart() { Points = 10 }; cartMock.Setup( c => c.GetCart( It.IsAny <CartController>())) .Returns(cart); var repoMock = new Mock <ICharacterRepository>(); repoMock.Setup(r => r.Characters) .Returns(new Character[] { new Character() { Id = 1, Price = 100 }, new Character() { Id = 2, Price = 4 }, new Character() { Id = 3, Price = 8 }, new Character() { Id = 4, Price = 2 }, }.AsQueryable() ); var voteMock = new Mock <IVoteRepository>(); voteMock.Setup(v => v.Votes) .Returns(new[] { new Vote() { User = "******", VoteID = 1, VoteItems = new [] { new VoteItem() { Character = new Character() { Id = 1, Price = 8 } } }, Week = 1 } }.AsQueryable() ); var controller = new CartController(repoMock.Object, voteMock.Object, cartMock.Object, null, null); controller.Manage(1); controller.Manage(2); controller.Manage(3); controller.Manage(4); Assert.AreEqual(4, cart.Points); Assert.AreEqual(2, cart.CharacterIds.Count); Assert.IsTrue(cart.CharacterIds.Contains(2)); Assert.IsTrue(cart.CharacterIds.Contains(4)); }
public CartController(ICardRepository cardRepo, Cart cart) { _cardRepo = cardRepo; _cart = cart; }
string Tsto(Cart cart) => $"{cart.pos.icol},{cart.pos.irow}";