public ProductImageApi(ProductImage p) { if (p != null) { Id = p.Id; ProductId = p.ProductId; ImageLink = p.ImageLink; } }
public bool CreateProduct(List<int> categoryIds,int? brandId,List<int> colorIds, IEnumerable<HttpPostedFileBase> files, string code, string name, bool isNew, decimal? price, string shortDescription, string detailDescription) { var product = new Product(); product.ProductCode = code; product.ProductName = name; product.Price = price; product.BrandId = brandId; product.ProductShortDescription = shortDescription; product.ProductDetailDescription = detailDescription; product.CreatedDate = DateTime.Now; product.UpdatedDate = DateTime.Now; product.IsNew = isNew; if(files==null) { files=new List<HttpPostedFileBase>(); } foreach (HttpPostedFileBase file in files) { var fName = file.FileName; var fNameIndex = fName.LastIndexOf('.'); fName = fName.Insert(fNameIndex, "_" + DateTime.Now.Ticks.ToString()); var folderPath = HttpContext.Current.Server.MapPath("~/images/product"); string filePath = Path.Combine(folderPath, fName); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } System.IO.File.WriteAllBytes(filePath, this.ReadData(file.InputStream)); var productImage = new ProductImage(); productImage.ProductImageUrl = "~/images/product/" + fName; product.ProductImages.Add(productImage); } if (categoryIds != null) { foreach (var categoryId in categoryIds) { var productCategory = new ProductCategory(); productCategory.CategoryId = categoryId; product.ProductCategories.Add(productCategory); } } if (colorIds != null) { foreach (var colorId in colorIds) { var productColor = new ProductColor(); productColor.ColorId = colorId; product.ProductColors.Add(productColor); } } Context.Products.Add(product); Context.SaveChanges(); return product.ProductId > 0; }
protected void grdProductImage_RowDeleting(object sender, GridViewDeleteEventArgs e) { productImage = new ProductImage(); productImage.ProductId = Convert.ToInt32(e.Keys["ProductId"]); productImage.ProductImageId = Convert.ToInt32(e.Keys["ProductImageId"]); if (e.Keys["ImageUrl"] != null) productImage.ImageUrl = e.Keys["ImageUrl"].ToString(); if (e.Keys["Description"] != null) productImage.Description = e.Keys["Description"].ToString(); }
public int DeleteProductImage(ProductImage pi) { try { db.ProductImages.Remove(pi); return db.SaveChanges(); } catch (Exception e) { throw new Exception(e.Message); } }
protected void btnSaveImage_Click(object sender, EventArgs e) { ProductManager productManager = new ProductManager(this); Product product; ProductImage productImages = new ProductImage(); if (fupProductImage.FileName != null) { productImages.ProductId = Convert.ToInt32(Page.ViewState["ProductId"]); productImages.Description = txtDescription.Text; productManager.InsertProductImage(Page.Company.CompanyId, productImages, fupProductImage.PostedFile); grdProductImage.DataBind(); } }
public Boolean Edit(String ID, String ModifiedBy) { try { _Obj = db.ProductImages.FirstOrDefault(pram => pram.Id == new Guid(ID)); if (_Obj != null) { _Obj.ModifiedOn = DateTime.Now; _Obj.ModifiedBy = new Guid(ModifiedBy); db.SaveChanges(); return true; } return false; } catch (Exception) { return false; } }
public ActionResult Edit(ProductImage productImage, HttpPostedFileBase PI) { if (Session["type"] == null || Session["type"].ToString() == "") { Session["DefaultView"] = "Edit"; Session["DefaultControll"] = "ProductImage"; return(RedirectToAction("Login", "Employee")); } productImage.ProductImage1 = System.IO.Path.GetFileName(PI.FileName); if (ModelState.IsValid) { db.Entry(productImage).State = EntityState.Modified; db.SaveChanges(); PI.SaveAs(Server.MapPath("../Images/ProductImage/UpdateProductImage/" + productImage.ID.ToString() + "_" + productImage.ProductImage1)); return(RedirectToAction("Index")); } ViewBag.ProductID = new SelectList(db.Products, "ID", "ProductName", productImage.ProductID); return(View(productImage)); }
public async Task <IActionResult> DeleteImage(int?id) { if (id == null) { return(NotFound()); } ProductImage productImage = await _context.ProductImages .FirstOrDefaultAsync(m => m.Id == id); if (productImage == null) { return(NotFound()); } Product product = await _context.Products.FirstOrDefaultAsync(p => p.ProductImages.FirstOrDefault(pi => pi.Id == productImage.Id) != null); _context.ProductImages.Remove(productImage); await _context.SaveChangesAsync(); return(RedirectToAction($"{nameof(Details)}/{product.Id}")); }
public async Task <int> AddImage(int productId, ProductImageCreateRequest request) { var productImage = new ProductImage() { Caption = request.Caption, DateCreated = DateTime.Now, IsDefault = request.IsDefault, ProductId = productId, SortOrder = request.SortOrder, }; if (request.ImageFile != null) { productImage.ImagePath = await this.SaveFile(request.ImageFile); productImage.FileSize = request.ImageFile.Length; } _context.ProductImages.Add(productImage); await _context.SaveChangesAsync(); return(productImage.Id); }
public async Task <IResult> AddProductImages(int id, List <IFormFile> img) { var result = new Result { Operation = Operation.Create, Status = Status.Success }; try { var productObj = _productRepository.GetProductDetail(id); ProductModel productModel = new ProductModel(); productModel.MapFromViewModel(productObj); productModel.ModifiedBy = _specificClaim.GetSpecificClaim("Id"); productModel.ModifiedDate = DateTime.Now; ImageExtention imageExtention = new ImageExtention(); var images = new List <ProductImage>(); foreach (IFormFile i in img) { ProductImage productimage = new ProductImage(); productimage.ImageName = i.FileName; productimage.ImageContent = imageExtention.Image(i); productimage.ImageExtenstion = Path.GetExtension(i.FileName); productimage.ProductId = productModel.ProductId; images.Add(productimage); } var addImages = await _productRepository.AddProductImages(productModel, images); return(addImages); } catch (Exception e) { result.Status = Status.Error; result.Message = e.Message; result.StatusCode = HttpStatusCode.InternalServerError; return(result); } }
public async Task <IActionResult> Create([Bind("ProductImageId,ColorOptionId,Path")] ProductImage productImage, IFormFile image, bool again) { // Check if user is authenticated if (User.Identity.IsAuthenticated) { if (ModelState.IsValid || image != null) { string filename = ChangePathName(productImage.Path); FileInfo fi = new FileInfo(image.FileName); string extension = fi.Extension; string path = basepath + filename + extension; productImage.Path = path; using (FileStream fs = System.IO.File.Create("wwwroot" + path)) { image.CopyTo(fs); fs.Flush(); } _context.Add(productImage); await _context.SaveChangesAsync(); if (again) { return(RedirectToAction("Create", "ProductImages", productImage.ColorOptionId)); } return(RedirectToAction("Index", "Products")); } ViewData["ColorOptionId"] = new SelectList(_context.ColorOptions, "ColorOptionId", "Color", productImage.ColorOptionId); return(View(productImage)); } else { return(NotFound()); } }
private void saveUploadedImage(HttpPostedFileBase image, int productId) { var img = new ProductImage() { FileName = image.FileName, ImageMimeType = image.ContentLength, ImageData = new byte[image.ContentLength], ProductID = productId }; image.InputStream.Read(img.ImageData, 0, image.ContentLength); var fileName = image.FileName; var fileOriginalPath = Server.MapPath("~/Uploads/Originals"); var fileThumbnailPath = Server.MapPath("~/Uploads/Thumbnails"); string savedFileName = Path.Combine(fileOriginalPath, fileName); image.SaveAs(savedFileName); var imageFile = Path.Combine(Server.MapPath("~/Uploads/Originals"), fileName); using (var srcImage = Image.FromFile(imageFile)) using (var newImage = new Bitmap(100, 100)) using (var graphics = Graphics.FromImage(newImage)) using (var stream = new MemoryStream()) { graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.DrawImage(srcImage, new Rectangle(0, 0, 100, 100)); newImage.Save(stream, ImageFormat.Png); var thumbNew = File(stream.ToArray(), "image/png"); img.ImageThumbnail = thumbNew.FileContents; } db.ProductImage.Add(img); db.SaveChanges(); }
public ActionResult Edit(HttpPostedFileBase file, [Bind(Include = "Id,ProductId,Title")] ProductImage model) { if (file == null) { ViewData["Product"] = db.Products.Find(model.ProductId); ModelState.AddModelError("", "تصویر انتخاب نگردیده است"); return(View(model)); } if (ModelState.IsValid) { try { var imge = db.ProductImages.Find(model.Id); FileUploader.DeleteFile("/uploadFiles/ProductImages/" + imge.Name); var name = FileUploader.SaveFile(file, "/uploadFiles/ProductImages/", model.Title, true); if (name == null) { throw new ArgumentException("تصویر به دلیل نا معلومی ذخیره نشد"); } imge.Title = model.Title; imge.ProductId = model.ProductId; imge.Name = name; imge.UpdateTime = DateTime.Now; db.Entry(imge).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index", new { id = model.ProductId })); } catch (Exception e) { ModelState.AddModelError("", e.Message); ViewData["Product"] = db.Products.Find(model.ProductId); return(View(model)); } } ViewData["Product"] = db.Products.Find(model.ProductId); return(View(model)); }
public async Task CreateProductAsync(ProductViewModel model) { var categoryId = this.categoriesService .GetAllCategories() .FirstOrDefault(x => x.Name == model.Category).Id; var product = new Product() { Name = model.Name, Price = model.Price, Description = model.Description, Specification = model.Specification, CreatedById = model.CreatedById, Type = (ProductType)Enum.Parse(typeof(ProductType), model.Type), CategoryId = categoryId, }; var images = await this.imagesService.UploadProductImagesAsync(model.Images); var productImages = new List <ProductImage>(); foreach (var image in images) { var productImage = new ProductImage() { Image = image, Product = product, }; productImages.Add(productImage); } product.ProductImages = productImages; await this.productRepository.AddAsync(product); await this.productRepository.SaveChangesAsync(); }
public async Task <IActionResult> Update([FromBody] ProductModel product, [FromServices] IHostingEnvironment host) { var result = new JsonData(); if (!string.IsNullOrEmpty(product.Img400)) { var file = new ProductImage { CreateTime = DateTime.Now, Name = Guid.NewGuid().ToString().ToLower(), Type = ImageType.Product, Length = Convert.FromBase64String(product.Img400.Replace("data:image/jpeg;base64,", "")).Length }; // 上传图片 var msg = await Service.UploadImageAsync(AppData.ApiUri + "/Product", Business.ID, file.Name + "." + file.ExtensionName, product.Img400, product.Img200, product.Img100); if (msg != "ok") { result.Msg = msg; return(Json(result)); } if (product.Images.Count > 0) { //Service.DeleteImage(product.Images.First(), AppData.ApiUri, Business.ID); Service.DeleteImage(product.Images.First()); } product.Images = new List <ProductImage> { file }; } product.Pinyin = UtilHelper.GetPinyin(product.Name); product.FirstLetter = UtilHelper.GetFirstPinyin(product.Name); // 图片上传成功后,修改商品 Service.Update(product); result.Success = true; result.Msg = "修改成功"; return(Ok(result)); }
public async Task <ActionResult <IEnumerable <ProductImage> > > uploadPhotoClient([FromForm] IFormFile[] imgFile, [FromForm] int idProduct) { return(await Task.Run <ActionResult <IEnumerable <ProductImage> > >(async() => { var productImagesList = this.db.ProductImages.Where(e => e.IdProduct == idProduct); // existe un cliente y la imgfile almenos algo if (imgFile.Length != 0) { string path = this.env.pathProductsPhotos; if (productImagesList != null) { // recorro cada imagen y la elimino await productImagesList.ForEachAsync(async(e) => { this.db.ProductImages.Remove(e); await this.photoUtilities.removePhoto(e.Url, path); }); this.db.SaveChanges(); } // guardo en cascada las imagenes relacionadas for (int i = 0; i < imgFile.Length; i++) { string nameFileEncript = ""; nameFileEncript = await this.photoUtilities.copyPhoto(imgFile[i], path); // guardo en la bd var productImageNew = new ProductImage(); productImageNew.IdProduct = idProduct; productImageNew.Url = nameFileEncript; this.db.ProductImages.Add(productImageNew); this.db.SaveChanges(); } var productImagesUpdated = this.db.ProductImages.Where(e => e.IdProduct == idProduct); return Ok(productImagesUpdated); } return BadRequest(); })); }
public async Task <IActionResult> EditProduct([FromRoute] int productId) { var product = await _productService.GetProductForEdit(productId); if (product == null) { return(NotFound()); } // update product product.ProductName = Request.Form["productName"]; product.ProductCode = Request.Form["productCode"]; product.Price = Convert.ToDecimal(Request.Form["price"]); await _productService.SaveProduct(product); // save new images if any if (Request.Form.Files != null && Request.Form.Files.ToList().Any()) { var files = Request.Form.Files.ToList(); foreach (var file in files) { var filePath = await UploadFile(file, product.ProductId); var image = new ProductImage { ProductId = product.ProductId, Description = file.FileName, ImageUrl = filePath }; await _productService.AddProductImage(image); } } product = await _productService.GetProductById(productId); return(Ok(product)); }
public async Task <IActionResult> Edit(int id, [Bind("ProductImageId,ProductId,ProductOption1Id,ProductOption2Id,ProductOption3Id,FileName,Image,FormFile")] ProductImage productImage) { if (id != productImage.ProductImageId) { return(NotFound()); } if (ModelState.IsValid) { try { if (productImage.FormFile != null) { MemoryStream ms = new MemoryStream(); await productImage.FormFile.CopyToAsync(ms); productImage.FileName = productImage.FormFile.FileName; productImage.Image = ms.ToArray(); } _context.Update(productImage); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductImageExists(productImage.ProductImageId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index), new { id = productImage.ProductId })); } return(View(productImage)); }
public IActionResult Add(AddProductViewModel model) { if (!ModelState.IsValid) { ViewBag.Categories = _unitOfWork.CategoryRepository.GetAll(new string[0]).ToList(); ViewBag.Brands = _unitOfWork.BrandRepository.GetAll(new string[0]).ToList(); return(View(model)); } var product = new Product() { Title = model.Title, Description = model.Description, Price = model.Price ?? default, BrandId = model.BrandId ?? default, CategoryId = model.CategoryId ?? default }; _unitOfWork.ProductRepository.Add(product); _unitOfWork.Complete(); foreach (var image in model.Images) { var newName = Guid.NewGuid(); var path = _hostEnvironment.WebRootPath + "/Uploads/" + newName + image.FileName; FileStream stream = new FileStream(path, FileMode.Create); image.CopyTo(stream); stream.Close(); var productImage = new ProductImage() { Path = newName + image.FileName, ProductId = product.Id }; _unitOfWork.ProductImageRepository.Add(productImage); _unitOfWork.Complete(); } return(RedirectToAction("Add")); }
public async Task <ActionResult <ProductImage> > UpdateProductImage(ProductImage productImage) { try { var productImageToUpdate = await _productImageRepository.GetProductImageOfProductId(productImage.ProductId); if (productImageToUpdate == null) { return(BadRequest()); } else { var updatedProductImage = await _productImageRepository.UpdateProductImage(productImage); return(updatedProductImage); } } catch (Exception) { return(StatusCode(StatusCodes.Status500InternalServerError, "Error geting updating data"));; } }
private void SaveImages(ProductImage item) { switch (item.ActionType) { case ActionType.Create: { _productImageService.Add(item); break; } case ActionType.Update: { _productImageService.Update(item); break; } case ActionType.Delete: { _productImageService.Remove(item); break; } } }
// GET: ProductImages/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ProductImage image = db.ProductImage.Find(id); ProductImageModel productImageModel = new ProductImageModel(); if (image == null) { return(HttpNotFound()); } else //mapping { productImageModel.Name = image.Name; productImageModel.Id = image.Id; } return(View(productImageModel)); }
// GET: ProductImages/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ProductImage image = db.ProductImage.Find(id); ProductImageModel productImageModel = new ProductImageModel(); if (image == null) { return(HttpNotFound()); } else //mapping { productImageModel.Id = image.Id; productImageModel.Name = image.Name; productImageModel.SourceString = ConvertImageDataToSourceString(image.Data); } return(View(productImageModel)); }
public List <ProductListModel> ProductListModel1(string seoUrl) { Category cat = categoryRepo.GetAllFirstCat(seoUrl); List <ProductCategory> cat1 = productCategoryRepo.GetCategoryId(cat.CategoryId); Product prod = new Product(); List <Product> prod1 = new List <Product>(); foreach (var item in cat1) { prod = GetAllFirstProd(item.ProductId); prod1.Add(prod); } var list = new List <ProductListModel>(); foreach (var item in prod1) { ProductImage pi = productImageRepo.FirstByProductId(item.ProductId); list.Add(new ProductListModel(item, pi)); } return(list); }
// add list image for a product public async Task <int> AddImage(int productId, List <IFormFile> files) { if (productId == 0) { throw new eShopException($"Can not find {productId}"); } var index = 0; foreach (var item in files) { index++; var productImage = new ProductImage() { ProductId = productId, CreateDate = DateTime.Now, FileSize = item.Length, ImagePath = await SaveFile(item), SortOrder = index }; _context.productImages.Add(productImage); } return(await _context.SaveChangesAsync()); }
public IHttpActionResult PutProduct(int id, [FromBody] Product p) { var prod = context.Products.Find(id); prod.CategoryID = p.CategoryID; prod.Name = p.Name; prod.Price = p.Price; prod.Desc = p.Desc; prod.Udated_at = new DateTime(); prod.TagName = p.TagName; foreach (var img in p.ProductImages) { var ig = new ProductImage { Id = 0, imgUrl = img.imgUrl, ProductID = p.ID }; context.ProductImages.Add(img); } context.SaveChanges(); return(Ok()); }
public HttpResponseMessage Create(HttpRequestMessage request, ProductImageViewModel productImageVm) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (ModelState.IsValid) { var newImage = new ProductImage(); newImage.UpdateProductImage(productImageVm); _productImageService.Add(newImage); _productImageService.Save(); response = request.CreateResponse(HttpStatusCode.OK, productImageVm); return response; } else { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); return response; } })); }
public async Task <IActionResult> DeleteProduct(int?id) { if (id == null) { return(NotFound()); } Product product = await _context.Products.FindAsync(id); if (product == null) { return(NotFound()); } ProductImage productImage = await _context.ProductImages.FirstOrDefaultAsync(i => i.ProductId == id); if (productImage != null) { Utility.DeleteImgFromFolder(_env.WebRootPath, productImage.Image); _context.Products.Remove(product); await _context.SaveChangesAsync(); } return(RedirectToAction(nameof(Index))); }
public HttpResponseMessage Create(HttpRequestMessage request, ProductImageViewModel productImageVm) { if (ModelState.IsValid) { var newImage = new ProductImage(); try { newImage.UpdateProductImage(productImageVm); _productImageService.Add(newImage); _productImageService.Save(); return(request.CreateResponse(HttpStatusCode.OK, productImageVm)); } catch (Exception dex) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, dex.Message)); } } else { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } }
internal static List<ProductImage> GetProductImages(List<ProductImageInfo> importedImages) { List<ProductImage> productImages = new List<ProductImage>(); foreach (var importedImage in importedImages) { ProductImage productImage = new ProductImage(); productImage.AlbumId = importedImage.Album.Id; productImage.Album = importedImage.Album.Title.Value; productImage.Id = importedImage.Image.Id; productImage.Width = importedImage.Image.Width; productImage.Height = importedImage.Image.Height; productImage.Title = importedImage.Image.Title; productImage.Url = importedImage.Image.Url; productImage.AlternativeText = importedImage.Image.AlternativeText; productImage.FileName = importedImage.Image.FilePath; productImage.FileSize = importedImage.ImageInfo.Length.ToString(); productImages.Add(productImage); } return productImages; }
public async Task <List <Product> > LoadProductData() { var lstObj = new List <Product>(); lstObj = await _context.Products.Select(n => n).ToListAsync(); foreach (var item in lstObj) { var imageObj = _context.ProductImages.FirstOrDefault(i => i.ProductId == item.Id && i.Index == 1); if (imageObj == null) { imageObj = new ProductImage { // path default. Path = "~/ProductImages/70x70.png", }; } item.GImage = imageObj; item.SubTypeName = _context.ProductSubTypes.FirstOrDefault(n => n.Id == item.ProductSubTypeId)?.Name ?? ""; item.TypeName = _context.ProductTypes.FirstOrDefault(n => n.Id == item.ProductTypeId)?.Name ?? ""; } return(lstObj); }
public ActionResult Create(Product newProduct, HttpPostedFileBase[] productImage, int CategoryIds, Size sizes) { newProduct.CategoryId = CategoryIds; newProduct.Size = sizes; newProduct.ProductImages = new List <ProductImage>(); foreach (var item in productImage) { ProductImage p = new ProductImage(); p.ImageURL = item.FileName; item.SaveAs(Server.MapPath("/Uploads/Product/") + item.FileName); newProduct.ProductImages.Add(p); } if (ModelState.IsValid) { db.Products.Add(newProduct); db.SaveChanges(); } ViewBag.Categories = db.Categories.ToList(); return(View()); }
private void RenderSingleAdditionalImage(StringBuilder sb, ProductImage img) { string mediumUrl = MerchantTribe.Commerce.Storage.DiskStorage.ProductAdditionalImageUrlMedium(MTApp, img.ProductId, img.Bvin, img.FileName, false); string largeUrl = MerchantTribe.Commerce.Storage.DiskStorage.ProductAdditionalImageUrlOriginal(MTApp, img.ProductId, img.Bvin, img.FileName, false); sb.Append("<a href=\"" + largeUrl + "\" alt=\"" + mediumUrl + "\" class=\"popover\">"); sb.Append("<img src=\""); sb.Append(MerchantTribe.Commerce.Storage.DiskStorage.ProductAdditionalImageUrlTiny(MTApp, img.ProductId, img.Bvin, img.FileName, false)); sb.Append("\" border=\"0\" alt=\"" + img.AlternateText + "\" />"); sb.Append("</a>"); }
public async Task <ImageFile> AddProductGalleryImageAsync(string fileName, string contentType, long length, byte[] imageBytes, int?productId) { var image = await AddProductImageAsync(fileName, contentType, length, imageBytes); if (productId != null) { var product = await this.productRepository.GetByIdAsync(productId); if (product != null) { var productImage = new ProductImage() { ImageId = image.Id, ProductId = product.Id }; this.productImageRepository.Add(productImage); await this.productImageRepository.SaveAsync(); } } return(image); }
public ActionResult DeleteAttachment(int?pID) { try { ProductImage model = unitOfWork.ProductImageRepository.GetByID(pID); if (model == null) { Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; return(Content("رکورد مورد نظر شما یافت نشد", System.Net.Mime.MediaTypeNames.Text.Plain)); } //Remove Item From DataBase unitOfWork.ProductImageRepository.Delete(model); unitOfWork.Save(); return(Json(true, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; return(Content(ex.ToString(), System.Net.Mime.MediaTypeNames.Text.Plain)); } }
public async Task <IActionResult> ChangeImageOrder(IEnumerable <int?> myIds) { int order = 1; List <ProductImage> productImages = new List <ProductImage>(); foreach (int?item in myIds) { if (item == null) { return(Json(data: false)); } ProductImage objProductImage = await _db.ProductImages.FindAsync(item); objProductImage.ImageOrder = order; productImages.Add(objProductImage); order++; } _db.ProductImages.UpdateRange(productImages); await _db.SaveChangesAsync(); return(Json(data: true)); }
public ActionResult Edit([Bind(Include = "Id,Name,DataInHttpPostedFileBase")] ProductImageModel productImageModel) { if (ModelState.IsValid) { //Finding the image to change ProductImage image = db.ProductImage.Find(productImageModel.Id); //If the user posted a new picture change the imagedata, //else don't do anything with it if (productImageModel.DataInHttpPostedFileBase != null) { //Using own method to convert the posted file to a bytearray image.Data = ConvertHttpPostedFileBaseToByteArray(productImageModel.DataInHttpPostedFileBase); } image.Name = productImageModel.Name; db.Entry(image).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(productImageModel)); }
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e) { if (e.CommandName == "alpha" || e.CommandName == "NoFilter") { String value = null; switch (e.CommandName) { case ("alpha"): { value = string.Format("{0}%", e.CommandArgument); break; } case ("NoFilter"): { value = "%"; break; } } ObjectDataSource1.SelectParameters["ProductName"].DefaultValue = value; ObjectDataSource1.DataBind(); RadGrid1.Rebind(); } else if (e.CommandName == "QuickUpdate") { string ProductID, Priority, InStock, IsHot, IsNew, IsBestSeller, IsSaleOff, IsShowOnHomePage, IsAvailable; var oProduct = new Product(); foreach (GridDataItem item in RadGrid1.Items) { ProductID = item.GetDataKeyValue("ProductID").ToString(); Priority = ((RadNumericTextBox)item.FindControl("txtPriority")).Text.Trim(); InStock = ((CheckBox)item.FindControl("chkInStock")).Checked.ToString(); IsHot = ((CheckBox)item.FindControl("chkIsHot")).Checked.ToString(); IsNew = ((CheckBox)item.FindControl("chkIsNew")).Checked.ToString(); IsBestSeller = ((CheckBox)item.FindControl("chkIsBestSeller")).Checked.ToString(); IsSaleOff = ((CheckBox)item.FindControl("chkIsSaleOff")).Checked.ToString(); IsShowOnHomePage = ((CheckBox)item.FindControl("chkIsShowOnHomePage")).Checked.ToString(); IsAvailable = ((CheckBox)item.FindControl("chkIsAvailable")).Checked.ToString(); oProduct.ProductQuickUpdate( ProductID, InStock, IsHot, IsNew, IsBestSeller, IsSaleOff, IsShowOnHomePage, Priority, IsAvailable ); } } else if (e.CommandName == "DeleteSelected") { string OldImageName; var oProduct = new Product(); string errorList = "", ProductName = ""; foreach (GridDataItem item in RadGrid1.SelectedItems) { try { var ProductID = item.GetDataKeyValue("ProductID").ToString(); ProductName = item["ProductName"].Text; oProduct.ProductDelete(ProductID); OldImageName = ((HiddenField)item.FindControl("hdnImageName")).Value; DeleteImage(OldImageName); } catch (Exception ex) { lblError.Text = ex.Message; if (ex.Message == ((int)ErrorNumber.ConstraintConflicted).ToString()) errorList += ", " + ProductName; } } if (!string.IsNullOrEmpty(errorList)) { e.Canceled = true; string strAlertMessage = "Sản phẩm <b>\"" + errorList.Remove(0, 1).Trim() + " \"</b> đang chứa thư viện ảnh hoặc file download .<br /> Xin xóa ảnh hoặc file trong sản phẩm này hoặc thiết lập hiển thị = \"không\"."; lblError.Text = strAlertMessage; } RadGrid1.Rebind(); } else if (e.CommandName == "InitInsert" || e.CommandName == "EditSelected" || e.CommandName == "Edit") { TempImage.Rows.Clear(); } else if (e.CommandName == "PerformInsert" || e.CommandName == "Update") { var command = e.CommandName; var row = command == "PerformInsert" ? (GridEditFormInsertItem)e.Item : (GridEditFormItem)e.Item; var FileImageName = (RadUpload)row.FindControl("FileImageName"); string ProductID = ((HiddenField)row.FindControl("hdnProductID")).Value; string OldImageName = ((HiddenField)row.FindControl("hdnOldImageName")).Value; string ImageName = FileImageName.UploadedFiles.Count > 0 ? FileImageName.UploadedFiles[0].GetName() : ""; string Priority = ((RadNumericTextBox)row.FindControl("txtPriority")).Text.Trim(); string MetaTittle = ((RadTextBox)row.FindControl("txtMetaTittle")).Text.Trim(); string MetaDescription = ((RadTextBox)row.FindControl("txtMetaDescription")).Text.Trim(); string ProductName = ((RadTextBox)row.FindControl("txtProductName")).Text.Trim(); string ConvertedProductName = Common.ConvertTitle(ProductName); string Description = HttpUtility.HtmlDecode(FCKEditorFix.Fix(((RadEditor)row.FindControl("txtDescription")).Content.Trim())); string Content = HttpUtility.HtmlDecode(FCKEditorFix.Fix(((RadEditor)row.FindControl("txtContent")).Content.Trim())); string Price = ((RadNumericTextBox)row.FindControl("txtPrice")).Text.Trim(); string OtherPrice = ((RadTextBox)row.FindControl("txtOtherPrice")).Text.Trim(); string SavePrice = ((RadNumericTextBox)row.FindControl("txtSavePrice")).Text.Trim(); string Discount = ((RadNumericTextBox)row.FindControl("txtDiscount")).Text.Trim(); string Tag = ((RadTextBox)row.FindControl("txtTag")).Text.Trim(); string CategoryID = ((RadComboBox)row.FindControl("ddlCategory")).SelectedValue; string ManufacturerID = ((RadComboBox)row.FindControl("ddlManufacturer")).SelectedValue; string OriginID = ((RadComboBox)row.FindControl("ddlOrigin")).SelectedValue; string InStock = ((CheckBox)row.FindControl("chkInStock")).Checked.ToString(); string IsHot = ((CheckBox)row.FindControl("chkIsHot")).Checked.ToString(); string IsNew = ((CheckBox)row.FindControl("chkIsNew")).Checked.ToString(); string IsBestSeller = ((CheckBox)row.FindControl("chkIsBestSeller")).Checked.ToString(); string IsSaleOff = ((CheckBox)row.FindControl("chkIsSaleOff")).Checked.ToString(); string IsShowOnHomePage = ((CheckBox)row.FindControl("chkIsShowOnHomePage")).Checked.ToString(); string IsAvailable = ((CheckBox)row.FindControl("chkIsAvailable")).Checked.ToString(); string MetaTittleEn = ((RadTextBox)row.FindControl("txtMetaTittleEn")).Text.Trim(); string MetaDescriptionEn = ((RadTextBox)row.FindControl("txtMetaDescriptionEn")).Text.Trim(); string ProductNameEn = ((RadTextBox)row.FindControl("txtProductNameEn")).Text.Trim(); string DescriptionEn = HttpUtility.HtmlDecode(FCKEditorFix.Fix(((RadEditor)row.FindControl("txtDescriptionEn")).Content.Trim())); string ContentEn = HttpUtility.HtmlDecode(FCKEditorFix.Fix(((RadEditor)row.FindControl("txtContentEn")).Content.Trim())); string TagEn = ((RadTextBox)row.FindControl("txtTagEn")).Text.Trim(); string Ri = ((RadTextBox)row.FindControl("txtRi")).Text.Trim(); string ThongSoSize = HttpUtility.HtmlDecode(FCKEditorFix.Fix(((RadEditor)row.FindControl("txtThongSoSize")).Content.Trim())); string ChatLieu = ((RadTextBox)row.FindControl("txtChatLieu")).Text.Trim(); if (e.CommandName == "PerformInsert") { var oProduct = new Product(); ImageName = oProduct.ProductInsert( ImageName, MetaTittle, MetaDescription, ProductName, ConvertedProductName, Description, Content, Tag, MetaTittleEn, MetaDescriptionEn, ProductNameEn, DescriptionEn, ContentEn, TagEn, Price, OtherPrice, SavePrice, Discount, CategoryID, ManufacturerID, OriginID, InStock, IsHot, IsNew, IsBestSeller, IsSaleOff, IsShowOnHomePage, Priority, IsAvailable, Ri, ThongSoSize, ChatLieu ); ProductID = oProduct.ProductID; string strFullPath = "~/res/product/" + ImageName; if (!string.IsNullOrEmpty(ImageName)) { FileImageName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); ResizeCropImage.ResizeByCondition(strFullPath, 800, 800); ResizeCropImage.CreateThumbNailByCondition("~/res/product/", "~/res/product/thumbs/", ImageName, 120, 120); } if (TempImage.Rows.Count > 0) { var oProductImage = new ProductImage(); foreach (DataRow dr in TempImage.Rows) { oProductImage.ProductImageInsert(dr["ImageName"].ToString(), "", "", "", "", "", ProductID, "True", ""); } } RadGrid1.Rebind(); } else { var dsUpdateParam = ObjectDataSource1.UpdateParameters; var strOldImagePath = Server.MapPath("~/res/product/" + OldImageName); var strOldThumbImagePath = Server.MapPath("~/res/product/thumbs/" + OldImageName); dsUpdateParam["ConvertedProductName"].DefaultValue = ConvertedProductName; dsUpdateParam["ImageName"].DefaultValue = ImageName; dsUpdateParam["CategoryID"].DefaultValue = CategoryID; dsUpdateParam["ManufacturerID"].DefaultValue = ManufacturerID; dsUpdateParam["OriginID"].DefaultValue = OriginID; dsUpdateParam["InStock"].DefaultValue = InStock; dsUpdateParam["IsHot"].DefaultValue = IsHot; dsUpdateParam["IsNew"].DefaultValue = IsNew; dsUpdateParam["IsBestSeller"].DefaultValue = IsBestSeller; dsUpdateParam["IsSaleOff"].DefaultValue = IsSaleOff; dsUpdateParam["IsShowOnHomePage"].DefaultValue = IsShowOnHomePage; dsUpdateParam["IsAvailable"].DefaultValue = IsAvailable; if (!string.IsNullOrEmpty(ImageName)) { if (File.Exists(strOldImagePath)) File.Delete(strOldImagePath); if (File.Exists(strOldThumbImagePath)) File.Delete(strOldThumbImagePath); ImageName = (string.IsNullOrEmpty(ConvertedProductName) ? "" : ConvertedProductName + "-") + ProductID + ImageName.Substring(ImageName.LastIndexOf('.')); string strFullPath = "~/res/product/" + ImageName; FileImageName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); ResizeCropImage.ResizeByCondition(strFullPath, 800, 800); ResizeCropImage.CreateThumbNailByCondition("~/res/product/", "~/res/product/thumbs/", ImageName, 120, 120); } } } else if (e.CommandName == "Cancel") { if (TempImage.Rows.Count > 0) { foreach (DataRow row in TempImage.Rows) { DeletePhotoAlbum(row["ImageName"].ToString()); } TempImage.Rows.Clear(); } } else if (e.CommandName == "DeleteImage") { var oProduct = new Product(); var lnkDeleteImage = (LinkButton)e.CommandSource; var s = lnkDeleteImage.Attributes["rel"].ToString().Split('#'); var strProductID = s[0]; var ImageName = s[1]; oProduct.ProductImageDelete(strProductID); DeleteImage(ImageName); RadGrid1.Rebind(); } }
protected void FileImageAlbum_FileUploaded(object sender, FileUploadedEventArgs e) { var FileImageAlbum = (RadAsyncUpload)sender; var Parent = FileImageAlbum.NamingContainer; var ProductID = ((HiddenField)Parent.FindControl("hdnProductID")).Value; var RadListView1 = (RadListView)Parent.FindControl("RadListView1"); var RadListView2 = (RadListView)Parent.FindControl("RadListView2"); string targetFolder = "~/res/product/album/"; string newName = Guid.NewGuid().GetHashCode().ToString("X") + e.File.GetExtension(); e.File.SaveAs(Server.MapPath(targetFolder + newName)); //ResizeCropImage.ResizeByCondition(targetFolder + newName, 800, 800); //ResizeCropImage.CreateThumbNailByCondition("~/res/product/album/", "~/res/product/album/thumbs/", newName, 120, 120); if (string.IsNullOrEmpty(ProductID)) { TempImage.Rows.Add(new object[] { newName }); RadListView2.DataSource = TempImage; RadListView2.DataBind(); } else { var oProductImage = new ProductImage(); oProductImage.ProductImageInsert(newName, "", "", "", "", "", ProductID, "True", ""); RadListView1.Rebind(); } }
public ProductImagesRepositories() { db = new DBDataContext(); _Obj = new ProductImage(); }
/// <summary> /// Submit Button Click Event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSubmit_Click(object sender, EventArgs e) { #region Declarations SKUAdmin skuAdminAccess = new SKUAdmin(); ProductAdmin productAdmin = new ProductAdmin(); SKUAttribute skuAttribute = new SKUAttribute(); SKU sku = new SKU(); ProductCategory productCategory = new ProductCategory(); ProductCategoryAdmin productCategoryAdmin=new ProductCategoryAdmin(); Product product = new Product(); System.IO.FileInfo fileInfo=null; bool retVal = false; //check if category was selected if (CategoryTreeView.CheckedNodes.Count > 0) { lblCategoryError.Visible = false; } else { lblCategoryError.Visible = true; return; } #endregion #region Set Product Properties //passing Values product.ProductID = ItemID; product.PortalID = ZNodeConfigManager.SiteConfig.PortalID; //if edit mode then get all the values first if (ItemID > 0) { product = productAdmin.GetByProductId(ItemID); if (ViewState["productSkuId"] != null) { sku.SKUID = int.Parse(ViewState["productSkuId"].ToString()); } } //General Info product.Name = txtProductName.Text; product.ImageFile = txtimagename.Text; product.ProductNum = txtProductNum.Text; product.PortalID = ZNodeConfigManager.SiteConfig.PortalID; if (ProductTypeList.SelectedIndex != -1) { product.ProductTypeID = Convert.ToInt32(ProductTypeList.SelectedValue); } else { //"Please add a product type before you add a new product"; } //MANUFACTURER if (ManufacturerList.SelectedIndex != -1) { if (ManufacturerList.SelectedItem.Text.Equals("No Manufacturer Selected")) { product.ManufacturerID = null; } else { product.ManufacturerID = Convert.ToInt32(ManufacturerList.SelectedValue); } } //Supplier if (ddlSupplier.SelectedIndex != -1) { if (ddlSupplier.SelectedItem.Text.Equals("None")) { product.SupplierID = null; } else { product.SupplierID = Convert.ToInt32(ddlSupplier.SelectedValue); } } product.DownloadLink = txtDownloadLink.Text.Trim(); product.ShortDescription = txtshortdescription.Text; product.Description = ctrlHtmlText.Html; product.RetailPrice = Convert.ToDecimal(txtproductRetailPrice.Text); if (txtproductSalePrice.Text.Trim().Length > 0) { product.SalePrice = Convert.ToDecimal(txtproductSalePrice.Text.Trim()); } else { product.SalePrice = null; } if (txtProductWholeSalePrice.Text.Trim().Length > 0) { product.WholesalePrice = Convert.ToDecimal(txtProductWholeSalePrice.Text.Trim()); } else { product.WholesalePrice = null; } //Quantity Available product.QuantityOnHand = Convert.ToInt32(txtProductQuantity.Text); if (txtReOrder.Text.Trim().Length > 0) { product.ReorderLevel = Convert.ToInt32(txtReOrder.Text); } else { product.ReorderLevel = null; } if(txtMaxQuantity.Text.Equals("")) { product.MaxQty = 10; } else { product.MaxQty = Convert.ToInt32(txtMaxQuantity.Text); } // Display Settings product.MasterPage = ddlPageTemplateList.SelectedItem.Text; product.DisplayOrder = int.Parse(txtDisplayOrder.Text.Trim()); // Tax Settings if(ddlTaxClass.SelectedIndex != -1) product.TaxClassID = int.Parse(ddlTaxClass.SelectedValue); //Shipping Option setting product.ShippingRuleTypeID = Convert.ToInt32(ShippingTypeList.SelectedValue); product.FreeShippingInd = chkFreeShippingInd.Checked; product.ShipSeparately = chkShipSeparately.Checked; if (txtProductWeight.Text.Trim().Length > 0) { product.Weight = Convert.ToDecimal(txtProductWeight.Text.Trim()); } else { product.Weight = null; } //Product Height - Which will be used to determine the shipping cost if (txtProductHeight.Text.Trim().Length > 0) { product.Height = decimal.Parse(txtProductHeight.Text.Trim()); } else { product.Height = null; } if (txtProductWidth.Text.Trim().Length > 0) { product.Width = decimal.Parse(txtProductWidth.Text.Trim()); } else { product.Width = null; } if (txtProductLength.Text.Trim().Length > 0) { product.Length = decimal.Parse(txtProductLength.Text.Trim()); } else { product.Length = null; } //Stock DataSet MyAttributeTypeDataSet = productAdmin.GetAttributeTypeByProductTypeID(int.Parse(ProductTypeList.SelectedValue)); if (MyAttributeTypeDataSet.Tables[0].Rows.Count == 0) { product.SKU = txtProductSKU.Text.Trim(); product.QuantityOnHand = Convert.ToInt32(txtProductQuantity.Text); } else { //SKU sku.ProductID = ItemID; sku.QuantityOnHand = Convert.ToInt32(txtProductQuantity.Text); sku.SKU = txtProductSKU.Text.Trim(); sku.ActiveInd = true; product.SKU = txtProductSKU.Text.Trim(); product.QuantityOnHand = 0; //Reset quantity available in the Product table,If SKU is selected } product.ImageAltTag = txtImageAltTag.Text.Trim(); #endregion #region Image Validation // Validate image if ((ItemID == 0 || RadioProductNewImage.Checked == true) && UploadProductImage.PostedFile.FileName.Length > 0) { //Check for Product Image fileInfo = new System.IO.FileInfo(UploadProductImage.PostedFile.FileName); if (fileInfo != null) { product.ImageFile = fileInfo.Name; sku.SKUPicturePath = fileInfo.Name; } } #endregion #region Database & Image Updates //set update date product.UpdateDte = System.DateTime.Now; //create transaction TransactionManager tranManager = ConnectionScope.CreateTransaction(); try { if (ItemID > 0) //PRODUCT UPDATE { //Update product Sku and Product values if (MyAttributeTypeDataSet.Tables[0].Rows.Count > 0) //If ProductType has SKU's { if (sku.SKUID > 0) //For this product already SKU if on exists { sku.UpdateDte = System.DateTime.Now; // Check whether Duplicate attributes is created string Attributes = String.Empty; DataSet MyAttributeTypeDataSet1 = productAdmin.GetAttributeTypeByProductTypeID(ProductTypeId); foreach (DataRow MyDataRow in MyAttributeTypeDataSet1.Tables[0].Rows) { System.Web.UI.WebControls.DropDownList lstControl = (System.Web.UI.WebControls.DropDownList)ControlPlaceHolder.FindControl("lstAttribute" + MyDataRow["AttributeTypeId"].ToString()); int selValue = int.Parse(lstControl.SelectedValue); Attributes += selValue.ToString() + ","; } // Split the string string Attribute = Attributes.Substring(0, Attributes.Length - 1); // To check SKU combination is already exists. bool RetValue = skuAdminAccess.CheckSKUAttributes(ItemID, sku.SKUID, Attribute); if (!RetValue) { //then Update the database with new property values retVal = productAdmin.Update(product, sku); } else { //Throw error if duplicate attribute lblMsg.Text = "This Attribute combination already exists for this product. Please select different combination."; return; } } else { retVal = productAdmin.Update(product); //If Product doesn't have any SKUs yet,then create new SKU in the database skuAdminAccess.Add(sku); } } else { retVal = productAdmin.Update(product); // If User selectes Default product type for this product, // then Remove all the existing SKUs for this product skuAdminAccess.DeleteByProductId(ItemID); } if (!retVal) { throw (new ApplicationException()); } // Delete existing categories productAdmin.DeleteProductCategories(ItemID); // Add Product Categories foreach (TreeNode Node in CategoryTreeView.CheckedNodes) { ProductCategory prodCategory = new ProductCategory(); ProductAdmin prodAdmin = new ProductAdmin(); prodCategory.CategoryID = int.Parse(Node.Value); prodCategory.ProductID = ItemID; prodAdmin.AddProductCategory(prodCategory); } // Delete existing SKUAttributes skuAdminAccess.DeleteBySKUId(sku.SKUID); // Add SKU Attributes foreach (DataRow MyDataRow in MyAttributeTypeDataSet.Tables[0].Rows) { System.Web.UI.WebControls.DropDownList lstControl = (System.Web.UI.WebControls.DropDownList)ControlPlaceHolder.FindControl("lstAttribute" + MyDataRow["AttributeTypeId"].ToString()); int selValue = int.Parse(lstControl.SelectedValue); if (selValue > 0) { skuAttribute.AttributeId = selValue; } skuAttribute.SKUID = sku.SKUID; skuAdminAccess.AddSKUAttribute(skuAttribute); } } else // PRODUCT ADD { product.ActiveInd = true; // Add Product/SKU if (MyAttributeTypeDataSet.Tables[0].Rows.Count > 0) { //if ProductType has SKUs, then insert sku with Product retVal = productAdmin.Add(product, sku, out _ProductID, out SKUId); } else { retVal = productAdmin.Add(product, out _ProductID); //if ProductType is Default } if (!retVal) { throw (new ApplicationException()); } // Add Category List for the Product foreach (TreeNode Node in CategoryTreeView.CheckedNodes) { ProductCategory prodCategory = new ProductCategory(); ProductAdmin prodAdmin = new ProductAdmin(); prodCategory.CategoryID = int.Parse(Node.Value); prodCategory.ProductID = _ProductID; prodAdmin.AddProductCategory(prodCategory); } // Add SKU Attributes foreach (DataRow MyDataRow in MyAttributeTypeDataSet.Tables[0].Rows) { System.Web.UI.WebControls.DropDownList lstControl = (System.Web.UI.WebControls.DropDownList)ControlPlaceHolder.FindControl("lstAttribute" + MyDataRow["AttributeTypeId"].ToString()); int selValue = int.Parse(lstControl.SelectedValue); if (selValue > 0) { skuAttribute.AttributeId = selValue; } skuAttribute.SKUID = SKUId; skuAdminAccess.AddSKUAttribute(skuAttribute); } ZNode.Libraries.Admin.ProductViewAdmin imageAdmin = new ProductViewAdmin(); ZNode.Libraries.DataAccess.Entities.ProductImage productImage = new ProductImage(); productImage.Name = txtimagename.Text; productImage.ActiveInd = false; productImage.ShowOnCategoryPage = false; productImage.ProductID = _ProductID; productImage.ProductImageTypeID = 1; productImage.DisplayOrder = 500; productImage.ImageAltTag = txtImageAltTag.Text.Trim(); productImage.AlternateThumbnailImageFile = txtImageAltTag.Text.Trim(); if (fileInfo != null) { productImage.ImageFile = fileInfo.Name; } imageAdmin.Insert(productImage); } // Commit transaction tranManager.Commit(); } catch // error occurred so rollback transaction { if (tranManager.IsOpen) tranManager.Rollback(); lblMsg.Text = "Unable to update product. Please try again."; return; } // Upload File if this is a new product or the New Image option was selected for an existing product if (RadioProductNewImage.Checked || ItemID == 0) { if (fileInfo != null) { UploadProductImage.SaveAs(Server.MapPath(ZNodeConfigManager.EnvironmentConfig.OriginalImagePath + fileInfo.Name)); ZNodeImage.ResizeImage(fileInfo, ZNode.Libraries.Framework.Business.ZNodeConfigManager.SiteConfig.MaxCatalogItemLargeWidth, Server.MapPath(ZNodeConfigManager.EnvironmentConfig.LargeImagePath)); ZNodeImage.ResizeImage(fileInfo, ZNode.Libraries.Framework.Business.ZNodeConfigManager.SiteConfig.MaxCatalogItemThumbnailWidth, Server.MapPath(ZNodeConfigManager.EnvironmentConfig.ThumbnailImagePath)); ZNodeImage.ResizeImage(fileInfo, ZNode.Libraries.Framework.Business.ZNodeConfigManager.SiteConfig.MaxCatalogItemMediumWidth, Server.MapPath(ZNodeConfigManager.EnvironmentConfig.MediumImagePath)); ZNodeImage.ResizeImage(fileInfo, ZNode.Libraries.Framework.Business.ZNodeConfigManager.SiteConfig.MaxCatalogItemSmallWidth, Server.MapPath(ZNodeConfigManager.EnvironmentConfig.SmallImagePath)); ZNodeImage.ResizeImage(fileInfo, ZNode.Libraries.Framework.Business.ZNodeConfigManager.SiteConfig.MaxCatalogItemSwatchWidth, Server.MapPath(ZNodeConfigManager.EnvironmentConfig.SwatchImagePath)); ZNodeImage.ResizeImage(fileInfo, ZNode.Libraries.Framework.Business.ZNodeConfigManager.SiteConfig.MaxCatalogItemCrossSellWidth, Server.MapPath(ZNodeConfigManager.EnvironmentConfig.CrossSellImagePath)); } } #endregion #region Redirect to next page //Redirect to next page if (ItemID > 0) { string ViewLink = "~/admin/secure/catalog/product/view.aspx?itemid=" + ItemID.ToString(); Response.Redirect(ViewLink); } else { string NextLink = "~/admin/secure/catalog/product/view.aspx?itemid=" + _ProductID.ToString(); Response.Redirect(NextLink); } #endregion }
private void LinkProductToImage(Guid productId, Guid imageId) { CatalogManager catManager = CatalogManager.GetManager(); Product p = catManager.GetProducts().Where(x => x.Id == productId).FirstOrDefault(); if (p == null) { return; // Product does not exist } LibrariesManager librariesManager = LibrariesManager.GetManager(); Telerik.Sitefinity.Libraries.Model.Image image = librariesManager.GetImage(imageId); if (image == null) { return; // Image does not exist } // Create, populate and save a ProductImage ProductImage pi = new ProductImage(); pi.AlbumId = image.Album.Id; pi.Album = image.Album.Title.Value; pi.Id = image.Id; pi.Width = image.Width; pi.Height = image.Height; pi.Title = image.Title; pi.Url = image.Url; pi.AlternativeText = image.AlternativeText; pi.FileName = image.FilePath; pi.FileSize = image.TotalSize.ToString(); // Add the ProductImage to the product's list of images p.Images.Add(pi); // Save the product catManager.SaveChanges(); // Create a content link between the product and the image ContentLinksManager contentLinksManager = ContentLinksManager.GetManager(); IEnumerable<ContentLink> contentLinks = contentLinksManager.GetContentLinks() .Where(cl => cl.ParentItemId == p.Id && cl.ComponentPropertyName == "ProductImage") .ToList(); IEnumerable<Guid> persistedIds = contentLinks.Select(cl => cl.ChildItemId); List<ProductImage> imagesToAdd = p.Images.Where(i => !persistedIds.Contains(i.Id)).ToList(); var createdContentLinks = new List<ContentLink>(); foreach (ProductImage productImage in imagesToAdd) { Telerik.Sitefinity.Libraries.Model.Image img2 = librariesManager.GetImage(productImage.Id); ContentLink contentLink = contentLinksManager.CreateContentLink("ProductImage", p, img2); createdContentLinks.Add(contentLink); } // Save the content link(s) contentLinksManager.SaveChanges(); }
/// <summary> /// this method insert the productImage /// </summary> /// <param name="productImage"></param> public void InsertProductImage(Company company, ProductImage entity, HttpPostedFile file) { string virtualPath = company.GetFilesDirectory(); string fileName = Path.GetFileName(file.FileName); entity.ImageUrl = virtualPath + fileName; // set the ImageUrl file.SaveAs(HttpContext.Current.Server.MapPath(entity.ImageUrl)); //save the file InsertProductImage(entity); }
/// <summary> /// Insert product images /// </summary> /// <param name="entity"></param> public void InsertProductImage(ProductImage entity) { DbContext.ProductImages.InsertOnSubmit(entity); //insert the productImage DbContext.SubmitChanges(); }
public AdminProductImageViewModel(ProductImage productImage) { ProductImageID = productImage.ProductImageID; ProductID = productImage.ProductID; Path = productImage.Path; }
public object SaveImage(ProductImage p) { SubSonicRepository<ProductImage> repository = base.GetRepository<ProductImage>(); return p.ProductImageID > 0 ? repository.Update(p) : repository.Add(p); }
public ProductImage LoadByProductId(String ProductID) { if (ProductID != null) { _Obj = db.ProductImages.FirstOrDefault(pram => pram.ProductId == new Guid(ProductID) && pram.Active == true); return _Obj; } return null; }
protected void RadListView1_ItemCommand(object sender, RadListViewCommandEventArgs e) { try { if (e.CommandName == "PerformInsert") { var item = e.ListViewItem; var FileImageName = (RadUpload)item.FindControl("FileImageName"); var strProductName = ((Label)FormView1.FindControl("lblProductName")).Text.Trim(); var strConvertedProductName = Common.ConvertTitle(strProductName); var strImageName = FileImageName.UploadedFiles.Count > 0 ? Guid.NewGuid().GetHashCode().ToString("X") + FileImageName.UploadedFiles[0].GetExtension() : ""; var strTitle = ((TextBox)item.FindControl("txtTitle")).Text.Trim(); var strDescription = ((TextBox)item.FindControl("txtDescription")).Text.Trim(); var strTitleEn = ((TextBox)item.FindControl("txtTitleEn")).Text.Trim(); var strDescriptionEn = ((TextBox)item.FindControl("txtDescriptionEn")).Text.Trim(); var IsAvailable = ((CheckBox)item.FindControl("chkAddIsAvailable")).Checked.ToString(); var Priority = ((RadNumericTextBox)item.FindControl("txtPriority")).Text.Trim(); var oProductImage = new ProductImage(); oProductImage.ProductImageInsert( strImageName, strConvertedProductName, strTitle, strDescription, strTitleEn, strDescriptionEn, Request.QueryString["PI"], IsAvailable, Priority); string strFullPath = "~/res/product/album/" + strImageName; if (!string.IsNullOrEmpty(strImageName)) { FileImageName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); //ResizeCropImage.ResizeByCondition(strFullPath, 600, 600); //ResizeCropImage.CreateThumbNailByCondition("~/res/product/album/", "~/res/product/album/thumbs/", strImageName, 120, 120); } RadListView1.InsertItemPosition = RadListViewInsertItemPosition.None; } else if (e.CommandName == "Update") { var item = e.ListViewItem; var FileImageName = (RadUpload)item.FindControl("FileImageName"); var dsUpdateParam = ObjectDataSource1.UpdateParameters; var strProductImageID = ((HiddenField)e.ListViewItem.FindControl("hdnProductImageID")).Value; var strProductName = ((Label)FormView1.FindControl("lblProductName")).Text.Trim(); var strConvertedProductName = Common.ConvertTitle(strProductName); var strOldImageName = ((HiddenField)e.ListViewItem.FindControl("hdnImageName")).Value; var strIsAvailable = ((CheckBox)item.FindControl("chkAddIsAvailable")).Checked.ToString(); var strImageName = FileImageName.UploadedFiles.Count > 0 ? Guid.NewGuid().GetHashCode().ToString("X") + FileImageName.UploadedFiles[0].GetExtension() : ""; dsUpdateParam["ImageName"].DefaultValue = !string.IsNullOrEmpty(strImageName) ? strImageName : strOldImageName; dsUpdateParam["ConvertedProductName"].DefaultValue = strConvertedProductName; dsUpdateParam["IsAvailable"].DefaultValue = strIsAvailable; if (!string.IsNullOrEmpty(strImageName)) { var strOldImagePath = Server.MapPath("~/res/product/album/" + strOldImageName); var strOldThumbImagePath = Server.MapPath("~/res/product/album/thumbs/" + strOldImageName); if (File.Exists(strOldImagePath)) File.Delete(strOldImagePath); if (File.Exists(strOldThumbImagePath)) File.Delete(strOldThumbImagePath); strImageName = (string.IsNullOrEmpty(strConvertedProductName) ? "" : strConvertedProductName + "-") + strProductImageID + strImageName.Substring(strImageName.LastIndexOf('.')); string strFullPath = "~/res/product/album/" + strImageName; FileImageName.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); //ResizeCropImage.ResizeByCondition(strFullPath, 600, 600); //ResizeCropImage.CreateThumbNailByCondition("~/res/product/album/", "~/res/product/album/thumbs/", strImageName, 120, 120); } } else if (e.CommandName == "Delete") { var strOldImageName = ((HiddenField)e.ListViewItem.FindControl("hdnImageName")).Value; DeleteImage(strOldImageName); } else if (e.CommandName == "QuickUpdate") { string ProductImageID, Priority, IsAvailable; var oProductImage = new ProductImage(); foreach (RadListViewDataItem item in RadListView1.Items) { ProductImageID = item.GetDataKeyValue("ProductImageID").ToString(); Priority = ((RadNumericTextBox)item.FindControl("txtPriority")).Text.Trim(); IsAvailable = ((CheckBox)item.FindControl("chkIsAvailable")).Checked.ToString(); oProductImage.ProductImageQuickUpdate( ProductImageID, IsAvailable, Priority ); } } else if (e.CommandName == "DeleteSelected") { var oProductImage = new ProductImage(); string ProductImageID, OldImageName; foreach (RadListViewDataItem item in RadListView1.Items) { var chkSelect = (CheckBox)item.FindControl("chkSelect"); if (chkSelect.Checked) { ProductImageID = item.GetDataKeyValue("ProductImageID").ToString(); OldImageName = ((HiddenField)item.FindControl("hdnImageName")).Value; DeleteImage(OldImageName); oProductImage.ProductImageDelete(ProductImageID); } } } RadListView1.Rebind(); } catch (Exception ex) { lblError.Text = ex.Message; } }
public ProductImage LoadById(String ID) { if (ID != null) { _Obj = db.ProductImages.FirstOrDefault(pram => pram.Id == new Guid(ID)); return _Obj; } return null; }