public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { // Get product id int id = model.Id; // Populate categories select list and gallery images using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); // Check model state if (!ModelState.IsValid) { return(View(model)); } // Make sure product name i unique using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } // Update product using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDTO.Name; db.SaveChanges(); } // Set TempData message TempData["SM"] = "You have edited the product!"; #region Image Upload // Chech for file upload if (file != null && file.ContentLength > 0) { // Get extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } // Set upload directory paths var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); // Delete file from directory DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (FileInfo file2 in di1.GetFiles()) { file2.Delete(); } foreach (FileInfo file3 in di2.GetFiles()) { file3.Delete(); } // Save image name string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Save original and thumb images var path = string.Format("{0}\\{1}", pathString1, imageName); var path2 = string.Format("{0}\\{1}", pathString2, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion // Redirect return(RedirectToAction("EditProduct")); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } // Check model state using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } int id; using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); model.CategoryName = catDTO.Name; db.Products.Add(product); db.SaveChanges(); id = product.Id; } TempData["SM"] = "You have added a product!"; #region Upload Image // Create necessary directories var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } // Check if a file was uploaded if (file != null && file.ContentLength > 0) { // Get file extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } // Init image name string imageName = file.FileName; // Save image name to DTO using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Set original and thumb image paths var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); // Save original file.SaveAs(path); // Create and save thumb WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("AddProduct")); }
private void btnSubmitAll_Click(object sender, EventArgs e) { decimal GAmount = 0; decimal DAmount = 0; decimal TotalAmount = 0; decimal GridTotalAmount = 0; List <ProductReceiptMapVM> productReceiptMapVMs = new List <ProductReceiptMapVM>(); ProductReceiptMapVM tempProductReceipt; ReceiptVM receipt = new ReceiptVM() { Id = 0, BSPId = this.selectedBSP.Id, Remark = "", Products = new List <ProductReceiptMapVM>(), }; foreach (DataGridViewRow row in receiptGridView.Rows) { tempProductReceipt = new ProductReceiptMapVM(); ProductVM product = JsonConvert.DeserializeObject <ProductVM>(row.Cells[9].Value.ToString()); GridTotalAmount += Convert.ToDecimal(row.Cells[8].Value); tempProductReceipt.ProductId = product.Id; tempProductReceipt.product = product; tempProductReceipt.ReceiptId = 0; tempProductReceipt.Quantity = Convert.ToInt32(row.Cells[4].Value); tempProductReceipt.ItemPrice = Convert.ToDecimal(row.Cells[5].Value); tempProductReceipt.ItemDiscountedPrice = Convert.ToDecimal(row.Cells[7].Value); productReceiptMapVMs.Add(tempProductReceipt); GAmount += tempProductReceipt.ItemPrice.Value * tempProductReceipt.Quantity; DAmount += (tempProductReceipt.ItemPrice.Value - tempProductReceipt.ItemDiscountedPrice.Value) * tempProductReceipt.Quantity; TotalAmount += tempProductReceipt.ItemDiscountedPrice.Value * tempProductReceipt.Quantity; } receipt.TotalAmount = GridTotalAmount; receipt.Products = productReceiptMapVMs; using (var amountValidation = new AmountValidationPopup(receipt, this)) using (var reportBll = new ReportHandler()) { var result = amountValidation.ShowDialog(); if (result == DialogResult.OK) { int returnValue = amountValidation.retrunValue; string returnReference = amountValidation.retrunReference; if (returnValue > 0) { DataTable dt = this.AddValiesToDataTable(receipt); /* print report */ var reportParameters = this.GetParameterJsonObject(returnReference); reportBll.ViewReport("billReceipt", reportParameters, dt); /* Refresh page */ this.clearProductForm(); this.ProductFormFieldValidation(); isReceiptFormEnable = false; cmbPhoneNumber.Enabled = true; txtName.Enabled = true; txtAddress.Enabled = true; this.initializeProductDropdowns(); this.initializeReceptTable(); this.bspFormReset(); this.resetTable(); } else { MessageBox.Show("Some error happen. Please try again"); } } } }
public Product Get(int id) { var data = ProductVM.get(UnitOfWork, id); return(data); }
public IActionResult Upsert(ProductVM productVM) { if (ModelState.IsValid) { var files = HttpContext.Request.Form.Files; string webRootPath = _webHostEnvironment.WebRootPath; if (productVM.Product.Id == 0) { //Creating string upload = webRootPath + WC.ImagePath; string fileName = Guid.NewGuid().ToString(); string extension = Path.GetExtension(files[0].FileName); using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create)) { files[0].CopyTo(fileStream); } productVM.Product.Image = fileName + extension; _db.Product.Add(productVM.Product); } else { //Update var objFromDb = _db.Product.AsNoTracking().FirstOrDefault(u => u.Id == productVM.Product.Id); if (files.Count > 0) { string upload = webRootPath + WC.ImagePath; string fileName = Guid.NewGuid().ToString(); string extension = Path.GetExtension(files[0].FileName); var oldFile = Path.Combine(upload, objFromDb.Image); if (System.IO.File.Exists(oldFile)) { System.IO.File.Delete(oldFile); } using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create)) { files[0].CopyTo(fileStream); } productVM.Product.Image = fileName + extension; } else { productVM.Product.Image = objFromDb.Image; } _db.Product.Update(productVM.Product); } _db.SaveChanges(); return(RedirectToAction("Index")); } productVM.CategorySelectList = _db.Category.Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }); productVM.ApplicationTypeSelectList = _db.ApplicationType.Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }); return(View(productVM)); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } return View(model); } using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "This product name is taken"); model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return View(model); } } int id; using (Db db = new Db()) { ProductDTO dto = new ProductDTO(); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; CategoryDTO categoryDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = categoryDTO.Name ?? ""; db.Products.Add(dto); db.SaveChanges(); id = dto.Id; } TempData["SM"] = "You have added a product"; #region Upload Image var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); string[] paths = new string[] { Path.Combine(originalDirectory.ToString(), "Products"), Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()), Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()+ "\\Thumbs"), Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"), Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs") }; foreach (var path in paths) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); } if (file != null && file.ContentLength > 0) { string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension"); } return View(model); } string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } string[] pathWithFiles = new string[] { string.Format($"{paths[1]}\\{imageName}"), string.Format($"{paths[2]}\\{imageName}") }; file.SaveAs(pathWithFiles[0]); WebImage wi = new WebImage(file.InputStream); wi.Resize(200, 200).Crop(1,1); wi.Save(pathWithFiles[1]); } #endregion return RedirectToAction("AddProduct"); }
public IActionResult Upsert(ProductVM productVM) { ProductVM productVM2 = new ProductVM() { Product = new Product(), CategoryList = _unitOfWork.Category.GetAll().Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }), MadeInList = SD.MadeInState }; if (ModelState.IsValid) { string webRootPath = _hostEnvironment.WebRootPath; var files = HttpContext.Request.Form.Files; if (files.Count > 0) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(webRootPath, @"Images\Products"); var extention = Path.GetExtension(files[0].FileName); if (productVM.Product.ImageUrl != null) { //this is an edit and we need to remove old image var imagePath = Path.Combine(webRootPath, productVM.Product.ImageUrl.TrimStart('\\')); if (System.IO.File.Exists(imagePath)) { System.IO.File.Delete(imagePath); } } using (var filesStreams = new FileStream(Path.Combine(uploads, fileName + extention), FileMode.Create)) { files[0].CopyTo(filesStreams); } productVM.Product.ImageUrl = @"\Images\Products\" + fileName + extention; } else { //update when they do not change the image if (productVM.Product.Id != 0) { Product objFromDb = _unitOfWork.Product.Get(productVM.Product.Id); productVM.Product.ImageUrl = objFromDb.ImageUrl; } } if (productVM.Product.Id == 0) { bool existProd = _unitOfWork.Product.GetAll().Any(a => a.ProductName.ToLower() == productVM.Product.ProductName.ToLower()); if (existProd) { ViewBag.existProd = true; } else { ViewBag.existProd = false; _unitOfWork.Product.Add(productVM.Product); } } else { _unitOfWork.Product.update(productVM.Product); } ViewBag.ShowMsg = true; ViewBag.existProd = false; _unitOfWork.Save(); return(View(productVM2)); } ViewBag.ShowMsg = true; ViewBag.existProd = false; return(View(productVM2)); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { // Check model state if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } // Make sure product name is unique using (Db db = new Db()) { if (db.Products.Any(a => a.Name.Equals(model.Name))) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } // Make product id(declare) int id; // Initialize product Dto the save it using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoriesDTO catDTO = db.Categories.FirstOrDefault(a => a.Id.Equals(model.CategoryId)); product.CategoryName = catDTO.Name; db.Products.Add(product); db.SaveChanges(); // Get inserted id id = product.Id; } // Dont forget about temp data message! TempData["SM"] = "You have added a product!"; #region Upload Image // Create necessary directories DirectoryInfo originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); string pathString = Path.Combine(originalDirectory.ToString(), "Products"); string pathStringWithId = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); string pathStringThumbs = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); string pathStringGallery = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); string pathStringGalleryThumbs = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString)) { Directory.CreateDirectory(pathString); } if (!Directory.Exists(pathStringWithId)) { Directory.CreateDirectory(pathStringWithId); } if (!Directory.Exists(pathStringThumbs)) { Directory.CreateDirectory(pathStringThumbs); } if (!Directory.Exists(pathStringGallery)) { Directory.CreateDirectory(pathStringGallery); } if (!Directory.Exists(pathStringGalleryThumbs)) { Directory.CreateDirectory(pathStringGalleryThumbs); } // Check if file was uploaded if (file != null && file.ContentLength > 0) { // Get file extension string fileExtension = file.ContentType.ToLower(); // Verify extension if (!fileExtension.Equals("image/jpg") && !fileExtension.Equals("image/jpeg") && !fileExtension.Equals("image/pjpeg") && !fileExtension.Equals("image/gif") && !fileExtension.Equals("image/x-png") && !fileExtension.Equals("image/png")) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension!"); return(View(model)); } } // Init image name string imageName = file.FileName; // Save image name to DTO using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Set original and thumb image paths string pathId = string.Format("{0}\\{1}", pathStringWithId, imageName); string pathThumbs = string.Format("{0}\\{1}", pathStringThumbs, imageName); // Save original file.SaveAs(pathId); // Create and save thumb WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(pathThumbs); } #endregion return(RedirectToAction("AddProduct")); }
public ActionResult Create(ProductVM product, HttpPostedFileBase[] ProductImageId, int sizeId, int colorId) { Product newPro = new Product() { ProductName = product.ProductName, UnitPrice = product.UnitPrice, DiscountRatio = product.DiscountRatio, DiscountExpiry = product.DiscountExpiry, CategoryId = product.CategoryId, Description = product.Description, CreatedDate = product.CreatedDate, CreatedBy = product.CreatedBy, StatusId = product.StatusId }; db.Products.Add(newPro); db.SaveChanges(); ProductSize proSize = new ProductSize() { ProductId = newPro.Id, SizeId = sizeId }; db.ProductSizes.Add(proSize); db.SaveChanges(); ProductColor proColor = new ProductColor() { ProductId = newPro.Id, ColorId = colorId }; db.ProductColors.Add(proColor); db.SaveChanges(); if (ProductImageId[0] == null) { return(RedirectToAction("Index")); } ///Lưu vào bảng ProIamge ProductImage proImage = new ProductImage(); foreach (var item in ProductImageId) { proImage.ImageUrl = item.FileName; proImage.ProductId = newPro.Id; db.ProductImages.Add(proImage); db.SaveChanges(); } ///Lấy id của url đầu tiên của Pro string findUrl = ProductImageId[0].FileName; var defaultImage = db.ProductImages.Where(x => x.ImageUrl == findUrl).FirstOrDefault(); newPro.ProductImageId = defaultImage.Id; db.SaveChanges(); string strFolder = Server.MapPath("~/Data/Products/" + newPro.Id); if (!Directory.Exists(strFolder)) { Directory.CreateDirectory(strFolder); } foreach (var item in ProductImageId) { item.SaveAs(strFolder + @"\" + item.FileName); } return(RedirectToAction("Index")); }
public ActionResult Edit(ProductVM productVM) { if (ModelState.IsValid == true) { if (productVM.ImageFile != null) { string fileName = Path.GetFileNameWithoutExtension(productVM.ImageFile.FileName); string extention = Path.GetExtension(productVM.ImageFile.FileName); HttpPostedFileBase postedFile = productVM.ImageFile; int length = postedFile.ContentLength; if (extention.ToLower() == ".jpg" || extention.ToLower() == ".jpeg" || extention.ToLower() == ".png") { if (length <= 1000000) { fileName = fileName + extention; productVM.ImagePath = "~/AppFiles/Images/" + fileName; fileName = Path.Combine(Server.MapPath("~/AppFiles/Images/"), fileName); productVM.ImageFile.SaveAs(fileName); var product = Mapper.Map <Product>(productVM); db.Entry(product).State = EntityState.Modified; int a = db.SaveChanges(); if (a > 0) { ModelState.Clear(); return(RedirectToAction("Index", "Product")); } else { TempData["UpdateMessage"] = "<script>alert('Data not Updated')</script>"; } } else { TempData["SizeMessage"] = "<script>alert('Image Size Should Less Than 1 MB')</script>"; } } else { TempData["ExtentionMessage"] = "<script>alert('Format Not Supported')</script>"; } } else { productVM.ImagePath = Session["Image"].ToString(); var product = Mapper.Map <Product>(productVM); db.Entry(product).State = EntityState.Modified; int a = db.SaveChanges(); if (a > 0) { TempData["UpdateMessage"] = "<script>alert('Data Updated Successfully')</script>"; ModelState.Clear(); return(RedirectToAction("Index", "Product")); } else { TempData["UpdateMessage"] = "<script>alert('Data not Updated')</script>"; } } } return(View()); }
public async System.Threading.Tasks.Task <IActionResult> Upsert(ProductVM productVM) { if (ModelState.IsValid) { string webRootPath = _hostEnvironment.WebRootPath; var files = HttpContext.Request.Form.Files; if (files.Count > 0) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(webRootPath, @"images\products"); var extenstion = Path.GetExtension(files[0].FileName); if (productVM.Product.ImageUrl != null) { var imageUrl = productVM.Product.ImageUrl; var imagePath = Path.Combine(webRootPath, productVM.Product.ImageUrl.TrimStart('\\')); if (System.IO.File.Exists(imagePath)) { System.IO.File.Delete(imagePath); } } using (var fileStreams = new FileStream(Path.Combine(uploads, fileName + extenstion), FileMode.Create)) { files[0].CopyTo(fileStreams); } var pathRoot = AppDomain.CurrentDomain.BaseDirectory; using (var fileStreams = new FileStream(Path.Combine(pathRoot, fileName + extenstion), FileMode.Create)) { files[0].CopyTo(fileStreams); } //TODO:CreateBucket try { if (await AmazonS3Util.DoesS3BucketExistAsync(client, bucketName)) { throw new Exception("Oluşturulmak istenilen Bucket Zaten Mevcut"); } else { var bucketRequest = new PutBucketRequest { BucketName = bucketName, UseClientRegion = true }; var bucketResponse = client.PutBucketAsync(bucketRequest); if (bucketResponse.Result.HttpStatusCode == System.Net.HttpStatusCode.OK) { var transferUtility = new TransferUtility(client); var transferRequest = new TransferUtilityUploadRequest { FilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + fileName + extenstion, BucketName = bucketName, CannedACL = S3CannedACL.PublicRead }; transferUtility.Upload(transferRequest); } } } catch (AmazonS3Exception e) { Console.WriteLine(e.Message.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } //productVM.Product.ImageUrl = @"\images\products\" + fileName + extenstion; } else { if (productVM.Product.Id != 0) { var productData = _uow.Product.Get(productVM.Product.Id); productVM.Product.ImageUrl = productData.ImageUrl; } } if (productVM.Product.Id == 0) { //Create _uow.Product.Add(productVM.Product); } else { //Update _uow.Product.Update(productVM.Product); } _uow.Save(); return(RedirectToAction("Index")); } else { productVM.CategoryList = _uow.Category.GetAll().Select(a => new SelectListItem { Text = a.CategoryName, Value = a.Id.ToString() }); productVM.CoverTypeList = _uow.CoverType.GetAll().Select(a => new SelectListItem { Text = a.Name, Value = a.Id.ToString() }); if (productVM.Product.Id != 0) { productVM.Product = _uow.Product.Get(productVM.Product.Id); } } return(View(productVM.Product)); }
public IActionResult EditProduct(ProductVM objVM, IFormFile file) { if (!ModelState.IsValid) { return(View(objVM)); } // Use the DB data to save the image Name var dbProduct = _db.Products.Where(p => p.Id == objVM.Product.Id).AsNoTracking().FirstOrDefault(); //When Updating the file, check whether there is a file uploaded. //The only way to know if by checking if the file length is greater than 0(if(file.Length >0)) //If yes, then the user uploaded a set of data you may need to save by creating a new FileStream Object // Else remember to save the DatabaseImageName as the new image Name before Updating the obj // or you simply say... if file == null ---use DBNAME var files = HttpContext.Request.Form.Files; if (files.Count > 0) { string webRootPath = _webHostEnvironment.WebRootPath; //Creating a file path that the image will be saved string upload = webRootPath + @"\ProductImages\"; string fileName = Guid.NewGuid().ToString(); string extension = Path.GetExtension(files[0].FileName); var oldFile = Path.Combine(upload, dbProduct.ProductImage); if (System.IO.File.Exists(oldFile)) { System.IO.File.Delete(oldFile); } using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create)) { files[0].CopyTo(fileStream); } objVM.Product.ProductImage = fileName + extension; ////Since the form will also be posting a file then we have to get the file path ////We created a folder(ProductImages) inside the wwwroot folder ////We use IWebHostEnvironment to get the WebRootPath- wwwroot.. ////Thereafter we will concatenate it with the folder name //string filePath = _webHostEnvironment.WebRootPath + "ProductImages"; ////A complete PathName is filePath + ImageName ////To create an Image Name for the Picture uploaded- //// Guid + PathExtension----.jpeg,png( IFormFile.FileName //string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName); //string fullFilePath = Path.Combine(filePath, fileName); ////Now that we have gotten the file path- we will create a FileStream //// that can read the File or store the Picture file for us ins //// we can use file.CopyTo() -- to copy the file to the file stream Object creaded //using (var stream = new FileStream(fullFilePath, FileMode.Create)) //{ // file.CopyTo(stream); //} ////After we had successfully copied the file into the stream, ////we should remember to save the fileName to the DB as shown below //obj.Product.ProductImage = fileName; } else { objVM.Product.ProductImage = dbProduct.ProductImage; } //Created Date- will remain the same as before-DB result objVM.Product.CreatedDate = dbProduct.CreatedDate; //Modified Date objVM.Product.ModifiedDate = DateTime.Now; //Remember to set is deletedto false so that it will show on the table objVM.Product.IsDelete = false; //Before Adding it to the Database map itfrom the View Model to the Domain Class //var product = _map.Map<Product>(obj); _db.Products.Update(objVM.Product); _db.SaveChanges(); return(RedirectToAction("Index")); }
public async Task <IActionResult> EditProduct(ProductVM product, string type) { var products = (from a in _context.Products .Join(_context.ProductCategories, ac => ac.CategoryIdLvl1, cc => cc.Id, (ac, cc) => new { ac, cc } ).ToList() group a by a.ac.Name into pp select new ProductWithCategoryVM { Product = pp.FirstOrDefault().ac, Categories = String.Join(", ", (pp.Select(x => x.cc.Name)).ToArray()), }).OrderBy(x => x.Product.UpdatedAt) .ToList(); if (type == "0") { //Edit Single Product var items = await _context.Products.Where(x => x.Name == product.Name).ToListAsync(); foreach (var item in items) { item.Description = product.Description; if (product.Tags != null) { item.Tags = product.Tags; } if (product.Price != 0 && product.DiscountPrice != 0) { item.Discount = 100 - Convert.ToInt32((product.DiscountPrice * 100) / product.Price); } else { item.Discount = 0; } item.SetProducts = product.setProductsValue; item.Price = product.DiscountPrice; item.UpdatedAt = DateTime.Now; item.ProductStatus = product.Status; } await _context.SaveChangesAsync(); return(Json(new { method = "edit", item = products.Select(s => new { s.Product.Id, s.Product.Name, s.Product.ProductStatus, Status = s.Product.ProductStatus.ToString(), Price = string.Format("{0:n0}", s.Product.Price).ToPersianNumbers(), Date = s.Product.UpdatedAt.ToPersianDateTextify(), s.Product.Description, s.Product.CategoryIdLvl1, s.Product.CategoryIdLvl2, s.Product.CategoryIdLvl3, //s.Product.CategoryIdLvl4, s.Product.Code, s.Product.Discount, s.Product.Tags, s.Product.SpecialSale, s.Product.ImageUrl, //UnitId = s.Product.Unit.Id, //Unit = s.Product.Unit.Name, s.Categories, UpdatedAt = s.Product.UpdatedAt.ToFriendlyPersianDateTextify(), product = s.Product.Description + "_" + s.Product.Id }).SingleOrDefault(x => x.Name == product.Name) })); } else { //Edit Multipite Product var items = new List <Product>(); var ids = product.Name.Split("_"); foreach (var item in ids) { if (item != "") { var p = await _context.Products.Where(x => x.Name == item).ToListAsync(); items.AddRange(p); } } foreach (var item in items) { item.Description = product.Description; item.Tags = product.Tags; if (product.Price != 0 && product.DiscountPrice != 0) { item.Discount = 100 - Convert.ToInt32((product.DiscountPrice * 100) / product.Price); } else { item.Discount = 0; } item.SetProducts = product.setProductsValue; item.Price = product.DiscountPrice; item.UpdatedAt = DateTime.Now; item.ProductStatus = product.Status; } await _context.SaveChangesAsync(); return(Json(new { method = "multipiteEdit", item = products.Select(s => new { s.Product.Id, s.Product.Name, s.Product.ProductStatus, Status = s.Product.ProductStatus.ToString(), Price = string.Format("{0:n0}", s.Product.Price).ToPersianNumbers(), Date = s.Product.UpdatedAt.ToPersianDateTextify(), s.Product.Description, s.Product.CategoryIdLvl1, s.Product.CategoryIdLvl2, s.Product.CategoryIdLvl3, //s.Product.CategoryIdLvl4, s.Product.Code, s.Product.SpecialSale, s.Product.Discount, s.Product.Tags, s.Product.ImageUrl, //UnitId = s.Product.Unit.Id, //Unit = s.Product.Unit.Name, s.Categories, UpdatedAt = s.Product.UpdatedAt.ToFriendlyPersianDateTextify(), product = s.Product.Description + "_" + s.Product.Id }).Where(x => product.Name.Split("_").Contains(x.Name)).ToList() })); } }
public async Task <IActionResult> AddToShop(ProductVM product) { if (product.Status == ProductStatus.آماده_برای_فروش && product.DiscountPrice == 0 || product.Status == ProductStatus.آماده_برای_فروش && product.Price == 0) { return(Json(new { method = "error", status = "0", message = "برای ورود به فروشگاه اول باید قیمت گذاری شود" })); } var items = await _context.Products.Where(x => x.Name == product.Name).ToListAsync(); foreach (var item in items) { item.Description = product.Description; item.Tags = product.Tags; if (product.Price != 0 && product.DiscountPrice != 0) { item.Discount = Convert.ToInt32(((product.Price - product.DiscountPrice) / product.Price) * 100); } else { item.Discount = 0; } item.SetProducts = product.setProductsValue; item.Price = product.Price; item.ProductStatus = product.Status; item.UpdatedAt = DateTime.Now; } await _context.SaveChangesAsync(); var products = (from a in _context.Products .Join(_context.ProductCategories, ac => ac.CategoryIdLvl1, cc => cc.Id, (ac, cc) => new { ac, cc } ).ToList() group a by a.ac.Name into pp select new ProductWithCategoryVM { Product = pp.FirstOrDefault().ac, Categories = String.Join(", ", (pp.Select(x => x.cc.Name)).ToArray()), }) .ToList(); return(Json(new { method = "create", item = products.Select(s => new { s.Product.Id, s.Product.Name, s.Product.ProductStatus, Status = s.Product.ProductStatus.ToString(), Price = string.Format("{0:n0}", s.Product.Price).ToPersianNumbers(), Date = s.Product.UpdatedAt.ToPersianDateTextify(), s.Product.Description, s.Product.CategoryIdLvl1, s.Product.CategoryIdLvl2, s.Product.CategoryIdLvl3, //s.Product.CategoryIdLvl4, s.Product.Code, s.Product.Discount, s.Product.Tags, s.Product.ImageUrl, s.Product.QR, //UnitId = s.Product.Unit.Id, //Unit = s.Product.Unit.Name, s.Categories, UpdatedAt = s.Product.UpdatedAt.ToFriendlyPersianDateTextify(), product = s.Product.Description + "_" + s.Product.Id }).SingleOrDefault(x => x.Name == product.Name) })); }
public IActionResult Edit(ProductVM editedProduct) { _productService.EditProduct(editedProduct); return(RedirectToAction("Index")); }
public async Task <ActionResult <ApiResult <string> > > PutProduct(long productid, ProductVM p) { var pr = _context.Products.Where(x => x.ProductID.Equals(productid)).FirstOrDefault(); if (pr != null) { pr.Name = p.Name; pr.ShortName = p.Name; _context.SaveChanges(); return(new ApiResult <string> { IsValid = true, Result = "Product '" + pr.Name + "' was successfully updated!" }); } return(new ApiResult <string> { IsValid = false, Result = "Product not found" }); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { // sprawdzamy model state if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } // sprawdzenie czy nazwa produktu jest unikalna using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "Ta nazwa produktu jest zajęta!"); return(View(model)); } } // deklaracja product id int id; // dodawanie produktu i zapis na bazie using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDto.Name; db.Products.Add(product); db.SaveChanges(); // pobranie id dodanego produktu id = product.Id; } // ustawiamy komunikat TempData["SM"] = "Dodałeś produkt"; #region Upload Image // Utworzenie potrzebnej struktury katalogów var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } if (file != null && file.ContentLength > 0) { // sprawdzenie rozszezenia pliku czy mamy do czynienia z obrazkiem string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "Obraz nie został przesłany - nieprawidłowe rozszerzenie obrazu."); return(View(model)); } } // inicjalizacja nazwy obrazka string imageName = file.FileName; // zapis nazwy obrazka do bazy using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); // zapisujemy orginalny obrazek file.SaveAs(path); // zapisujemy miniaturke WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("AddProduct")); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { // Get product id int id = model.Id; // Populate categories select list and gallery images using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(a => Path.GetFileName(a)); // Check model state if (!ModelState.IsValid) { return(View(model)); } // Make sure product name is unique using (Db db = new Db()) { if (db.Products.Where(a => a.Id != id).Any(b => b.Name.Equals(model.Name))) { ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } // Update product using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoriesDTO catDTO = db.Categories.FirstOrDefault(a => a.Id == model.CategoryId); dto.CategoryName = catDTO.Name; db.SaveChanges(); } // Dont forget about tempdata TempData["SM"] = "You have edited the product!"; #region Image Upload // Check for file upload if (file != null && file.ContentLength > 0) { // Get file extension string fileExtension = file.ContentType.ToLower(); // Verify extension if (!fileExtension.Equals("image/jpg") && !fileExtension.Equals("image/jpeg") && !fileExtension.Equals("image/pjpeg") && !fileExtension.Equals("image/gif") && !fileExtension.Equals("image/x-png") && !fileExtension.Equals("image/png")) { using (Db db = new Db()) { ModelState.AddModelError("", "The image was not uploaded - wrong image extension!"); return(View(model)); } } // Set upload directory paths DirectoryInfo originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); string pathStringWithId = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); string pathStringThumbs = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); // Delete filese from directories !!! DirectoryInfo productsDirectoryInfo = new DirectoryInfo(pathStringWithId); DirectoryInfo productsThumbsDirectoryInfo = new DirectoryInfo(pathStringThumbs); foreach (FileInfo item in productsDirectoryInfo.GetFiles()) { item.Delete(); } foreach (FileInfo item in productsThumbsDirectoryInfo.GetFiles()) { item.Delete(); } // Save image name string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Save original and thumb images string pathId = string.Format("{0}\\{1}", pathStringWithId, imageName); string pathThumbs = string.Format("{0}\\{1}", pathStringThumbs, imageName); // Save original file.SaveAs(pathId); // Create and save thumb WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(pathThumbs); } #endregion return(RedirectToAction("EditProduct")); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { // pobranie id produktu int id = model.Id; // pobranie kategorii dla listy rozwijanej using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } // ustawiamy zdjecia model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); // sprawdzamy model state if (!ModelState.IsValid) { return(View(model)); } // sprawdzenie unikalnosci nazwy produktu using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "Ta nazwa produktu jest zajęta"); return(View(model)); } } // Edycja produktu i zapis na bazie using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDto.Name; db.SaveChanges(); } // ustawienie TempData TempData["SM"] = "Edytowałeś produkt"; #region Image Upload // sprawdzamy czy jest plik if (file != null && file.ContentLength > 0) { // sprawdzamy rozszerzenie pliku czy to jest obrazek string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "Obraz nie został przesłany - nieprawidłowe rozszerzenie obrazu."); return(View(model)); } } // Utworzenie potrzebnej struktury katalogów var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); // usuwamy stare pliki z katalogow DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (var file2 in di1.GetFiles()) { file2.Delete(); } foreach (var file3 in di2.GetFiles()) { file3.Delete(); } // Zapis nazwy obrazka na bazie string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Zapis nowych plików var path = string.Format("{0}\\{1}", pathString1, imageName); var path2 = string.Format("{0}\\{1}", pathString2, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("EditProduct")); }
public IActionResult Upsert(ProductVM productVM) { if (ModelState.IsValid) { string webRootPath = _hostEnvironment.WebRootPath; var files = HttpContext.Request.Form.Files; if (files.Count > 0) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(webRootPath, @"images\products"); var extension = Path.GetExtension(files[0].FileName); if (productVM.Product.ImageUrl != null) { var imageUrl = productVM.Product.ImageUrl; var imagePath = Path.Combine(webRootPath, productVM.Product.ImageUrl.TrimStart('\\')); if (System.IO.File.Exists(imagePath)) { System.IO.File.Delete(imagePath); } } using (var fileStreams = new FileStream(Path.Combine(uploads, fileName + extension), FileMode.Create)) { files[0].CopyTo(fileStreams); } productVM.Product.ImageUrl = @"\images\products\" + fileName + extension; } else { if (productVM.Product.Id != 0) { var productData = _uow.Product.Get(productVM.Product.Id); productVM.Product.ImageUrl = productData.ImageUrl; } } if (productVM.Product.Id == 0) { //Create _uow.Product.Add(productVM.Product); } else { //Update _uow.Product.Update(productVM.Product); } _uow.Save(); return(RedirectToAction("Index")); } else { productVM.CategoryList = _uow.Category.GetAll().Select(a => new SelectListItem { Text = a.CategoryName, Value = a.Id.ToString() }); productVM.CoverTypeList = _uow.CoverType.GetAll().Select(a => new SelectListItem { Text = a.Name, Value = a.Id.ToString() }); if (productVM.Product.Id != 0) { productVM.Product = _uow.Product.Get(productVM.Product.Id); } } return(View(productVM.Product)); }
public async Task <ActionResult> AddProduct(ProductVM model, HttpPostedFileBase file) { if (!ModelState.IsValid) { model.Categories = new SelectList(await db.Categories.ToListAsync(), "Id", "Name"); return(View(model)); } // Make sure product name is unique if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(await db.Categories.ToListAsync(), "Id", "Name"); ModelState.AddModelError("", "That product Name is taken"); return(View(model)); } CategoryDTO category = await db.Categories.FirstOrDefaultAsync(c => c.Id == model.CategoryId); db.Products.Add(new ProductDTO { Name = model.Name, Slug = model.Name.Replace(" ", "-"), Description = model.Description, CategoryId = model.CategoryId, CategoryName = category.Name, Category = category, Price = model.Price }); await db.SaveChangesAsync(); // Get the product id int productId = await db.Products.OrderByDescending(p => p.Id) .Select(p => p.Id).FirstOrDefaultAsync(); TempData["SM"] = "You have Added a product"; #region Product Image /* * Create necessary directories */ var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); // pathString1 = "\Images\Uploads\Products"; var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); // Need specific product holder var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + productId.ToString()); // Need main image thumb var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + productId.ToString() + "\\Thumbs"); // For Gallery Images var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + productId.ToString() + "\\Gallery"); // For Gallery thumbs var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + productId.ToString() + "\\Gallery\\Thumbs" + productId.ToString()); // Check if these Directories exists. If not, create them if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } // Check if file was uploaded if (file != null && file.ContentLength > 0) { // Get file extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/png" && ext != "image/gif") { model.Categories = new SelectList(await db.Categories.ToListAsync(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension"); return(View(model)); } // Init image name string imgName = file.FileName; // Save image name to dto var product = await db.Products.FindAsync(productId); product.ImageName = imgName; db.Entry(product).State = EntityState.Modified; await db.SaveChangesAsync(); // Set original or thumb image paths var path = string.Format("{0}\\{1}", pathString2, imgName); var path2 = string.Format("{0}\\{1}", pathString3, imgName); // Save original file.SaveAs(path); // Create and Save thumb WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("AddProduct")); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { int id = model.Id; using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id.ToString() + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); if (!ModelState.IsValid) { return View(model); } using (Db db = new Db()) { if(db.Products.Where(x=> x.Id!=id).Any(x=>x.Name==model.Name)) { ModelState.AddModelError("", "That product name is taken"); return View(model); } model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDto.Name; db.SaveChanges(); } TempData["SM"] = "You have edited the product"; #region Image Upload if(file!=null&&file.ContentLength>0) { string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension"); } return View(model); } var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); string[] paths = new string[] { Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()), Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()+ "\\Thumbs") }; foreach (var path in paths) { DirectoryInfo di = new DirectoryInfo(path); foreach(var files in di.GetFiles()) { files.Delete(); } } string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } string[] pathWithFiles = new string[] { string.Format($"{paths[0]}\\{imageName}"), string.Format($"{paths[1]}\\{imageName}") }; file.SaveAs(pathWithFiles[0]); WebImage wi = new WebImage(file.InputStream); wi.Resize(200, 200).Crop(1, 1); wi.Save(pathWithFiles[1]); } #endregion return RedirectToAction("EditProduct"); }
public void Delete(ProductVM obj) { var entity = _context.Products.Where(e => e.Id == obj.Id).FirstOrDefault(); entity.IsDeleted = true; }
public async Task <ActionResult <IEnumerable <Product> > > Get() { var data = ProductVM.getAll(UnitOfWork); return(data); }
public IActionResult Upsert(ProductVM productVM) { if (ModelState.IsValid) { var files = HttpContext.Request.Form.Files; string webRootPath = _webHostEnvironment.WebRootPath; if (productVM.Product.Id == 0) { //Creating new string upload = webRootPath + WC.ImagePath; string fileName = Guid.NewGuid().ToString(); string extension = Path.GetExtension(files[0].FileName); using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create)) { files[0].CopyTo(fileStream); } productVM.Product.Image = fileName + extension; _prodRepo.Add(productVM.Product); } else { //Updating var objFromDb = _prodRepo.FirstOrDefault(u => u.Id == productVM.Product.Id, isTracking: false); if (files.Count > 0)//It is meen that new file uploaded { string upload = webRootPath + WC.ImagePath; string fileName = Guid.NewGuid().ToString(); string extension = Path.GetExtension(files[0].FileName); //Delete Old image var oldFile = Path.Combine(upload, objFromDb.Image); if (System.IO.File.Exists(oldFile)) { System.IO.File.Delete(oldFile); } //Load new Image using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create)) { files[0].CopyTo(fileStream); } productVM.Product.Image = fileName + extension; } else { productVM.Product.Image = objFromDb.Image; } _prodRepo.Update(productVM.Product); } //_prodRepo.Product.Add(productVM.Product); _prodRepo.Save(); return(RedirectToAction("Index")); } //Not valid data //Recreate select list //productVM.CategorySelectList = _prodRepo.Category.Select(i => new SelectListItem //{ // Text = i.Name, // Value = i.Id.ToString() //}); //productVM.ApplicationTypeSelectList = _prodRepo.ApplicationType.Select(i => new SelectListItem //{ // Text = i.Name, // Value = i.Id.ToString() //}); productVM.CategorySelectList = _prodRepo.GetAllDropdownList(WC.CategoryName); productVM.ApplicationTypeSelectList = _prodRepo.GetAllDropdownList(WC.ApplicationTypeName); return(View(productVM)); }
public void OnGet(int productId) { ProductDetail = _productVMService.GetProduct(productId); ProductIndex = _productVMService.GetProductsVM(HttpContext, null); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { //Проверяем модель на валидность if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } //Проверяем имя продукта на уникальность using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } //Объявляем переменную productID int id; //Инициализируем и сохраяняем модель в базу using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDTO.Name; product.Manufacturer = model.Manufacturer; db.Products.Add(product); db.SaveChanges(); id = product.Id; } //Дабавляем сообщение в TempData TempData["SM"] = "You have added a new product!"; #region Upload Image //Создаём необходимые ссылки на дериктории var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); //Проверяем, имеется ли дериктория (если нет, то создаем) if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } //Проверяем был ли файл загружен if (file != null && file.ContentLength > 0) { //Получаем расширение файла string ext = file.ContentType.ToLower(); //Проверяем расширения загружаемого файла if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image is not uploaded - wrong image extension!"); return(View(model)); } } //Объявляем переменную с именем изображения string imageName = file.FileName; //Сохраняем имя изображения в модель DTO using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } //Назначаем пути к оригинальному и уменьшеному изображению var path = string.Format($"{pathString2}\\{imageName}"); var path2 = string.Format($"{pathString3}\\{imageName}"); //Сохраняем оригинальное изображение file.SaveAs(path); //Создаём и сохраняем уменьшенную копию WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion //Переадресовываем пользователя return(RedirectToAction("AddProduct")); }
public async Task <IActionResult> Upsert(ProductVM productVM) { if (ModelState.IsValid) { string webRootPath = _hostEnvironment.WebRootPath; var files = HttpContext.Request.Form.Files; if (files.Count > 0) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(webRootPath, @"images\products"); var extenstion = Path.GetExtension(files[0].FileName); if (productVM.Product.ImageUrl != null) { //this is an edit and we need to remove old image var imagePath = Path.Combine(webRootPath, productVM.Product.ImageUrl.TrimStart('\\')); if (System.IO.File.Exists(imagePath)) { System.IO.File.Delete(imagePath); } } using (var filesStreams = new FileStream(Path.Combine(uploads, fileName + extenstion), FileMode.Create)) { files[0].CopyTo(filesStreams); } productVM.Product.ImageUrl = @"\images\products\" + fileName + extenstion; } else { //update when they do not change the image if (productVM.Product.Id != 0) { Product objFromDb = _unitOfWork.Product.Get(productVM.Product.Id); productVM.Product.ImageUrl = objFromDb.ImageUrl; } } if (productVM.Product.Id == 0) { _unitOfWork.Product.Add(productVM.Product); } else { _unitOfWork.Product.Update(productVM.Product); } _unitOfWork.Save(); return(RedirectToAction(nameof(Index))); } else { IEnumerable <Category> catList = await _unitOfWork.Category.GetAllAsync(); productVM.CategoryList = catList.Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }); productVM.CoverTypeList = _unitOfWork.CoverType.GetAll().Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }); if (productVM.Product.Id != 0) { productVM.Product = _unitOfWork.Product.Get(productVM.Product.Id); } } return(View(productVM)); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { //Получаем Id продукта int id = model.Id; //Заполняем список категориями и изображениями using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); //Проверяем модель на валидность if (!ModelState.IsValid) { return(View(model)); } //Проверяем имя продукта на уникальность using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } //Обновляем продукт в базе данных using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.Manufacturer = model.Manufacturer; dto.ImageName = model.ImageName; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDTO.Name; db.SaveChanges(); } //Устанавливаем сообщение в TempData TempData["SM"] = "You have edited that product!"; //Логика обработки изображений #region Image Upload // Проверяем загружен ли файл if (file != null && file.ContentLength > 0) { //Получаем расширение файла string ext = file.ContentType.ToLower(); //Проверяем расширение файла if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { ModelState.AddModelError("", "The image is not uploaded - wrong image extension!"); return(View(model)); } } //Устанавливаем пути для загрузки var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); //Удаляем существующие файлы и директориях DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (var file2 in di1.GetFiles()) { file2.Delete(); } foreach (var file3 in di2.GetFiles()) { file3.Delete(); } //Сохраняем имя изображение string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } var path = string.Format($"{pathString1}\\{imageName}"); var path2 = string.Format($"{pathString2}\\{imageName}"); //Сохраняем оригинальное изображение file.SaveAs(path); //Создаём и сохраняем уменьшенную копию WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion //Переадресовываем пользователя return(RedirectToAction("EditProduct")); }
private void SubscribeHandlers(ProductVM product) { product.EntityDeleted += (s, e) => _products.Remove(SelectedProduct); }
public ProductVmWp(ProductVM core) { _core = core; }