public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();

            //Iterate the items in the cart, adding Order Details for each
            foreach (var cartItem in cartItems)
            {
                var orderDetails = new OrderDetail
                {
                    AlbumId = cartItem.AlbumId,
                    OrderId = order.OrderId,
                    UnitPrice = cartItem.Album.Price
                };

                storeDB.OrderDetails.AddObject(orderDetails);

                orderTotal += (cartItem.Count * cartItem.Album.Price);
            }

            //Save the order
            storeDB.SaveChanges();

            //Empty the shopping cart
            EmptyCart();

            //Return the OrderId as a confirmation number
            return order.OrderId;
        }
Beispiel #2
0
        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();

            // Iterate over the items in the cart, adding the order details for each
            foreach (var item in cartItems) {
                var orderDetail = new OrderDetail {
                    AlbumId = item.AlbumId,
                    OrderId = order.OrderId,
                    UnitPrice = item.Album.Price,
                    Quantity = item.Count
                };

                // Set the order total of the shopping cart
                orderTotal += (item.Count * item.Album.Price);

                storeDB.OrderDetails.Add(orderDetail);

            }

            // Set the order's total to the orderTotal count
            order.Total = orderTotal;

            // Save the order
            storeDB.SaveChanges();

            // Empty the shopping cart
            EmptyCart();

            // Return the OrderId as the confirmation number
            return order.OrderId;
        }
        public ActionResult AddressAndPayment(FormCollection values)
        {
            var order = new Order();
            TryUpdateModel(order);

            try
            {
                order.Username = User.Identity.Name;
                order.OrderDate = DateTime.Now;

                // Inserir encomenda na base de dados
                storeDB.AddToOrders(order);
                storeDB.SaveChanges();

                // Processar a encomenda
                cart = ShoppingCart.GetCart(this.HttpContext);
                cart.CreateOrder(order);

                return RedirectToAction("Complete",
                    new { id = order.OrderId });
            }
            catch
            {
                return RedirectToAction("Index", "ShoppingCart");
            }
        }
        public async Task AddressAndPayment_RedirectToCompleteWhenSuccessful()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();

            var orderId = 10;
            var order = new Order()
            {
                OrderId = orderId,
            };

            // Session initialization
            var cartId = "CartId_A";
            var sessionFeature = new SessionFeature()
            {
                Session = CreateTestSession(),
            };
            httpContext.SetFeature<ISessionFeature>(sessionFeature);
            httpContext.Session.SetString("Session", cartId);

            // FormCollection initialization
            httpContext.Request.Form =
                new FormCollection(
                    new Dictionary<string, string[]>()
                        { { "PromoCode", new string[] { "FREE" } } }
                    );

            // UserName initialization
            var claims = new List<Claim> { new Claim(ClaimTypes.Name, "TestUserName") };
            httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
            
            // DbContext initialization
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            var cartItems = CreateTestCartItems(
                cartId,
                itemPrice: 10,
                numberOfItem: 1);
            dbContext.AddRange(cartItems.Select(n => n.Album).Distinct());
            dbContext.AddRange(cartItems);
            dbContext.SaveChanges();

            var controller = new CheckoutController()
            {
                DbContext = dbContext,
            };
            controller.ActionContext.HttpContext = httpContext;
            
            // Act
            var result = await controller.AddressAndPayment(order, CancellationToken.None);

            // Assert
            var redirectResult = Assert.IsType<RedirectToActionResult>(result);
            Assert.Equal("Complete", redirectResult.ActionName);
            Assert.Null(redirectResult.ControllerName);
            Assert.NotNull(redirectResult.RouteValues);

            Assert.Equal(orderId, redirectResult.RouteValues["Id"]);
        }
        public async Task<IActionResult> AddressAndPayment(Order order)
        {
            var formCollection = await Context.Request.GetFormAsync();

            try
            {
                if (string.Equals(formCollection.GetValues("PromoCode").FirstOrDefault(), PromoCode,
                    StringComparison.OrdinalIgnoreCase) == false)
                {
                    return View(order);
                }
                else
                {
                    // TODO [EF] Swap to store generated identity key when supported
                    var nextId = db.Orders.Any()
                        ? db.Orders.Max(o => o.OrderId) + 1
                        : 1;

                    order.OrderId = nextId;
                    order.Username = this.Context.User.Identity.GetUserName();
                    order.OrderDate = DateTime.Now;

                    //Add the Order
                    db.Orders.Add(order);

                    //Process the order
                    var cart = ShoppingCart.GetCart(db, this.Context);
                    cart.CreateOrder(order);

                    // Save all changes
                    db.SaveChanges();

                    return RedirectToAction("Complete",
                        new { id = order.OrderId });
                }
            }
            catch
            {
                //Invalid - redisplay with errors
                return View(order);
            }
        }
        public ActionResult AddressAndPayment(FormCollection values)
        {
            var order = new Order();
            TryUpdateModel(order);

            try
            {
                if (string.Equals(values["PromoCode"], PromoCode,
                    StringComparison.OrdinalIgnoreCase) == false)
                {
                    return View(order);
                }
                else
                {
                    order.Username = User.Identity.Name;
                    order.OrderDate = DateTime.Now;

                    //Save Order
                    storeDB.Orders.Add(order);
                    storeDB.SaveChanges();

                    //Process the order
                    var cart = ShoppingCart.GetCart(this.HttpContext);
                    cart.CreateOrder(order);

                    return RedirectToAction("Complete",
                        new { id = order.OrderId });
                }

            }
            catch
            {
                //Invalid - redisplay with errors
                return View(order);
            }
        }
        public async Task AddressAndPayment_ReturnsOrderIfInvalidPromoCode()
        {
            // Arrange
            var context = new DefaultHttpContext();
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();

            // AddressAndPayment action reads the Promo code from FormCollection.
            context.Request.Form =
                new FormCollection(new Dictionary<string, StringValues>());

            var controller = new CheckoutController();
            controller.ControllerContext.HttpContext = context;

            // Do not need actual data for Order; the Order object will be checked for the reference equality.
            var order = new Order();

            // Act
            var result = await controller.AddressAndPayment(dbContext, order, CancellationToken.None);

            // Assert
            var viewResult = Assert.IsType<ViewResult>(result);
            Assert.Null(viewResult.ViewName);

            Assert.NotNull(viewResult.ViewData);
            Assert.Same(order, viewResult.ViewData.Model);
        }
        public async Task AddressAndPayment_ReturnsOrderIfInvalidOrderModel()
        {
            // Arrange
            var controller = new CheckoutController();
            controller.ModelState.AddModelError("a", "ModelErrorA");
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();

            var order = new Order();

            // Act
            var result = await controller.AddressAndPayment(dbContext, order, CancellationToken.None);

            // Assert
            var viewResult = Assert.IsType<ViewResult>(result);
            Assert.Null(viewResult.ViewName);

            Assert.NotNull(viewResult.ViewData);
            Assert.Same(order, viewResult.ViewData.Model);
        }
        public async Task AddressAndPayment_ReturnsOrderIfRequestCanceled()
        {
            // Arrange
            var context = new DefaultHttpContext();
            context.Request.Form =
                new FormCollection(new Dictionary<string, StringValues>());
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();

            var controller = new CheckoutController();
            controller.ControllerContext.HttpContext = context;

            var order = new Order();

            // Act
            var result = await controller.AddressAndPayment(dbContext, order, new CancellationToken(true));

            // Assert
            var viewResult = Assert.IsType<ViewResult>(result);
            Assert.Null(viewResult.ViewName);

            Assert.NotNull(viewResult.ViewData);
            Assert.Same(order, viewResult.ViewData.Model);
        }
        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();

            // TODO [EF] Swap to store generated identity key when supported
            var nextId = _db.OrderDetails.Any()
                ? _db.OrderDetails.Max(o => o.OrderDetailId) + 1
                : 1;

            // Iterate over the items in the cart, adding the order details for each
            foreach (var item in cartItems)
            {
                //var album = _db.Albums.Find(item.AlbumId);
                var album = _db.Albums.Single(a => a.AlbumId == item.AlbumId);

                var orderDetail = new OrderDetail
                {
                    OrderDetailId = nextId,
                    AlbumId = item.AlbumId,
                    OrderId = order.OrderId,
                    UnitPrice = album.Price,
                    Quantity = item.Count,
                };

                // Set the order total of the shopping cart
                orderTotal += (item.Count * album.Price);

                _db.OrderDetails.Add(orderDetail);

                nextId++;
            }

            // Set the order's total to the orderTotal count
            order.Total = orderTotal;

            // Empty the shopping cart
            EmptyCart();

            // Return the OrderId as the confirmation number
            return order.OrderId;
        }
        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();

            // Iterate over the items in the cart, adding the order details for each
            foreach (var item in cartItems)
            {
                //var album = _db.Albums.Find(item.AlbumId);
                var album = _db.Albums.Single(a => a.AlbumId == item.AlbumId);

                var orderDetail = new OrderDetail
                {
                    AlbumId = item.AlbumId,
                    OrderId = order.OrderId,
                    UnitPrice = album.Price,
                    Quantity = item.Count,
                };

                // Set the order total of the shopping cart
                orderTotal += (item.Count * album.Price);

                _db.OrderDetails.Add(orderDetail);
            }

            // Set the order's total to the orderTotal count
            order.Total = orderTotal;

            // Empty the shopping cart
            EmptyCart();

            // Return the OrderId as the confirmation number
            return order.OrderId;
        }
 /// <summary>
 /// Create a new Order object.
 /// </summary>
 /// <param name="orderId">Initial value of the OrderId property.</param>
 /// <param name="orderDate">Initial value of the OrderDate property.</param>
 /// <param name="total">Initial value of the Total property.</param>
 public static Order CreateOrder(global::System.Int32 orderId, global::System.DateTime orderDate, global::System.Decimal total)
 {
     Order order = new Order();
     order.OrderId = orderId;
     order.OrderDate = orderDate;
     order.Total = total;
     return order;
 }
 /// <summary>
 /// Deprecated Method for adding a new object to the Orders EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToOrders(Order order)
 {
     base.AddObject("Orders", order);
 }