public void Can_save_and_load_productManufacturer() { var productManufacturer = new ProductManufacturer { IsFeaturedProduct = true, DisplayOrder = 1, Product = new Product() { Name = "Name 1", Published = true, Deleted = false, CreatedOnUtc = new DateTime(2010, 01, 01), UpdatedOnUtc = new DateTime(2010, 01, 02) }, Manufacturer = new Manufacturer() { Name = "Name", Description = "Description 1", MetaKeywords = "Meta keywords", MetaDescription = "Meta description", MetaTitle = "Meta title", PictureId = 3, PageSize = 4, PriceRanges = "1-3;", Published = true, Deleted = false, DisplayOrder = 5, CreatedOnUtc = new DateTime(2010, 01, 01), UpdatedOnUtc = new DateTime(2010, 01, 02), } }; var fromDb = SaveAndLoadEntity(productManufacturer); fromDb.ShouldNotBeNull(); fromDb.IsFeaturedProduct.ShouldEqual(true); fromDb.DisplayOrder.ShouldEqual(1); fromDb.Product.ShouldNotBeNull(); fromDb.Product.Name.ShouldEqual("Name 1"); fromDb.Manufacturer.ShouldNotBeNull(); fromDb.Manufacturer.Name.ShouldEqual("Name"); }
/// <summary> /// Updates the product manufacturer mapping /// </summary> /// <param name="productManufacturer">Product manufacturer mapping</param> public virtual void UpdateProductManufacturer(ProductManufacturer productManufacturer) { if (productManufacturer == null) throw new ArgumentNullException("productManufacturer"); _productManufacturerRepository.Update(productManufacturer); //cache _cacheManager.RemoveByPattern(MANUFACTURERS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTMANUFACTURERS_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(productManufacturer); }
public ActionResult ProductManufacturerInsert(GridCommand command, ProductModel.ProductManufacturerModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) return AccessDeniedView(); var productId = model.ProductId; var manufacturerId = Int32.Parse(model.Manufacturer); //use Manufacturer property (not ManufacturerId) because appropriate property is stored in it //a vendor should have access only to his products if (_workContext.CurrentVendor != null) { var product = _productService.GetProductById(productId); if (product != null && product.VendorId != _workContext.CurrentVendor.Id) { return Content("This is not your product"); } } var existingProductmanufacturers = _manufacturerService.GetProductManufacturersByManufacturerId(manufacturerId, 0, int.MaxValue, true); if (existingProductmanufacturers.FindProductManufacturer(productId, manufacturerId) == null) { var productManufacturer = new ProductManufacturer() { ProductId = productId, ManufacturerId = manufacturerId, DisplayOrder = model.DisplayOrder }; //a vendor cannot edit "IsFeaturedProduct" property if (_workContext.CurrentVendor == null) { productManufacturer.IsFeaturedProduct = model.IsFeaturedProduct; } _manufacturerService.InsertProductManufacturer(productManufacturer); } return ProductManufacturerList(command, productId); }
/// <summary> /// Import products from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportProductsFromXlsx(Stream stream) { // ok, we can run the real code of the sample now using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) throw new NasException("No worksheet found"); //the columns var properties = new string[] { "Name", "ShortDescription", "FullDescription", "VendorId", "ProductTemplateId", "ShowOnHomePage", "MetaKeywords", "MetaDescription", "MetaTitle", "SeName", "AllowCustomerReviews", "Published", "ProductVariantName", "SKU", "ManufacturerPartNumber", "Gtin", "IsGiftCard", "GiftCardTypeId", "RequireOtherProducts", "RequiredProductVariantIds", "AutomaticallyAddRequiredProductVariants", "IsDownload", "DownloadId", "UnlimitedDownloads", "MaxNumberOfDownloads", "DownloadActivationTypeId", "HasSampleDownload", "SampleDownloadId", "HasUserAgreement", "UserAgreementText", "IsRecurring", "RecurringCycleLength", "RecurringCyclePeriodId", "RecurringTotalCycles", "IsShipEnabled", "IsFreeShipping", "AdditionalShippingCharge", "IsTaxExempt", "TaxCategoryId", "ManageInventoryMethodId", "StockQuantity", "DisplayStockAvailability", "DisplayStockQuantity", "MinStockQuantity", "LowStockActivityId", "NotifyAdminForQuantityBelow", "BackorderModeId", "AllowBackInStockSubscriptions", "OrderMinimumQuantity", "OrderMaximumQuantity", "AllowedQuantities", "DisableBuyButton", "DisableWishlistButton", "CallForPrice", "Price", "OldPrice", "ProductCost", "SpecialPrice", "SpecialPriceStartDateTimeUtc", "SpecialPriceEndDateTimeUtc", "CustomerEntersPrice", "MinimumCustomerEnteredPrice", "MaximumCustomerEnteredPrice", "Weight", "Length", "Width", "Height", "CreatedOnUtc", "CategoryIds", "ManufacturerIds", "Picture1", "Picture2", "Picture3", }; int iRow = 2; while (true) { bool allColumnsAreEmpty = true; for (var i = 1; i <= properties.Length; i++) if (worksheet.Cells[iRow, i].Value != null && !String.IsNullOrEmpty(worksheet.Cells[iRow, i].Value.ToString())) { allColumnsAreEmpty = false; break; } if (allColumnsAreEmpty) break; string name = worksheet.Cells[iRow, GetColumnIndex(properties, "Name")].Value as string; string shortDescription = worksheet.Cells[iRow, GetColumnIndex(properties, "ShortDescription")].Value as string; string fullDescription = worksheet.Cells[iRow, GetColumnIndex(properties, "FullDescription")].Value as string; int vendorId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "VendorId")].Value); int productTemplateId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTemplateId")].Value); bool showOnHomePage = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShowOnHomePage")].Value); string metaKeywords = worksheet.Cells[iRow, GetColumnIndex(properties, "MetaKeywords")].Value as string; string metaDescription = worksheet.Cells[iRow, GetColumnIndex(properties, "MetaDescription")].Value as string; string metaTitle = worksheet.Cells[iRow, GetColumnIndex(properties, "MetaTitle")].Value as string; string seName = worksheet.Cells[iRow, GetColumnIndex(properties, "SeName")].Value as string; bool allowCustomerReviews = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowCustomerReviews")].Value); bool published = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "Published")].Value); string productVariantName = worksheet.Cells[iRow, GetColumnIndex(properties, "ProductVariantName")].Value as string; string sku = worksheet.Cells[iRow, GetColumnIndex(properties, "SKU")].Value as string; string manufacturerPartNumber = worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerPartNumber")].Value as string; string gtin = worksheet.Cells[iRow, GetColumnIndex(properties, "Gtin")].Value as string; bool isGiftCard = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsGiftCard")].Value); int giftCardTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "GiftCardTypeId")].Value); bool requireOtherProducts = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "RequireOtherProducts")].Value); string requiredProductVariantIds = worksheet.Cells[iRow, GetColumnIndex(properties, "RequiredProductVariantIds")].Value as string; bool automaticallyAddRequiredProductVariants = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AutomaticallyAddRequiredProductVariants")].Value); bool isDownload = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsDownload")].Value); int downloadId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadId")].Value); bool unlimitedDownloads = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UnlimitedDownloads")].Value); int maxNumberOfDownloads = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MaxNumberOfDownloads")].Value); int downloadActivationTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadActivationTypeId")].Value); bool hasSampleDownload = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasSampleDownload")].Value); int sampleDownloadId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "SampleDownloadId")].Value); bool hasUserAgreement = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasUserAgreement")].Value); string userAgreementText = worksheet.Cells[iRow, GetColumnIndex(properties, "UserAgreementText")].Value as string; bool isRecurring = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRecurring")].Value); int recurringCycleLength = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCycleLength")].Value); int recurringCyclePeriodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCyclePeriodId")].Value); int recurringTotalCycles = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringTotalCycles")].Value); bool isShipEnabled = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsShipEnabled")].Value); bool isFreeShipping = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsFreeShipping")].Value); decimal additionalShippingCharge = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "AdditionalShippingCharge")].Value); bool isTaxExempt = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTaxExempt")].Value); int taxCategoryId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "TaxCategoryId")].Value); int manageInventoryMethodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ManageInventoryMethodId")].Value); int stockQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "StockQuantity")].Value); bool displayStockAvailability = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockAvailability")].Value); bool displayStockQuantity = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockQuantity")].Value); int minStockQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MinStockQuantity")].Value); int lowStockActivityId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "LowStockActivityId")].Value); int notifyAdminForQuantityBelow = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "NotifyAdminForQuantityBelow")].Value); int backorderModeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BackorderModeId")].Value); bool allowBackInStockSubscriptions = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowBackInStockSubscriptions")].Value); int orderMinimumQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMinimumQuantity")].Value); int orderMaximumQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMaximumQuantity")].Value); string allowedQuantities = worksheet.Cells[iRow, GetColumnIndex(properties, "AllowedQuantities")].Value as string; bool disableBuyButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableBuyButton")].Value); bool disableWishlistButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableWishlistButton")].Value); bool callForPrice = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CallForPrice")].Value); decimal price = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Price")].Value); decimal oldPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "OldPrice")].Value); decimal productCost = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductCost")].Value); decimal? specialPrice = null; var specialPriceExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPrice")].Value; if (specialPriceExcel != null) specialPrice = Convert.ToDecimal(specialPriceExcel); DateTime? specialPriceStartDateTimeUtc = null; var specialPriceStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceStartDateTimeUtc")].Value; if (specialPriceStartDateTimeUtcExcel != null) specialPriceStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceStartDateTimeUtcExcel)); DateTime? specialPriceEndDateTimeUtc = null; var specialPriceEndDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceEndDateTimeUtc")].Value; if (specialPriceEndDateTimeUtcExcel != null) specialPriceEndDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceEndDateTimeUtcExcel)); bool customerEntersPrice = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CustomerEntersPrice")].Value); decimal minimumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MinimumCustomerEnteredPrice")].Value); decimal maximumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MaximumCustomerEnteredPrice")].Value); decimal weight = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Weight")].Value); decimal length = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Length")].Value); decimal width = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Width")].Value); decimal height = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Height")].Value); DateTime createdOnUtc = DateTime.FromOADate(Convert.ToDouble(worksheet.Cells[iRow, GetColumnIndex(properties, "CreatedOnUtc")].Value)); string categoryIds = worksheet.Cells[iRow, GetColumnIndex(properties, "CategoryIds")].Value as string; string manufacturerIds = worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerIds")].Value as string; string picture1 = worksheet.Cells[iRow, GetColumnIndex(properties, "Picture1")].Value as string; string picture2 = worksheet.Cells[iRow, GetColumnIndex(properties, "Picture2")].Value as string; string picture3 = worksheet.Cells[iRow, GetColumnIndex(properties, "Picture3")].Value as string; var productVariant = _productService.GetProductVariantBySku(sku); if (productVariant != null) { //product var product = productVariant.Product; product.Name = name; product.ShortDescription = shortDescription; product.FullDescription = fullDescription; product.VendorId = vendorId; product.ProductTemplateId = productTemplateId; product.ShowOnHomePage = showOnHomePage; product.MetaKeywords = metaKeywords; product.MetaDescription = metaDescription; product.MetaTitle = metaTitle; product.AllowCustomerReviews = allowCustomerReviews; product.Published = published; product.CreatedOnUtc = createdOnUtc; product.UpdatedOnUtc = DateTime.UtcNow; _productService.UpdateProduct(product); //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); //variant productVariant.Name = productVariantName; productVariant.Sku = sku; productVariant.ManufacturerPartNumber = manufacturerPartNumber; productVariant.Gtin = gtin; productVariant.IsGiftCard = isGiftCard; productVariant.GiftCardTypeId = giftCardTypeId; productVariant.RequireOtherProducts = requireOtherProducts; productVariant.RequiredProductVariantIds = requiredProductVariantIds; productVariant.AutomaticallyAddRequiredProductVariants = automaticallyAddRequiredProductVariants; productVariant.IsDownload = isDownload; productVariant.DownloadId = downloadId; productVariant.UnlimitedDownloads = unlimitedDownloads; productVariant.MaxNumberOfDownloads = maxNumberOfDownloads; productVariant.DownloadActivationTypeId = downloadActivationTypeId; productVariant.HasSampleDownload = hasSampleDownload; productVariant.SampleDownloadId = sampleDownloadId; productVariant.HasUserAgreement = hasUserAgreement; productVariant.UserAgreementText = userAgreementText; productVariant.IsRecurring = isRecurring; productVariant.RecurringCycleLength = recurringCycleLength; productVariant.RecurringCyclePeriodId = recurringCyclePeriodId; productVariant.RecurringTotalCycles = recurringTotalCycles; productVariant.IsShipEnabled = isShipEnabled; productVariant.IsFreeShipping = isFreeShipping; productVariant.AdditionalShippingCharge = additionalShippingCharge; productVariant.IsTaxExempt = isTaxExempt; productVariant.TaxCategoryId = taxCategoryId; productVariant.ManageInventoryMethodId = manageInventoryMethodId; productVariant.StockQuantity = stockQuantity; productVariant.DisplayStockAvailability = displayStockAvailability; productVariant.DisplayStockQuantity = displayStockQuantity; productVariant.MinStockQuantity = minStockQuantity; productVariant.LowStockActivityId = lowStockActivityId; productVariant.NotifyAdminForQuantityBelow = notifyAdminForQuantityBelow; productVariant.BackorderModeId = backorderModeId; productVariant.AllowBackInStockSubscriptions = allowBackInStockSubscriptions; productVariant.OrderMinimumQuantity = orderMinimumQuantity; productVariant.OrderMaximumQuantity = orderMaximumQuantity; productVariant.AllowedQuantities = allowedQuantities; productVariant.DisableBuyButton = disableBuyButton; productVariant.DisableWishlistButton = disableWishlistButton; productVariant.CallForPrice = callForPrice; productVariant.Price = price; productVariant.OldPrice = oldPrice; productVariant.ProductCost = productCost; productVariant.SpecialPrice = specialPrice; productVariant.SpecialPriceStartDateTimeUtc = specialPriceStartDateTimeUtc; productVariant.SpecialPriceEndDateTimeUtc = specialPriceEndDateTimeUtc; productVariant.CustomerEntersPrice = customerEntersPrice; productVariant.MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice; productVariant.MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice; productVariant.Weight = weight; productVariant.Length = length; productVariant.Width = width; productVariant.Height = height; productVariant.Published = published; productVariant.CreatedOnUtc = createdOnUtc; productVariant.UpdatedOnUtc = DateTime.UtcNow; _productService.UpdateProductVariant(productVariant); } else { //product var product = new Product() { Name = name, ShortDescription = shortDescription, FullDescription = fullDescription, ShowOnHomePage = showOnHomePage, MetaKeywords = metaKeywords, MetaDescription = metaDescription, MetaTitle = metaTitle, AllowCustomerReviews = allowCustomerReviews, Published = published, CreatedOnUtc = createdOnUtc, UpdatedOnUtc = DateTime.UtcNow }; _productService.InsertProduct(product); //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); //variant productVariant = new ProductVariant() { ProductId = product.Id, Name = productVariantName, Sku = sku, ManufacturerPartNumber = manufacturerPartNumber, Gtin = gtin, IsGiftCard = isGiftCard, GiftCardTypeId = giftCardTypeId, RequireOtherProducts = requireOtherProducts, RequiredProductVariantIds = requiredProductVariantIds, AutomaticallyAddRequiredProductVariants = automaticallyAddRequiredProductVariants, IsDownload = isDownload, DownloadId = downloadId, UnlimitedDownloads = unlimitedDownloads, MaxNumberOfDownloads = maxNumberOfDownloads, DownloadActivationTypeId = downloadActivationTypeId, HasSampleDownload = hasSampleDownload, SampleDownloadId = sampleDownloadId, HasUserAgreement = hasUserAgreement, UserAgreementText = userAgreementText, IsRecurring = isRecurring, RecurringCycleLength = recurringCycleLength, RecurringCyclePeriodId = recurringCyclePeriodId, RecurringTotalCycles = recurringTotalCycles, IsShipEnabled = isShipEnabled, IsFreeShipping = isFreeShipping, AdditionalShippingCharge = additionalShippingCharge, IsTaxExempt = isTaxExempt, TaxCategoryId = taxCategoryId, ManageInventoryMethodId = manageInventoryMethodId, StockQuantity = stockQuantity, DisplayStockAvailability = displayStockAvailability, DisplayStockQuantity = displayStockQuantity, MinStockQuantity = minStockQuantity, LowStockActivityId = lowStockActivityId, NotifyAdminForQuantityBelow = notifyAdminForQuantityBelow, BackorderModeId = backorderModeId, AllowBackInStockSubscriptions = allowBackInStockSubscriptions, OrderMinimumQuantity = orderMinimumQuantity, OrderMaximumQuantity = orderMaximumQuantity, AllowedQuantities = allowedQuantities, DisableBuyButton = disableBuyButton, CallForPrice = callForPrice, Price = price, OldPrice = oldPrice, ProductCost = productCost, SpecialPrice = specialPrice, SpecialPriceStartDateTimeUtc = specialPriceStartDateTimeUtc, SpecialPriceEndDateTimeUtc = specialPriceEndDateTimeUtc, CustomerEntersPrice = customerEntersPrice, MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice, MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice, Weight = weight, Length = length, Width = width, Height = height, Published = published, CreatedOnUtc = createdOnUtc, UpdatedOnUtc = DateTime.UtcNow }; _productService.InsertProductVariant(productVariant); } //category mappings if (!String.IsNullOrEmpty(categoryIds)) { foreach (var id in categoryIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (productVariant.Product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null) { //ensure that category exists var category = _categoryService.GetCategoryById(id); if (category != null) { var productCategory = new ProductCategory() { ProductId = productVariant.Product.Id, CategoryId = category.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _categoryService.InsertProductCategory(productCategory); } } } } //manufacturer mappings if (!String.IsNullOrEmpty(manufacturerIds)) { foreach (var id in manufacturerIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (productVariant.Product.ProductManufacturers.FirstOrDefault(x => x.ManufacturerId == id) == null) { //ensure that manufacturer exists var manufacturer = _manufacturerService.GetManufacturerById(id); if (manufacturer != null) { var productManufacturer = new ProductManufacturer() { ProductId = productVariant.Product.Id, ManufacturerId = manufacturer.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _manufacturerService.InsertProductManufacturer(productManufacturer); } } } } //pictures foreach (var picture in new string[] { picture1, picture2, picture3 }) { if (String.IsNullOrEmpty(picture)) continue; productVariant.Product.ProductPictures.Add(new ProductPicture() { Picture = _pictureService.InsertPicture(File.ReadAllBytes(picture), "image/jpeg", _pictureService.GetPictureSeName(name), true), DisplayOrder = 1, }); _productService.UpdateProduct(productVariant.Product); } //update "HasTierPrices" and "HasDiscountsApplied" properties _productService.UpdateHasTierPricesProperty(productVariant); _productService.UpdateHasDiscountsApplied(productVariant); //next product iRow++; } } }
/// <summary> /// Create a copy of product with all depended data /// </summary> /// <param name="product">The product to copy</param> /// <param name="newName">The name of product duplicate</param> /// <param name="isPublished">A value indicating whether the product duplicate should be published</param> /// <param name="copyImages">A value indicating whether the product images should be copied</param> /// <returns>Product copy</returns> public virtual Product CopyProduct(Product product, string newName, bool isPublished, bool copyImages) { if (product == null) throw new ArgumentNullException("product"); if (String.IsNullOrEmpty(newName)) throw new ArgumentException("Product name is required"); Product productCopy = null; //uncomment this line to support transactions //using (var scope = new System.Transactions.TransactionScope()) { // product productCopy = new Product() { Name = newName, ShortDescription = product.ShortDescription, FullDescription = product.FullDescription, VendorId = product.VendorId, ProductTemplateId = product.ProductTemplateId, AdminComment = product.AdminComment, ShowOnHomePage = product.ShowOnHomePage, MetaKeywords = product.MetaKeywords, MetaDescription = product.MetaDescription, MetaTitle = product.MetaTitle, AllowCustomerReviews = product.AllowCustomerReviews, LimitedToStores = product.LimitedToStores, Published = isPublished, Deleted = product.Deleted, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow }; //validate search engine name _productService.InsertProduct(productCopy); //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0); var languages = _languageService.GetAllLanguages(true); //localization foreach (var lang in languages) { var name = product.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id); var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(shortDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id); var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(fullDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id); var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false); if (!String.IsNullOrEmpty(metaKeywords)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id); var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(metaDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id); var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false); if (!String.IsNullOrEmpty(metaTitle)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id); //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id); } //product tags foreach (var productTag in product.ProductTags) { productCopy.ProductTags.Add(productTag); } _productService.UpdateProduct(product); // product pictures if (copyImages) { foreach (var productPicture in product.ProductPictures) { var picture = productPicture.Picture; var pictureCopy = _pictureService.InsertPicture( _pictureService.LoadPictureBinary(picture), picture.MimeType, _pictureService.GetPictureSeName(newName), true); _productService.InsertProductPicture(new ProductPicture() { ProductId = productCopy.Id, PictureId = pictureCopy.Id, DisplayOrder = productPicture.DisplayOrder }); } } // product <-> categories mappings foreach (var productCategory in product.ProductCategories) { var productCategoryCopy = new ProductCategory() { ProductId = productCopy.Id, CategoryId = productCategory.CategoryId, IsFeaturedProduct = productCategory.IsFeaturedProduct, DisplayOrder = productCategory.DisplayOrder }; _categoryService.InsertProductCategory(productCategoryCopy); } // product <-> manufacturers mappings foreach (var productManufacturers in product.ProductManufacturers) { var productManufacturerCopy = new ProductManufacturer() { ProductId = productCopy.Id, ManufacturerId = productManufacturers.ManufacturerId, IsFeaturedProduct = productManufacturers.IsFeaturedProduct, DisplayOrder = productManufacturers.DisplayOrder }; _manufacturerService.InsertProductManufacturer(productManufacturerCopy); } // product <-> releated products mappings foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true)) { _productService.InsertRelatedProduct( new RelatedProduct() { ProductId1 = productCopy.Id, ProductId2 = relatedProduct.ProductId2, DisplayOrder = relatedProduct.DisplayOrder }); } // product <-> cross sells mappings foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true)) { _productService.InsertCrossSellProduct( new CrossSellProduct() { ProductId1 = productCopy.Id, ProductId2 = csProduct.ProductId2, }); } // product specifications foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes) { var psaCopy = new ProductSpecificationAttribute() { ProductId = productCopy.Id, SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId, AllowFiltering = productSpecificationAttribute.AllowFiltering, ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage, DisplayOrder = productSpecificationAttribute.DisplayOrder }; _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy); } //store mapping var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product); foreach (var id in selectedStoreIds) { _storeMappingService.InsertStoreMapping(productCopy, id); } // product variants var productVariants = product.ProductVariants; foreach (var productVariant in productVariants) { CopyProductVariant(productVariant, productCopy.Id, productVariant.Name, productVariant.Published, copyImages); } //uncomment this line to support transactions //scope.Complete(); } return productCopy; }