private void ExamineImageButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == true) { System.Drawing.Image img = System.Drawing.Image.FromFile(openFileDialog.FileName); string[] fileName = openFileDialog.FileName.Split('\\'); string name = fileName[fileName.Length - 1].Split('.')[0]; ImageProduct imageList = new ImageProduct { Image = img, idProducto = 1, Description = name, Id = Guid.NewGuid() }; BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.UriSource = new Uri("https://drive.google.com/file/d/1uNokKACEDvZARxWnl6vRVNDeNAcBv5v_/view?usp=sharing"); bitmap.EndInit(); imageProduct.Source = bitmap; //upicImageAdd.Image = imageList.Image.Width > upicImageAdd.Width || imageList.Image.Height > upicImageAdd.Height ? PhotoExtension.ResizeImage(imageList.Image, upicImageAdd.Width, upicImageAdd.Height) : imageList.Image; //utxtDescription.Text = imageList.Description; //ulblFileName.Text = OpenFileDialog.FileName; //ImageRibbonList = imageList; } }
public ActionResult Edit(Product product) { if (ModelState.IsValid) { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName.Replace(" ", "_")); ImageProduct fileDetail = new ImageProduct() { FileImages = fileName.Replace(" ", "_"), ImageProductID = Guid.NewGuid(), ProductID = product.ProductID }; var path = Path.Combine(Server.MapPath("~/Upload/Images/"), fileName.Replace(" ", "_")); file.SaveAs(path); db.Entry(fileDetail).State = EntityState.Added; } } db.Entry(product).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CategoryID = new SelectList(db.Categorys, "CategoryID", "CategoryName", product.CategoryID); return(View(product)); }
public JsonResult DeleteFile(string id) { if (String.IsNullOrEmpty(id)) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { Result = "Error" })); } try { Guid guid = new Guid(id); ImageProduct fileDetail = db.ImageProduct.Find(guid); if (fileDetail == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(Json(new { Result = "Error" })); } //Remove from database db.ImageProduct.Remove(fileDetail); db.SaveChanges(); //Delete file from the file system var path = Path.Combine(Server.MapPath("~/Upload/Images/"), fileDetail.ImageProductID + fileDetail.FileImages); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } return(Json(new { Result = "OK" })); } catch (Exception ex) { return(Json(new { Result = "ERROR", Message = ex.Message })); } }
public async Task <IActionResult> PutImageProduct(int id, ImageProduct imageProduct) { if (id != imageProduct.Id) { return(BadRequest()); } _context.Entry(imageProduct).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ImageProductExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <ImageProduct> > PostImageProduct(ImageProduct imageProduct) { _context.imageProduct.Add(imageProduct); await _context.SaveChangesAsync(); return(CreatedAtAction("GetImageProduct", new { id = imageProduct.Id }, imageProduct)); }
public int CreateProduct(CreateProductDto productDto) { CategoryProduct categoryProduct; if (productDto.IdCategoryProduct == 0) { var myCategoryProduct = _genericRepository.Filter <CategoryProduct> (p => p.Name == productDto.NameCategory.ToLower()).FirstOrDefault(); categoryProduct = myCategoryProduct == null ? CategoryProduct.Create(productDto.NameCategory) : myCategoryProduct; } else { categoryProduct = _genericRepository.Filter <CategoryProduct> (p => p.IdCategoryProduct == productDto.IdCategoryProduct).FirstOrDefault(); } var product = Product.Create(categoryProduct, productDto.NameProduct , productDto.Description, decimal.Parse(productDto.Price)); for (var image = 1; image <= productDto.QuantityImages; image++) { var imageProduct = ImageProduct.Create(image); product.ImageProducts.Add(imageProduct); } _genericRepository.Add(product); _genericRepository.SaveChanges(); return(product.IdProduct); }
public ActionResult Edit(ProductDisplay productDisplay) { if (ModelState.IsValid) { var imgUpload = new ImageProduct(); if (Session["avatarUploadEdit"] != null) { foreach (var item in productDisplay.ListImage) { if (item.Type == 1) { item.Src = Session["avatarUploadEdit"].ToString();; } } } var result = new ProductDisplayDAO().Update(productDisplay); if (result == 1) { return(RedirectToAction("Index", "Product")); } else { ModelState.AddModelError("", "Đã xảy ra lỗi, Cập nhật không thành công!"); } } return(View("Index")); }
public PartialViewResult AddImageItem(int OffSet) { ImageProduct model = new ImageProduct(); model.OffSet = OffSet; return(PartialView("_ImageItemProduct", model)); }
public ActionResult Create(ProductDisplay productDisplay) { if (ModelState.IsValid) { ImageProduct img = new ImageProduct(); productDisplay.ListImage = new List <ImageProduct>(); img.Src = Session["imageProduct"].ToString(); productDisplay.ListImage.Add(img); productDisplay.Product.CreateDate = DateTime.Now; productDisplay.Product.Status = 1; productDisplay.Product.Type = 0; var result = new ProductDisplayDAO().Insert(productDisplay); if (result > 0) { return(RedirectToAction("Index", "Product")); } else { ModelState.AddModelError("", "Thêm mới sản phẩm không thành công!"); } } return(View()); }
public IActionResult Add(ImageModel model) { ImageProduct item; model.image = model.image.Replace("data:image/jpeg;base64,", ""); try { if (_cardContext.Images.Any(s => s.idProduct == model.id)) { item = _cardContext.Images.FirstOrDefault(s => s.idProduct == model.id); item.image = Convert.FromBase64String(model.image); _cardContext.Update(item); _cardContext.SaveChanges(); return(Ok(new { model = _cardContext.Products.Include(s => s.vendor).Include(s => s.type), apiStatus = "successfully_updated", message = "Successfully updated the image", success = true })); } item = new ImageProduct { idProduct = model.id, image = Convert.FromBase64String(model.image) }; _cardContext.Add(item); _cardContext.SaveChanges(); return(Ok(new { model = _cardContext.Products.Include(s => s.vendor).Include(s => s.type), apiStatus = "successfully_added", message = "Successfully added the image", success = true })); } catch (Exception ex) { return(Ok(new { apiStatus = "internal_error_added", message = ex.Message, success = false })); } }
/// <summary> /// Tutti gli articoli che sono con il flag CaricainECommerce e /// </summary> public void AggiornaWeb() { using (var uof = new UnitOfWork()) { using (var groupsync = new CategorySync()) { groupsync.AllineaCategorieReparti(); } var listArt = UpdateProducts(uof); using (var stockPr = new StockProducts(this)) { var listStockArt = stockPr.UpdateStock(uof); listArt.AddRange(listStockArt); } using (var imgPr = new ImageProduct(this)) { listArt.AddRange(imgPr.UpdateImages(uof)); } var listArtId = listArt.FindAll(a => a.Aggiornamento.ForzaAggiornamento == true).Select(a => a.ArticoloID).Distinct().ToList(); var aggToFix = uof.AggiornamentoWebArticoloRepository.Find(a => listArtId.Contains(a.ArticoloID) && a.ForzaAggiornamento).ToList(); foreach (var item in aggToFix) { uof.AggiornamentoWebArticoloRepository.Update(item); } uof.Commit(); } }
public async Task <IActionResult> Create(ProductViewModels viewModels) { var product = _mapper.Map <Product>(viewModels.Product); if (HttpContext.Request.Form.Files != null) { var fileName = string.Empty; var files = HttpContext.Request.Form.Files; foreach (var file in files) { if (file.Length > 0) { fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var myUniqueFileName = Convert.ToString(Guid.NewGuid()); var FileExtension = Path.GetExtension(fileName); string newFileName = myUniqueFileName + FileExtension; var imageProduct = new ImageProduct() { Image = newFileName }; product.ImageProducts.Add(imageProduct); string[] contentTypes = new string[] { ".jpg", ".png", ".jpeg" }; if (!contentTypes.Contains(FileExtension)) { return(RedirectToAction("Index", "Products")); } // Combines two strings into a path. fileName = Path.Combine(_hosting.WebRootPath, "photos") + $@"\{newFileName}"; //if you want to store path of folder in database using (FileStream fs = System.IO.File.Create(fileName)) { file.CopyTo(fs); fs.Flush(); } } } if (ModelState.IsValid) { _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["DepartmentId"] = new SelectList(_context.Brands, "Id", "Name", product.DepartmentId); return(View(product)); } return(View(viewModels)); }
public int AddImageSecundaryOfProduct(ImageProductDto imageProductDto) { var imageProducts = _genericRepository.Filter <ImageProduct> (p => p.IdProduct == imageProductDto.IdProduct).ToList(); var newImageName = imageProducts.Count() + 1; var newImageProduct = ImageProduct.Create(imageProductDto.IdProduct, newImageName); _genericRepository.Add(newImageProduct); _genericRepository.SaveChanges(); return(newImageName); }
//phương thức cập nhật hình ảnh sản phẩm public void UpdateImageProduct(ImageProduct imageProduct, Product2 product, long id) { Console.WriteLine("imageId={0},productId={1},id={2}", imageProduct.Id, product.Id, id); int I = product.Images.Count; if (imageProduct.Product.Id == product.Id && imageProduct.Id == id) { dbContext.Entry(imageProduct).State = EntityState.Modified; dbContext.SaveChanges(); } }
/// <summary> /// Combines segments into image product. /// </summary> /// <param name="segments">The segments.</param> /// <returns>ImageProduct.</returns> /// <exception cref="System.ArgumentNullException"></exception> public static ImageProduct AsImageProduct(this QuickBlockTransferSegment[] segments) { if (segments == null) { throw new ArgumentNullException(nameof(segments)); } var lastSegment = segments[segments.Length - 1]; var content = segments.Select(b => b.Content).ToList().Combine(); return(ImageProduct.Create(lastSegment.Filename, lastSegment.TimeStamp, content, lastSegment.ReceivedAt, lastSegment.Source)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,IdProduct,Name,Status")] ImageProduct imageProduct, IFormFile ful) { if (id != imageProduct.Id) { return(NotFound()); } if (ModelState.IsValid) { try { if (ful != null) { string t = imageProduct.Id + "." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1]; var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/products", imageProduct.Name); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/products", t); using (var stream = new FileStream(path, FileMode.Create)) { await ful.CopyToAsync(stream); } imageProduct.Name = t; _context.Update(imageProduct); await _context.SaveChangesAsync(); } else { _context.Update(imageProduct); await _context.SaveChangesAsync(); } } catch (DbUpdateConcurrencyException) { if (!ImageProductExists(imageProduct.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["IdProduct"] = new SelectList(_context.product, "Id", "Name", imageProduct.IdProduct); return(View(imageProduct)); }
public bool Update(ImageProduct image) { try { this.unitOfWork.ImageProductRepository.Update(image); this.unitOfWork.Save(); return(true); } catch (Exception e) { Console.WriteLine(e.ToString()); return(false); } }
public bool Add(int productId, string url) { try { ImageProduct image = new ImageProduct(productId, url); this.unitOfWork.ImageProductRepository.Add(image); this.unitOfWork.Save(); return(true); } catch (Exception e) { Console.WriteLine(e.ToString()); return(false); } }
public IActionResult Update(EditProductViewModel model) { if (ModelState.IsValid) { Product productForUpdate = productRepository.GetSingleProduct(model.Id); productForUpdate.Description = model.Description; productForUpdate.Name = model.Name; productForUpdate.CategoryId = model.CategoryId;//Check if (model.MainImages != null) { productForUpdate.mainImages = IFormFileToString(model.MainImages); } if (model.Images != null && model.Images.Count != 0) { List <ImageProduct> imgeProductsList = new List <ImageProduct>(); if (model?.Images?.Count > 0) { foreach (var item in model.Images) { ImageProduct imageValue = new ImageProduct() { image = IFormFileToString(item) }; imgeProductsList.Add(imageValue); } } productForUpdate.imageProducts = imgeProductsList; } productRepository.Update(productForUpdate); return(RedirectToAction("Index")); } else { var errors = ModelState.Select(x => x.Value.Errors) .Where(y => y.Count > 0) .ToList(); } return(View()); }
// GET: Products/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var product = await _context.Product.FindAsync(id); if (product == null) { return(NotFound()); } ImageProduct imageproduct = new ImageProduct(product.Id, product.SKU, product.Name, product.Price, product.Description, product.Instalments, product.Stock, product.Image, product.Active); return(View(imageproduct)); }
/// <summary> /// Add the images. /// </summary> /// <param name="image">image object.</param> /// <returns>status add images</returns> public bool Add_Images(ImageProduct image) { using (var data = new Entities()) { bool rt; try { data.ImageProducts.Add(image); data.SaveChanges(); rt = true; } catch (Exception) { rt = false; } return(rt); } }
public ActionResult DeleteImage(ImageProduct pImg) { var repo = Repository.Create <ImageProduct>(); if (pImg.ImageID == 0 || pImg.ProductID == 0) { return(Content("error")); } String status = ""; if (repo.Delete(pImg.ImageID, pImg.ProductID)) { status = "success"; } else { status = "error"; } repo.SaveChanges(); return(Content(status)); }
//[ValidateAntiForgeryToken] public ActionResult Create(Product product, HttpPostedFileBase ImageFile, ImageProduct imageProduct) { if (ImageFile != null) { string fileExtention = Path.GetExtension(ImageFile.FileName); string fileName = Guid.NewGuid().ToString() + fileExtention.ToString(); ImageFile.SaveAs(Server.MapPath("~/ProductImages/" + fileName)); imageProduct.ImageName = fileName; imageProduct.ProductId = product.Id; db.Products.Add(product); db.ImagesProducts.Add(imageProduct); db.SaveChanges(); ModelState.Clear(); return(RedirectToAction("Index")); } return(RedirectToAction("Index")); }
private static void UnZip(CompressedProduct product, IEventPublisher ctx) { using (var zip = new ZipArchive(product.GetStream(), ZipArchiveMode.Read)) { foreach (var file in zip.Entries) { using (var fileStream = file.Open()) { var fileName = file.Name.ToUpperInvariant(); var contentType = ContentTypeParser.GetFileContentType(fileName); switch (contentType) { case ContentFileType.Text: using (var text = new StreamReader(fileStream)) { var textProduct = TextProduct.Create(fileName, file.LastWriteTime, text.ReadToEnd(), product.ReceivedAt, product.Source); ctx.SendMessage(textProduct); ProcessorEventSource.Log.Info(nameof(ZipExtractor), textProduct.ToString()); } break; case ContentFileType.Image: var imageProduct = ImageProduct.Create( fileName, file.LastWriteTime, ReadAllBytes(fileStream), product.ReceivedAt, product.Source); ctx.SendMessage(imageProduct); ProcessorEventSource.Log.Info(nameof(ZipExtractor), imageProduct.ToString()); break; // There are no zips within zips :-) default: ProcessorEventSource.Log.Warning(nameof(ZipExtractor), "Unknown content file type: " + file.Name); return; } } } } }
public async Task <IActionResult> Create([Bind("Id,SKU,Name,Price,Description,Instalments,Stock,Content,Active")] ImageProduct ImgPd) { Product product = new Product(ImgPd.Id, ImgPd.SKU, ImgPd.Name, ImgPd.Price, ImgPd.Description, ImgPd.Instalments, ImgPd.Stock, ImgPd.Active); if (ModelState.IsValid) { string Path = Configuration.GetValue("ImagePath", ".\\wwwroot\\"); string imgName = ($"{product.SKU}.jpg"); using (var stream = new FileStream(Path + imgName, FileMode.Create)) { await ImgPd.Content.CopyToAsync(stream); } product.Image = @"\images\" + imgName; _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(product)); }
public async Task <IActionResult> Create([Bind("Id,IdProduct,Name,Status")] ImageProduct imageProduct, IFormFile ful) { if (ModelState.IsValid) { _context.Add(imageProduct); await _context.SaveChangesAsync(); var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot/images/products", imageProduct.Id + "." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1]); using (var stream = new FileStream(path, FileMode.Create)) { await ful.CopyToAsync(stream); } imageProduct.Name = imageProduct.Id + "." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1]; _context.Update(imageProduct); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["IdProduct"] = new SelectList(_context.product, "Id", "Name", imageProduct.IdProduct); return(View(imageProduct)); }
public async Task <ApiResult <string> > UpdateImage(int id, ImageProduct bundle) { var product = await _context.Products.FindAsync(id); if (product == null) { return(new ApiErrorResult <string>("Sản phẩm không tồn tại")); } // xóa ảnh củ if (product.Image != null) { await _storageService.DeleteFileAsync(product.Image); } // lưu lại ảnh mới product.Image = await this.SaveFile(bundle.Image); _context.Products.Update(product); await _context.SaveChangesAsync(); return(new ApiSuccessResult <string>(product.Image)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,SKU,Name,Price,Description,Instalments,Stock,Content,Active")] ImageProduct ImgPd) { Product product = new Product(ImgPd.Id, ImgPd.SKU, ImgPd.Name, ImgPd.Price, ImgPd.Description, ImgPd.Instalments, ImgPd.Stock, ImgPd.Active); if (id != product.Id) { return(NotFound()); } if (ModelState.IsValid) { try { string Path = Configuration.GetValue("ImagePath", ".\\images\\"); string imgName = ($"{product.SKU}.jpg"); using (var stream = new FileStream(Path + imgName, FileMode.Create)) { await ImgPd.Content.CopyToAsync(stream); } product.Image = @"\images\" + imgName; _context.Update(product); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(product)); }
// GET: Admin/ImageProducts public async Task <IActionResult> Index(int?id, string s_name, string s_stt) { ViewData["IdProduct"] = new SelectList(_context.product, "Id", "Name"); ImageProduct imageProduct = null; if (id != null) { imageProduct = await _context.imageProduct.FirstOrDefaultAsync(m => m.Id == id); } if (s_name != null) { if (s_stt == null) { ViewBag.ListImgProduct = (from p in _context.imageProduct where p.product.Name.IndexOf(s_name) >= 0 select p).ToList(); } else { ViewBag.ListImgProduct = (from p in _context.imageProduct where p.product.Name.IndexOf(s_name) >= 0 && p.Status == Convert.ToBoolean(s_stt) select p).ToList(); } } return(View(imageProduct)); }
public IActionResult Add(AddProductViewModel model) { if (ModelState.IsValid) { Product product = new Product { CategoryId = model.CategoryId, Description = model.Description, Name = model.Name, //isShow = true, //count = 0, //Price = 0, }; product.mainImages = IFormFileToString(model.MainImages); List <ImageProduct> imgeProductsList = new List <ImageProduct>(); if (model?.Images?.Count > 0) { foreach (var item in model.Images) { ImageProduct imageValue = new ImageProduct() { image = IFormFileToString(item) }; imgeProductsList.Add(imageValue); } } product.imageProducts = imgeProductsList; productRepository.Add(product); //iimgeProduct.AddList(imgeProductsList); return(RedirectToAction("Index")); } model.CategoryForDisplay = categoryRepository.GetCategorylevel2().ToList(); return(View(model)); }