public ViewResult Index(Cart cart, string returnUrl)
 {
     return View(new CartIndexViewModel
     {
         Cart = cart,
         ReturnUrl = returnUrl
     });
 }
        public void ProcessOrder(Cart cart, ShippingDetails shippingInfo)
        {
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.EnableSsl = emailSettings.UseSsl;
                smtpClient.Host = emailSettings.ServerName;
                smtpClient.Port = emailSettings.ServerPort;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials
                    = new NetworkCredential(emailSettings.Username, emailSettings.Password);

                if (emailSettings.WriteAsFile)
                {
                    smtpClient.DeliveryMethod
                        = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    smtpClient.PickupDirectoryLocation = emailSettings.FileLocation;
                    smtpClient.EnableSsl = false;
                }

                StringBuilder body = new StringBuilder()
                    .AppendLine("Новый заказ обработан")
                    .AppendLine("---")
                    .AppendLine("Товары:");

                foreach (var line in cart.Lines)
                {
                    var subtotal = line.Game.Price * line.Quantity;
                    body.AppendFormat("{0} x {1} (итого: {2:c}",
                        line.Quantity, line.Game.Name, subtotal);
                }

                body.AppendFormat("Общая стоимость: {0:c}", cart.ComputeTotalValue())
                    .AppendLine("---")
                    .AppendLine("Доставка:")
                    .AppendLine(shippingInfo.Name)
                    .AppendLine(shippingInfo.Line1)
                    .AppendLine(shippingInfo.Line2 ?? "")
                    .AppendLine(shippingInfo.Line3 ?? "")
                    .AppendLine(shippingInfo.City)
                    .AppendLine(shippingInfo.Country)
                    .AppendLine("---")
                    .AppendFormat("Подарочная упаковка: {0}",
                        shippingInfo.GiftWrap ? "Да" : "Нет");

                MailMessage mailMessage = new MailMessage(
                                       emailSettings.MailFromAddress,	// От кого
                                       emailSettings.MailToAddress,		// Кому
                                       "Новый заказ отправлен!",		// Тема
                                       body.ToString()); 				// Тело письма

                if (emailSettings.WriteAsFile)
                {
                    mailMessage.BodyEncoding = Encoding.Unicode;
                }

                smtpClient.Send(mailMessage);
            }
        }
 /*
 public Cart GetCart()
 {
     Cart cart = (Cart)Session["Cart"];
     if (cart == null)
     {
         cart = new Cart();
         Session["Cart"] = cart;
     }
     return cart;
 }
 */
 public RedirectToRouteResult AddToCart(Cart cart, int gameId, string url)
 {
     Game game = _repository.Games.FirstOrDefault(g => g.GameId == gameId);
     if(game != null)
     {
         cart.AddItem(game, 1);
     }
     return RedirectToAction("Index", new { url });
 }
        public RedirectToRouteResult RemoveFromCart(Cart cart, int gameId, string returnUrl)
        {
            Game game = repository.Games
                .FirstOrDefault(g => g.GameId == gameId);

            if (game != null)
            {
                cart.RemoveLine(game);
            }
            return RedirectToAction("Index", new { returnUrl });
        }
        public void CalculateTotalCart()
        {
            Game game1 = new Game { GameId = 1, Name = "Game 1", Price = 100 };
            Game game2 = new Game { GameId = 2, Name = "Game 2", Price = 200 };

            Cart cart = new Cart();
            cart.AddItem(game1, 1);
            cart.AddItem(game2, 1);
            cart.AddItem(game1, 5);

            decimal totalCost = cart.ComputeTotalValue();
            Assert.AreEqual(totalCost, 800);
        }
Example #6
0
 public void Adding_Product_To_Cart_Goes_To_Cart_Screen()
 {
     // Arrange - create the mock repository
     Mock<IProductRepository> mock = new Mock<IProductRepository>();
     mock.Setup(m => m.Products).Returns(new Product[] { new Product {ProductID = 1, Name = "P1", Category = "Apples"}, }.AsQueryable());
     // Arrange - create a Cart
     Cart cart = new Cart();
     // Arrange - create the controller
     CartController target = new CartController(mock.Object, null);
     // Act - add a product to the cart
     RedirectToRouteResult result = target.AddToCart(cart, 2, "myUrl");
     // Assert
     Assert.AreEqual(result.RouteValues["action"], "Index");
     Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
 }
        public void CanAddNewLines()
        {
            Game game1 = new Game { GameId = 1, Name = "Game 1" };
            Game game2 = new Game { GameId = 2, Name = "Game 2" };

            Cart cart = new Cart();
            cart.AddItem(game1, 2);
            cart.AddItem(game2, 1);

            List<CartLine> res = cart.Lines.ToList();

            Assert.AreEqual(res.Count, 2);
            Assert.AreEqual(res[0].Game, game1);
            Assert.AreEqual(res[1].Game, game2);
        }
