public void Create(CreateProductViewModel model) { using (ITransaction transaction = _session.BeginTransaction()) { try { var product = new Product(model.Name, new Money(model.Price)); _productRepository.Add(product); } catch (MoneyWithMoreThanTwoDecimalPlacesException m1) { throw new ApplicationException(String.Format("Invalid product price: {0}", m1.Value)); } catch (MoneyCannotBeNegativeException m2) { throw new ApplicationException(String.Format("Product price can't be negative: {0}", m2.Value)); } catch (InvalidProductNameException p1) { throw new ApplicationException(String.Format("Invalid product name")); } transaction.Commit(); } }
public CreateProductViewModel GetCreateData(CreateProductViewModel model) { return new CreateProductViewModel() { Name = model.Name, Price = model.Price }; }
// // GET: /Admin/Product/Create public ActionResult Create() { var rep = new SubcategoryRepository(); var viewModel = new CreateProductViewModel(); viewModel.subcategories = rep.Table; viewModel.product = new Product(); return View(viewModel); }
public void CreateProduct() { var controller = _container.Resolve<ProductController>(); var model = new CreateProductViewModel() { Name = "Product 1", Price = 12.3m }; var result = controller.Create(model) as RedirectToRouteResult; }
public async Task <IActionResult> DeleteProductPost([FromBody] CreateProductViewModel model) { var product = await _productService.DeleteProduct(model); if (product != null) { return(Success(product)); } else { return(Error(Utils.Constant.ResponseStatusCode.UniqRowDuplicate, "Can't delete product")); } }
public async Task <IActionResult> Create() { var categories = await _mediator.Send(new GetAllCategoriesQuery()); var suppliers = await _mediator.Send(new GetAllSuppliersQuery()); var viewModel = new CreateProductViewModel { Categories = categories.ToSelectList(nameof(Category.CategoryId), nameof(Category.CategoryName)), Suppliers = suppliers.ToSelectList(nameof(Supplier.SupplierId), nameof(Supplier.CompanyName)), }; return(View(viewModel)); }
public async Task ShouldNotCreateWithoutRequiredFields() { var server = new ServerFake(); var user = server.AppDbContext.CreateUser(); var viewModel = new CreateProductViewModel(); var response = await server.CreateAuthenticatedClient(user).PostAsJsonAsync("products/create", viewModel); var json = await response.Content.ReadAsJsonAsync <ErrorsJson>(); var errors = new[] { "Name: Required", "InventoryControl: Required" }; Assert.Equal((HttpStatusCode)422, response.StatusCode); Assert.Equal(json.Errors.OrderBy(e => e), errors.OrderBy(e => e)); }
public async Task <IActionResult> Create(CreateProductViewModel viewModel) { Guid userId = new Guid(this.User.FindFirstValue(ClaimTypes.NameIdentifier)); var newId = Guid.NewGuid(); await _productService.CreateAsync(newId, userId, viewModel.Name, viewModel.Category, viewModel.Price, viewModel.Description); //QRCodeGenerator qrGenerator = new QRCodeGenerator(); //QRCodeData qrCodeData = qrGenerator.CreateQrCode("The text which should be encoded.", QRCodeGenerator.ECCLevel.Q); //QRCode qrCode = new QRCode(qrCodeData); //Bitmap qrCodeImage = qrCode.GetGraphic(20); //wwait _fileService.UpdateAsync(newId); return(RedirectToAction(nameof(Browse))); }
public async Task <IActionResult> Create([Bind("Name, Price, Description, Stock")] CreateProductViewModel products) { if (ModelState.IsValid) { var product = _mapper.Map <ProductModel>(products); await _service.AddProduct(product); return(RedirectToAction("Index")); } else { return(View()); } }
/// <summary> /// Render giao diện tạo sản phẩm mới /// </summary> /// <returns></returns> public ActionResult Create() { isAdminLogged(); var model = new CreateProductViewModel() { IdProduct = _productService.GenerateProductId() }; model.ProductTypes = _productTypeService.GetAllProductType(); model.Units = _unitService.GetAllUnit(); ViewBag.Parent = "Quản lý sản phẩm"; ViewBag.Child = "Tạo sản phẩm mới"; return(View(model)); }
public async Task <MessageResponse> Add(CreateProductViewModel viewModel) { var entity = _mapper.Map <Product>(viewModel); await _unitOfWork.GetRepository <Product>().InsertAsync(entity); await _unitOfWork.SaveChangesAsync(); return(new MessageResponse { Message = "Saved", Success = true }); }
private string ProcessUploadedFile(CreateProductViewModel model) { string uniqueFileName = null; if (model.ProductPhoto != null) { string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "img"); uniqueFileName = Guid.NewGuid().ToString() + "_" + model.ProductPhoto.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); model.ProductPhoto.CopyTo(new FileStream(filePath, FileMode.Create)); } return(uniqueFileName); }
public ActionResult Create(int?page) { try { var createProduct = new CreateProductViewModel(); ViewBag.CurrentPage = page; return(View(createProduct)); } catch (Exception ex) { _logger.Warn(ex.Message); return(View("Error")); } }
// GET: Product public async Task <ActionResult> Index() { List <Product> products = await _productRepository.GetAllAsync(); List <CreateProductViewModel> createProductViewModels = new List <CreateProductViewModel>(); foreach (var p in products) { CreateProductViewModel createProductViewModel = new CreateProductViewModel(p); createProductViewModels.Add(createProductViewModel); } return(View("Index", createProductViewModels)); }
public IActionResult EditProduct(int ProductId) { CreateProductViewModel model = new CreateProductViewModel(); var product = repo.GetProducts().FirstOrDefault(p => p.Id == ProductId); model.Name = product.Name; model.Description = product.Description; model.Price = (double)product.Price; model.Categories = repo.GetCategories(); model.SelectedCategory = product.Category.Name; model.Id = ProductId; return(View(model)); }
public void Create(CreateProductViewModel createProduct) { var product = new Product { ProductName = createProduct.ProductName, Price = createProduct.Price, Description = createProduct.Description, Image = createProduct.Image, Id = createProduct.Id }; _context.Products.Add(product); _context.SaveChangesAsync(); }
public IActionResult Create(CreateProductViewModel model) { if (ModelState.IsValid) { var product = new Product { Name = model.Name, BrandId = model.BrandId, CategoryId = model.CategoryId, CPU = model.CPU, Description = model.Description, FrontCamera = model.FrontCamera, OS = model.OS, Price = model.Price, Ram = model.Ram, RearCamera = model.RearCamera, Remain = model.Remain, Rom = model.Rom, Screen = model.Screen }; var createProduct = productRepository.Create(product); if (model.ImageFiles != null) { var uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images\\products"); foreach (var imageFile in model.ImageFiles) { var fileName = $"{Guid.NewGuid()}{Path.GetExtension(imageFile.FileName)}"; var filePath = Path.Combine(uploadFolder, fileName); using var fs = new FileStream(filePath, FileMode.Create); imageFile.CopyTo(fs); imageRepository.Create(new Image { ImageId = Guid.NewGuid().ToString(), ProductId = createProduct.ProductId, ImageName = fileName }); } } return(RedirectToAction("ViewProduct", "Home", new { id = createProduct.ProductId })); } ViewBag.Categories = categoryRepository.Get(); ViewBag.Brands = brandRepository.Get(); return(View()); }
public IActionResult CreateProduct(CreateProductViewModel vm) { if (!ModelState.IsValid) { return(View(vm)); } vm.Products = _dbContext.Products .Include(pc => pc.ProductCategory) .ThenInclude(p => p.Category); _dbContext.Add(vm.Product); _dbContext.SaveChanges(); return(View(vm)); }
public IActionResult Create(CreateProductViewModel model) { if (!ModelState.IsValid) { return(this.View(model)); } var id = this.productsService.Create( model.Name, model.Price, model.Description, model.Type); return(this.RedirectToAction(nameof(Details), routeValues: id)); }
// GET: Product/Edit/5 public ActionResult Edit(int id) { getProduct.InputArgument = p => p.Id == id; getProduct.Execute(); var retrievedProduct = getProduct.OutputArgument.Single(); CreateProductViewModel viewModel = new CreateProductViewModel { Code = retrievedProduct.Code, Name = retrievedProduct.Name, Photo = retrievedProduct.Photo, Price = retrievedProduct.Price }; return(View(viewModel)); }
public void AddProduct(CreateProductViewModel viewModel) { Product p = new Product(); p.ProductName = viewModel.ProductName; p.Price = viewModel.Price; p.PictureLink = viewModel.ImageURL; p.ProductDescription = viewModel.ProductDescription; p.Stock = viewModel.AmountToAdd; p.CategoryId = viewModel.Category; Context.Products.Add(p); Context.SaveChanges(); }
public async Task <CommandResult <Guid> > CreateProduct([FromBody] CreateProductViewModel viewModel) { var createProductModel = _mapper.Map <ProductModel>(viewModel); var result = await _productManager.CreateProduct(createProductModel); if (result.IsSucceeded) { foreach (var img in viewModel.Images) { this.ConfirmImageAdded(img); } } return(result); }
public async Task <ActionResult> Create(CreateProductViewModel createProductViewModel) //IFormCollection collection { try { await _service.CreateProduct(ProductFactory.Make(createProductViewModel)); return(RedirectToAction(nameof(Index))); } catch (Exception exc) { return(View("Error", new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, Description = exc?.Message })); } }
public async Task Details_ReturnsExpectedResult(int id) { // Arrange ProductController controller = new ProductController(_productRepository.Object, _categoryRepository.Object, _orderRepository.Object); // Act ViewResult result = await controller.Details(id) as ViewResult; //Assert CreateProductViewModel productVM = (CreateProductViewModel)result.Model; Assert.NotNull(result); Assert.NotNull(productVM); Assert.True(productVM.ProductID == id); }
public async Task Edit_OnPost_WithModelStateInvalid_ReturnsEditViewWithSameData() { // Arrange ProductController controller = new ProductController(_productRepository.Object, _categoryRepository.Object, _orderRepository.Object); controller.ModelState.AddModelError("Required", "Name Parameter Required"); // Act ViewResult result = await controller.Edit(TestCVM) as ViewResult; CreateProductViewModel resultCVM = (CreateProductViewModel)result.Model; //Assert Assert.IsTrue("Edit" == result.ViewName); Assert.IsTrue(resultCVM.Description == TestCVM.Description); }
public IActionResult Create(CreateProductViewModel model) { if (!ModelState.IsValid) { return(this.View(model)); } var id = this.productsService.Create( model.Name, model.Price, model.Description, model.Type); return(this.Redirect($"/Products/Details/{id}")); }
public ActionResult Edit(int id) { var product = _product.GetProduct(id); var model = new CreateProductViewModel { CategoryId = product.CategoryId, Size = product.Size, ProductId = product.ProductId, ProductName = product.ProductName, UnitPrice = product.UnitPrice }; ViewBag.CategoryId = new SelectList(_category.GetAllCategories(), "CategoryId", "CategoryName", model.CategoryId); return(View(model)); }
public async Task <IActionResult> Create(CreateProductViewModel viewModel) { if (ModelState.IsValid) { _context.Add(viewModel.Product); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } viewModel.ProductTypes = new SelectList(_context.productTypes, "ProductTypeID", "Naam", viewModel.Product.ProductTypeID); viewModel.Product.IsZichtbaar = true; viewModel.Product.StartDatum = DateTime.Now; viewModel.Product.EindDatum = default; return(RedirectToAction(nameof(IndexManager))); }
// GET: Product/Details/5 public async Task <ActionResult> Details(int id) { Product product = await _productRepository.GetByIDAsync(id); if (product != null) { CreateProductViewModel createProductViewModel = new CreateProductViewModel(product); return(View("Details", createProductViewModel)); } else { ViewBag.Message = "Product Not Found"; return(View("Error")); } }
public async Task <ActionResult> Create(CreateProductViewModel createProductViewModel) { if (ModelState.IsValid) { var product = new Product(); Mapper.Map(createProductViewModel, product); product.CustomerId = await _customerIdService.GetCustomerId(); await _productRepository.Add(product); return(RedirectToAction("Detail", "SubCategory", new { subCategoryId = createProductViewModel.SubCategoryId })); } return(RedirectToAction("Create", new { subCategoryId = createProductViewModel.SubCategoryId })); }
public ActionResult Create(CreateProductViewModel createProductViewModel) { // mapping from CreateProductViewModel into Product // save if (ModelState.IsValid) { var product = _mapper.Map <Product>(createProductViewModel); _uow.Products.Create(product); _uow.Save(); return(RedirectToAction("Index")); } return(View()); }
public IActionResult AddProduct(CreateProductViewModel model) { var product = new Product() { Name = model.Name, Price = model.Price, Description = model.Description, Type = (ProductType)Enum.Parse(typeof(ProductType), model.ProductType) }; this.dbContext.Products.Add(product); this.dbContext.SaveChanges(); return(this.Redirect($"/products/details?id={product.Id}")); }
public ActionResult Create(CreateProductViewModel model) { try { if (ModelState.IsValid) { var user = User.Identity.GetUserId(); byte[] content = null; string fileExtension = null; //image size up to 10MB if (model.UploadPhoto != null && model.UploadPhoto.ContentLength <= (1024 * 1024 * 10)) { using (var mem = new MemoryStream(model.UploadPhoto.ContentLength)) { model.UploadPhoto.InputStream.CopyTo(mem); content = mem.GetBuffer(); fileExtension = model.UploadPhoto.FileName.Split(new[] { '.' }).Last(); } } var book = new Product { OriginalPrice = model.OriginaPrice ?? 0, SalePrice = model.SalePrice ?? 0, CategoryId = model.CategoryId, Year = model.Year ?? 0, ConditionId = model.ConditionId, CreatedOn = DateTime.Now, Name = model.Name, SellerId = user, Description = model.Description, Image = new Image { Content = content, FileExtension = fileExtension } }; this.db.Products.Add(book); this.db.SaveChanges(); TempData["Success"] = "Your Ad has been successfully submitted!"; } return(RedirectToAction("Create", "Product")); } catch { TempData["Failed"] = "File upload failed!"; return(RedirectToAction("Create", "Product")); } }
public IActionResult Create(CreateProductViewModel model) { if (ModelState.IsValid) { var product = new Product { Name = model.Name, CategoryId = model.CategoryId, Description = model.Description, Price = model.Price, Remain = model.Remain, publisher = model.pushisher, DoP = model.DoP }; var createProduct = productRepository.Create(product); if (model.ImageFiles != null) { var uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images\\products"); foreach (var imageFile in model.ImageFiles) { var fileName = $"{Guid.NewGuid()}{Path.GetExtension(imageFile.FileName)}"; var filePath = Path.Combine(uploadFolder, fileName); using var fs = new FileStream(filePath, FileMode.Create); imageFile.CopyTo(fs); imageRepository.Create(new Image { ImageId = Guid.NewGuid().ToString(), ProductId = createProduct.ProductId, ImageName = fileName }); } } return(RedirectToAction("index", "ProductsManager", new { id = createProduct.ProductId })); } ViewBag.Categories = categoryRepository.Get(); return(View()); }
public ActionResult Create(CreateProductViewModel model) { if (!ModelState.IsValid) { model = _appService.GetCreateData(model); return View(model); } try { _appService.Create(model); return RedirectToAction("Index"); } catch(ApplicationException ex) { model = _appService.GetCreateData(model); model.AddMessage(ex.Message); return View(model); } }
public ActionResult Create(Product product) { try { var poductRep = new ProductRepository(); if (poductRep.Create(product)) return RedirectToAction("Index"); } catch { } var rep = new SubcategoryRepository(); var viewModel = new CreateProductViewModel(); viewModel.subcategories = rep.Table; viewModel.product = product; return View(viewModel); }