Ejemplo n.º 1
0
 [HttpPost] //JSON
 public Guid?PostFromBody([FromBody] ProductCreateInputModel model)
 {
     return(ModelState.IsValid  ? _productService.InserProduct(new ProductModel()
     {
         Id = model.Id, Name = model.Name, Price = model.Price
     }).Id : null as Guid?);
 }
Ejemplo n.º 2
0
        public async Task CreateProduct_WithCorrectData_ShouldSuccessfullyCreate()
        {
            var list = new List <Product>();

            var mockRepo = new Mock <IDeletableEntityRepository <Product> >();

            mockRepo.Setup(x => x.All()).Returns(list.AsQueryable());
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Product>())).Callback((Product product) => list.Add(product));

            var service = new ProductService(mockRepo.Object);

            IFormFile image = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, "Data", "dummy.png");

            var newsCreateInput = new ProductCreateInputModel
            {
                UserId      = 6,
                Name        = "Arsenal Hat 2020",
                Price       = 25M,
                Description = null,
                Quantity    = 20,
                Image       = image,
            };

            await service.CreateAsync(newsCreateInput, "12", "/img/Arsenal_FC.png");

            Assert.Single(list.Where(x => x.CreatedByUserId == "12"));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Post([FromBody] ProductCreateInputModel model)
        {
            try
            {
                if (model == null)
                {
                    throw new Exception("Name and price is required.");
                }
                else
                {
                    if (!ModelState.IsValid)
                    {
                        throw new Exception("Name is required and has to be between 1 and 100 characters.");
                    }
                    else if (model.Price <= 0)
                    {
                        throw new Exception("Price value needs to be positive.");
                    }
                    else
                    {
                        _context._Products.Add(model);
                        await _context.SaveChangesAsync();

                        return(Ok(model.Id));
                    }
                }
            }
            catch (Exception exception)
            {
                return(StatusCode(500, "Error: " + exception.Message));
            }
        }
Ejemplo n.º 4
0
        public async Task TestAddingProduct()
        {
            this.SeedDatabase();

            ProductDetailsViewModel productDetailsViewModel;

            using (var stream = File.OpenRead(TestImagePath))
            {
                var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
                {
                    Headers     = new HeaderDictionary(),
                    ContentType = TestImageContentType,
                };

                var model = new ProductCreateInputModel
                {
                    Name        = this.firstProduct.Name,
                    Code        = this.firstProduct.Code,
                    Description = this.firstProduct.Description,
                    Price       = this.firstProduct.Price,
                    Image       = file,
                    BrandId     = 1,
                    CategoryId  = 1,
                };

                productDetailsViewModel = await this.productsService.CreateAsync(model);
            }

            await this.cloudinaryService.DeleteImage(this.cloudinary, productDetailsViewModel.Name + Suffixes.ProductSuffix);

            var count = await this.productsRepository.All().CountAsync();

            Assert.Equal(1, count);
        }
Ejemplo n.º 5
0
        public async Task CreateProduct_WithWrongImageFormat_ShouldThrowArgumentException()
        {
            var list = new List <Product>();

            var mockRepo = new Mock <IDeletableEntityRepository <Product> >();

            mockRepo.Setup(x => x.All()).Returns(list.AsQueryable());
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Product>())).Callback((Product product) => list.Add(product));

            var service = new ProductService(mockRepo.Object);

            IFormFile image = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, "Data", "dummy.text");

            var newsCreateInput = new ProductCreateInputModel
            {
                UserId      = 6,
                Name        = "Arsenal Hat 2020",
                Price       = 25M,
                Description = null,
                Quantity    = 20,
                Image       = image,
            };

            await Assert.ThrowsAsync <ArgumentException>(() => service.CreateAsync(newsCreateInput, "12", "/img/Arsenal_FC.png"));
        }
        public Guid Post(string name, string price)
        {
            decimal price_decimal = decimal.Parse(price.Replace('.', ','));
            ProductCreateInputModel product_create_input = new ProductCreateInputModel(name, price_decimal);

            return(product_actions.CreateProduct(product_create_input));
        }