Example #8
0
 public void Calculate_Cart_Total()
 {
     // Arrange - create some test products
     Product p1 = new Product { ProductID = 1, Name = "P1", Price = 100M};
     Product p2 = new Product { ProductID = 2, Name = "P2" , Price = 50M};
     // Arrange - create a new cart
     Cart target = new Cart();
     // Act
     target.AddItem(p1, 1);
     target.AddItem(p2, 1);
     target.AddItem(p1, 3);
     decimal result = target.ComputeTotalValue();
     // Assert
     Assert.AreEqual(result, 450M);
 }
        public void ProcessOrder(Cart cart, ShippingDetails shippingInfo)
        {
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.EnableSsl = emailSettings.UseSsl;
                smtpClient.Host = emailSettings.ServerName;
                smtpClient.Port = emailSettings.ServerPort;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(emailSettings.Username, emailSettings.Password);
                if (emailSettings.WriteAsFile)
                {
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    smtpClient.PickupDirectoryLocation = emailSettings.FileLocation;
                    smtpClient.EnableSsl = false;
                }

                StringBuilder body = new StringBuilder().AppendLine("A new order has been submitted").AppendLine("---").AppendLine("Items:");

                foreach (var line in cart.Lines)
                {
                    var subtotal = line.Product.Price * line.Quantity;
                    body.AppendFormat("{0} x {1} (subtotal: {2:c}", line.Quantity, line.Product.Name, subtotal);
                }

                body.AppendFormat("Total order value: {0:c}", cart.ComputeTotalValue())
                    .AppendLine("---")
                    .AppendLine("Ship to:")
                    .AppendLine(shippingInfo.Name)
                    .AppendLine(shippingInfo.Line1)
                    .AppendLine(shippingInfo.Line2 ?? "")
                    .AppendLine(shippingInfo.Line3 ?? "")
                    .AppendLine(shippingInfo.City)
                    .AppendLine(shippingInfo.State ?? "")
                    .AppendLine(shippingInfo.Country)
                    .AppendLine(shippingInfo.Zip)
                    .AppendLine("---")
                    .AppendFormat("Gift wrap: {0}", shippingInfo.GiftWrap ? "Yes" : "No");

                MailMessage mailMessage = new MailMessage(emailSettings.MailFromAddress, emailSettings.MailToAddress, "New order submitted!", body.ToString());

                if (emailSettings.WriteAsFile)
                {
                    mailMessage.BodyEncoding = Encoding.ASCII;
                }

                //smtpClient.Send(mailMessage);
            }
        }
        public void CanRemoveLine()
        {
            Game game1 = new Game { GameId = 1, Name = "Game 1" };
            Game game2 = new Game { GameId = 2, Name = "Game 2" };
            Game game3 = new Game { GameId = 3, Name = "Game 3" };

            Cart cart = new Cart();
            cart.AddItem(game1, 1);
            cart.AddItem(game2, 1);
            cart.AddItem(game1, 5);
            cart.AddItem(game3, 2);

            cart.RemoveLine(game2);
            Assert.AreEqual(cart.Lines.Count(), 2);
            Assert.AreEqual(cart.Lines.Where(g => g.Game == game2).Count(), 0);
        }
        public void CanAddQuantityForExitingLines()
        {
            Game game1 = new Game { GameId = 1, Name = "Game 1" };
            Game game2 = new Game { GameId = 2, Name = "Game 2" };

            Cart cart = new Cart();

            cart.AddItem(game1, 1);
            cart.AddItem(game2, 1);
            cart.AddItem(game1, 5);
            List<CartLine> results = cart.Lines.OrderBy(c => c.Game.GameId).ToList();

            Assert.AreEqual(results.Count(), 2);
            Assert.AreEqual(results[0].Quantity, 6);
            Assert.AreEqual(results[1].Quantity, 1);
        }
 public ViewResult Checkout(Cart cart, ShippingDetails shippingDetails)
 {
     if(cart.Lines.Count() == 0)
     {
         ModelState.AddModelError("", "Your cart is empty");
     }
     if(ModelState.IsValid)
     {
         _orderProcessor.ProcessOrder(cart, shippingDetails);
         cart.Clear();
         return View("Completed");
     }
     else
     {
         return View(shippingDetails);
     }
 }
Example #13
0
        public void Calculate_Cart_Total()
        {
            // Организация - создание нескольких тестовых игр
            Game game1 = new Game { GameId = 1, Name = "Игра1", Price = 100 };
            Game game2 = new Game { GameId = 2, Name = "Игра2", Price = 55 };

            // Организация - создание корзины
            Cart cart = new Cart();

            // Действие
            cart.AddItem(game1, 1);
            cart.AddItem(game2, 1);
            cart.AddItem(game1, 5);
            decimal result = cart.ComputeTotalValue();

            // Утверждение
            Assert.AreEqual(result, 655);
        }
