コード例 #1
0
ファイル: ProductController.cs プロジェクト: war-man/Empyreal
        //end DataTranfer

        /// <summary>
        /// Chuyển đổi từ Entity => ViewModel
        /// </summary>
        /// <param name="product"></param>
        /// <param name="productDetails"></param>
        /// <param name="images"></param>
        /// <param name="viewModel"> ViewModel chứa Input</param>
        /// <history>
        /// [Lương Mỹ] Create [29/04/2019]
        /// </history>
        private void Mapping(Product product, List <ProductDetail> productDetails, List <Image> images,
                             ref ProductUpdateViewModel viewModel)
        {
            // Entity => ViewModel
            #region --- Excute ---

            viewModel = new ProductUpdateViewModel(product);

            // ProductDetail Entity => List<ProductDetail>
            for (int i = 0; i < productDetails.Count; i++)
            {
                var proDetailVModel = productDetails[i];
                ProductDetailBasicViewModel proVModel = new ProductDetailBasicViewModel(proDetailVModel);
                viewModel.ProductDetails.Add(proVModel);
            }

            // Image Entity => List<Image>
            for (int i = 0; i < images.Count; i++)
            {
                Image img = images[i];
                ImageBasicViewModel imgVModel = new ImageBasicViewModel(img);
                viewModel.Images.Add(imgVModel);
            }

            #endregion --- Excute ---
        }
コード例 #2
0
        public async Task <IActionResult> Update(ProductUpdateViewModel product
                                                 , ProductFeatureInsertViewModel vm
                                                 , ProductGalleryViewModel Pics)
        {
            // ثبت محصول
            var productId = await _productRepostitory.UpdateProduct(product, Pics.file);

            vm.ProductId = product.Id;

            if (Pics.oldGallery != null)
            {
                // بررسی گالری عکس گذشته
                await _productGalleryRepository.UpdateRemindedGallery(Pics.oldGallery.Select(x => Convert.ToInt32(x)).ToList(), product.Id);
            }

            if (Pics.galleryImage != null)
            {
                // آپلود گالری
                await _productGalleryRepository.UploadGalley(Pics.galleryImage, productId);
            }

            if (vm.Items != null)
            {
                // ویژگی ها
                await _productFeatureRepository.UpdateFeatureRange(vm);
            }
            // نمایش پیغام
            TempData.AddResult(SweetAlertExtenstion.Ok());

            // بازگشت به لیست محصولات
            return(Redirect(IndexUrlWithQueryString));
        }
コード例 #3
0
        public IActionResult Edit([Bind("Id,Name,Description,Photopath,IsActive")] ProductUpdateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var changeProduct = new Product()
                {
                    Id          = model.Id,
                    Name        = model.Name,
                    Description = model.Description,
                    IsActive    = model.IsActive,
                };
                if (model.Photopath != null)
                {
                    if (model.ExistingPhotoPath != null)
                    {
                        string filepath = Path.Combine(hostingenvironment.WebRootPath
                                                       , "images", model.ExistingPhotoPath);
                        System.IO.File.Delete(filepath);
                    }
                    changeProduct.Photopath = FilePath(model);
                }

                _context.Update(changeProduct);

                return(RedirectToAction(nameof(Index)));
            }
            return(View(model));
        }
コード例 #4
0
        public ResultViewModel Put([FromBody] ProductUpdateViewModel model)
        {
            model.Validate();
            if (model.Invalid)
            {
                return(new ResultViewModel
                {
                    Success = false,
                    Message = "Não foi possivel cadastrar o produto",
                    Data = model.Notifications
                });
            }

            Product product = repository.Find(model.Id);

            product.Title          = model.Title;
            product.CategoryId     = model.CategoryId;
            product.Description    = model.Description;
            product.Image          = model.Image;
            product.LastUpdateDate = DateTime.Now;
            product.Price          = model.Price;
            product.Quantity       = model.Quantity;

            repository.Update(product);

            return(new ResultViewModel
            {
                Success = true,
                Message = "Produto alterado com sucesso",
                Data = product
            });
        }
