public ActionResult AsyncUpload(bool minimalMode = false, string fieldName = null) { var postedFile = Request.ToPostedFileResult(); if (postedFile == null) { throw new ArgumentException("No file uploaded"); } var download = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = "", DownloadBinary = postedFile.Buffer, ContentType = postedFile.ContentType, // we store filename without extension for downloads Filename = postedFile.FileTitle, Extension = postedFile.FileExtension, IsNew = true, IsTransient = true }; _downloadService.InsertDownload(download); return Json(new { success = true, downloadId = download.Id, html = this.RenderPartialViewToString(TEMPLATE, download.Id, new { minimalMode = minimalMode, fieldName = fieldName }) }); }
public void Can_save_and_load_download() { var guid = Guid.NewGuid(); var download = new Download { DownloadGuid = guid, UseDownloadUrl = true, DownloadUrl = "http://www.someUrl.com/file.zip", DownloadBinary = new byte[] { 1, 2, 3 }, ContentType = "application/x-zip-co", Filename = "file", Extension = ".zip", IsNew = true }; var fromDb = SaveAndLoadEntity(download); fromDb.ShouldNotBeNull(); fromDb.DownloadGuid.ShouldEqual(guid); fromDb.UseDownloadUrl.ShouldEqual(true); fromDb.DownloadUrl.ShouldEqual("http://www.someUrl.com/file.zip"); fromDb.DownloadBinary.ShouldEqual(new byte[] { 1, 2, 3 }); fromDb.ContentType.ShouldEqual("application/x-zip-co"); fromDb.Filename.ShouldEqual("file"); fromDb.Extension.ShouldEqual(".zip"); fromDb.IsNew.ShouldEqual(true); }
/// <summary> /// Deletes a download /// </summary> /// <param name="download">Download</param> public virtual void DeleteDownload(Download download) { if (download == null) throw new ArgumentNullException("download"); _downloadRepository.Delete(download); _eventPubisher.EntityDeleted(download); }
public ActionResult SaveDownloadUrl(string downloadUrl) { //insert var download = new Download() { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = true, DownloadUrl = downloadUrl, IsNew = true }; _downloadService.InsertDownload(download); return Json(new { downloadId = download.Id }, JsonRequestBehavior.AllowGet); }
/// <summary>Takes selected elements from collection and creates a attribute XML string from it.</summary> /// <param name="formatWithProductId">how the name of the controls are formatted. frontend includes productId, backend does not.</param> public static string CreateSelectedAttributesXml(this NameValueCollection collection, int productId, IList<ProductVariantAttribute> variantAttributes, IProductAttributeParser productAttributeParser, ILocalizationService localizationService, IDownloadService downloadService, CatalogSettings catalogSettings, HttpRequestBase request, List<string> warnings, bool formatWithProductId = true, int bundleItemId = 0) { if (collection == null) return ""; string controlId; string selectedAttributes = ""; foreach (var attribute in variantAttributes) { controlId = AttributeFormatedName(attribute.ProductAttributeId, attribute.Id, formatWithProductId ? productId : 0, bundleItemId); switch (attribute.AttributeControlType) { case AttributeControlType.DropdownList: case AttributeControlType.RadioList: case AttributeControlType.ColorSquares: { var ctrlAttributes = collection[controlId]; if (ctrlAttributes.HasValue()) { int selectedAttributeId = int.Parse(ctrlAttributes); if (selectedAttributeId > 0) selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedAttributeId.ToString()); } } break; case AttributeControlType.Checkboxes: { var cblAttributes = collection[controlId]; if (cblAttributes.HasValue()) { foreach (var item in cblAttributes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { int selectedAttributeId = int.Parse(item); if (selectedAttributeId > 0) selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedAttributeId.ToString()); } } } break; case AttributeControlType.TextBox: case AttributeControlType.MultilineTextbox: { var txtAttribute = collection[controlId]; if (txtAttribute.HasValue()) { string enteredText = txtAttribute.Trim(); selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, enteredText); } } break; case AttributeControlType.Datepicker: { var date = collection[controlId + "_day"]; var month = collection[controlId + "_month"]; var year = collection[controlId + "_year"]; DateTime? selectedDate = null; try { selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(date)); } catch { } if (selectedDate.HasValue) { selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedDate.Value.ToString("D")); } } break; case AttributeControlType.FileUpload: if (request == null) { Guid downloadGuid; Guid.TryParse(collection[controlId], out downloadGuid); var download = downloadService.GetDownloadByGuid(downloadGuid); if (download != null) { selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, download.DownloadGuid.ToString()); } } else { var httpPostedFile = request.Files[controlId]; if (httpPostedFile != null && httpPostedFile.FileName.HasValue()) { int fileMaxSize = catalogSettings.FileUploadMaximumSizeBytes; if (httpPostedFile.ContentLength > fileMaxSize) { warnings.Add(string.Format(localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), (int)(fileMaxSize / 1024))); } else { //save an uploaded file var download = new Download() { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = "", DownloadBinary = httpPostedFile.GetDownloadBits(), ContentType = httpPostedFile.ContentType, Filename = System.IO.Path.GetFileNameWithoutExtension(httpPostedFile.FileName), Extension = System.IO.Path.GetExtension(httpPostedFile.FileName), IsNew = true }; downloadService.InsertDownload(download); //save attribute selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, download.DownloadGuid.ToString()); } } } break; default: break; } } return selectedAttributes; }
protected void ParseAndSaveCheckoutAttributes(List<OrganizedShoppingCartItem> cart, FormCollection form) { string selectedAttributes = ""; var checkoutAttributes = _checkoutAttributeService.GetAllCheckoutAttributes(); if (!cart.RequiresShipping()) { //remove attributes which require shippable products checkoutAttributes = checkoutAttributes.RemoveShippableAttributes(); } foreach (var attribute in checkoutAttributes) { string controlId = string.Format("checkout_attribute_{0}", attribute.Id); switch (attribute.AttributeControlType) { case AttributeControlType.DropdownList: case AttributeControlType.RadioList: case AttributeControlType.ColorSquares: { var rblAttributes = form[controlId]; if (!String.IsNullOrEmpty(rblAttributes)) { int selectedAttributeId = int.Parse(rblAttributes); if (selectedAttributeId > 0) selectedAttributes = _checkoutAttributeParser.AddCheckoutAttribute(selectedAttributes, attribute, selectedAttributeId.ToString()); } } break; case AttributeControlType.Checkboxes: { var cblAttributes = form[controlId]; if (!String.IsNullOrEmpty(cblAttributes)) { foreach (var item in cblAttributes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { int selectedAttributeId = int.Parse(item); if (selectedAttributeId > 0) selectedAttributes = _checkoutAttributeParser.AddCheckoutAttribute(selectedAttributes, attribute, selectedAttributeId.ToString()); } } } break; case AttributeControlType.TextBox: case AttributeControlType.MultilineTextbox: { var txtAttribute = form[controlId]; if (!String.IsNullOrEmpty(txtAttribute)) { string enteredText = txtAttribute.Trim(); selectedAttributes = _checkoutAttributeParser.AddCheckoutAttribute(selectedAttributes, attribute, enteredText); } } break; case AttributeControlType.Datepicker: { var date = form[controlId + "_day"]; var month = form[controlId + "_month"]; var year = form[controlId + "_year"]; DateTime? selectedDate = null; try { selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(date)); } catch { } if (selectedDate.HasValue) { selectedAttributes = _checkoutAttributeParser.AddCheckoutAttribute(selectedAttributes, attribute, selectedDate.Value.ToString("D")); } } break; case AttributeControlType.FileUpload: { var postedFile = this.Request.Files[controlId].ToPostedFileResult(); if (postedFile != null && postedFile.FileName.HasValue()) { int fileMaxSize = _catalogSettings.FileUploadMaximumSizeBytes; if (postedFile.Size > fileMaxSize) { //TODO display warning //warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), (int)(fileMaxSize / 1024))); } else { //save an uploaded file var download = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = "", DownloadBinary = postedFile.Buffer, ContentType = postedFile.ContentType, Filename = postedFile.FileTitle, Extension = postedFile.FileExtension, IsNew = true }; _downloadService.InsertDownload(download); //save attribute selectedAttributes = _checkoutAttributeParser.AddCheckoutAttribute(selectedAttributes, attribute, download.DownloadGuid.ToString()); } } } break; default: break; } } //save checkout attributes _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.CheckoutAttributes, selectedAttributes); }
public ActionResult UploadFileProductAttribute(int productId, int productAttributeId) { var product = _productService.GetProductById(productId); if (product == null || !product.Published || product.Deleted) { return Json(new { success = false, downloadGuid = Guid.Empty, }); } // ensure that this attribute belong to this product and has "file upload" type var pva = _productAttributeService .GetProductVariantAttributesByProductId(productId) .Where(pa => pa.ProductAttributeId == productAttributeId) .FirstOrDefault(); if (pva == null || pva.AttributeControlType != AttributeControlType.FileUpload) { return Json(new { success = false, downloadGuid = Guid.Empty, }); } var postedFile = Request.ToPostedFileResult(); if (postedFile == null) { throw new ArgumentException("No file uploaded"); } int fileMaxSize = _catalogSettings.FileUploadMaximumSizeBytes; if (postedFile.Size > fileMaxSize) { return Json(new { success = false, message = string.Format(_localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), (int)(fileMaxSize / 1024)), downloadGuid = Guid.Empty, }); } var download = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = "", DownloadBinary = postedFile.Buffer, ContentType = postedFile.ContentType, // we store filename without extension for downloads Filename = postedFile.FileTitle, Extension = postedFile.FileExtension, IsNew = true, IsTransient = true }; _downloadService.InsertDownload(download); return Json(new { success = true, message = _localizationService.GetResource("ShoppingCart.FileUploaded"), downloadGuid = download.DownloadGuid, }); }
public void Can_cascade_delete_attachment() { var account = new EmailAccount { Email = "*****@*****.**", Host = "127.0.0.1", Username = "******", Password = "******" }; var download = new Download { ContentType = "text/plain", DownloadBinary = new byte[10], DownloadGuid = Guid.NewGuid(), Extension = "txt", Filename = "file" }; // add attachment var attach = new QueuedEmailAttachment { StorageLocation = EmailAttachmentStorageLocation.FileReference, Name = "file.txt", MimeType = "text/plain", File = download }; var qe = new QueuedEmail { Priority = 1, From = "From", To = "To", Subject = "Subject", CreatedOnUtc = DateTime.UtcNow, EmailAccount = account }; qe.Attachments.Add(attach); var fromDb = SaveAndLoadEntity(qe); fromDb.ShouldNotBeNull(); Assert.AreEqual(fromDb.Attachments.Count, 1); attach = fromDb.Attachments.FirstOrDefault(); attach.ShouldNotBeNull(); download = attach.File; download.ShouldNotBeNull(); var attachId = attach.Id; var downloadId = download.Id; // delete Attachment.Download context.Set<Download>().Remove(download); context.SaveChanges(); base.ReloadContext(); attach = context.Set<QueuedEmailAttachment>().Find(attachId); attach.ShouldBeNull(); // add new attachment attach = new QueuedEmailAttachment { StorageLocation = EmailAttachmentStorageLocation.FileReference, Name = "file.txt", MimeType = "text/plain" }; qe = context.Set<QueuedEmail>().FirstOrDefault(); qe.Attachments.Add(attach); fromDb = SaveAndLoadEntity(qe); fromDb.ShouldNotBeNull(); // delete QueuedEmail context.Set<QueuedEmail>().Remove(fromDb); context.SaveChanges(); base.ReloadContext(); // Attachment should also be gone now attach = context.Set<QueuedEmailAttachment>().FirstOrDefault(); attach.ShouldBeNull(); }
/// <summary> /// Inserts a download /// </summary> /// <param name="download">Download</param> public virtual void InsertDownload(Download download) { if (download == null) throw new ArgumentNullException("download"); _downloadRepository.Insert(download); _eventPubisher.EntityInserted(download); }
public ActionResult UploadFileProductAttribute(int productId, int productAttributeId) { var product = _productService.GetProductById(productId); if (product == null || !product.Published || product.Deleted) { return Json(new { success = false, downloadGuid = Guid.Empty, }, "text/plain"); } //ensure that this attribute belong to this product and has "file upload" type var pva = _productAttributeService .GetProductVariantAttributesByProductId(productId) .Where(pa => pa.ProductAttributeId == productAttributeId) .FirstOrDefault(); if (pva == null || pva.AttributeControlType != AttributeControlType.FileUpload) { return Json(new { success = false, downloadGuid = Guid.Empty, }, "text/plain"); } //we process it distinct ways based on a browser //find more info here http://stackoverflow.com/questions/4884920/mvc3-valums-ajax-file-upload Stream stream = null; var fileName = ""; var contentType = ""; if (String.IsNullOrEmpty(Request["qqfile"])) { // IE HttpPostedFileBase httpPostedFile = Request.Files[0]; if (httpPostedFile == null) throw new ArgumentException("No file uploaded"); stream = httpPostedFile.InputStream; fileName = Path.GetFileName(httpPostedFile.FileName); contentType = httpPostedFile.ContentType; } else { //Webkit, Mozilla stream = Request.InputStream; fileName = Request["qqfile"]; } var fileBinary = new byte[stream.Length]; stream.Read(fileBinary, 0, fileBinary.Length); var fileExtension = Path.GetExtension(fileName); if (!String.IsNullOrEmpty(fileExtension)) fileExtension = fileExtension.ToLowerInvariant(); int fileMaxSize = _catalogSettings.FileUploadMaximumSizeBytes; if (fileBinary.Length > fileMaxSize) { //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return Json(new { success = false, message = string.Format(_localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), (int)(fileMaxSize / 1024)), downloadGuid = Guid.Empty, }, "text/plain"); } var download = new Download() { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = "", DownloadBinary = fileBinary, ContentType = contentType, //we store filename without extension for downloads Filename = Path.GetFileNameWithoutExtension(fileName), Extension = fileExtension, IsNew = true }; _downloadService.InsertDownload(download); //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return Json(new { success = true, message = _localizationService.GetResource("ShoppingCart.FileUploaded"), downloadGuid = download.DownloadGuid, }, "text/plain"); }
public ActionResult AsyncUpload() { //we process it distinct ways based on a browser //find more info here http://stackoverflow.com/questions/4884920/mvc3-valums-ajax-file-upload Stream stream = null; var fileName = ""; var contentType = ""; if (String.IsNullOrEmpty(Request["qqfile"])) { // IE HttpPostedFileBase httpPostedFile = Request.Files[0]; if (httpPostedFile == null) throw new ArgumentException("No file uploaded"); stream = httpPostedFile.InputStream; fileName = Path.GetFileName(httpPostedFile.FileName); contentType = httpPostedFile.ContentType; } else { //Webkit, Mozilla stream = Request.InputStream; fileName = Request["qqfile"]; } var fileBinary = new byte[stream.Length]; stream.Read(fileBinary, 0, fileBinary.Length); var fileExtension = Path.GetExtension(fileName); if (!String.IsNullOrEmpty(fileExtension)) fileExtension = fileExtension.ToLowerInvariant(); var download = new Download() { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = false, DownloadUrl = "", DownloadBinary = fileBinary, ContentType = contentType, //we store filename without extension for downloads Filename = Path.GetFileNameWithoutExtension(fileName), Extension = fileExtension, IsNew = true }; _downloadService.InsertDownload(download); //when returning JSON the mime-type must be set to text/plain //otherwise some browsers will pop-up a "Save As" dialog. return Json(new { success = true, downloadId = download.Id, fileName = download.Filename + download.Extension, downloadUrl = Url.Action("DownloadFile", new { downloadId = download.Id }) }, "text/plain"); }
/// <summary> /// Create a copy of product with all depended data /// </summary> /// <param name="product">The product</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> /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param> /// <returns>Product entity</returns> public virtual Product CopyProduct(Product product, string newName, bool isPublished, bool copyImages, bool copyAssociatedProducts = true) { if (product == null) throw new ArgumentNullException("product"); if (String.IsNullOrEmpty(newName)) throw new ArgumentException("Product name is required"); Product productCopy = null; var utcNow = DateTime.UtcNow; // product download & sample download int downloadId = 0; int? sampleDownloadId = null; if (product.IsDownload) { var download = _downloadService.GetDownloadById(product.DownloadId); if (download != null) { var downloadCopy = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = download.UseDownloadUrl, DownloadUrl = download.DownloadUrl, DownloadBinary = download.DownloadBinary, ContentType = download.ContentType, Filename = download.Filename, Extension = download.Extension, IsNew = download.IsNew, }; _downloadService.InsertDownload(downloadCopy); downloadId = downloadCopy.Id; } if (product.HasSampleDownload) { var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault()); if (sampleDownload != null) { var sampleDownloadCopy = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = sampleDownload.UseDownloadUrl, DownloadUrl = sampleDownload.DownloadUrl, DownloadBinary = sampleDownload.DownloadBinary, ContentType = sampleDownload.ContentType, Filename = sampleDownload.Filename, Extension = sampleDownload.Extension, IsNew = sampleDownload.IsNew }; _downloadService.InsertDownload(sampleDownloadCopy); sampleDownloadId = sampleDownloadCopy.Id; } } } // product productCopy = new Product { ProductTypeId = product.ProductTypeId, ParentGroupedProductId = product.ParentGroupedProductId, VisibleIndividually = product.VisibleIndividually, Name = newName, ShortDescription = product.ShortDescription, FullDescription = product.FullDescription, ProductTemplateId = product.ProductTemplateId, AdminComment = product.AdminComment, ShowOnHomePage = product.ShowOnHomePage, HomePageDisplayOrder = product.HomePageDisplayOrder, MetaKeywords = product.MetaKeywords, MetaDescription = product.MetaDescription, MetaTitle = product.MetaTitle, AllowCustomerReviews = product.AllowCustomerReviews, LimitedToStores = product.LimitedToStores, Sku = product.Sku, ManufacturerPartNumber = product.ManufacturerPartNumber, Gtin = product.Gtin, IsGiftCard = product.IsGiftCard, GiftCardType = product.GiftCardType, RequireOtherProducts = product.RequireOtherProducts, RequiredProductIds = product.RequiredProductIds, AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts, IsDownload = product.IsDownload, DownloadId = downloadId, UnlimitedDownloads = product.UnlimitedDownloads, MaxNumberOfDownloads = product.MaxNumberOfDownloads, DownloadExpirationDays = product.DownloadExpirationDays, DownloadActivationType = product.DownloadActivationType, HasSampleDownload = product.HasSampleDownload, SampleDownloadId = sampleDownloadId, HasUserAgreement = product.HasUserAgreement, UserAgreementText = product.UserAgreementText, IsRecurring = product.IsRecurring, RecurringCycleLength = product.RecurringCycleLength, RecurringCyclePeriod = product.RecurringCyclePeriod, RecurringTotalCycles = product.RecurringTotalCycles, IsShipEnabled = product.IsShipEnabled, IsFreeShipping = product.IsFreeShipping, AdditionalShippingCharge = product.AdditionalShippingCharge, IsEsd = product.IsEsd, IsTaxExempt = product.IsTaxExempt, TaxCategoryId = product.TaxCategoryId, ManageInventoryMethod = product.ManageInventoryMethod, StockQuantity = product.StockQuantity, DisplayStockAvailability = product.DisplayStockAvailability, DisplayStockQuantity = product.DisplayStockQuantity, MinStockQuantity = product.MinStockQuantity, LowStockActivityId = product.LowStockActivityId, NotifyAdminForQuantityBelow = product.NotifyAdminForQuantityBelow, BackorderMode = product.BackorderMode, AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions, OrderMinimumQuantity = product.OrderMinimumQuantity, OrderMaximumQuantity = product.OrderMaximumQuantity, AllowedQuantities = product.AllowedQuantities, DisableBuyButton = product.DisableBuyButton, DisableWishlistButton = product.DisableWishlistButton, AvailableForPreOrder = product.AvailableForPreOrder, CallForPrice = product.CallForPrice, Price = product.Price, OldPrice = product.OldPrice, ProductCost = product.ProductCost, SpecialPrice = product.SpecialPrice, SpecialPriceStartDateTimeUtc = product.SpecialPriceStartDateTimeUtc, SpecialPriceEndDateTimeUtc = product.SpecialPriceEndDateTimeUtc, CustomerEntersPrice = product.CustomerEntersPrice, MinimumCustomerEnteredPrice = product.MinimumCustomerEnteredPrice, MaximumCustomerEnteredPrice = product.MaximumCustomerEnteredPrice, LowestAttributeCombinationPrice = product.LowestAttributeCombinationPrice, Weight = product.Weight, Length = product.Length, Width = product.Width, Height = product.Height, AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc, AvailableEndDateTimeUtc = product.AvailableEndDateTimeUtc, DisplayOrder = product.DisplayOrder, Published = isPublished, Deleted = product.Deleted, CreatedOnUtc = utcNow, UpdatedOnUtc = utcNow, DeliveryTimeId = product.DeliveryTimeId, QuantityUnitId = product.QuantityUnitId, BasePriceEnabled = product.BasePriceEnabled, BasePriceMeasureUnit = product.BasePriceMeasureUnit, BasePriceAmount = product.BasePriceAmount, BasePriceBaseAmount = product.BasePriceBaseAmount, BundleTitleText = product.BundleTitleText, BundlePerItemShipping = product.BundlePerItemShipping, BundlePerItemPricing = product.BundlePerItemPricing, BundlePerItemShoppingCart = product.BundlePerItemShoppingCart }; _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); var bundleTitleText = product.GetLocalized(x => x.BundleTitleText, lang.Id, false, false); if (!String.IsNullOrEmpty(bundleTitleText)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.BundleTitleText, bundleTitleText, lang.Id); //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id); } // 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, false, false); _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 <-> attributes mappings var associatedAttributes = new Dictionary<int, int>(); var associatedAttributeValues = new Dictionary<int, int>(); foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductId(product.Id)) { var productVariantAttributeCopy = new ProductVariantAttribute { ProductId = productCopy.Id, ProductAttributeId = productVariantAttribute.ProductAttributeId, TextPrompt = productVariantAttribute.TextPrompt, IsRequired = productVariantAttribute.IsRequired, AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId, DisplayOrder = productVariantAttribute.DisplayOrder }; _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy); //save associated value (used for combinations copying) associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id); // product variant attribute values var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id); foreach (var productVariantAttributeValue in productVariantAttributeValues) { var pvavCopy = new ProductVariantAttributeValue { ProductVariantAttributeId = productVariantAttributeCopy.Id, Name = productVariantAttributeValue.Name, ColorSquaresRgb = productVariantAttributeValue.ColorSquaresRgb, PriceAdjustment = productVariantAttributeValue.PriceAdjustment, WeightAdjustment = productVariantAttributeValue.WeightAdjustment, IsPreSelected = productVariantAttributeValue.IsPreSelected, DisplayOrder = productVariantAttributeValue.DisplayOrder, ValueTypeId = productVariantAttributeValue.ValueTypeId, LinkedProductId = productVariantAttributeValue.LinkedProductId, Quantity = productVariantAttributeValue.Quantity, }; _productAttributeService.InsertProductVariantAttributeValue(pvavCopy); //save associated value (used for combinations copying) associatedAttributeValues.Add(productVariantAttributeValue.Id, pvavCopy.Id); //localization foreach (var lang in languages) { var name = productVariantAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) _localizedEntityService.SaveLocalizedValue(pvavCopy, x => x.Name, name, lang.Id); } } } // attribute combinations using (var scope = new DbContextScope(lazyLoading: false, forceNoTracking: false)) { scope.LoadCollection(product, (Product p) => p.ProductVariantAttributeCombinations); } foreach (var combination in product.ProductVariantAttributeCombinations) { //generate new AttributesXml according to new value IDs string newAttributesXml = ""; var parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml); foreach (var oldPva in parsedProductVariantAttributes) { if (associatedAttributes.ContainsKey(oldPva.Id)) { int newPvaId = associatedAttributes[oldPva.Id]; var newPva = _productAttributeService.GetProductVariantAttributeById(newPvaId); if (newPva != null) { var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id); foreach (var oldPvaValueStr in oldPvaValuesStr) { if (newPva.ShouldHaveValues()) { //attribute values int oldPvaValue = int.Parse(oldPvaValueStr); if (associatedAttributeValues.ContainsKey(oldPvaValue)) { int newPvavId = associatedAttributeValues[oldPvaValue]; var newPvav = _productAttributeService.GetProductVariantAttributeValueById(newPvavId); if (newPvav != null) { newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, newPvav.Id.ToString()); } } } else { //just a text newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, oldPvaValueStr); } } } } } var combinationCopy = new ProductVariantAttributeCombination { ProductId = productCopy.Id, AttributesXml = newAttributesXml, StockQuantity = combination.StockQuantity, AllowOutOfStockOrders = combination.AllowOutOfStockOrders, // SmartStore extension Sku = combination.Sku, Gtin = combination.Gtin, ManufacturerPartNumber = combination.ManufacturerPartNumber, Price = combination.Price, AssignedPictureIds = copyImages ? combination.AssignedPictureIds : null, Length = combination.Length, Width = combination.Width, Height = combination.Height, BasePriceAmount = combination.BasePriceAmount, BasePriceBaseAmount = combination.BasePriceBaseAmount, DeliveryTimeId = combination.DeliveryTimeId, QuantityUnitId = combination.QuantityUnitId, IsActive = combination.IsActive //IsDefaultCombination = combination.IsDefaultCombination }; _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy); } // tier prices foreach (var tierPrice in product.TierPrices) { _productService.InsertTierPrice(new TierPrice { ProductId = productCopy.Id, StoreId = tierPrice.StoreId, CustomerRoleId = tierPrice.CustomerRoleId, Quantity = tierPrice.Quantity, Price = tierPrice.Price }); } // product <-> discounts mapping foreach (var discount in product.AppliedDiscounts) { productCopy.AppliedDiscounts.Add(discount); _productService.UpdateProduct(productCopy); } // update "HasTierPrices" and "HasDiscountsApplied" properties _productService.UpdateHasTierPricesProperty(productCopy); _productService.UpdateLowestAttributeCombinationPriceProperty(productCopy); _productService.UpdateHasDiscountsApplied(productCopy); // associated products if (copyAssociatedProducts && product.ProductType != ProductType.BundledProduct) { var searchContext = new ProductSearchContext { OrderBy = ProductSortingEnum.Position, ParentGroupedProductId = product.Id, PageSize = int.MaxValue, ShowHidden = true }; string copyOf = _localizationService.GetResource("Admin.Common.CopyOf"); var associatedProducts = _productService.SearchProducts(searchContext); foreach (var associatedProduct in associatedProducts) { var associatedProductCopy = CopyProduct(associatedProduct, string.Format("{0} {1}", copyOf, associatedProduct.Name), isPublished, copyImages, false); associatedProductCopy.ParentGroupedProductId = productCopy.Id; _productService.UpdateProduct(productCopy); } } // bundled products var bundledItems = _productService.GetBundleItems(product.Id, true); foreach (var bundleItem in bundledItems) { var newBundleItem = bundleItem.Item.Clone(); newBundleItem.BundleProductId = productCopy.Id; newBundleItem.CreatedOnUtc = utcNow; newBundleItem.UpdatedOnUtc = utcNow; _productService.InsertBundleItem(newBundleItem); foreach (var itemFilter in bundleItem.Item.AttributeFilters) { var newItemFilter = itemFilter.Clone(); newItemFilter.BundleItemId = newBundleItem.Id; _productAttributeService.InsertProductBundleItemAttributeFilter(newItemFilter); } } return productCopy; }
public ActionResult SaveDownloadUrl(string downloadUrl, bool minimalMode = false, string fieldName = null) { var download = new Download { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = true, DownloadUrl = downloadUrl, IsNew = true, IsTransient = true }; _downloadService.InsertDownload(download); return Json(new { success = true, downloadId = download.Id, html = this.RenderPartialViewToString(TEMPLATE, download.Id, new { minimalMode = minimalMode, fieldName = fieldName }) }, JsonRequestBehavior.AllowGet); }
private ActionResult GetFileContentResultFor(Download download, Product product) { if (download.DownloadBinary == null) { return Content(T("Common.Download.NoDataAvailable")); } var id = (product != null ? product.Id : download.Id); var fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : id.ToString(); var contentType = !String.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream"; return new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }; }
public virtual void UpdateDownload(Download download) { if (download == null) throw new ArgumentNullException("download"); download.UpdatedOnUtc = DateTime.UtcNow; _downloadRepository.Update(download); _eventPubisher.EntityUpdated(download); }