Example #14
0
        // [HttpPost]
        public ViewResult Checkout(Cart cart, ShippingDetails shippingDetails)
        {
            if (cart.Lines.Count() == 0)
            {
                ModelState.AddModelError("", "Извините, ваша корзина пуста!");
            }

            if (ModelState.IsValid)
            {
                orderProcessor.ProcessOrder(cart, shippingDetails);
                cart.Clear();
                return View("Completed");
            }
            else
            {
                return View(shippingDetails);
            }
        }
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            Cart cart = null;
            if(controllerContext.HttpContext.Session != null)
            {
                cart = (Cart)controllerContext.HttpContext.Session[_sessionKey];
            }

            if(cart == null)
            {
                cart = new Cart();
                if(controllerContext.HttpContext.Session != null)
                {
                    controllerContext.HttpContext.Session[_sessionKey] = cart;
                }
            }
            return cart;
        }
Example #16
0
        public void Can_Add_New_Lines()
        {
            // Организация - создание нескольких тестовых игр
            Game game1 = new Game { GameId = 1, Name = "Игра1" };
            Game game2 = new Game { GameId = 2, Name = "Игра2" };

            // Организация - создание корзины
            Cart cart = new Cart();

            // Действие
            cart.AddItem(game1, 1);
            cart.AddItem(game2, 1);
            List<CartLine> results = cart.Lines.ToList();

            // Утверждение
            Assert.AreEqual(results.Count(), 2);
            Assert.AreEqual(results[0].Game, game1);
            Assert.AreEqual(results[1].Game, game2);
        }
Example #17
0
        public void Can_Add_Quantity_For_Existing_Lines()
        {
            // Организация - создание нескольких тестовых игр
            Game game1 = new Game { GameId = 1, Name = "Игра1" };
            Game game2 = new Game { GameId = 2, Name = "Игра2" };

            // Организация - создание корзины
            Cart cart = new Cart();

            // Действие
            cart.AddItem(game1, 1);
            cart.AddItem(game2, 1);
            cart.AddItem(game1, 5);
            List<CartLine> results = cart.Lines.OrderBy(c => c.Game.GameId).ToList();

            // Утверждение
            Assert.AreEqual(results.Count(), 2);
            Assert.AreEqual(results[0].Quantity, 6);    // 6 экземпляров добавлено в корзину
            Assert.AreEqual(results[1].Quantity, 1);
        }
Example #18
0
 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
     ViewResult 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 I am passing an invalid model to the view
     Assert.AreEqual(false, result.ViewData.ModelState.IsValid);
 }