Ejemplo n.º 7
0
        public async Task <int> CreateAsync(ProductCreateInputModel input, string image)
        {
            var product = new Product
            {
                Name          = input.Name,
                Price         = input.Price,
                ProductTypeId = input.ProductTypeId,
                Image         = image,
                ProductType   = input.Type,
            };

            foreach (var inputCharacteristic in input.Characteristics)
            {
                var characteristic = this.characteristicRepository.All()
                                     .FirstOrDefault(x => x.Name == inputCharacteristic.CharacteristicName);
                if (characteristic == null)
                {
                    characteristic = new Characteristic()
                    {
                        Name = inputCharacteristic.CharacteristicName
                    };
                }

                product.Characteristics.Add(new ProductCharacteristic()
                {
                    Characteristic               = characteristic,
                    Model                        = inputCharacteristic.Model,
                    Weight                       = inputCharacteristic.Weight,
                    Ram                          = inputCharacteristic.Ram,
                    Memory                       = inputCharacteristic.Memory,
                    Os                           = inputCharacteristic.Os,
                    Resolution                   = inputCharacteristic.Resolution,
                    Color                        = inputCharacteristic.Color,
                    ScreenSizeInInches           = inputCharacteristic.ScreenSizeInInches,
                    Battery                      = inputCharacteristic.Battery,
                    DualSim                      = inputCharacteristic.DualSim,
                    Wifi                         = inputCharacteristic.Wifi,
                    Technology                   = inputCharacteristic.Technology,
                    D3                           = inputCharacteristic.D3,
                    ReactionTime                 = inputCharacteristic.ReactionTime,
                    Illumination                 = inputCharacteristic.Illumination,
                    PrintingSpeed                = inputCharacteristic.PrintingSpeed,
                    Format                       = inputCharacteristic.Format,
                    Capacity                     = inputCharacteristic.Capacity,
                    CoolingPower                 = inputCharacteristic.CoolingPower,
                    HeatingPower                 = inputCharacteristic.HeatingPower,
                    Speaker                      = inputCharacteristic.Speaker,
                    Microphone                   = inputCharacteristic.Microphone,
                    Gps                          = inputCharacteristic.Gps,
                    Wlan                         = inputCharacteristic.Wlan,
                    CallNotificationsAndMessages = inputCharacteristic.CallNotificationsAndMessages,
                });
            }

            await this.productRepository.AddAsync(product);

            await this.productRepository.SaveChangesAsync();

            return(product.Id);
        }
Ejemplo n.º 8
0
        public void EditProduct(ProductCreateInputModel model)
        {
            GetProductIfExist(model.Id);
            Product modelProduct = MapModelProductToDataProduct(model);

            _IProductDao.Update(modelProduct);
        }
Ejemplo n.º 9
0
 public void ValidateProductCreateInput(ProductCreateInputModel productCreateInput)
 {
     if (productCreateInput == null)
     {
         throw new InputNullException(Resource.Exception.ExceptionMessage.InputIsNull);
     }
 }
Ejemplo n.º 10
0
 private Product MapModelProductToDataProduct(ProductCreateInputModel modelProduct)
 {
     return(new Product()
     {
         Id = modelProduct.Id.ToString(), Name = modelProduct.Name, Price = modelProduct.Price
     });
 }