コード例 #5
0
        public async Task <ActionResult> Update(ProductUpdateViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (model.Id <= 0)
            {
                return(BadRequest());
            }

            try
            {
                return(Ok(await _productsRepository.Update(model.Front2Entity())));
            }
            catch (CustomErrorException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
コード例 #6
0
ファイル: ProductController.cs プロジェクト: war-man/Empyreal
        public async Task <IActionResult> ProductUpdate(int productID, bool isUpdate)
        {
            ProductUpdateViewModel viewModel = new ProductUpdateViewModel(new Product());

            viewModel.IsUpdate = isUpdate;
            //viewModel.ProductType = JsonConvert.SerializeObject(productTypeService.GetAvaliable());

            #region --- Default ---


            if (viewModel.IsUpdate)
            {
                ViewData["Title"] = "Chỉnh sửa sản phẩm";
            }
            else
            {
                ViewData["Title"] = "Thêm mới sản phẩm";
            }

            #endregion --- Default ---

            string  message = string.Empty;
            bool    isError = false;
            Product product = new Product();
            List <ProductDetail> productDetails = new List <ProductDetail>();
            List <Image>         images         = new List <Image>();
            //
            bool result = GetDataFromSever(productID, out product, out productDetails, out images, out isError, out message);

            if (result)
            {
                viewModel.IsError = isError;
                viewModel.Message = message;

                //ModelState.AddModelError("IsError", message);
                goto Finish;
            }
            //
            Mapping(product, productDetails, images, ref viewModel);
            //
            InitComboBox(ref viewModel);
            // Use for History
            if (isUpdate)
            {
                string JSON_ProductOld = ParseJson_ProductOld(product);
                viewModel.ProductOld = JSON_ProductOld;
            }

            var ENVIRONMENT_USER_ID = await userManager.GetUserAsync(User);

            if (ENVIRONMENT_USER_ID == null)
            {
                return(RedirectToAction("SignIn", "Login"));
            }
            viewModel.UserID   = ENVIRONMENT_USER_ID.Id;
            viewModel.UserName = ENVIRONMENT_USER_ID.UserName;
            //
Finish:
            return(View(viewModel));
        }
コード例 #7
0
ファイル: ProductController.cs プロジェクト: war-man/Empyreal
        public IActionResult ProductUpdate(ProductUpdateViewModel viewModel)
        {
            int isReturn = 0;
            var message  = string.Empty;

            // Input => ViewModel
            ConfigViewModel(ref viewModel);

            // Product Entity
            Product product = null;
            History history = null;

            //Excute
            try
            {
                DataTranfer(out product, out history, viewModel);
            }
            catch (Exception e)
            {
                message = e.Message;
                productService.RollBack();
                goto Finish;
            }

            // Call Service => Execute
            #region --- Main Execute ---

            // Execute Insert
            try
            {
                if (!viewModel.IsUpdate)
                {
                    history.Summary = "Thêm mới";
                    history.Content = "Tên sản phẩm: " + product.Name;
                }
                else
                {
                    history.Summary = "Chỉnh sửa";
                }

                isReturn = productService.Update(product, history);
            }
            catch (Exception e)
            {
                message = e.Message;
                goto Finish;
            }


Finish:
            // isReturn = 0: Error || 1: Success
            // Giải thích: isReturn = dbContext.Commit = số dòng được thay đổi trong sql
            viewModel.IsError = (isReturn == 0);
            viewModel.Message = message;


            #endregion --- Main Execute ---

            return(View(viewModel));
        }
コード例 #8
0
        public async Task <IActionResult> Update(int id, [FromBody] ProductUpdateViewModel value)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var success = await _domainService.Update(id, value.Name, value.Description, value.Price);

                if (success)
                {
                    return(Ok("Product updated."));
                }
                else
                {
                    return(NotFound("Product not found."));
                }
            }
            catch
            {
                return(BadRequest("Unable to update the product."));
            }
        }
コード例 #9
0
        public async Task <IActionResult> Update(
            ProductUpdateViewModel model, IEnumerable <IFormFile> pictures)
        {
            if (pictures.IsNullOrEmpty())
            {
                await this.productService.UpdateAsync(model);

                return(this.RedirectToDetails(model.Id));
            }

            foreach (var picture in pictures)
            {
                var uniqueFileName = this.fileProcessor.GetUniqueFileName(picture.FileName);
                var stream         = picture.OpenReadStream();
                /// Upload the new picture to S3:
                var pictureUrl = await this.amazonS3FileManager.UploadFileAsync(
                    this.awsFunctionOptions.BucketName,
                    stream,
                    uniqueFileName,
                    S3CannedACL.PublicRead);

                await this.pictureService.CreateAsync(pictureUrl, model.Id);
            }

            await this.productService.UpdateAsync(model);

            return(this.RedirectToDetails(model.Id));
        }
コード例 #10
0
        public ActionResult Edit(int id)
        {
            var product = _service.Get(id);

            var model = ProductUpdateViewModel.CreateModel(product);

            return(View(model));
        }