Example #19
0
        public void Adding_Game_To_Cart_Goes_To_Cart_Screen()
        {
            // Организация - создание имитированного хранилища
            Mock<IGameRepository> mock = new Mock<IGameRepository>();
            mock.Setup(m => m.Games).Returns(new List<Game> {
            new Game {GameId = 1, Name = "Игра1", Category = "Кат1"},
            }.AsQueryable());

            // Организация - создание корзины
            Cart cart = new Cart();

            // Организация - создание контроллера
            CartController controller = new CartController(mock.Object);

            // Действие - добавить игру в корзину
            RedirectToRouteResult result = controller.AddToCart(cart, 2, "myUrl");

            // Утверждение
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #20
0
 public void Cannot_Checkout_Invalid_ShippingDetails()
 {
     // Arrange - create a mock order processor
     Mock<IOrderProcessor> mock = new Mock<IOrderProcessor>();
     // Arrange - create a cart with an item
     Cart cart = new Cart();
     cart.AddItem(new Product(), 1);
     // Arrange - create an instance of the controller
     CartController target = new CartController(null, mock.Object);
     // Arrange - add an error to the model
     target.ModelState.AddModelError("error", "error");
     // Act - try to checkout
     ViewResult result = target.Checkout(cart, new 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 I am passing an invalid model to the view
     Assert.AreEqual(false, result.ViewData.ModelState.IsValid);
 }
Example #21
0
        public object BindModel(ControllerContext controllerContext,
                ModelBindingContext bindingContext)
        {
            // Получить объект Cart из сеанса
                Cart cart = null;
                if (controllerContext.HttpContext.Session != null)
                {
                    cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
                }

                // Создать объект Cart если он не обнаружен в сеансе
                if (cart == null)
                {
                    cart = new Cart();
                    if (controllerContext.HttpContext.Session != null)
                    {
                        controllerContext.HttpContext.Session[sessionKey] = cart;
                    }
                }

                // Возвратить объект Cart
                return cart;
        }
Example #22
0
        public void Can_Add_To_Cart()
        {
            // Организация - создание имитированного хранилища
            Mock<IGameRepository> mock = new Mock<IGameRepository>();
            mock.Setup(m => m.Games).Returns(new List<Game> {
            new Game {GameId = 1, Name = "Игра1", Category = "Кат1"},
            }.AsQueryable());

            // Организация - создание корзины
            Cart cart = new Cart();

            // Организация - создание контроллера
            CartController controller = new CartController(mock.Object);

            // Действие - добавить игру в корзину
            controller.AddToCart(cart, 1, null);

            // Утверждение
            Assert.AreEqual(cart.Lines.Count(), 1);
            Assert.AreEqual(cart.Lines.ToList()[0].Game.GameId, 1);
        }
Example #23
0
 public void Can_Clear_Contents()
 {
     // Arrange - create some test products
     Product p1 = new Product { ProductID = 1, Name = "P1", Price = 100M };
     Product p2 = new Product { ProductID = 2, Name = "P2", Price = 50M };
     // Arrange - create a new cart
     Cart target = new Cart();
     // Arrange - add some items
     target.AddItem(p1, 1);
     target.AddItem(p2, 1);
     // Act - reset the cart
     target.Clear();
     // Assert
     Assert.AreEqual(target.Lines.Count(), 0);
 }
Example #24
0
 public void Can_Remove_Line()
 {
     // Arrange - create some test products
     Product p1 = new Product { ProductID = 1, Name = "P1" };
     Product p2 = new Product { ProductID = 2, Name = "P2" };
     Product p3 = new Product { ProductID = 3, Name = "P3" };
     // Arrange - create a new cart
     Cart target = new Cart();
     // Arrange - add some products to the cart
     target.AddItem(p1, 1);
     target.AddItem(p2, 3);
     target.AddItem(p3, 5);
     target.AddItem(p2, 1);
     // Act
     target.RemoveLine(p2);
     // Assert
     Assert.AreEqual(target.Lines.Where(c => c.Product == p2).Count(), 0);
     Assert.AreEqual(target.Lines.Count(), 2);
 }
Example #25
0
        public void Can_View_Cart_Contents()
        {
            // Организация - создание корзины
            Cart cart = new Cart();

            // Организация - создание контроллера
            CartController target = new CartController(null);

            // Действие - вызов метода действия Index()
            CartIndexViewModel result
                = (CartIndexViewModel)target.Index(cart, "myUrl").ViewData.Model;

            // Утверждение
            Assert.AreSame(result.Cart, cart);
            Assert.AreEqual(result.ReturnUrl, "myUrl");
        }
Example #26
0
        public void Can_Remove_Line()
        {
            // Организация - создание нескольких тестовых игр
            Game game1 = new Game { GameId = 1, Name = "Игра1" };
            Game game2 = new Game { GameId = 2, Name = "Игра2" };
            Game game3 = new Game { GameId = 3, Name = "Игра3" };

            // Организация - создание корзины
            Cart cart = new Cart();

            // Организация - добавление нескольких игр в корзину
            cart.AddItem(game1, 1);
            cart.AddItem(game2, 4);
            cart.AddItem(game3, 2);
            cart.AddItem(game2, 1);

            // Действие
            cart.RemoveLine(game2);

            // Утверждение
            Assert.AreEqual(cart.Lines.Where(c => c.Game == game2).Count(), 0);
            Assert.AreEqual(cart.Lines.Count(), 2);
        }
Example #27
0
 public void Can_View_Cart_Contents()
 {
     // Arrange - create a Cart
     Cart cart = new Cart();
     // Arrange - create the controller
     CartController target = new CartController(null, null);
     // Act - call the Index action method
     CartIndexView result = (CartIndexView)target.Index(cart, "myUrl").ViewData.Model;
     // Assert
     Assert.AreSame(result.Cart, cart);
     Assert.AreEqual(result.ReturnUrl, "myUrl");
 }
Example #28
0
        public void Can_Clear_Contents()
        {
            // Организация - создание нескольких тестовых игр
            Game game1 = new Game { GameId = 1, Name = "Игра1", Price = 100 };
            Game game2 = new Game { GameId = 2, Name = "Игра2", Price = 55 };

            // Организация - создание корзины
            Cart cart = new Cart();

            // Действие
            cart.AddItem(game1, 1);
            cart.AddItem(game2, 1);
            cart.AddItem(game1, 5);
            cart.Clear();

            // Утверждение
            Assert.AreEqual(cart.Lines.Count(), 0);
        }
 public PartialViewResult Summary(Cart cart)
 {
     return PartialView(cart);
 }
 public ViewResult Checkout(Cart cart, ShippingDetails shippingDetails)
 {
     return View(new ShippingDetails());
 }