예제 #1
0
        public async Task <bool> updateImage(string[] FileName, long UserId, long ProductId)
        {
            try {
                ProductImageDto imageDto = new ProductImageDto();

                string path = Path.Combine(FolderPath.webRootPath, FolderPath.ProductImage);
                foreach (var item in FileName)
                {
                    Byte[]     bytes            = Convert.FromBase64String(item.Split(',')[1]);
                    string     newFileName      = DateTime.Now.Ticks.ToString("HHmmss");
                    string     ogirinalFileName = RendomFileName(newFileName);
                    FileStream file             = File.Create(path + "\\" + ogirinalFileName);
                    await file.WriteAsync(bytes, 0, bytes.Length);

                    file.Close();
                    var ProductImageData = _mapper.Map <ProductsImages>(imageDto);

                    var imgRes = SaveAsyncUtility <ProductsImages> .UpdateDefaultFieldsForAddAndUpdate(ProductImageData, UserId, false);

                    imgRes.ImageName = ogirinalFileName;
                    imgRes.ProductId = ProductId;
                    await _context.AddAsync(imgRes);

                    await _context.SaveChangesAsync();
                }
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
 public ProductImageDto GetSingleProductImage(ProductImageDto request, int RequestUserId, string TokenKey)
 {
     try
     {
         CheckAuthentication(RequestUserId, TokenKey);
         var data      = GetAllCachedData <ProductImageEntity>().AsQueryable();
         var predicate = PredicateBuilderHelper.True <ProductImageEntity>();
         if (request.Id.HasValue)
         {
             predicate = predicate.And(q => q.Id == request.Id);
         }
         if (request.ActivationStatus > 0)
         {
             predicate = predicate.And(q => q.ActivationStatus == request.ActivationStatus);
         }
         if (!request.ImageUrl.IsNullOrEmpty())
         {
             predicate = predicate.And(q => q.ImageUrl.Contains(request.ImageUrl));
         }
         var result = data.FirstOrDefault(predicate);
         return(result.ConvertTo <ProductImageDto>());
     }
     catch (KnownException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         Logger.AddLog(LogTypeEnum.Error, "ProductManager.GetSingleProductImage", null, ex.Message, request.ToJson(), ex);
         throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex);
     }
 }
        public void ConvertToDto_ProductImageNotNull_ReturnSameProductId()
        {
            ProductImage image = MockProductImage();

            ProductImageDto imageDto = image.ConvertToDto();

            Assert.Equal(image.ProductId, imageDto.ProductId);
        }
예제 #4
0
        public async Task <string> InsertImage(ProductImageDto dto)
        {
            if (!menu.AdminAccess)
            {
                return(null);
            }
            dto.Image = Request.Files[0];
            string message = await _productService.InsertImage(dto);

            return(message);
        }
예제 #5
0
        public static ProductImage ToEntity(this ProductImageDto dto)
        {
            if (dto == null)
            {
                return(null);
            }

            return(new ProductImage
            {
                ImageId = dto.ImageId,
                ProductId = dto.ProductId,
                Photo = dto.Photo,
                IsActive = dto.IsActive,
                IsPrimary = dto.IsPrimary,
            });
        }
        public async Task <ApiResponse> UploadImageMultile([FromForm] ProductImageDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(new ApiResponse($"{ModelState}", ModelState, 400));
                }
                if (dto.ProductId != Guid.Empty)
                {
                    var product = await _productService.GetByIdAsync(dto.ProductId);

                    if (product == null)
                    {
                        return(new ApiResponse("khong tim thay", dto.ProductId, 404));
                    }
                    List <ProductImage> listPr = new List <ProductImage>();

                    foreach (IFormFile file in dto.Image)
                    {
                        ProductImage pr = new ProductImage();
                        MemoryStream ms = new MemoryStream();
                        file.CopyTo(ms);
                        pr.Image     = ms.ToArray();
                        pr.ProductId = product.Id;
                        pr.Name      = file.FileName;
                        pr.Url       = file.FileName;
                        ms.Close();
                        ms.Dispose();
                        listPr.Add(pr);
                    }
                    var productImage = _mapper.Map <List <ProductImage> >(listPr);
                    await _productImageService.AddManyAsync(productImage);

                    var vm = _mapper.Map <List <ProductImageViewModel> >(productImage);

                    return(new ApiResponse("them thanh cong", vm, 201));
                }
                return(new ApiResponse("khong ton tai", 405));
            }
            catch (Exception ex)
            {
                return(new ApiResponse("khong tim thay", ex, 404));
            }
        }
