public ViewResult Checkout(Cart cart)
        {
            ShippingDetails shippingDetails = new ShippingDetails();

            int userID = WebSecurity.CurrentUserId;
            IEnumerable<Customer> customers = repositoryCustomer.Customers.Where(x => x.UserID == userID);
            IEnumerable<Address> addresses = from x in repositoryAddress.Addresses
                                             join y in repositoryCustomer.Customers on x.CustomerID equals y.CustomerID
                                             where y.UserID == userID
                                             select x;
            foreach (var customer in customers)
            {
                shippingDetails.Name = customer.FirstName;
            }
            foreach (var address in addresses)
            {
                shippingDetails.Line1 = address.StreetLine1;
                shippingDetails.Line2  = address.StreetLine2;
                shippingDetails.Line3  = address.StreetLine3;
                shippingDetails.City  = address.City;
                shippingDetails.PostalCode  = address.PostalCode;
                shippingDetails.Country  = address.County;
            }

            //for testing
            //int rc = testStoreOfInfo(cart);

            return View(shippingDetails);
        }
        public RedirectToRouteResult AddToCart(Cart cart, int productId,
                string returnUrl)
        {
            Product product = repository.Products
                .FirstOrDefault(p => p.ProductID == productId);

            if (product != null) {
                cart.AddItem(product, 1);
            }
            return RedirectToAction("Index", new { returnUrl });
        }
        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 object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            // get the Cart from the session

            Cart cart = null;
            if (controllerContext.HttpContext.Session != null) {
                cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
            }
            // create the Cart if there wasn't one in the session data
            if (cart == null) {
                cart = new Cart();
                if (controllerContext.HttpContext.Session != null) {
                    controllerContext.HttpContext.Session[sessionKey] = cart;
                }
            }
            // return the cart
            return cart;
        }
        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);
        }
        public void Can_Add_New_Lines()
        {
            // Arrange - create some test products
            Product p1 = new Product { ProductID = 1, Name = "P1" };
            Product p2 = new Product { ProductID = 2, Name = "P2" };

            // Arrange - create a new cart
            Cart target = new Cart();

            // Act
            target.AddItem(p1, 1);
            target.AddItem(p2, 1);
            CartLine[] results = target.Lines.ToArray();

            // Assert
            Assert.AreEqual(results.Length, 2);
            Assert.AreEqual(results[0].Product, p1);
            Assert.AreEqual(results[1].Product, p2);
        }
        public void Can_Add_Quantity_For_Existing_Lines()
        {
            // Arrange - create some test products
            Product p1 = new Product { ProductID = 1, Name = "P1" };
            Product p2 = new Product { ProductID = 2, Name = "P2" };

            // Arrange - create a new cart
            Cart target = new Cart();

            // Act
            target.AddItem(p1, 1);
            target.AddItem(p2, 1);
            target.AddItem(p1, 10);
            CartLine[] results = target.Lines.OrderBy(c => c.Product.ProductID).ToArray();

            // Assert
            Assert.AreEqual(results.Length, 2);
            Assert.AreEqual(results[0].Quantity, 11);
            Assert.AreEqual(results[1].Quantity, 1);
        }
        public int testStoreOfInfo(Cart cart)
        {
            int orderID;

            string firstName,  lastName,  company,  email,
                streetLine1,  streetLine2,  streetLine3,
                city,  postalCode,  county,   country;
            string paymentConfirmation;

            firstName = "firstName";
            lastName = "lastName"; company = "company"; email = "email";
            streetLine1 = "streetLine1"; streetLine2 = "streetLine2"; streetLine3 = "streetLine3";
            city = "city"; postalCode = "postalCode"; county = "county"; country = "country";
            paymentConfirmation = "paymentConfirmation";

            orderID = StoreOrderAndOrderItems(cart);

            orderID = UpdateOrderShipTo(orderID, firstName, lastName, company, email,
                streetLine1, streetLine2, streetLine3,
                city, postalCode, county, country);

            orderID = UpdateOrderConfirmation(orderID, paymentConfirmation);

            return 1;
        }
 public PartialViewResult Summary(Cart cart)
 {
     return PartialView(cart);
 }
        public int StoreOrderAndOrderItems(Cart cart)
        {
            Order order = new Order();
            //order.OrderID
            order.OrderDate = DateTime.Now;
            order.ShipDate = DateTime.Now;
            order.TotalOrder = cart.ComputeTotalValue();
            order.ProductCount = cart.ComputeNumItems();
            order.FirstName = string.Empty;
            order.LastName = string.Empty;
            order.Company = string.Empty;
            order.Email = string.Empty;
            order.StreetLine1 = string.Empty;
            order.StreetLine2 = string.Empty;
            order.StreetLine3 = string.Empty;
            order.City = string.Empty;
            order.PostalCode = string.Empty;
            order.County = string.Empty;
            order.Country = string.Empty;
            order.PaymentConfirmation = string.Empty;
            order.CreatedAt = DateTime.Now;
            order.UpdatedAt = DateTime.Now;
            order.BillToAddressID = 1;
            order.ShipToAddressID = 1;
            order.CustomerID = 1;

            orderRepository.SaveOrder(order);

            foreach (var line in cart.Lines)
            {
                OrderItem orderItem = new OrderItem();

                Product product = repository.Products
                 .FirstOrDefault(p => p.ProductID == line.Product.ProductID);

                //orderItem.OrderItemID
                orderItem.Name = line.Product.Name;
                orderItem.Description= line.Product.Description;
                orderItem.Price = line.Product.Price;
                orderItem.Category = line.Product.Category;
                orderItem.Special = line.Product.Special;
                orderItem.ImageData = line.Product.ImageData;
                orderItem.ImageMimeType = line.Product.ImageMimeType;
                orderItem.Seller = line.Product.Seller;
                orderItem.Buyer = line.Product.Buyer;
                orderItem.Quantity = line.Quantity;
                orderItem.OrderID = order.OrderID;
                orderItem.ProductID = product.ProductID;
                orderItem.CategoryID = product.CategoryID;
                orderItemRepository.SaveOrderItem(orderItem);

            }

            return order.OrderID;
        }
        public RedirectToRouteResult RemoveFromCart(Cart cart, int productId,
                string returnUrl)
        {
            Product product = repository.Products
                .FirstOrDefault(p => p.ProductID == productId);

            if (product != null) {
                cart.RemoveLine(product);
            }
            return RedirectToAction("Index", new { returnUrl });
        }
 public ViewResult Index(Cart cart, string returnUrl)
 {
     return View(new CartIndexViewModel {
         ReturnUrl = returnUrl,
         Cart = cart
     });
 }
 public ActionResult Checkout(Cart cart, ShippingDetails shippingDetails)
 {
     return RedirectToAction("List", "Product");
     //return View("Completed");
 }
        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);
        }
        // PayPal
        public ActionResult CheckoutWithPayPal(Cart cart)
        {
            if (cart.Lines.Count() == 0)
            {
                ModelState.AddModelError("", "Sorry, your cart is empty!");
                return View("Completed");
            }
            else
            {

                int orderID = StoreOrderAndOrderItems(cart);
                UserSessionData.OrderID = orderID;

                NVPAPICaller payPalCaller = new NVPAPICaller();
                payPalCaller.SetCredentials();

                string retMsg = "";
                string token = "";
                decimal amtVal = cart.ComputeTotalValue();
                string amt = amtVal.ToString();
                bool ret = payPalCaller.ShortcutExpressCheckout(cart, amt, ref token, ref retMsg);
                if (ret)
                {

                    UserSessionData.Token = token;
                    UserSessionData.PaymentAmount = amtVal;

                    return Redirect(retMsg);
                }
                else
                {
                    return View("Completed");
                }
            }
        }
        public bool ShortcutExpressCheckout(Cart cart, string amt, ref string token, ref string retMsg)
        {
            int i;

            if (bSandbox)
            {
                pEndPointURL = pEndPointURL_SB;
                host = host_SB;
            }

            NVPCodec encoder = new NVPCodec();
            encoder["METHOD"] = "SetExpressCheckout";
            encoder["RETURNURL"] = returnURL;
            encoder["CANCELURL"] = cancelURL;
            encoder["BRANDNAME"] = "NCIRL Web Store";
            encoder["PAYMENTREQUEST_0_AMT"] = amt;
            encoder["PAYMENTREQUEST_0_ITEMAMT"] = amt;
            encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
            encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "EUR";

            i = 0;
            foreach (var line in cart.Lines)
            {
                encoder["L_PAYMENTREQUEST_0_NAME" + i] = line.Product.Name.ToString();
                encoder["L_PAYMENTREQUEST_0_AMT" + i] = line.Product.Price.ToString();
                encoder["L_PAYMENTREQUEST_0_QTY" + i] = line.Quantity.ToString();
                i++;
            }

            string pStrrequestforNvp = encoder.Encode();
            string pStresponsenvp = HttpCall(pStrrequestforNvp);

            NVPCodec decoder = new NVPCodec();
            decoder.Decode(pStresponsenvp);

            string strAck = decoder["ACK"].ToLower();
            if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
            {
                token = decoder["TOKEN"];
                string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
                retMsg = ECURL;
                return true;
            }
            else
            {
                retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
                    "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
                    "Desc2=" + decoder["L_LONGMESSAGE0"];
                return false;
            }
        }
        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(shippingInfo.PostalCode ?? "")
                    .AppendLine("---")
                    .AppendFormat("Gift wrap: {0}",
                        shippingInfo.GiftWrap ? "Yes" : "No");

                MailMessage mailMessage = new MailMessage(
                                       emailSettings.MailFromAddress,   // From
                                       emailSettings.MailToAddress,     // To
                                       "New order submitted!",          // Subject
                                       body.ToString());                // Body

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

                smtpClient.Send(mailMessage);
            }
        }