public HttpResponse Add(AddProductInputModel model) { if (!this.IsUserSignedIn()) { return(this.Redirect("/Users/Login")); } if (string.IsNullOrEmpty(model.Name) || model.Name.Length < 4 || model.Name.Length > 20) { return(this.Error("Name is required and should be between 4 and 20 characters long.")); } if (!Uri.TryCreate(model.ImageUrl, UriKind.Absolute, out _)) { return(this.Error("Image url should be valid.")); } if (model.Price < 0) { return(this.Error("Price cannot be negative.")); } if (model.Description.Length > 10) { return(this.Error("Description length should be 10 characters at most.")); } this.productsService.AddProduct(model); return(this.Redirect("/")); }
public async Task EditAsync(AddProductInputModel inputModel) { var productToEdit = GetProductById(inputModel.Id, true); var newAdditionalImages = inputModel.AdditionalImages.Where(x => x != null).ToList(); //Edit all of the images for the product context.ProductsImages.RemoveRange(productToEdit.AdditionalImages); for (int i = 0; i < newAdditionalImages.Count; i++) { var newImage = newAdditionalImages[i]; productToEdit.AdditionalImages.Add(new ProductImage { Image = newImage, ProductId = productToEdit.Id }); } //Edit all of the simple properties productToEdit.Description = inputModel.Description; productToEdit.Warranty = inputModel.Warranty; productToEdit.MainImage = inputModel.MainImage; productToEdit.Model = inputModel.Model; productToEdit.Name = inputModel.Name; productToEdit.Price = inputModel.Price; productToEdit.QuantityInStock = inputModel.QuantityInStock; await context.SaveChangesAsync(); }
public async Task <IActionResult> Post([FromBody] AddProductInputModel input) { if (!ModelState.IsValid) { return(BadRequest(GetErrorListFromModelState.GetErrorList(ModelState))); } if (!TypesManager.checkStatus(input.Type)) { return(BadRequest(new { errors = new { Type = ErrorConst.InvalidType } })); } var product = new Product { Name = input.Name, Description = input.Description, Type = input.Type, OwnerId = input.OwnerId }; _context.Products.Add(product); try { await _context.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { return(GetCatchExceptionErrors.getErrors(this, ex)); } }
public void AddProductWithOverPriceSuccessTest() { var repository = new Mock <IProductRepository>(); var errorCollector = new ErrorCollector(); var exportService = new Mock <IExportService>().Object; repository.Setup(r => r.AddProduct(It.IsAny <IProduct>())).Returns(new Product { Id = 1, Code = "T1", Name = "Test 1", Price = Constants.ProductMaxPrice + 1 }); var service = new ProductService(repository.Object, errorCollector, exportService); var inputModel = new AddProductInputModel { Code = "T1", Name = "Test 1", Price = Constants.ProductMaxPrice + 1, ConfirmPrice = true }; var outputModel = service.AddProduct(inputModel); Assert.IsNotNull(outputModel); Assert.IsFalse(errorCollector.Errors.Any()); Assert.IsNotNull(outputModel.Product); }
public void AddProductWithAlreadyExistingCodeTest() { var repository = new Mock <IProductRepository>(); var errorCollector = new ErrorCollector(); var exportService = new Mock <IExportService>().Object; repository.Setup(r => r.GetProducts(It.IsAny <string>())).Returns(new[] { new Product { Code = "T1", Name = "Test One", Price = 15 } }); var service = new ProductService(repository.Object, errorCollector, exportService); var inputModel = new AddProductInputModel { Code = "T1", Name = "Test 1", Price = 10 }; var outputModel = service.AddProduct(inputModel); Assert.IsNull(outputModel); Assert.IsTrue(errorCollector.Errors.Any()); }
public GenericResponse <IAddProductOutputModel> Add([FromBody] AddProductInputModel inputModel) { return(new GenericResponse <IAddProductOutputModel> { Code = 200, Result = _service.AddProduct(inputModel) }); }
public ActionResult GetAddProductView(int id) { var model = new AddProductInputModel { Id = id }; return(this.PartialView("_GetAddProductViewPartial", model)); }
public ActionResult GetAddProductView(int id) { var model = new AddProductInputModel { Id = id }; return this.PartialView("_GetAddProductViewPartial", model); }
public async Task <IActionResult> Create() { var model = new AddProductInputModel() { Categories = await this.categoriesService.GetAllAsSelectListItemAsync(), Brands = await this.brandsService.GetAllAsSelectListItemAsync(), }; return(this.View(model)); }
public ActionResult AddProduct(AddProductInputModel model) { if (ModelState.IsValid) { var newProduct = new Product { Name = model.Name, Description = this.sanitizer.Sanitize(model.Description), DateAdded = DateTime.UtcNow, Price = model.Price, Quantity = model.Quantity, ProductType = (ProductType)model.ProductType, HazardClassificationId = int.Parse(model.HazardClassificationId), ProducerId = int.Parse(model.ProducerId) }; var productIndustries = new List <Industry>(); for (int i = 0; i < model.Industries.Count; i++) { if (model.Industries[i].IsSelected) { productIndustries.Add(new Industry { Id = model.Industries[i].Id, Name = model.Industries[i].Name }); } } newProduct.Industries = productIndustries; if (model.UploadedImage != null) { using (var memory = new MemoryStream()) { model.UploadedImage.InputStream.CopyTo(memory); var content = memory.GetBuffer(); var image = new Image { Content = content, FileExtension = model.UploadedImage.FileName.Split(new[] { '.' }).Last() }; newProduct.Image = image; } } this.products.Add(newProduct); return(Redirect("/")); } return(View()); }
public async Task <IActionResult> AddProduct(AddProductInputModel input) { if (!this.User.IsInRole("Administrator")) { return(this.Redirect("/Products/Home")); } await this.productsService.AddProduct(input); return(this.Redirect("/Products/Home")); }
public async Task <IActionResult> CreateProduct([FromBody] AddProductInputModel inputModel) { var product = new Product(); _mapper.Map(inputModel, product); _catalogContext.Products.Add(product); await _catalogContext.SaveChangesAsync(); return(CreatedAtAction(nameof(GetById), new { id = product.Id }, null)); }
public HttpResponse Add(AddProductInputModel inputModel) { if (inputModel.Name.Length < 4 || inputModel.Name.Length > 20 || inputModel.Description.Length > 10) { return(this.Redirect("/Products/Add")); } int productId = productService.Add(inputModel.Name, inputModel.Description, inputModel.ImageUrl, inputModel.Category, inputModel.Gender, inputModel.Price); return(this.Redirect($"/Products/Details?id={productId}")); }
public async Task <int> CreateProductAsync(AddProductInputModel model) { var product = this.mapper.Map <Product>(model); await this.context.Products.AddAsync(product); await this.context.SaveChangesAsync(); await this.inventoryService.RecalculateAvailableInventoryAsync(product.Id); return(product.Id); }
public async Task <IActionResult> AddProduct(AddProductInputModel product) { try { var productId = await this.warehouseService.AddProduct(product); return(RedirectToAction(nameof(Search))); } catch (Exception ex) { return(BadRequest(ex)); } }
public void Add(AddProductInputModel input) { this.db.Products.Add(new Product { Name = input.Name, Description = input.Description, ImageUrl = input.ImageUrl, Category = (Category)Enum.Parse(typeof(Category), input.Category), Gender = (Gender)Enum.Parse(typeof(Gender), input.Gender), Price = input.Price }); this.db.SaveChanges(); }
public async Task <IActionResult> Edit(string productId, string errorReturnUrl) { //Check if product with this id exists. MAYBE I WILL REPLACE THIS LATER WILL HAVE TO SWITCH TO DEVELOPMENT AND SEED if (this.productService.ProductExistsById(productId) == false) { return(this.NotFound()); //return this.View("/Views/Shared/Error.cshtml"); } AddProductInputModel inputModel = null; //Add each model state error from the last action to this one. Fill the input model with he values from the last post action if (TempData[GlobalConstants.ErrorsFromPOSTRequest] != null && TempData[GlobalConstants.InputModelFromPOSTRequestType]?.ToString() == nameof(AddProductInputModel)) { ModelStateHelper.MergeModelStates(TempData, this.ModelState); var inputModelJSON = TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString(); inputModel = JsonSerializer.Deserialize <AddProductInputModel>(inputModelJSON); var product = this.productService.GetProductById(productId, true); //Get the categories for the product inputModel.CategoriesIds = this.categoryService.GetCategoriesForProduct(product.Id).Select(x => x.Id).ToList(); } //If there wasn't an error with the edit form prior to this, just fill the inputModel like normal else { var product = this.productService.GetProductById(productId, true); inputModel = this.mapper.Map <AddProductInputModel>(product); //Get the categories for the product inputModel.CategoriesIds = this.categoryService.GetCategoriesForProduct(product.Id).Select(x => x.Id).ToList(); //Set the correct additional images paths for (int i = 0; i < product.AdditionalImages.Count; i++) { var image = product.AdditionalImages.ToList()[i]; inputModel.AdditionalImages[i] = image.Image; } } //Set the input model mode to edit inputModel.IsAdding = false; //Set input model short description inputModel.ShortDescription = this.productService.GetShordDescription(inputModel.Description, 40); return(this.View("/Views/Products/Add.cshtml", inputModel)); }
public void Create(AddProductInputModel model) { using (var db = new CakesDbContext()) { var product = new Product { Name = model.Name, Price = model.Price, ImageUrl = model.ImageUrl }; db.Add(product); db.SaveChanges(); } }
public async Task <long> AddProduct(AddProductInputModel productInputModel) { var newProduct = new Product() { AvailableQuantity = productInputModel.AvailableQuantity, CategoryId = productInputModel.CategoryId, MinQuantity = productInputModel.MinQuantity, Name = productInputModel.Name, Price = productInputModel.Price, SupplierId = productInputModel.SupplierId }; this.db.Products.Add(newProduct); return(await this.db.SaveChangesAsync()); }
public async Task <IActionResult> Add() { AddProductInputModel inputModel = null; //Add each model state error from the last action to this one if (TempData[GlobalConstants.ErrorsFromPOSTRequest] != null) { ModelStateHelper.MergeModelStates(TempData, ModelState); var inputModelJSON = TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString(); inputModel = JsonSerializer.Deserialize <AddProductInputModel>(inputModelJSON); } return(this.View(inputModel)); }
public HttpResponse Add(AddProductInputModel model) { if (!this.IsUserLoggedIn()) { return(this.Redirect("/Users/Login")); } if (model.Name.Length < 4 || model.Name.Length > 20) { return(this.Error("Product name should be between 4 and 20 characters!")); } this.productsService.Add(model); return(this.Redirect("/")); }
public async Task AddProduct(AddProductInputModel input) { var filename = this.UploadFile(input); var product = new Product() { Name = input.Name, Description = input.Description, DownloadLink = input.DownloadLink, MainPhoto = filename, }; await this.db.Products.AddAsync(product); await this.db.SaveChangesAsync(); }
public void AddProductWithInvalidInputModelTest() { var repository = new Mock <IProductRepository>().Object; var errorCollector = new ErrorCollector(); var exportService = new Mock <IExportService>().Object; var service = new ProductService(repository, errorCollector, exportService); var inputModel = new AddProductInputModel { }; var outputModel = service.AddProduct(inputModel); Assert.IsNull(outputModel); Assert.IsTrue(errorCollector.Errors.Any()); }
private string UploadFile(AddProductInputModel input) { string fileName = null; if (input.MainImage != null) { string uploadDir = Path.Combine(this.hostingEnvironment.WebRootPath, "productImages"); fileName = Guid.NewGuid().ToString() + "-" + input.MainImage.FileName; string filePath = Path.Combine(uploadDir, fileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { input.MainImage.CopyTo(fileStream); } } return(fileName); }
public HttpResponse Add(AddProductInputModel input) { if (string.IsNullOrWhiteSpace(input.Name) || input.Name.Length < 4 || input.Name.Length > 20) { return(this.Error("Invalid product name")); } if (input?.Description.Length > 10) { return(this.Error("Invalid description.")); } this.productsService.Add(input); return(this.Redirect("/Home/Home")); }
public async Task <IActionResult> Create(AddProductInputModel input) { if (!this.ModelState.IsValid) { input.Categories = await this.categoriesService.GetAllAsSelectListItemAsync(); input.Brands = await this.brandsService.GetAllAsSelectListItemAsync(); return(this.View(input)); } var id = await this.productsService.CreateAsync(input.Name, input.Description, input.Price, input.Picture, input.BrandId, input.CategoryId); this.TempData["InfoMessage"] = GlobalMessages.SuccessCreateMessage; return(this.RedirectToAction(nameof(this.GetAll))); }
public async Task <IActionResult> AddProduct(AddProductInputModel model) { if (!this.productService.IsSkuAvailable(model.SKU)) { this.ModelState.AddModelError("SKU", GlobalConstants.UnavailableSKU); return(this.View(model)); } if (!this.ModelState.IsValid) { return(this.View()); } model.CreatedById = this.userManager.GetUserId(this.User); await this.productService.CreateProductAsync(model); return(this.Redirect("/Products/ManageProducts")); }
public void Add(AddProductInputModel model) { var category = (Category)Enum.Parse(typeof(Category), model.Category, true); var gender = (Gender)Enum.Parse(typeof(Gender), model.Gender, true); var product = new Product() { Category = category, Description = model.Description, Gender = gender, ImageUrl = model.ImageUrl, Name = model.Name, Price = model.Price }; this.db.Products.Add(product); this.db.SaveChanges(); }
public void AddProduct(AddProductInputModel input) { var genderAsEnum = Enum.Parse <Gender>(input.Gender); var categoryAsEnum = Enum.Parse <Category>(input.Category); var product = new Product { Description = input.Description, Name = input.Name, ImageUrl = input.ImageUrl, Price = input.Price, Category = categoryAsEnum, Gender = genderAsEnum, }; this.db.Products.Add(product); this.db.SaveChanges(); }
public async Task SetUp() { _fixture = new Fixture(); _products = _fixture.CreateMany <Product>(10).ToList(); var options = new DbContextOptionsBuilder <CatalogContext>() .UseInMemoryDatabase(databaseName: $"Catalog_{Guid.NewGuid()}") .Options; _dbContext = new CatalogContext(options); await _dbContext.Products.AddRangeAsync(_products); await _dbContext.SaveChangesAsync(); _model = _fixture.Create <AddProductInputModel>(); _validator = new AddProductModelValidator(_dbContext); }
public void AddProductWithPriceOverMaxLimitTest() { var repository = new Mock <IProductRepository>().Object; var errorCollector = new ErrorCollector(); var exportService = new Mock <IExportService>().Object; var service = new ProductService(repository, errorCollector, exportService); var inputModel = new AddProductInputModel { Code = "T1", Name = "Test 1", Price = Constants.ProductMaxPrice + 1 }; var outputModel = service.AddProduct(inputModel); Assert.IsNull(outputModel); Assert.IsTrue(errorCollector.Errors.Any()); }