public ActionResult Create([Bind(Include = "ID,Name,Price,Description,Created,Modified")] Product product, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                product.Created  = DateTime.UtcNow;
                product.Modified = DateTime.UtcNow;
                //TODO: This is throwing an Error too, I think it's just because it's null. Do a check for if it's null.Same for Edit--if you don't explicitly
                //insert an image into the image field then it's going to throw a NullReferenceExceptions
                string fileName = image.FileName;

                if (ConfigurationManager.AppSettings["UseLocalStorage"] == "true")
                {
                    int i = 1;
                    while (System.IO.File.Exists(Server.MapPath("/content/images/" + fileName)))
                    {
                        fileName = System.IO.Path.GetFileNameWithoutExtension(fileName) + i.ToString() + System.IO.Path.GetExtension(fileName);
                        i++;
                    }
                    image.SaveAs(Server.MapPath("/content/images/" + fileName));
                    //fileName = "/content/images/" + fileName;
                }
                else
                {
                    CloudStorageAccount account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
                    var blobClient    = account.CreateCloudBlobClient();
                    var rootContainer = blobClient.GetRootContainerReference();
                    rootContainer.CreateIfNotExists();
                    rootContainer.SetPermissions(new BlobContainerPermissions {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });
                    var blob = rootContainer.GetBlockBlobReference(fileName);
                    blob.UploadFromStream(image.InputStream);

                    fileName = blob.Uri.ToString();
                }

                if (db.ProductImages.Any(x => x.ID == product.ID))
                {
                    ProductImage pi = db.ProductImages.FirstOrDefault(x => x.ProductID == product.ID);
                    pi.FilePath = "/content/images/" + fileName;
                    pi.Modified = DateTime.UtcNow;
                }
                else
                {
                    product.ProductImages.Add(new ProductImage
                    {
                        FilePath = "/content/images/" + fileName,
                        Created  = DateTime.UtcNow,
                        Modified = DateTime.UtcNow
                    });
                }

                db.Products.Add(product);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(product));
        }
