コード例 #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?);
 }
コード例 #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"));
        }
コード例 #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));
            }
        }
コード例 #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);
        }
コード例 #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"));
        }
コード例 #6
0
        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));
        }
コード例 #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);
        }
コード例 #8
0
ファイル: ProductService.cs プロジェクト: Sedrium/Api
        public void EditProduct(ProductCreateInputModel model)
        {
            GetProductIfExist(model.Id);
            Product modelProduct = MapModelProductToDataProduct(model);

            _IProductDao.Update(modelProduct);
        }
コード例 #9
0
 public void ValidateProductCreateInput(ProductCreateInputModel productCreateInput)
 {
     if (productCreateInput == null)
     {
         throw new InputNullException(Resource.Exception.ExceptionMessage.InputIsNull);
     }
 }
コード例 #10
0
ファイル: ProductService.cs プロジェクト: Sedrium/Api
 private Product MapModelProductToDataProduct(ProductCreateInputModel modelProduct)
 {
     return(new Product()
     {
         Id = modelProduct.Id.ToString(), Name = modelProduct.Name, Price = modelProduct.Price
     });
 }
コード例 #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("/"));
        }
コード例 #12
0
        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());
        }
コード例 #13
0
ファイル: ProductService.cs プロジェクト: BozhidarIliev/BOXTY
        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();
        }
コード例 #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("/"));
        }
コード例 #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);
            }
        }
コード例 #16
0
ファイル: ProductService.cs プロジェクト: Sedrium/Api
        public Guid SetProduct(ProductCreateInputModel model)
        {
            model.Id = Guid.NewGuid();
            Product modelProduct = MapModelProductToDataProduct(model);

            _IProductDao.Create(modelProduct);
            return(model.Id);
        }
コード例 #17
0
        public int SaveProduct(ProductCreateInputModel createProduct)
        {
            Product product = _productMapper.MapProductCreateInputModel(createProduct);

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

            Console.WriteLine();
        }
コード例 #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);
        }
コード例 #21
0
 public Guid Post([FromBody] ProductCreateInputModel model)
 {
     if (ModelState.IsValid)
     {
         return(_productService.Add(model));
     }
     else
     {
         return(default);
コード例 #22
0
        public async Task <IActionResult> Add()
        {
            var productCreateInputModel = new ProductCreateInputModel()
            {
                SubCategories = await this.subCategoryService.GetAllAsync <CategoryDisplayInputModel>(),
            };

            return(this.View(productCreateInputModel));
        }
コード例 #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);
        }
コード例 #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));
        }
コード例 #25
0
ファイル: ProductController.cs プロジェクト: grofab95/Product
        public Guid Post(ProductCreateInputModel model)
        {
            var product = new ProductSummary
            {
                Name  = model.Name,
                Price = model.Price
            };

            return(_productDao.AddProduct(product));
        }
コード例 #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());
        }
コード例 #27
0
        public ActionResult AddProduct(ProductCreateInputModel model)
        {
            var p = _productsController.Add(model);

            if (p == null)
            {
                return(View());
            }
            return(AllProducts());
        }
コード例 #28
0
        public IActionResult Create()
        {
            var productTypes = this.productTypesService.GetAll <ProductTypeDropDownViewModel>();
            var viewModel    = new ProductCreateInputModel()
            {
                ProductTypes = productTypes,
            };

            return(this.View(viewModel));
        }
コード例 #29
0
        public IActionResult Create()
        {
            var categories = categoryService.GetAllCategories <CategoryDropDownViewModel>();
            var viewModel  = new ProductCreateInputModel
            {
                Categories = categories,
            };

            return(View(viewModel));
        }
コード例 #30
0
        public IActionResult Create()
        {
            var categories = this.productCategoriesService.GetAll <ProductDropDownViewModel>();
            var viewModel  = new ProductCreateInputModel
            {
                Categories = categories,
            };

            return(this.View(viewModel));
        }