Ejemplo n.º 11
0
        public IActionResult Create(ProductCreateInputModel productCreateInputModel)
        {
            if (!this.ModelState.IsValid)
            {
                var childCategories = this.childCategoriesService.GetAllChildCategories();

                this.ViewData["categories"] = childCategories.Select(childCategory => new ProductCreateChildCategoryViewModel
                {
                    Id = childCategory.Id,
                    ParentCategoryName = childCategory.ParentCategory.Name,
                    Name = childCategory.Name,
                })
                                              .ToList();

                return(this.View());
            }

            string pictureUrl = this.cloudinaryService.UploadPicture(
                productCreateInputModel.Image,
                productCreateInputModel.Name);

            ProductServiceModel productServiceModel = AutoMapper.Mapper.Map <ProductServiceModel>(productCreateInputModel);

            productServiceModel.Image = pictureUrl;

            this.productsService.Create(productServiceModel);

            return(this.Redirect("/"));
        }
        public List <string> CreateProduct(ProductCreateInputModel model, string id)
        {
            ICollection <string> modelErrors = Validator.ValidateModel(model);

            if (this.Data.Products.Any(r => r.Id == model.Id))
            {
                modelErrors.Add("Already Exists");

                return(modelErrors.ToList());
            }

            if (modelErrors.Count != 0)
            {
                return(modelErrors.ToList());
            }

            var product = new Product
            {
                Name    = model.Name,
                Price   = model.Price,
                Barcode = CreateBarcode(model.Barcode),
                Picture = model.Picture,
            };

            this.Data.Products.Add(product);

            this.Data.SaveChanges();

            return(modelErrors.ToList());
        }