Beispiel #2
0
        // GET: Cart
        public ActionResult Index()
        {
            ///////////
            CartModel model = new CartModel();

            using (AppStoreEntities entities = new AppStoreEntities())
            {
                Order o = null;
                //OrdersProduct item = null;
                if (User.Identity.IsAuthenticated)
                {
                    AspNetUser currentUser = entities.AspNetUsers.Single(x => x.UserName == User.Identity.Name);
                    o = currentUser.Orders.FirstOrDefault(x => x.TimeCompleted == null);
                    //item = o.OrderProducts.FirstOrDefault(x => x.OrderID == o.ID);
                    if (o == null)
                    {
                        o             = new Order();
                        o.OrderNumber = Guid.NewGuid();
                        currentUser.Orders.Add(o);
                        entities.SaveChanges();
                    }
                }
                ////////////
                else
                {
                    if (Request.Cookies.AllKeys.Contains("orderNumber"))
                    {
                        Guid orderNumber = Guid.Parse(Request.Cookies["orderNumber"].Value);
                        o = entities.Orders.FirstOrDefault(x => x.TimeCompleted == null && x.OrderNumber == orderNumber);
                        //item = o.OrderProducts.FirstOrDefault(x => x.OrderID == o.ID);
                    }
                    if (o == null)
                    {
                        o             = new Order();
                        o.OrderNumber = Guid.NewGuid();
                        entities.Orders.Add(o);
                        Response.Cookies.Add(new HttpCookie("orderNumber", o.OrderNumber.ToString()));
                        entities.SaveChanges();
                    }
                }
                ///////////
                model.Items = o.OrdersProducts.Select(x => new CartItemModel
                {
                    Product = new ProductModel
                    {
                        Description = x.Product.Description,
                        ID          = x.Product.ID,
                        Name        = x.Product.Name,
                        Price       = x.Product.Price,
                        Images      = x.Product.ProductImages.Select(y => y.FilePath)
                    },
                    Quantity = x.Quantity
                }).ToArray();
                model.SubTotal = o.OrdersProducts.Sum(x => x.Product.Price * x.Quantity);
            }
            //ViewBag.PageGenerationTime = DateTime.UtcNow;
            return(View(model));
        }
        public ActionResult Create([Bind(Include = "ID,Name,Description,Created,Modified")] Category category)
        {
            if (ModelState.IsValid)
            {
                db.Categories.Add(category);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(category));
        }
        public ActionResult Create([Bind(Include = "CategoryID,ProductID,Created,Modified")] CategoriesProduct categoriesProduct)
        {
            if (ModelState.IsValid)
            {
                db.CategoriesProducts.Add(categoriesProduct);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CategoryID = new SelectList(db.Categories, "ID", "Name", categoriesProduct.CategoryID);
            ViewBag.ProductID  = new SelectList(db.Products, "ID", "Name", categoriesProduct.ProductID);
            return(View(categoriesProduct));
        }
        public ActionResult Index(ProductModel model)
        {
            using (AppStoreEntities entities = new AppStoreEntities())
            {
                if (User.Identity.IsAuthenticated)
                {
                    AspNetUser currentUser = entities.AspNetUsers.Single(x => x.UserName == User.Identity.Name);
                    Order      o           = currentUser.Orders.FirstOrDefault(x => x.TimeCompleted == null);
                    if (o == null)
                    {
                        o             = new Order();
                        o.OrderNumber = Guid.NewGuid();
                        currentUser.Orders.Add(o);
                    }
                    var product = o.OrdersProducts.FirstOrDefault(x => x.ProductID == model.ID);
                    if (product == null)
                    {
                        product           = new OrdersProduct();
                        product.ProductID = model.ID ?? 0;
                        product.Quantity  = 0;
                        o.OrdersProducts.Add(product);
                    }
                    product.Quantity += 1;
                }
                else
                {
                    Order o = null;
                    if (Request.Cookies.AllKeys.Contains("orderNumber"))
                    {
                        Guid orderNumber = Guid.Parse(Request.Cookies["orderNumber"].Value);
                        o = entities.Orders.FirstOrDefault(x => x.TimeCompleted == null && x.OrderNumber == orderNumber);
                    }
                    if (o == null)
                    {
                        o             = new Order();
                        o.OrderNumber = Guid.NewGuid();
                        entities.Orders.Add(o);
                        Response.Cookies.Add(new HttpCookie("orderNumber", o.OrderNumber.ToString()));
                    }
                    var product = o.OrdersProducts.FirstOrDefault(x => x.ProductID == model.ID);
                    if (product == null)
                    {
                        product           = new OrdersProduct();
                        product.ProductID = model.ID ?? 0;
                        product.Quantity  = 0;
                        o.OrdersProducts.Add(product);
                    }
                    product.Quantity += 1;
                }

                entities.SaveChanges();
                TempData.Add("AddedToCart", true);
            }
            return(RedirectToAction("Index", "Cart"));
        }
Beispiel #6
0
        public ActionResult Create([Bind(Include = "ID,ProductID,Email,Rating,Body,Created,Modified")] Review review, int id)
        {
            if (ModelState.IsValid)
            {
                using (AppStoreEntities entities = new AppStoreEntities())
                {
                    if (User.Identity.IsAuthenticated)
                    {
                        review.Created   = DateTime.UtcNow;
                        review.Modified  = DateTime.UtcNow;
                        review.ProductID = id;
                        AspNetUser currentUser = entities.AspNetUsers.Single(x => x.UserName == User.Identity.Name);
                        review.Email = currentUser.Email;

                        db.Reviews.Add(review);
                        db.SaveChanges();
                    }
                }
            }
            return(RedirectToAction("Index", "Product", new { id = id }));

            //ViewBag.ProductID = new SelectList(db.Products, "ID", "Name", review.ProductID);
            //return View(review);
        }
Beispiel #7
0
        //////////

        public ActionResult RemoveItem(int?id)
        {
            using (AppStoreEntities entities = new AppStoreEntities())
            {
                if (User.Identity.IsAuthenticated)
                {
                    AspNetUser    currentUser = entities.AspNetUsers.Single(x => x.UserName == User.Identity.Name);
                    Order         o           = currentUser.Orders.FirstOrDefault(x => x.TimeCompleted == null);
                    OrdersProduct item        = o.OrdersProducts.FirstOrDefault(x => x.ProductID == id);
                    if (item.Quantity == 1)
                    {
                        item.Product.OrdersProducts = null;
                        if (o.OrdersProducts.Count == 1)
                        {
                            o.OrdersProducts = null;
                        }
                    }
                    else
                    {
                        item.Quantity -= 1;
                    }
                }
                else
                {
                    if (Request.Cookies.AllKeys.Contains("orderNumber"))
                    {
                        Guid          orderNumber = Guid.Parse(Request.Cookies["orderNumber"].Value);
                        Order         o           = entities.Orders.FirstOrDefault(x => x.TimeCompleted == null && x.OrderNumber == orderNumber);
                        OrdersProduct item        = o.OrdersProducts.FirstOrDefault(x => x.ProductID == id);
                        if (item.Quantity == 1)
                        {
                            item.Product.OrdersProducts = null;
                            if (o.OrdersProducts.Count == 1)
                            {
                                o.OrdersProducts = null;
                            }
                        }
                        else
                        {
                            item.Quantity -= 1;
                        }
                    }
                }
                entities.SaveChanges();
            }
            return(RedirectToAction("Index", "Cart"));
        }
Beispiel #8
0
        public async Task <ActionResult> Index(CheckoutModel model)
        {
            if (ModelState.IsValid)
            {
                using (AppStoreEntities entities = new AppStoreEntities())
                {
                    Order o = null;
                    if (User.Identity.IsAuthenticated)
                    {
                        AspNetUser currentUser = entities.AspNetUsers.Single(x => x.UserName == User.Identity.Name);
                        o = currentUser.Orders.FirstOrDefault(x => x.TimeCompleted == null);
                        if (o == null)
                        {
                            o             = new Order();
                            o.OrderNumber = Guid.NewGuid();
                            currentUser.Orders.Add(o);
                            entities.SaveChanges();
                        }
                    }
                    else
                    {
                        if (Request.Cookies.AllKeys.Contains("orderNumber"))
                        {
                            Guid orderNumber = Guid.Parse(Request.Cookies["orderNumber"].Value);
                            o = entities.Orders.FirstOrDefault(x => x.TimeCompleted == null && x.OrderNumber == orderNumber);
                        }
                        if (o == null)
                        {
                            o             = new Order();
                            o.OrderNumber = Guid.NewGuid();
                            entities.Orders.Add(o);
                            Response.Cookies.Add(new HttpCookie("orderNumber", o.OrderNumber.ToString()));
                            entities.SaveChanges();
                        }
                    }
                    if (o.OrdersProducts.Sum(x => x.Quantity) == 0)
                    {
                        return(RedirectToAction("Index", "Cart"));
                    }

                    o.BuyerEmail = User.Identity.Name;
                    Address newShippingAddress = new Address();
                    newShippingAddress.Address1 = model.ShippingAddress1;
                    newShippingAddress.Address2 = model.ShippingAddress2;
                    newShippingAddress.City     = model.ShippingCity;
                    newShippingAddress.State    = model.ShippingState;
                    newShippingAddress.Zip      = model.ZipCode;
                    newShippingAddress.Country  = model.ShippingCountry;
                    o.Address1 = newShippingAddress;

                    WhereTo = ("\n Your Order will be shipped to the following address: \n" + model.ShippingAddress1 + "\n " + model.ShippingAddress2 + "\n " + model.ShippingCity + "\n " + model.ShippingState + "\n " + model.ZipCode);

                    entities.sp_CompleteOrder(o.ID);

                    string merchantId  = ConfigurationManager.AppSettings["Braintree.MerchantID"];
                    string publicKey   = ConfigurationManager.AppSettings["Braintree.PublicKey"];
                    string privateKey  = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                    string environment = ConfigurationManager.AppSettings["Braintree.Environment"];

                    Braintree.BraintreeGateway braintree = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);

                    Braintree.TransactionRequest newTransaction = new Braintree.TransactionRequest();
                    newTransaction.Amount = o.OrdersProducts.Sum(x => x.Quantity * x.Product.Price) ?? 0.01m;

                    Braintree.TransactionCreditCardRequest creditCard = new Braintree.TransactionCreditCardRequest();
                    creditCard.CardholderName  = model.CreditCardName;
                    creditCard.CVV             = model.CreditCardVerificationValue;
                    creditCard.ExpirationMonth = model.CreditCardExpiration.Value.Month.ToString().PadLeft(2, '0');
                    creditCard.ExpirationYear  = model.CreditCardExpiration.Value.Year.ToString();
                    creditCard.Number          = model.CreditCardNumber;

                    newTransaction.CreditCard = creditCard;

                    // If the user is logged in, associate this transaction with their account
                    if (User.Identity.IsAuthenticated)
                    {
                        Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
                        search.Email.Is(User.Identity.Name);
                        var customers = braintree.Customer.Search(search);
                        newTransaction.CustomerId = customers.FirstItem.Id;
                    }

                    Braintree.Result <Braintree.Transaction> result = await braintree.Transaction.SaleAsync(newTransaction);

                    if (!result.IsSuccess())
                    {
                        ModelState.AddModelError("CreditCard", "Could not authorize payment");
                        return(View(model));
                    }

                    string sendGridApiKey = ConfigurationManager.AppSettings["SendGrid.ApiKey"];

                    SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridApiKey);
                    SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage();
                    //TODO: Go into SendGrid and set up a template and insert the if below
                    //message.SetTemplateId("524c7845-3ed9-4d53-81c8-b467443f8c5c");
                    message.Subject = string.Format("Receipt for order {0}", o.ID);
                    message.From    = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey");
                    message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(o.BuyerEmail));

                    string prodcuctsReceipt = "You've Ordered: ";
                    WhatWasOrdered = prodcuctsReceipt;

                    foreach (var item in o.OrdersProducts)
                    {
                        string addition = string.Format("\n " + "{0} copies of {1}", item.Quantity, item.Product.Name);
                        prodcuctsReceipt += addition;
                    }


                    SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/plain", string.Format("Thank you for ordering through Ye Olde App Store \n {0} {1}", prodcuctsReceipt, WhereTo));
                    message.AddSubstitution("%ordernum%", o.ID.ToString());
                    message.AddContent(contents.Type, contents.Value);

                    SendGrid.Response response = await client.SendEmailAsync(message);

                    o.TimeCompleted = DateTime.UtcNow;

                    entities.SaveChanges();
                }
                return(RedirectToAction("profile", "Home"));
            }
            return(View(model));
        }