コード例 #11
0
        public async Task UpdateAsync(ProductUpdateViewModel model)
        {
            CoreValidator.ThrowIfNull(model);

            var product = this.customMapper.Map <ProductUpdateViewModel, Product>(model);

            await this.productRepository.UpdateAsync(product);
        }
コード例 #12
0
        public IActionResult Update(int id)
        {
            var product = _productRepository.GetOne(id);

            var model = new ProductUpdateViewModel(product);

            return(View(model));
        }
コード例 #13
0
        public ActionResult Update(int productId)
        {
            var model = new ProductUpdateViewModel {
                Product = _productService.GetById(productId), Categories = _categoryService.GetAll()
            };

            return(View(model));
        }
コード例 #14
0
        public ActionResult Update(ProductUpdateViewModel model)
        {
            if (ModelState.IsValid)
            {
                _productService.Update(model.Product);
            }

            return(RedirectToAction("Index"));
        }
コード例 #15
0
        public IActionResult Update(int productId)
        {
            var model = new ProductUpdateViewModel
            {
                Product = _productService.GetById(productId)
            };

            return(View(model));
        }
コード例 #16
0
 public static ProductModel Front2Entity(this ProductUpdateViewModel model)
 {
     return(new ProductModel()
     {
         Id = model.Id,
         Name = model.Name,
         Price = model.Price,
         Image = model.Image != null?Util.ByteEncode(model.Image) : null
     });
 }
コード例 #17
0
        public IActionResult UpdateProduct(ProductUpdateViewModel newProduct)
        {
            var result = _productService.UpdateProduct(newProduct);

            if (result)
            {
                return(StatusCode(200));
            }
            return(StatusCode(400));
        }
コード例 #18
0
        public IActionResult Update(int ProductID)
        {
            ProductUpdateViewModel model = new ProductUpdateViewModel()
            {
                Product    = _productService.GetByID(ProductID),
                Categories = _categoryService.GetAll()
            };

            return(View(model));
        }
コード例 #19
0
        public IActionResult Update(int productId, int subCategoryId)
        {
            ProductUpdateViewModel model = new ProductUpdateViewModel()
            {
                Product       = _productService.GetByProductId(productId),
                Categories    = _categoryService.GetAllCategories(),
                SubCategories = _subCategoryService.GetAll(),
            };

            return(View(model));
        }
コード例 #20
0
        public IActionResult UpdateProduct(int productId)
        {
            var model = new ProductUpdateViewModel
            {
                Product    = _productService.GetProduct(productId),
                Categories = new SelectList(_categoryService.GetAllCategories(), "Id", "CategoryName"),
                Units      = new SelectList(_unitService.GetUnits(), "Id", "UnitName")
            };

            return(View(model));
        }
コード例 #21
0
ファイル: ProductController.cs プロジェクト: war-man/Empyreal
        //end GetDataFromSevice


        /// <summary>
        /// Khởi tạo ComboBox cho Create / Update
        /// </summary>
        /// <returns>
        /// out viewModel
        /// </returns>
        private void InitComboBox(ref ProductUpdateViewModel viewModel)
        {
            //Get Data ComboBox
            var comboBox = new ComboBoxController();

            viewModel.Catalogs = comboBox.GetCatalogs(MODE_UPDATE);

            viewModel.Sizes  = comboBox.GetProductType("Size");
            viewModel.Colors = comboBox.GetProductType("Color");

            return;
        }
コード例 #22
0
 private Product ToProduct(ProductUpdateViewModel viewModel)
 {
     return(new Product
     {
         BasePrice = viewModel.BasePrice,
         Category = viewModel.Category,
         DiscountRate = viewModel.DiscountRate,
         Name = viewModel.Name,
         TaxRate = viewModel.TaxRate,
         Id = viewModel.Id,
     });
 }
コード例 #23
0
        public async Task <bool> UpdateAsync(ProductUpdateViewModel productViewlModel)
        {
            Product product      = _mapper.Map <ProductUpdateViewModel, Product>(productViewlModel);
            var     affectedRows = await _productRepository.UpdateAsync(product);

            if (affectedRows > 0)
            {
                return(true);
            }

            return(false);
        }