Ejemplo n.º 13
0
        public async Task AddProduct(ProductCreateInputModel model, string imagePath)
        {
            Product product = new Product
            {
                Name        = model.Name,
                Price       = model.Price,
                CategoryId  = model.CategoryId,
                Description = model.Description,
            };

            Directory.CreateDirectory($"{imagePath}/products/");

            var extension = Path.GetExtension(model.Image.FileName).TrimStart('.');

            if (!this.allowedExtensions.Any(x => extension.EndsWith(x)))
            {
                throw new Exception($"Invalid image extension {extension}");
            }

            var dbImage = new Image
            {
                Extension = extension,
            };

            product.Image = dbImage;

            var physicalPath = $"{imagePath}/products/{dbImage.Id}.{extension}";

            using Stream fileStream = new FileStream(physicalPath, FileMode.Create);
            await model.Image.CopyToAsync(fileStream);

            await productRepository.AddAsync(product);

            await productRepository.SaveChangesAsync();
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Create(ProductCreateInputModel productCreateInputModel)
        {
            if (!this.ModelState.IsValid)
            {
                var allProductTypes = await this.productService.GetAllProductTypes().ToListAsync();

                this.ViewData["types"] = allProductTypes.Select(productType => new ProductCreateProductTypeViewModel
                {
                    Name = productType.Name
                })
                                         .ToList();;

                return(this.View());
            }

            string pictureUrl = await this.cloudinaryService.UploadPictureAsync(
                productCreateInputModel.Picture,
                productCreateInputModel.Name);

            ProductServiceModel productServiceModel = AutoMapper.Mapper.Map <ProductServiceModel>(productCreateInputModel);

            productServiceModel.Picture = pictureUrl;

            await this.productService.Create(productServiceModel);

            return(this.Redirect("/"));
        }
Ejemplo n.º 15
0
        public async Task TestAddingAlreadyExistingProduct()
        {
            this.SeedDatabase();
            await this.SeedProducts();

            using (var stream = File.OpenRead(TestImagePath))
            {
                var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
                {
                    Headers     = new HeaderDictionary(),
                    ContentType = TestImageContentType,
                };

                var model = new ProductCreateInputModel
                {
                    Name        = this.firstProduct.Name,
                    Code        = this.firstProduct.Code,
                    Description = this.firstProduct.Description,
                    Price       = this.firstProduct.Price,
                    Image       = file,
                    BrandId     = 1,
                    CategoryId  = 1,
                };

                var exception = await Assert
                                .ThrowsAsync <ArgumentException>(async() => await this.productsService.CreateAsync(model));

                await this.cloudinaryService.DeleteImage(this.cloudinary, model.Name + Suffixes.ProductSuffix);

                Assert.Equal(string.Format(ExceptionMessages.ProductAlreadyExists, model.Name), exception.Message);
            }
        }
Ejemplo n.º 16
0
        public Guid SetProduct(ProductCreateInputModel model)
        {
            model.Id = Guid.NewGuid();
            Product modelProduct = MapModelProductToDataProduct(model);

            _IProductDao.Create(modelProduct);
            return(model.Id);
        }
Ejemplo n.º 17
0
        public int SaveProduct(ProductCreateInputModel createProduct)
        {
            Product product = _productMapper.MapProductCreateInputModel(createProduct);

            _context.Products.Add(product);
            _context.SaveChanges();
            return(product.Id);
        }
Ejemplo n.º 18
0
 public Product GetProduct(ProductCreateInputModel product)
 {
     return(new Product()
     {
         Id = Guid.NewGuid(),
         Name = product.Name,
         Price = product.Price ?? throw new NullReferenceException()
     });
        public void Create(ProductCreateInputModel input)
        {
            MicroserviceResponse response = Execute(
                _client.BaseAddress.ToString(),
                input,
                HttpMethod.Post);

            Console.WriteLine();
        }
Ejemplo n.º 20
0
        public static bool ValidateData(ProductCreateInputModel productCreate, out List <string> errorList)
        {
            errorList = new List <string>();

            bool isNameOk  = CheckName(productCreate.Name, ref errorList);
            bool isPriceOk = CheckPrice(productCreate.Price, ref errorList);

            return(isNameOk && isPriceOk);
        }
Ejemplo n.º 21
0
 public Guid Post([FromBody] ProductCreateInputModel model)
 {
     if (ModelState.IsValid)
     {
         return(_productService.Add(model));
     }
     else
     {
         return(default);
Ejemplo n.º 22
0
        public async Task <IActionResult> Add()
        {
            var productCreateInputModel = new ProductCreateInputModel()
            {
                SubCategories = await this.subCategoryService.GetAllAsync <CategoryDisplayInputModel>(),
            };

            return(this.View(productCreateInputModel));
        }
Ejemplo n.º 23
0
        /*
         * Create a new Product and return its Id.
         */
        public async Task <Guid> Create(ProductCreateInputModel model)
        {
            Product product = model;

            _context.Set <Product>().Add(product);
            await SaveChangesAsync();

            return(product.Id);
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> Details(long Id)
        {
            ProductServiceModel     productFromDB = this.productService.GetById(Id);
            ProductCreateInputModel product       = productFromDB.To <ProductCreateInputModel>();
            var FrequencyList = product.FrequencyRule = productFromDB.FrequencyRule.Split(",").ToList();

            product.FrequencyRule = FrequencyList;
            return(this.View(product));
        }
Ejemplo n.º 25
0
        public Guid Post(ProductCreateInputModel model)
        {
            var product = new ProductSummary
            {
                Name  = model.Name,
                Price = model.Price
            };

            return(_productDao.AddProduct(product));
        }
Ejemplo n.º 26
0
        public ActionResult <Guid> GuidPost([FromBody] ProductCreateInputModel model)
        {
            var newProduct = _productRepository.Add(model);

            if (newProduct != null)
            {
                return(Created(Url != null ? Url.ToString() : "", newProduct.Id));
            }
            return(NoContent());
        }
Ejemplo n.º 27
0
        public ActionResult AddProduct(ProductCreateInputModel model)
        {
            var p = _productsController.Add(model);

            if (p == null)
            {
                return(View());
            }
            return(AllProducts());
        }
Ejemplo n.º 28
0
        public IActionResult Create()
        {
            var productTypes = this.productTypesService.GetAll <ProductTypeDropDownViewModel>();
            var viewModel    = new ProductCreateInputModel()
            {
                ProductTypes = productTypes,
            };

            return(this.View(viewModel));
        }
Ejemplo n.º 29
0
        public IActionResult Create()
        {
            var categories = categoryService.GetAllCategories <CategoryDropDownViewModel>();
            var viewModel  = new ProductCreateInputModel
            {
                Categories = categories,
            };

            return(View(viewModel));
        }
Ejemplo n.º 30
0
        public IActionResult Create()
        {
            var categories = this.productCategoriesService.GetAll <ProductDropDownViewModel>();
            var viewModel  = new ProductCreateInputModel
            {
                Categories = categories,
            };

            return(this.View(viewModel));
        }