예제 #7
0
        public async Task <string> InsertImage(ProductImageDto dto)
        {
            string message     = "";
            var    con         = _baseInterface.GetConnection();
            var    transaction = con.BeginTransaction();

            try
            {
                int result  = 0;
                var product = await _productRepository.GetProductByIdAsync(dto.ProductId);

                if (product == null || dto.Image is null)
                {
                    return("Product is not available or image cannot be empty");
                }

                var productImages = await GetProductImageByProductId(dto.ProductId);

                if (productImages.Count() > 0)
                {
                    if (dto.IsPrimary == true)
                    {
                        _productRepository.ProductPrimaryImage(con, transaction, dto.ProductId);
                    }
                }
                else
                {
                    dto.IsPrimary = true;
                }

                var entity = dto.ToEntity();
                entity.Photo = _imageService.ConvertToByte(dto.Image);
                result       = _productRepository.InsertProductImage(entity, transaction, con);
                message      = _messageClass.ShowSuccessMessage(result);
                transaction.Commit();
            }
            catch (SqlException ex)
            {
                message = _messageClass.ShowErrorMessage(string.Format("{0} ~ {1}", ex.Number.ToString(), ex.Message));
                transaction.Rollback();
            }
            return(message);
        }
예제 #8
0
        //        [Permission(Action = ActionName.CanCreate)]
        public IHttpActionResult CreateProductImage([FromBody] ProductImageDto productImage)
        {
            return(CreateResponse(() =>
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var model = Mapper.Map <ProductImage>(productImage);

                _productImageService.Add(model);
                UnitOfWork.Commit();

                productImage.Id = model.Id;

                return Created(new Uri(Request.RequestUri + "/" + productImage.Id), productImage);
            }));
        }
        public ProductImageDto CreateOrUpdateProductImage(ProductImageDto dto, int RequestUserId, string TokenKey)
        {
            try
            {
                CheckAuthentication(RequestUserId, TokenKey);

                #region Empty Control
                if (dto.ImageUrl.IsNullOrEmpty())
                {
                    throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("ImageUrl"));
                }
                #endregion

                var data   = GetAllCachedData <ProductTypeEntity>().ToList();
                var entity = dto.ConvertTo <ProductTypeEntity>();
                var conn   = Db.CreateConnection(true);
                if (dto.Id > 0)
                {
                    entity.UpdateUser = RequestUserId;
                    entity.UpdateDate = DateTimeHelper.Now;
                    conn.Update(entity, Db._DbTransaction);
                    data.RemoveAt(data.FindIndex(q => q.Id == entity.Id));
                }
                else
                {
                    int Id = conn.Insert(entity, Db._DbTransaction).ToInt();
                    entity = conn.Get <ProductTypeEntity>(Id);
                }
                data.Add(entity);
                FillCacheData(data);
                return(entity.ConvertTo <ProductImageDto>());
            }
            catch (KnownException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                Logger.AddLog(LogTypeEnum.Error, "ProductManager.CreateOrUpdateProductImage", RequestUserId, ex.Message, dto.ToJson(), ex);
                throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex);
            }
        }
        public async Task UpdateProductImages(UpdateProductImagesInput inputProductImages)
        {
            byte[] byteArray;
            string _fileType;

            string[] _fileExtArr;
            string   _fileExt   = "jpeg";
            var      imageBytes = _tempFileCacheManager.GetFile(inputProductImages.FileToken);

            if (inputProductImages.FileType != null)
            {
                _fileType   = inputProductImages.FileType;
                _fileExtArr = _fileType.Split("/");
                if (_fileExtArr.Length > 1)
                {
                    _fileExt = _fileExtArr[1];
                }
            }


            if (imageBytes == null)
            {
                throw new UserFriendlyException("There is no such image file with the token: " + inputProductImages.FileToken);
            }

            using (var bmpImage = new Bitmap(new MemoryStream(imageBytes)))
            {
                var width  = (inputProductImages.Width == 0 || inputProductImages.Width > bmpImage.Width) ? bmpImage.Width : inputProductImages.Width;
                var height = (inputProductImages.Height == 0 || inputProductImages.Height > bmpImage.Height) ? bmpImage.Height : inputProductImages.Height;
                var bmCrop = bmpImage.Clone(new Rectangle(inputProductImages.X, inputProductImages.Y, width, height), bmpImage.PixelFormat);

                using (var stream = new MemoryStream())
                {
                    bmCrop.Save(stream, bmpImage.RawFormat);
                    byteArray = stream.ToArray();
                }
            }

            if (byteArray.Length > MaxProductImagesBytes)
            {
                throw new UserFriendlyException(L("Image_Warn_SizeLimit", AppConsts.MaxImageBytesUserFriendlyValue));
            }

            var inputDto = new ProductImageDto
            {
                ProductId   = inputProductImages.ProductId,
                Url         = inputProductImages.FileToken + "." + _fileExt,
                Description = inputProductImages.Description
            };

            var productImageDto = ObjectMapper.Map <ProductImage>(inputDto);


            if (AbpSession.TenantId != null)
            {
                productImageDto.TenantId = (int?)AbpSession.TenantId;
            }

            productImageDto.Bytes = byteArray;

            await _productImageRepository.InsertAsync(productImageDto);
        }