コード例 #24
0
        public bool UpdateProduct(ProductUpdateViewModel newProduct)
        {
            var product = _context.Products.Find(newProduct.Id);
            var result  = _mapper.Map <ProductUpdateViewModel, Product>(newProduct, product);
            var tracker = _context.Database.BeginTransaction();

            try
            {
                #region Update Info
                _context.Update(result);
                _context.SaveChanges();
                #endregion

                #region Update Categories
                var currentCategories = product.ProductCategories.Where(c => !c.IsDeleted).ToList();
                var newCategories     = newProduct.CategoryIds.Select(c => new ProductCategory()
                {
                    CategoryId = c
                }).ToList();

                var deletedCategories = currentCategories.ExceptBy(newCategories, c => c.CategoryId).ToList();
                if (deletedCategories.Any())
                {
                    foreach (var deletedCategory in deletedCategories)
                    {
                        deletedCategory.IsDeleted   = true;
                        deletedCategory.DateUpdated = DateTime.Now;
                        _context.Update(deletedCategory);
                    }
                    _context.SaveChanges();
                }

                var addedCategories = newCategories.ExceptBy(currentCategories, c => c.CategoryId).ToList();
                if (addedCategories.Any())
                {
                    _context.AddRange(addedCategories.Select(c => new ProductCategory()
                    {
                        CategoryId = c.CategoryId, ProductId = newProduct.Id
                    }));
                    _context.SaveChanges();
                }
                #endregion

                tracker.Commit();
                return(true);
            }
            catch (DbUpdateException)
            {
                tracker.Rollback();
                return(false);
            }
        }
コード例 #25
0
        public async Task When_UpdateProduct_Fails_ProductNotFound()
        {
            // ACT
            var viewModel = new ProductUpdateViewModel {
            };

            IncludeViewStateValidation(viewModel, _controller);

            var result = await _controller.Update(999, viewModel);

            // ASSERT: Return type
            Assert.IsType <BadRequestObjectResult>(result);
        }
コード例 #26
0
        public ActionResult Edit(ProductUpdateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var @event = new UpdateProductEvent(model.Id);

                if (!string.Equals(model.Name, model.Original.Name))
                {
                    @event.Name = model.Name;
                }
                if (!string.Equals(model.Description, model.Original.Description))
                {
                    @event.Description = model.Description;
                }
                if (!string.Equals(model.Color, model.Original.Color))
                {
                    @event.Color = model.Color;
                }
                if (!string.Equals(model.Size, model.Original.Size))
                {
                    @event.Size = model.Size;
                }
                if (!decimal.Equals(model.Price, model.Original.Price))
                {
                    @event.Price = model.Price;
                }

                var addedTags   = model.TagsList?.Where(x => model.Original.Tags?.Contains(x) != true);
                var removedTags = model.Original.Tags?.Where(x => model.TagsList?.Contains(x) != true);

                if (addedTags?.Any() == true)
                {
                    @event.AddedTags = addedTags;
                }
                if (removedTags?.Any() == true)
                {
                    @event.RemovedTags = removedTags;
                }

                var result = _service.Update(@event);

                PopulateModelState(result);

                if (ModelState.IsValid)
                {
                    return(RedirectToAction("Index", "Product"));
                }
            }

            return(View(model));
        }
コード例 #27
0
        public async Task When_UpdateProduct_Success()
        {
            // ACT
            var viewModel = new ProductUpdateViewModel {
                Name = "Prod 4", Description = "Desc 4", Price = 62
            };

            IncludeViewStateValidation(viewModel, _controller);

            var result = await _controller.Update(1, viewModel);

            // ASSERT: Return type
            Assert.IsType <OkObjectResult>(result);
        }
コード例 #28
0
        public ActionResult Update([FromForm] ProductUpdateViewModel productUpdateViewModel)
        {
            if (ModelState.IsValid)
            {
                if (productUpdateViewModel.File != null)
                {
                    AddPhoto(productUpdateViewModel.Product.ProductId, productUpdateViewModel.File);
                }

                _productService.Update(productUpdateViewModel.Product);
            }

            return(RedirectToAction("Index"));
        }
コード例 #29
0
        public ActionResult Update([FromRoute] int id, [FromBody] ProductUpdateViewModel viewModel)
        {
            var maybeProduct = _productRepository.FindById(id);

            if (!maybeProduct.HasValue)
            {
                return(NotFound());
            }

            _mapper.Map(viewModel, maybeProduct.Value);

            _uow.Commit();

            return(NoContent());
        }
コード例 #30
0
        public async Task <ActionResult> Update(ProductUpdateViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                await db.UpdateMapAndSave(viewModel);

                return(Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet));
            }
            ViewBag.Categories = await db.IncludeCategoriesDropdown();

            ViewBag.Suppliers = await db.IncludeSuppliersDropdown();

            ViewBag.Manufactures = await db.IncludeManufacturesDropdown();

            return(new HttpStatusCodeResult(HttpStatusCode.NotModified));
        }