public void Can_save_and_load_productPicture()
        {
            var productPicture = new ProductPicture
                                     {
                                         DisplayOrder = 1,
                                         Product = new Product()
                                                       {
                                                           Name = "Name 1",
                                                           Published = true,
                                                           Deleted = false,
                                                           CreatedOnUtc = new DateTime(2010, 01, 01),
                                                           UpdatedOnUtc = new DateTime(2010, 01, 02)
                                                       },
                                         Picture = new Picture()
                                                                      {
                                                                          PictureBinary = new byte[] { 1, 2, 3 },
                                                                          MimeType = "image/pjpeg",
                                                                          IsNew = true
                                                                      }
                                     };

            var fromDb = SaveAndLoadEntity(productPicture);
            fromDb.ShouldNotBeNull();
            fromDb.DisplayOrder.ShouldEqual(1);

            fromDb.Product.ShouldNotBeNull();
            fromDb.Product.Name.ShouldEqual("Name 1");

            fromDb.Picture.ShouldNotBeNull();
            fromDb.Picture.MimeType.ShouldEqual("image/pjpeg");
        }
示例#2
0
        private void ProcessProductPictures(ICollection<ImportRow<Product>> batch, ImportResult result)
        {
            // true, cause pictures must be saved and assigned an id
            // prior adding a mapping.
            _rsProductPicture.AutoCommitEnabled = true;

            ProductPicture lastInserted = null;
            int equalPictureId = 0;

            foreach (var row in batch)
            {
                var pictures = new string[]
                {
             					row.GetValue<string>("Picture1"),
                    row.GetValue<string>("Picture2"),
                    row.GetValue<string>("Picture3")
                };

                int i = 0;
                try
                {
                    for (i = 0; i < pictures.Length; i++)
                    {
                        var picture = pictures[i];

                        if (picture.IsEmpty() || !File.Exists(picture))
                            continue;

                        var currentPictures = _rsProductPicture.TableUntracked.Expand(x => x.Picture).Where(x => x.ProductId == row.Entity.Id).Select(x => x.Picture).ToList();
                        var pictureBinary = _pictureService.FindEqualPicture(picture, currentPictures, out equalPictureId);

                        if (pictureBinary != null && pictureBinary.Length > 0)
                        {
                            // no equal picture found in sequence
                            var newPicture = _pictureService.InsertPicture(pictureBinary, "image/jpeg", _pictureService.GetPictureSeName(row.EntityDisplayName), true, false, false);
                            if (newPicture != null)
                            {
                                var mapping = new ProductPicture
                                {
                                    ProductId = row.Entity.Id,
                                    PictureId = newPicture.Id,
                                    DisplayOrder = 1,
                                };
                                _rsProductPicture.Insert(mapping);
                                lastInserted = mapping;
                            }
                        }
                        else
                        {
                            result.AddInfo("Found equal picture in data store. Skipping field.", row.GetRowInfo(), "Picture" + (i + 1).ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    result.AddWarning(ex.Message, row.GetRowInfo(), "Picture" + (i + 1).ToString());
                }

            }

            // Perf: notify only about LAST insertion and update
            if (lastInserted != null)
                _eventPublisher.EntityInserted(lastInserted);
        }
        /// <summary>
        /// Inserts a product picture
        /// </summary>
        /// <param name="productPicture">Product picture</param>
        public virtual void InsertProductPicture(ProductPicture productPicture)
        {
            if (productPicture == null)
                throw new ArgumentNullException("productPicture");

            _productPictureRepository.Insert(productPicture);

            //event notification
            _eventPublisher.EntityInserted(productPicture);
        }
        /// <summary>
        /// Deletes a product picture
        /// </summary>
        /// <param name="productPicture">Product picture</param>
        public virtual void DeleteProductPicture(ProductPicture productPicture)
        {
            if (productPicture == null)
                throw new ArgumentNullException("productPicture");

            // codehint: sm-add
            UnassignDeletedPictureFromVariantCombinations(productPicture);

            _productPictureRepository.Delete(productPicture);

            //event notification
            _eventPublisher.EntityDeleted(productPicture);
        }
        private void UnassignDeletedPictureFromVariantCombinations(ProductPicture productPicture)
        {
            var picId = productPicture.Id;
            bool touched = false;

            var combinations =
                from c in this._productVariantAttributeCombinationRepository.Table
                where c.ProductId == productPicture.Product.Id && !String.IsNullOrEmpty(c.AssignedPictureIds)
                select c;

            foreach (var c in combinations)
            {
                var ids = c.GetAssignedPictureIds().ToList();
                if (ids.Contains(picId))
                {
                    ids.Remove(picId);
                    //c.AssignedPictureIds = ids.Count > 0 ? String.Join<int>(",", ids) : null;
                    c.SetAssignedPictureIds(ids.ToArray());
                    touched = true;
                    // we will save after we're done. It's faster.
                }
            }

            // save in one shot!
            if (touched)
            {
                _dbContext.SaveChanges();
            }
        }
        protected virtual void ProcessProductPictures(ImportExecuteContext context, IEnumerable<ImportRow<Product>> batch)
        {
            // true, cause pictures must be saved and assigned an id prior adding a mapping.
            _productPictureRepository.AutoCommitEnabled = true;

            ProductPicture lastInserted = null;
            var equalPictureId = 0;
            var numberOfPictures = (context.ExtraData.NumberOfPictures ?? int.MaxValue);

            foreach (var row in batch)
            {
                var imageUrls = row.GetDataValue<List<string>>("ImageUrls");
                if (imageUrls.IsNullOrEmpty())
                    continue;

                var imageNumber = 0;
                var displayOrder = -1;
                var seoName = _pictureService.GetPictureSeName(row.EntityDisplayName);
                var imageFiles = new List<FileDownloadManagerItem>();

                // collect required image file infos
                foreach (var urlOrPath in imageUrls)
                {
                    var image = CreateDownloadImage(urlOrPath, seoName, ++imageNumber);

                    if (image != null)
                        imageFiles.Add(image);

                    if (imageFiles.Count >= numberOfPictures)
                        break;
                }

                // download images
                if (imageFiles.Any(x => x.Url.HasValue()))
                {
                    // async downloading in batch processing is inefficient cause only the image processing benefits from async,
                    // not the record processing itself. a per record processing may speed up the import.

                    AsyncRunner.RunSync(() => _fileDownloadManager.DownloadAsync(DownloaderContext, imageFiles.Where(x => x.Url.HasValue() && !x.Success.HasValue)));
                }

                // import images
                foreach (var image in imageFiles.OrderBy(x => x.DisplayOrder))
                {
                    try
                    {
                        if ((image.Success ?? false) && File.Exists(image.Path))
                        {
                            Succeeded(image);
                            var pictureBinary = File.ReadAllBytes(image.Path);

                            if (pictureBinary != null && pictureBinary.Length > 0)
                            {
                                var currentProductPictures = _productPictureRepository.TableUntracked.Expand(x => x.Picture)
                                    .Where(x => x.ProductId == row.Entity.Id)
                                    .ToList();

                                var currentPictures = currentProductPictures
                                    .Select(x => x.Picture)
                                    .ToList();

                                if (displayOrder == -1)
                                {
                                    displayOrder = (currentProductPictures.Any() ? currentProductPictures.Select(x => x.DisplayOrder).Max() : 0);
                                }

                                pictureBinary = _pictureService.ValidatePicture(pictureBinary);
                                pictureBinary = _pictureService.FindEqualPicture(pictureBinary, currentPictures, out equalPictureId);

                                if (pictureBinary != null && pictureBinary.Length > 0)
                                {
                                    // no equal picture found in sequence
                                    var newPicture = _pictureService.InsertPicture(pictureBinary, image.MimeType, seoName, true, false, false);
                                    if (newPicture != null)
                                    {
                                        var mapping = new ProductPicture
                                        {
                                            ProductId = row.Entity.Id,
                                            PictureId = newPicture.Id,
                                            DisplayOrder = ++displayOrder
                                        };

                                        _productPictureRepository.Insert(mapping);
                                        lastInserted = mapping;
                                    }
                                }
                                else
                                {
                                    context.Result.AddInfo("Found equal picture in data store. Skipping field.", row.GetRowInfo(), "ImageUrls" + image.DisplayOrder.ToString());
                                }
                            }
                        }
                        else if (image.Url.HasValue())
                        {
                            context.Result.AddInfo("Download of an image failed.", row.GetRowInfo(), "ImageUrls" + image.DisplayOrder.ToString());
                        }
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddWarning(exception.ToAllMessages(), row.GetRowInfo(), "ImageUrls" + image.DisplayOrder.ToString());
                    }
                }
            }

            // Perf: notify only about LAST insertion and update
            if (lastInserted != null)
            {
                _services.EventPublisher.EntityInserted(lastInserted);
            }
        }