Ejemplo n.º 1
0
        public async Task <IActionResult> PutCart(int id, Cart cart)
        {
            if (id != cart.CartId)
            {
                return(BadRequest());
            }

            _context.Entry(cart).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CartExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Ejemplo n.º 2
0
        public async Task when_an_item_is_in_stock__Then_it_can_be_added_to_a_users_basket()
        {
            //arrange
            var user = new User {
                Basket = new Basket()
            };
            var item = new Item {
                Name        = "a name",
                Description = "a descirption",
                Stock       = 1,
                Price       = 10.0M
            };

            _context.Users.Add(user);
            _context.Items.Add(item);
            await _context.SaveChangesAsync();

            //act
            await this._testClass.AddItemsToBasket(user.Id, new List <BasketItemDto> {
                new BasketItemDto {
                    ItemId   = item.Id,
                    Quantity = 1
                }
            });

            //assert
            user =
                await _context.Users
                .Include(x => x.Basket)
                .SingleAsync(x => x.Id == user.Id);

            Assert.Equal(item.Id, user.Basket.Items.Single().Item.Id);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> PutCustomers(Guid id, Customers customers)
        {
            if (id != customers.Id)
            {
                return(BadRequest());
            }

            _context.Entry(customers).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomersExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Ejemplo n.º 4
0
        public async Task <ActionResult> EditShipment(ShipmentViewModel model)
        {
            using (var context = new ShoppingCartContext())
            {
                //new item
                if (model.Id == 0)
                {
                    var shipment = new Shipment
                    {
                        Code      = model.Code,
                        Recipient = model.Recipient,
                        ShipDate  = DateTime.Parse(model.ShipDate),
                    };

                    context.Shipments.Add(shipment);
                    await context.SaveChangesAsync();

                    var orderLists = model.OrderIdsString.Split(',');

                    context.Orders.Where(o => orderLists.Contains(o.OrderNumber.ToString())).ForEach(order =>
                    {
                        order.ShipmentId = shipment.Id;
                    });
                }

                await context.SaveChangesAsync();
            }
            return(View());
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Detail(ShoppingCart CartObject)
        {
            CartObject.Id = 0;

            //  var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            //   var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
            //   CartObject.UserId = claim.Value;

            CartObject.UserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            ShoppingCart cartFromDb = await _c.ShopingCart.Where(c => c.UserId == CartObject.UserId &&
                                                                 c.ArtworkId == CartObject.ArtworkId).FirstOrDefaultAsync();

            if (cartFromDb == null)
            {
                await _c.ShopingCart.AddAsync(CartObject);
            }
            else
            {
                cartFromDb.Count = cartFromDb.Count + CartObject.Count;
            }
            await _c.SaveChangesAsync();

            var count = _c.ShopingCart.Where(c => c.UserId == CartObject.UserId).ToList().Count();

            HttpContext.Session.SetInt32("ssCartCount", count);

            return(RedirectToAction("Desc"));
        }
Ejemplo n.º 6
0
        public async Task <bool> Delete(long id)
        {
            try
            {
                var product = await Get(id);

                _context.Products.Remove(product);
                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public override async Task <ShoppingCartModel> CreateShoppigCart(ShoppingCartModel request, ServerCallContext context)
        {
            var shoppingCart = _mapper.Map <ShoppingCart>(request);
            var isExists     = await _shoppingCartContext.ShoppingCarts.AnyAsync(x => x.UserName == shoppingCart.UserName);

            if (isExists)
            {
                throw new RpcException(new Status(StatusCode.NotFound, "Invalid Request."));
            }

            _shoppingCartContext.ShoppingCarts.Add(shoppingCart);
            await _shoppingCartContext.SaveChangesAsync();

            var shoppingCartModel = _mapper.Map <ShoppingCartModel>(request);

            return(shoppingCartModel);
        }
        public override async Task <ShoppingCartModel> CreateShoppingCart(ShoppingCartModel request, ServerCallContext context)
        {
            var shoppingCart = _mapper.Map <ShoppingCart>(request);

            var isExist = await _shoppingCartContext.ShoppingCart.AnyAsync(s => s.UserName == shoppingCart.UserName);

            if (isExist)
            {
                _logger.LogError($"Invalid UserName for ShoppingCart creation. UserName : {shoppingCart.UserName}");
                throw new RpcException(new Status(StatusCode.NotFound, $"ShoppingCart with UserName = {request.Username} is already exist."));
            }

            _shoppingCartContext.ShoppingCart.Add(shoppingCart);
            await _shoppingCartContext.SaveChangesAsync();

            _logger.LogInformation($"ShoppingCart is successfully created.UserName : {shoppingCart.UserName}");

            return(_mapper.Map <ShoppingCartModel>(shoppingCart));
        }
Ejemplo n.º 9
0
        public async Task CreateCartItem(CartItemDTO cartItem)
        {
            CartItem myCartItem = new CartItem()
            {
                ProductId = cartItem.ProductId,
                Product   = cartItem.Product,
                Price     = cartItem.Price,
                Quantity  = cartItem.Quantity
            };
            await _context.CartItems.AddAsync(myCartItem);                                                   //Add CartItem to CartItems table

            await _context.SaveChangesAsync();                                                               //Save all the changes

            await _context.CartItems.Include(i => i.Product).Include(i => i.Product.Category).ToListAsync(); //shows the Product entity(with it's Category) inside CartItem

            cartItem.ProductId = myCartItem.ProductId;

            cartItem.Product = myCartItem.Product;//this makes product not to be null in postman
        }
Ejemplo n.º 10
0
        public async Task CreateCategory(CategoryDTO category)
        {
            //create new object
            Category myCategory = new Category()
            {
                //We do not pass CategoryId here becuase Identity column auto generates CategoryId While creating a new category
                //In this case we do not have collision in our database
                CategoryName = category.CategoryName
            };
            await _context.Categories.AddAsync(myCategory); //Add myCategory to Categories table

            await _context.SaveChangesAsync();              //Save all the changes

            //Now when we added myCategory to database and saved the changes, then CategoryId is generated automatically
            //i.e myCategory.CategoryId is auto generated
            //we want to pass CategoryId back with our DTO
            //this is how we add CategoryId to our DTO and return it
            category.CategoryId = myCategory.CategoryId;
        }
Ejemplo n.º 11
0
        public override async Task <ShoppingCartModel> CreateShoppingCart(ShoppingCartModel request, ServerCallContext context)
        {
            var shooppingCart = _mapper.Map <ShoppingCart>(request);

            var isExist = await _shoppingCartContext.ShoppingCarts
                          .AnyAsync(r => r.UserName == shooppingCart.UserName);

            if (isExist)
            {
                _logger.LogError($"CreateShoppingCart for {request.Username}");
                throw new RpcException(new Status(StatusCode.AlreadyExists, "There is shoppingCart"));
            }

            _shoppingCartContext.ShoppingCarts.Add(shooppingCart);
            await _shoppingCartContext.SaveChangesAsync();

            var shoppingCartModel = _mapper.Map <ShoppingCartModel>(shooppingCart);


            return(shoppingCartModel);
        }
Ejemplo n.º 12
0
        public async Task CreateProduct(ProductDTO product)
        {
            Product myProduct = new Product()
            {
                //ProductId is Auto generated
                ProductName = product.ProductName,
                Price       = product.Price,
                CategoryId  = product.CategoryId,
                Category    = product.Category
            };

            await _context.Products.AddAsync(myProduct); //Add Product to Products table

            await _context.SaveChangesAsync();           //Save all the changes

            await _context.Products.Include(i => i.Category).ToListAsync();

            product.ProductId = myProduct.ProductId;

            product.Category = myProduct.Category;//this makes the Category not become null
        }
Ejemplo n.º 13
0
        public async Task <bool> AddToCart(string productId, string deviceId, string userId)
        {
            var cart = await GetCurrentCartForUser(deviceId, userId);

            if (cart == null)
            {
                cart            = new Models.ShoppingCart();
                cart.ClientGuid = deviceId;

                if (userId != null)
                {
                    try
                    {
                        cart.User = _context.Users.SingleOrDefault(u => u.Id == Int32.Parse(userId));
                    }
                    catch (Exception e)
                    {
                        return(false);
                    }
                }

                _context.ShoppingCarts.Add(cart);
            }

            var item = _context.ProductShoppingCarts.SingleOrDefault(
                pc => pc.ShoppingCartId == cart.ShoppingCartId && pc.ProductId == Int32.Parse(productId)
                );

            if (item == null)
            {
                item                = new ProductShoppingCart();
                item.ProductId      = Int32.Parse(productId);
                item.ShoppingCartId = cart.ShoppingCartId;
                cart.ProductShoppingCarts.Add(item);

                await _context.SaveChangesAsync();
            }

            return(true);
        }
Ejemplo n.º 14
0
        public async Task <ActionResult> EditAppSetting(AppSettingViewModel model)
        {
            if (ModelState.IsValid)
            {
                var id = (int)TempData["AppSettingEditId"];
                using (var context = new ShoppingCartContext())
                {
                    if (id > 0)
                    {
                        var appSeting = context.AppSettings.Single(c => c.Id == id);
                        appSeting.Description = model.Description;
                        appSeting.Code        = model.Code;
                        appSeting.Value       = model.Value;
                        appSeting.ValueType   = model.ValueType;


                        await context.SaveChangesAsync();
                    }
                    else
                    {
                        var ret = new AppSetting
                        {
                            Code        = model.Code,
                            Description = model.Description,
                            Value       = model.Value,
                            ValueType   = model.ValueType
                        };

                        context.AppSettings.Add(ret);

                        await context.SaveChangesAsync();
                    }
                }
            }
            return(View());
        }
Ejemplo n.º 15
0
            public async Task <Unit> Handle(Execute request, CancellationToken cancellationToken)
            {
                var shoppingCart = new Models.ShoppingCart
                {
                    CreationDate = request.CreationDate
                };

                _context.ShoppingCart.Add(shoppingCart);
                var rows = await _context.SaveChangesAsync();

                if (rows == 0)
                {
                    throw new Exception("There was an error creating Shopping Cart");
                }

                int id = shoppingCart.ShoppingCartId;

                foreach (var item in request.ProductsList)
                {
                    var shoopingCartDetail = new ShoppingCartDetail
                    {
                        CreationDate    = DateTime.Now,
                        ShoppingCartId  = id,
                        SelectedProduct = item
                    };
                    _context.ShoppingCartDetail.Add(shoopingCartDetail);
                }

                id = await _context.SaveChangesAsync();

                if (id > 0)
                {
                    return(Unit.Value);
                }
                throw new Exception("There was an error inserting Shopping Cart details");
            }
Ejemplo n.º 16
0
        public async Task <User> Create(User user)
        {
            var tUser = await Login(user.Email, user.Password);

            if (tUser != null)
            {
                throw new Exception("User already exists");
            }

            try{
                _context.Users.Add(user);
                await _context.SaveChangesAsync();

                return(user);
            }catch (Exception) {
                return(null);
            }
        }
Ejemplo n.º 17
0
        public async Task ImportItems()
        {
            var fileName = "example_data.csv";
            var rows     = File.ReadAllLines(fileName).Skip(1);
            var items    = rows.Select(x =>
            {
                var fields = x.Split(',');
                return(new Item
                {
                    Name = fields[1],
                    Description = fields[2],
                    Stock = Int32.Parse(fields[3]),
                    Price = Decimal.Parse(fields[4])
                });
            });

            _context.Items.AddRange(items);
            await _context.SaveChangesAsync();
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> Create([Bind("Name,Price")] Item item)
        {
            try
            {
                item.Type = ItemType.Service;

                if (ModelState.IsValid)
                {
                    _context.Add(item);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. ");
            }
            return(View(item));
        }
Ejemplo n.º 19
0
        public async Task <ActionResult> EditOrder(OrderDetailSummaryViewModel model)
        {
            if (ModelState.IsValid)
            {
                string paymentStatus = Request.Form["paymentStatus"].ToString();
                string paymentType   = Request.Form["paymentType"].ToString();
                string orderStatus   = Request.Form["orderStatus"].ToString();

                var order = _context.Orders.Single(o => o.OrderNumber == model.OrderNumber);
                //var id = TempData["OrderId"];
                //var id = model.OrderId;

                order.PaymentTransaction.Amount = model.PaymentTransaction.Amount;
                order.PostedAmount = model.PaymentTransaction.Amount;
                order.PaymentTransaction.PaymentStatusId = _context.PaymentStatuses.Single(p => p.Description == paymentStatus).Id;
                //order.TrueProfit = model.TrueProfit - (model.Discount/2);
                //order.Commission = model.Commission - (model.Discount/2);
                order.Profit -= model.Discount - order.Discount;

                order.Total = order.Total + order.Discount - model.Discount;

                order.Discount = model.Discount;


                order.PaymentTransaction.PaymentTypeId =
                    _context.PaymentTypes.Single(p => p.Description == paymentType).Id;

                order.OrderStatusId = _context.OrderStatuses.Single(s => s.Description == orderStatus).Id;
                order.Notes         = model.OrderStatusNote;

                await _context.SaveChangesAsync();

                return(RedirectToAction("ViewOrder", new { order.Id }));
            }

            return(View());
        }
Ejemplo n.º 20
0
        public async Task when_an_order_is_placed__Then_an_order_is_created_and_the_items_stock_is_updated()
        {
            //arrange
            var user = new User {
                Basket = new Basket {
                    Items = new List <BasketItem> {
                        new BasketItem {
                            Item = new Item {
                                Name        = "a name",
                                Description = "a description",
                                Stock       = 1,
                                Price       = 10.0M
                            },
                            Quantity = 1
                        }
                    }
                }
            };

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            //act
            await this._testClass.Add(user.Id);

            //assert
            var order = await _context.Orders.SingleAsync();

            Assert.Equal(1, order.Items.Count());
            var item = await _context.Items.SingleAsync(x => x.Id == order.Items.Single().Item.Id);

            Assert.Equal(0, item.Stock);
            user = await _context.Users.SingleAsync(x => x.Id == user.Id);

            Assert.Equal(0, user.Basket.Items.Count());
        }
        public async Task <ActionResult> EditProduct(EditProductViewModel model)
        {
            var id = (int)TempData["ProductEditId"];

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (var context = new ShoppingCartContext())
            {
                //new product
                if (id == -1)
                {
                    var newProd = new Product()
                    {
                        Code = SeqHelper.Next("Item").ToString(),
                        //Code = (string.IsNullOrEmpty(model.ProductView.Code)) ? SeqHelper.Next("Item").ToString() : (model.ProductView.Code),
                        Description    = model.ProductView.Description,
                        FeatureProduct = true,
                        //Weight = 0.5m,
                        //QuantityOnHand = 22,
                        BuyInPrice        = model.ProductView.BuyInPrice,
                        DetailDescription = model.ProductView.DetailDescription,
                        Categories        = new List <Category>()
                        {
                            context.Categories.SingleOrDefault(c => c.Code == "1001")
                        },
                        Active         = model.ProductView.Active,
                        Notes          = model.ProductView.Notes,
                        ReviewVideoUrl = (model.ProductView.ReviewVideoUrl.IsNullOrWhiteSpace()) ? "" : model.ProductView.ReviewVideoUrl
                    };

                    if (model.ProductView.ProductImage != null)
                    {
                        if (model.ProductView.ProductImage.ContentLength > (4 * 1024 * 1024))
                        {
                            ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return(View());
                        }
                        if (
                            !(model.ProductView.ProductImage.ContentType == "image/jpeg" ||
                              model.ProductView.ProductImage.ContentType == "image/gif"))
                        {
                            ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                            return(View());
                        }

                        byte[] data = new byte[model.ProductView.ProductImage.ContentLength];
                        model.ProductView.ProductImage.InputStream.Read(data, 0,
                                                                        model.ProductView.ProductImage.ContentLength);

                        newProd.Image = data;
                    }

                    //alt image 0
                    if (model.ProductView.ProductImageAlt0 != null)
                    {
                        if (model.ProductView.ProductImageAlt0.ContentLength > (4 * 1024 * 1024))
                        {
                            ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return(View());
                        }
                        if (
                            !(model.ProductView.ProductImageAlt0.ContentType == "image/jpeg" ||
                              model.ProductView.ProductImageAlt0.ContentType == "image/gif"))
                        {
                            ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                        }

                        byte[] data = new byte[model.ProductView.ProductImageAlt0.ContentLength];
                        model.ProductView.ProductImageAlt0.InputStream.Read(data, 0,
                                                                            model.ProductView.ProductImageAlt0.ContentLength);

                        newProd.ImageAlt0 = data;
                    }

                    //alt image 1
                    if (model.ProductView.ProductImageAlt1 != null)
                    {
                        if (model.ProductView.ProductImageAlt1.ContentLength > (4 * 1024 * 1024))
                        {
                            ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return(View());
                        }
                        if (
                            !(model.ProductView.ProductImageAlt1.ContentType == "image/jpeg" ||
                              model.ProductView.ProductImageAlt1.ContentType == "image/gif"))
                        {
                            ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                        }

                        byte[] data = new byte[model.ProductView.ProductImageAlt1.ContentLength];
                        model.ProductView.ProductImageAlt1.InputStream.Read(data, 0,
                                                                            model.ProductView.ProductImageAlt1.ContentLength);

                        newProd.ImageAlt1 = data;
                    }

                    context.Products.Add(newProd);
                    await context.SaveChangesAsync();


                    id = newProd.Id;

                    //update pricing
                    foreach (var p in model.Offers)
                    {
                        context.ProductOffers.Add(new ProductOffer()
                        {
                            ProductId   = id,
                            PriceTypeId = p.PriceTypeId,
                            Price       = p.Price
                        });
                    }

                    //weight
                    decimal ounces = model.ProductView.WeightOunce;
                    decimal lbs    = model.ProductView.WeightPounds;
                    decimal weight = lbs + (ounces / 16);
                    newProd.Weight = weight;

                    //quantity on hand
                    newProd.QuantityOnHand = model.ProductView.QuantityOnHand;

                    //categories
                    foreach (var cat in model.Categories)
                    {
                        if (cat.IsChecked)
                        {
                            newProd.Categories.Add(context.Categories.Single(c => c.Code == cat.Code));
                        }
                    }

                    await context.SaveChangesAsync();

                    //return View("Index");
                    //return RedirectToAction("EditProduct", newProd.Id);
                }
                else
                {
                    //existing product
                    var product = context.Products.Single(p => p.Id == id);

                    //string paymentTypeValue = Request.Form["paymentType"].ToString();

                    product.Description = model.ProductView.Description;
                    //product.Code = model.ProductView.Code;
                    product.DetailDescription = model.ProductView.DetailDescription;
                    product.BuyInPrice        = model.ProductView.BuyInPrice;
                    product.Active            = model.ProductView.Active;
                    product.Notes             = model.ProductView.Notes;
                    product.ReviewVideoUrl    = (model.ProductView.ReviewVideoUrl.IsNullOrWhiteSpace())
                        ? ""
                        : model.ProductView.ReviewVideoUrl;

                    if (model.ProductView.ProductImage != null)
                    {
                        if (model.ProductView.ProductImage.ContentLength > (4 * 1024 * 1024))
                        {
                            ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return(View());
                        }
                        if (
                            !(model.ProductView.ProductImage.ContentType == "image/jpeg" ||
                              model.ProductView.ProductImage.ContentType == "image/gif"))
                        {
                            ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                        }

                        byte[] data = new byte[model.ProductView.ProductImage.ContentLength];
                        model.ProductView.ProductImage.InputStream.Read(data, 0,
                                                                        model.ProductView.ProductImage.ContentLength);

                        product.Image = data;
                    }

                    //alt image 0
                    if (model.ProductView.ProductImageAlt0 != null)
                    {
                        if (model.ProductView.ProductImageAlt0.ContentLength > (4 * 1024 * 1024))
                        {
                            ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return(View());
                        }
                        if (
                            !(model.ProductView.ProductImageAlt0.ContentType == "image/jpeg" ||
                              model.ProductView.ProductImageAlt0.ContentType == "image/gif"))
                        {
                            ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                        }

                        byte[] data = new byte[model.ProductView.ProductImageAlt0.ContentLength];
                        model.ProductView.ProductImageAlt0.InputStream.Read(data, 0,
                                                                            model.ProductView.ProductImageAlt0.ContentLength);

                        product.ImageAlt0 = data;
                    }

                    //alt image 1
                    if (model.ProductView.ProductImageAlt1 != null)
                    {
                        if (model.ProductView.ProductImageAlt1.ContentLength > (4 * 1024 * 1024))
                        {
                            ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return(View());
                        }
                        if (
                            !(model.ProductView.ProductImageAlt1.ContentType == "image/jpeg" ||
                              model.ProductView.ProductImageAlt1.ContentType == "image/gif"))
                        {
                            ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                        }

                        byte[] data = new byte[model.ProductView.ProductImageAlt1.ContentLength];
                        model.ProductView.ProductImageAlt1.InputStream.Read(data, 0,
                                                                            model.ProductView.ProductImageAlt1.ContentLength);

                        product.ImageAlt1 = data;
                    }

                    //update pricing
                    foreach (var p in model.Offers)
                    {
                        var update = context.ProductOffers.SingleOrDefault(
                            po => po.ProductId == product.Id && p.PriceTypeId == po.PriceTypeId);
                        if (update != null)
                        {
                            update.Price = p.Price;
                        }
                        else
                        {
                            context.ProductOffers.Add(new ProductOffer()
                            {
                                ProductId    = product.Id,
                                PriceTypeId  = p.PriceTypeId,
                                Discountable = true,
                                Price        = p.Price,
                                Code         = product.Code + "-" + "O"
                            });
                        }
                    }

                    //weight
                    decimal ounces = model.ProductView.WeightOunce;
                    decimal lbs    = model.ProductView.WeightPounds;
                    decimal weight = lbs + (ounces / 16);
                    product.Weight = weight;


                    //quantity on hand
                    product.QuantityOnHand = model.ProductView.QuantityOnHand;


                    //categories
                    model.ProductView.Categories.AddRange(
                        context.Products.Where(p => p.Id == id).SelectMany(prod => prod.Categories));

                    var setCat = model.ProductView.Categories;

                    //load both  collection before removing many-to-many can work !
                    context.Entry(product).Collection("Categories").Load();

                    foreach (var cat in model.Categories)
                    {
                        if (cat.IsChecked && !setCat.Select(c => c.Code).ToList().Contains(cat.Code))
                        {
                            product.Categories.Add(context.Categories.Single(c => c.Code == cat.Code));
                        }
                        if (!cat.IsChecked && setCat.Select(c => c.Code).ToList().Contains(cat.Code))
                        {
                            product.Categories.Remove(context.Categories.Single(c => c.Code == cat.Code));
                        }
                    }

                    await context.SaveChangesAsync();
                }

                return(RedirectToAction("EditProduct", id));
            }
        }
        public async Task <ActionResult> EditCategory(CategoryViewModel model)
        {
            if (ModelState.IsValid)
            {
                var id = (int)TempData["CategoryEditId"];
                using (var context = new ShoppingCartContext())
                {
                    if (id > 0)
                    {
                        var cat = context.Categories.Single(c => c.Id == id);
                        cat.Description = model.Description;

                        if (model.IconImage != null)
                        {
                            if (model.IconImage.ContentLength > (4 * 1024 * 1024))
                            {
                                ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                                return(View());
                            }
                            if (
                                !(model.IconImage.ContentType == "image/jpeg" ||
                                  model.IconImage.ContentType == "image/gif"))
                            {
                                ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                            }

                            byte[] data = new byte[model.IconImage.ContentLength];
                            model.IconImage.InputStream.Read(data, 0,
                                                             model.IconImage.ContentLength);

                            cat.Icon = data;
                        }

                        cat.Active = model.Active;

                        await context.SaveChangesAsync();

                        return(RedirectToAction("EditCategory", cat.Id));
                    }
                    else
                    {
                        var ret = new Category();
                        ret.Code        = SeqHelper.Next("Category").ToString();
                        ret.Description = model.Description;

                        if (model.IconImage != null)
                        {
                            if (model.IconImage.ContentLength > (4 * 1024 * 1024))
                            {
                                ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                                return(View());
                            }
                            if (
                                !(model.IconImage.ContentType == "image/jpeg" ||
                                  model.IconImage.ContentType == "image/gif"))
                            {
                                ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                            }

                            byte[] data = new byte[model.IconImage.ContentLength];
                            model.IconImage.InputStream.Read(data, 0,
                                                             model.IconImage.ContentLength);

                            ret.Icon = data;
                        }
                        ret.Active = model.Active;

                        context.Categories.Add(ret);

                        await context.SaveChangesAsync();

                        return(RedirectToAction("EditCategory", ret.Id));
                    }
                }
            }
            return(View());
        }
 public async Task <int> SaveAsync() => await _context.SaveChangesAsync();
Ejemplo n.º 24
0
 public async Task Commit()
 {
     await _context.SaveChangesAsync();
 }
Ejemplo n.º 25
0
        public async Task <IActionResult> Checkout([FromBody] Order order)
        {
            var customer = _shoppingCartContext.Customer.SingleOrDefault(c => c.Name == order.Customer);

            if (customer == null)
            {
                return(BadRequest());
            }

            order.Id = Guid.NewGuid();

            var shoppingCart = await _repository.GetShoppingCartAsync(order.Customer);

            if (shoppingCart == null)
            {
                return(BadRequest());
            }
            order.Date = DateTime.Now;

            if (customer.Type == CustomerType.Silver)
            {
                order.Amount = order.Amount * (decimal)0.98;
            }
            else if (customer.Type == CustomerType.Silver)
            {
                order.Amount = order.Amount * (decimal)0.97;
            }

            var lastYearOrders  = _shoppingCartContext.Order.Where(x => x.Date >= DateTime.Now.AddYears(-1)).Sum(x => x.Amount) + order.Amount;
            var oldCustomerType = customer.Type;

            if (lastYearOrders >= 500 && lastYearOrders < 800)
            {
                customer.Type = CustomerType.Silver;
            }
            else if (lastYearOrders >= 800)
            {
                customer.Type = CustomerType.Gold;
            }

            if (customer.Type != oldCustomerType)
            {
                _shoppingCartContext.Update(customer);
            }

            var orderLine = new OrderLine()
            {
                OrderId  = order.Id,
                Products = shoppingCart.Products
            };

            _shoppingCartContext.Order.Add(order);
            _shoppingCartContext.OrderLine.Add(orderLine);
            await _shoppingCartContext.SaveChangesAsync();

            if (!_paymentProvider.Authorize(customer.Name, order.Amount))
            {
                return(BadRequest());
            }

            //Notify customer
            await _notificationProvider.SendEmailAsync(customer.Email, $"Order {order.Id} is placed", "Thank you for your order");

            //Notify courier
            await _notificationProvider.SendEmailAsync("courier@localhost", $"Order {order.Id} is placed", $"The order will be send to {order.Address}");

            return(Ok(order));
        }
Ejemplo n.º 26
0
        public async Task <ActionResult> EditContent(ContentDetailSummaryViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("EditContent", model));
            }


            using (var context = new ShoppingCartContext())
            {
                string contentTypeSelected = Request.Form["contentTypeSelection"].ToString();

                if (contentTypeSelected == "None")
                {
                    ModelState.AddModelError("ContentType", "Please select content type");
                    return(View("EditContent", model));
                }
                string contentType = context.ContentTypes.Single(t => t.Code == contentTypeSelected).Code;

                //edit existing
                if (model.Id > 0)
                {
                    var content = context.Contents.Single(c => c.Id == model.Id);
                    content.Description   = model.Description;
                    content.ContentTypeId = context.ContentTypes.Single(ct => ct.Code == contentType).Id;

                    if (contentType == "Ad")
                    {
                        //int itemId = context.Products.Single(p => p.Code == model.ItemCode).Id;
                        //content.ImageUrl = string.Format("/Store/Details/{0}", itemId);
                        content.ImageUrl = model.RouteTo;
                        //content.ItemCode = model.ItemCode;
                        content.DisplayOrder = model.DisplayOrder;
                        content.AdText       = model.AdText;
                        content.AdTextStyle  = model.AdTextStyle;

                        if (model.ContentImage != null)
                        {
                            if (model.ContentImage.ContentLength > (4 * 1024 * 1024))
                            {
                                ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            }
                            if (
                                !(model.ContentImage.ContentType == "image/jpeg" ||
                                  model.ContentImage.ContentType == "image/gif"))
                            {
                                ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                            }

                            byte[] data = new byte[model.ContentImage.ContentLength];
                            model.ContentImage.InputStream.Read(data, 0,
                                                                model.ContentImage.ContentLength);

                            content.Image = data;
                        }
                    }


                    if (contentType == "Text")
                    {
                        content.TextLocation = model.TextLocation;
                        content.TextValue    = model.TextValue;
                    }

                    await context.SaveChangesAsync();
                }
                else
                {
                    var newContent = new Content()
                    {
                        Code          = SeqHelper.Next("Content").ToString(),
                        Description   = model.Description,
                        ContentTypeId = context.ContentTypes.Single(ct => ct.Code == contentType).Id,
                    };


                    if (contentType == "Ad")
                    {
                        //int itemId = context.Products.Single(p => p.Code == model.ItemCode).Id;
                        newContent.ImageUrl = model.RouteTo;
                        //newContent.ImageUrl = string.Format("/Store/Details/{0}", itemId);
                        //newContent.ItemCode = model.ItemCode;
                        newContent.DisplayOrder = model.DisplayOrder;
                        newContent.AdText       = model.AdText;
                        newContent.AdTextStyle  = model.AdTextStyle;

                        if (model.ContentImage != null)
                        {
                            if (model.ContentImage.ContentLength > (4 * 1024 * 1024))
                            {
                                ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            }
                            if (
                                !(model.ContentImage.ContentType == "image/jpeg" ||
                                  model.ContentImage.ContentType == "image/gif"))
                            {
                                ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                            }

                            byte[] data = new byte[model.ContentImage.ContentLength];
                            model.ContentImage.InputStream.Read(data, 0,
                                                                model.ContentImage.ContentLength);

                            newContent.Image = data;
                        }
                    }

                    if (contentType == "Text")
                    {
                        newContent.TextLocation = model.TextLocation;
                        newContent.TextValue    = model.TextValue;
                    }


                    context.Contents.Add(newContent);
                    await context.SaveChangesAsync();

                    var newId = newContent.Id;
                    return(RedirectToAction("EditContent", "ContentManagement", new { id = newId, contentType = contentType }));
                }
                return(RedirectToAction("EditContent", "ContentManagement", new { id = model.Id, contentType = contentType }));
            }
        }