protected void BindProductInfo(Product product)
        {
            lProductName.Text = Server.HtmlEncode(product.LocalizedName);
            lShortDescription.Text = product.LocalizedShortDescription;
            lFullDescription.Text = product.LocalizedFullDescription;
            //manufacturers
            List<Manufacturer> manufacturers = new List<Manufacturer>();
            foreach (var pm in product.ProductManufacturers)
            {
                var manufacturer = pm.Manufacturer;
                if (manufacturer != null)
                    manufacturers.Add(manufacturer);
            }
            if (manufacturers.Count > 0)
            {
                if (manufacturers.Count == 1)
                {
                    lManufacturersTitle.Text = GetLocaleResourceString("Products.Manufacturer");
                }
                else
                {
                    lManufacturersTitle.Text = GetLocaleResourceString("Products.Manufacturers");
                }
                rptrManufacturers.DataSource = manufacturers;
                rptrManufacturers.DataBind();
            }
            else
            {
                phManufacturers.Visible = false;
            }

            //pictures
        }
        private static Product DBMapping(DBProduct dbItem)
        {
            if (dbItem == null)
                return null;

            Product item = new Product();
            item.ProductID = dbItem.ProductID;
            item.Name = dbItem.Name;
            item.ShortDescription = dbItem.ShortDescription;
            item.FullDescription = dbItem.FullDescription;
            item.AdminComment = dbItem.AdminComment;
            item.ProductTypeID = dbItem.ProductTypeID;
            item.TemplateID = dbItem.TemplateID;
            item.ShowOnHomePage = dbItem.ShowOnHomePage;
            item.MetaKeywords = dbItem.MetaKeywords;
            item.MetaDescription = dbItem.MetaDescription;
            item.MetaTitle = dbItem.MetaTitle;
            item.SEName = dbItem.SEName;
            item.AllowCustomerReviews = dbItem.AllowCustomerReviews;
            item.AllowCustomerRatings = dbItem.AllowCustomerRatings;
            item.RatingSum = dbItem.RatingSum;
            item.TotalRatingVotes = dbItem.TotalRatingVotes;
            item.Published = dbItem.Published;
            item.Deleted = dbItem.Deleted;
            item.CreatedOn = dbItem.CreatedOn;
            item.UpdatedOn = dbItem.UpdatedOn;

            return item;
        }
 public string GetProductImageUrl(Product product)
 {
     var picture = product.DefaultPicture;
     if (picture != null)
     {
         return PictureManager.GetPictureUrl(picture, SettingManager.GetSettingValueInteger("Media.ShoppingCart.ThumbnailImageSize", 80));
     }
     else
     {
         return PictureManager.GetDefaultPictureUrl(SettingManager.GetSettingValueInteger("Media.ShoppingCart.ThumbnailImageSize", 80));
     }
 }
Example #4
0
        private void CreateChildControlsTree()
        {
            product = ProductManager.GetProductById(this.ProductId);
            if (product != null)
            {
                Control child = null;

                ProductTemplate productTemplate = product.ProductTemplate;
                if (productTemplate == null)
                    throw new NopException(string.Format("Product template path can not be empty. Product ID={0}", product.ProductId));

                child = base.LoadControl(productTemplate.TemplatePath);
                this.ProductPlaceHolder.Controls.Add(child);
            }
        }
 protected void BindProductInfo(Product product)
 {
     //pictures
     var pictures = PictureService.GetPicturesByProductId(product.ProductId);
     if (pictures.Count > 0)
     {
         defaultImage.ImageUrl = PictureService.GetPictureUrl(pictures[0]);
         defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
         defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
         lvProductPictures.DataSource = pictures;
         lvProductPictures.DataBind();
     }
     else if (pictures.Count == 1)
     {
         defaultImage.ImageUrl = PictureService.GetPictureUrl(pictures[0]);
         defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
         defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
         lvProductPictures.Visible = false;
     }
     else
     {
         defaultImage.ImageUrl = PictureService.GetDefaultPictureUrl(SettingManager.GetSettingValueInteger("Media.Product.DetailImageSize", 1000));
         defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
         defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
         lvProductPictures.Visible = false;
     }
     if (SettingManager.GetSettingValueBoolean("Media.Product.DefaultPictureZoomEnabled", false))
     {
         var picture = product.DefaultPicture;
         if (picture != null)
         {
             lnkMainLightbox.Attributes["href"] = PictureService.GetPictureUrl(picture);
             lnkMainLightbox.Attributes["rel"] = "lightbox-pd";
         }
     }
 }
 public int CompareByLowToHigh(Product a, Product b)
 {
     if (a.ProductVariants.Count > 0 && b.ProductVariants.Count > 0)
     {
         if (a.ProductVariants[0].Price > b.ProductVariants[0].Price)
         {
             return 1;
         }
         else
         {
             if (a.ProductVariants[0].Price == b.ProductVariants[0].Price)
             {
                 return 0;
             }
             else
             {
                 return -1;
             }
         }
     }
     else
     {
         if (a.ProductVariants.Count > 0)
         {
             return 1;
         }
         else
         {
             return -1;
         }
     }
 }
 public int CompareByNew(Product a, Product b)
 {
     if (a.CreatedOn > b.CreatedOn)
     {
         return -1;
     }
     if (a.CreatedOn == b.CreatedOn)
     {
         return 0;
     }
     else
     {
         return 1;
     }
 }
Example #8
0
        protected void SaveLocalizableContent(Product product)
        {
            if (product == null)
                return;

            if (!this.HasLocalizableContent)
                return;

            foreach (RepeaterItem item in rptrLanguageDivs.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {
                    var txtLocalizedMetaKeywords = (TextBox)item.FindControl("txtLocalizedMetaKeywords");
                    var txtLocalizedMetaDescription = (TextBox)item.FindControl("txtLocalizedMetaDescription");
                    var txtLocalizedMetaTitle = (TextBox)item.FindControl("txtLocalizedMetaTitle");
                    var txtLocalizedSEName = (TextBox)item.FindControl("txtLocalizedSEName");
                    var lblLanguageId = (Label)item.FindControl("lblLanguageId");

                    int languageId = int.Parse(lblLanguageId.Text);
                    string metaKeywords = txtLocalizedMetaKeywords.Text;
                    string metaDescription = txtLocalizedMetaDescription.Text;
                    string metaTitle = txtLocalizedMetaTitle.Text;
                    string seName = txtLocalizedSEName.Text;

                    bool allFieldsAreEmpty = (string.IsNullOrEmpty(metaKeywords) &&
                        string.IsNullOrEmpty(metaDescription) &&
                        string.IsNullOrEmpty(metaTitle) &&
                        string.IsNullOrEmpty(seName));

                    var content = ProductManager.GetProductLocalizedByProductIdAndLanguageId(product.ProductId, languageId);
                    if (content == null)
                    {
                        if (!allFieldsAreEmpty && languageId > 0)
                        {
                            //only insert if one of the fields are filled out (avoid too many empty records in db...)
                            content = ProductManager.InsertProductLocalized(product.ProductId,
                                   languageId, string.Empty, string.Empty, string.Empty,
                                   metaKeywords, metaDescription, metaTitle, seName);
                        }
                    }
                    else
                    {
                        if (languageId > 0)
                        {
                            content = ProductManager.UpdateProductLocalized(content.ProductLocalizedId, content.ProductId,
                                languageId, content.Name, content.ShortDescription, content.FullDescription,
                                metaKeywords, metaDescription, metaTitle, seName);
                        }
                    }
                }
            }
        }
Example #9
0
        protected void BindProductInfo(Product product)
        {
            lProductName.Text = Server.HtmlEncode(product.LocalizedName);
            lShortDescription.Text = product.LocalizedShortDescription;
            lFullDescription.Text = product.LocalizedFullDescription;
            //manufacturers
            List<Manufacturer> manufacturers = new List<Manufacturer>();
            foreach (var pm in product.ProductManufacturers)
            {
                var manufacturer = pm.Manufacturer;
                if (manufacturer != null)
                    manufacturers.Add(manufacturer);
            }
            if (manufacturers.Count > 0)
            {
                if (manufacturers.Count == 1)
                {
                    lManufacturersTitle.Text = GetLocaleResourceString("Products.Manufacturer");
                }
                else
                {
                    lManufacturersTitle.Text = GetLocaleResourceString("Products.Manufacturers");
                }
                rptrManufacturers.DataSource = manufacturers;
                rptrManufacturers.DataBind();
            }
            else
            {
                phManufacturers.Visible = false;
            }

            //pictures
            var pictures = this.PictureService.GetPicturesByProductId(product.ProductId);
            if (pictures.Count > 1)
            {
                defaultImage.ImageUrl = this.PictureService.GetPictureUrl(pictures[0], this.SettingManager.GetSettingValueInteger("Media.Product.DetailImageSize", 300));
                defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                lvProductPictures.DataSource = pictures;
                lvProductPictures.DataBind();
            }
            else if (pictures.Count == 1)
            {
                defaultImage.ImageUrl = this.PictureService.GetPictureUrl(pictures[0], this.SettingManager.GetSettingValueInteger("Media.Product.DetailImageSize", 300));
                defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                lvProductPictures.Visible = false;
            }
            else
            {
                defaultImage.ImageUrl = this.PictureService.GetDefaultPictureUrl(this.SettingManager.GetSettingValueInteger("Media.Product.DetailImageSize", 300));
                defaultImage.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                defaultImage.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                lvProductPictures.Visible = false;
            }
            if(this.SettingManager.GetSettingValueBoolean("Media.Product.DefaultPictureZoomEnabled", false))
            {
                var picture = product.DefaultPicture;
                if (picture != null)
                {
                    lnkMainLightbox.Attributes["href"] = this.PictureService.GetPictureUrl(picture);
                    lnkMainLightbox.Attributes["rel"] = "lightbox-pd";
                }
            }
        }
Example #10
0
 /// <summary>
 /// Gets product SE (search engine) name
 /// </summary>
 /// <param name="product">Product</param>
 /// <returns>Product SE (search engine) name</returns>
 public static string GetProductSEName(Product product)
 {
     if (product == null)
         throw new ArgumentNullException("product");
     string seName = GetSEName(product.SEName);
     if (String.IsNullOrEmpty(seName))
     {
         seName = GetSEName(product.Name);
     }
     return seName;
 }
Example #11
0
        /// <summary>
        /// Gets product URL
        /// </summary>
        /// <param name="product">Product</param>
        /// <returns>Product URL</returns>
        public static string GetProductUrl(Product product)
        {
            if (product == null)
                throw new ArgumentNullException("product");
            string seName = GetProductSEName(product);

            string url2 = SEOHelper.EnableUrlRewriting ? IoC.Resolve<ISettingManager>().GetSettingValue("SEO.Product.UrlRewriteFormat") : "{0}Product.aspx?ProductID={1}";
            string url = string.Format(url2, CommonHelper.GetStoreLocation(), product.ProductId, seName);
            return url.ToLowerInvariant();
        }
Example #12
0
 /// <summary>
 /// Gets product URL
 /// </summary>
 /// <param name="product">Product</param>
 /// <returns>Product URL</returns>
 public static string GetProductURL(Product product)
 {
     if (product == null)
         throw new ArgumentNullException("product");
     string seName = GetSEName(product.SEName);
     if (String.IsNullOrEmpty(seName))
     {
         seName = GetSEName(product.Name);
     }
     string url = string.Format(SettingManager.GetSettingValue("SEO.Product.UrlRewriteFormat"), CommonHelper.GetStoreLocation(), product.ProductID, seName);
     return url;
 }
Example #13
0
        /// <summary>
        /// Replaces a message template tokens
        /// </summary>
        /// <param name="customer">Customer instance</param>
        /// <param name="product">Product instance</param>
        /// <param name="template">Template</param>
        /// <param name="additinalKeys">Additinal keys</param>
        /// <returns>New template</returns>
        private string ReplaceMessageTemplateTokens(Customer customer, Product product,
            string template, NameValueCollection additinalKeys)
        {
            var tokens = new NameValueCollection();
            tokens.Add("Store.Name", IoC.Resolve<ISettingManager>().StoreName);
            tokens.Add("Store.URL", IoC.Resolve<ISettingManager>().StoreUrl);
            tokens.Add("Store.Email", this.DefaultEmailAccount.Email);

            tokens.Add("Customer.Email", HttpUtility.HtmlEncode(customer.Email));
            tokens.Add("Customer.Username", HttpUtility.HtmlEncode(customer.Username));
            tokens.Add("Customer.FullName", HttpUtility.HtmlEncode(customer.FullName));
            tokens.Add("Customer.VatNumber", HttpUtility.HtmlEncode(customer.VatNumber));
            tokens.Add("Customer.VatNumberStatus", HttpUtility.HtmlEncode(customer.VatNumberStatus.ToString()));

            tokens.Add("Product.Name", HttpUtility.HtmlEncode(product.Name));
            tokens.Add("Product.ShortDescription", product.ShortDescription);
            tokens.Add("Product.ProductURLForCustomer", SEOHelper.GetProductUrl(product));

            foreach (string token in tokens.Keys)
            {
                template = Replace(template, String.Format(@"%{0}%", token), tokens[token]);
            }

            if (additinalKeys != null)
            {
                foreach (string token in additinalKeys.Keys)
                {
                    template = Replace(template, String.Format(@"%{0}%", token), additinalKeys[token]);
                }
            }

            return template;
        }
Example #14
0
        /// <summary>
        /// Updates the product
        /// </summary>
        /// <param name="product">Product</param>
        public void UpdateProduct(Product product)
        {
            if (product == null)
                throw new ArgumentNullException("product");

            product.Name = CommonHelper.EnsureNotNull(product.Name);
            product.Name = CommonHelper.EnsureMaximumLength(product.Name, 400);
            product.ShortDescription = CommonHelper.EnsureNotNull(product.ShortDescription);
            product.FullDescription = CommonHelper.EnsureNotNull(product.FullDescription);
            product.AdminComment = CommonHelper.EnsureNotNull(product.AdminComment);
            product.MetaKeywords = CommonHelper.EnsureNotNull(product.MetaKeywords);
            product.MetaKeywords = CommonHelper.EnsureMaximumLength(product.MetaKeywords, 400);
            product.MetaDescription = CommonHelper.EnsureNotNull(product.MetaDescription);
            product.MetaDescription = CommonHelper.EnsureMaximumLength(product.MetaDescription, 4000);
            product.MetaTitle = CommonHelper.EnsureNotNull(product.MetaTitle);
            product.MetaTitle = CommonHelper.EnsureMaximumLength(product.MetaTitle, 400);
            product.SEName = CommonHelper.EnsureNotNull(product.SEName);
            product.SEName = CommonHelper.EnsureMaximumLength(product.SEName, 100);

            if (!_context.IsAttached(product))
                _context.Products.Attach(product);

            _context.SaveChanges();

            if (this.CacheEnabled)
            {
                _cacheManager.RemoveByPattern(PRODUCTS_PATTERN_KEY);
                _cacheManager.RemoveByPattern(PRODUCTVARIANTS_PATTERN_KEY);
                _cacheManager.RemoveByPattern(TIERPRICES_PATTERN_KEY);
                _cacheManager.RemoveByPattern(CUSTOMERROLEPRICES_PATTERN_KEY);
            }

            //raise event
            EventContext.Current.OnProductUpdated(null,
                new ProductEventArgs() { Product = product });
        }
        public Product SaveInfo()
        {
            DateTime nowDT = DateTime.UtcNow;

            string name = txtName.Text.Trim();
            string shortDescription = txtShortDescription.Text.Trim();
            string fullDescription = txtFullDescription.Value.Trim();
            string adminComment = txtAdminComment.Text.Trim();
            int templateId = int.Parse(this.ddlTemplate.SelectedItem.Value);
            bool showOnHomePage = cbShowOnHomePage.Checked;
            bool allowCustomerReviews = cbAllowCustomerReviews.Checked;
            bool allowCustomerRatings = cbAllowCustomerRatings.Checked;
            bool published = cbPublished.Checked;
            string sku = txtSKU.Text.Trim();
            string manufacturerPartNumber = txtManufacturerPartNumber.Text.Trim();
            bool isGiftCard = cbIsGiftCard.Checked;
            int giftCardType = int.Parse(this.ddlGiftCardType.SelectedItem.Value);
            bool isDownload = cbIsDownload.Checked;
            int productVariantDownloadId = 0;
            if (isDownload)
            {
                bool useDownloadURL = cbUseDownloadURL.Checked;
                string downloadURL = txtDownloadURL.Text.Trim();
                byte[] productVariantDownloadBinary = null;
                string downloadContentType = string.Empty;
                string downloadFilename = string.Empty;
                string downloadExtension = string.Empty;

                HttpPostedFile productVariantDownloadFile = fuProductVariantDownload.PostedFile;
                if ((productVariantDownloadFile != null) && (!String.IsNullOrEmpty(productVariantDownloadFile.FileName)))
                {
                    productVariantDownloadBinary = productVariantDownloadFile.GetDownloadBits();
                    downloadContentType = productVariantDownloadFile.ContentType;
                    downloadFilename = Path.GetFileNameWithoutExtension(productVariantDownloadFile.FileName);
                    downloadExtension = Path.GetExtension(productVariantDownloadFile.FileName);
                }

                var productVariantDownload = new Download()
                {
                    UseDownloadUrl = useDownloadURL,
                    DownloadUrl = downloadURL,
                    DownloadBinary = productVariantDownloadBinary,
                    ContentType = downloadContentType,
                    Filename = downloadFilename,
                    Extension = downloadExtension,
                    IsNew = true
                };
                this.DownloadService.InsertDownload(productVariantDownload);
                productVariantDownloadId = productVariantDownload.DownloadId;
            }

            bool unlimitedDownloads = cbUnlimitedDownloads.Checked;
            int maxNumberOfDownloads = txtMaxNumberOfDownloads.Value;
            int? downloadExpirationDays = null;
            if (!String.IsNullOrEmpty(txtDownloadExpirationDays.Text.Trim()))
                downloadExpirationDays = int.Parse(txtDownloadExpirationDays.Text.Trim());
            DownloadActivationTypeEnum downloadActivationType = (DownloadActivationTypeEnum)Enum.ToObject(typeof(DownloadActivationTypeEnum), int.Parse(this.ddlDownloadActivationType.SelectedItem.Value));
            bool hasUserAgreement = cbHasUserAgreement.Checked;
            string userAgreementText = txtUserAgreementText.Value;

            bool hasSampleDownload = cbHasSampleDownload.Checked;
            int productVariantSampleDownloadId = 0;
            if (hasSampleDownload)
            {
                bool useSampleDownloadURL = cbUseSampleDownloadURL.Checked;
                string sampleDownloadURL = txtSampleDownloadURL.Text.Trim();
                byte[] productVariantSampleDownloadBinary = null;
                string sampleDownloadContentType = string.Empty;
                string sampleDownloadFilename = string.Empty;
                string sampleDownloadExtension = string.Empty;

                HttpPostedFile productVariantSampleDownloadFile = fuProductVariantSampleDownload.PostedFile;
                if ((productVariantSampleDownloadFile != null) && (!String.IsNullOrEmpty(productVariantSampleDownloadFile.FileName)))
                {
                    productVariantSampleDownloadBinary = productVariantSampleDownloadFile.GetDownloadBits();
                    sampleDownloadContentType = productVariantSampleDownloadFile.ContentType;
                    sampleDownloadFilename = Path.GetFileNameWithoutExtension(productVariantSampleDownloadFile.FileName);
                    sampleDownloadExtension = Path.GetExtension(productVariantSampleDownloadFile.FileName);
                }

                var productVariantSampleDownload = new Download()
                {
                    UseDownloadUrl = useSampleDownloadURL,
                    DownloadUrl = sampleDownloadURL,
                    DownloadBinary = productVariantSampleDownloadBinary,
                    ContentType = sampleDownloadContentType,
                    Filename = sampleDownloadFilename,
                    Extension = sampleDownloadExtension,
                    IsNew = true
                };
                this.DownloadService.InsertDownload(productVariantSampleDownload);
                productVariantSampleDownloadId = productVariantSampleDownload.DownloadId;
            }

            bool isRecurring = cbIsRecurring.Checked;
            int cycleLength = txtCycleLength.Value;
            RecurringProductCyclePeriodEnum cyclePeriod = (RecurringProductCyclePeriodEnum)Enum.ToObject(typeof(RecurringProductCyclePeriodEnum), int.Parse(this.ddlCyclePeriod.SelectedItem.Value));
            int totalCycles = txtTotalCycles.Value;

            bool isShipEnabled = cbIsShipEnabled.Checked;
            bool isFreeShipping = cbIsFreeShipping.Checked;
            decimal additionalShippingCharge = txtAdditionalShippingCharge.Value;
            bool isTaxExempt = cbIsTaxExempt.Checked;
            int taxCategoryId = int.Parse(this.ddlTaxCategory.SelectedItem.Value);
            int manageStock = Convert.ToInt32(ddlManageStock.SelectedValue);
            int stockQuantity = txtStockQuantity.Value;
            bool displayStockAvailability = cbDisplayStockAvailability.Checked;
            bool displayStockQuantity = cbDisplayStockQuantity.Checked;
            int minStockQuantity = txtMinStockQuantity.Value;
            LowStockActivityEnum lowStockActivity = (LowStockActivityEnum)Enum.ToObject(typeof(LowStockActivityEnum), int.Parse(this.ddlLowStockActivity.SelectedItem.Value));
            int notifyForQuantityBelow = txtNotifyForQuantityBelow.Value;
            int backorders = int.Parse(this.ddlBackorders.SelectedItem.Value);
            int orderMinimumQuantity = txtOrderMinimumQuantity.Value;
            int orderMaximumQuantity = txtOrderMaximumQuantity.Value;
            int warehouseId = int.Parse(this.ddlWarehouse.SelectedItem.Value);
            bool disableBuyButton = cbDisableBuyButton.Checked;
            bool callForPrice = cbCallForPrice.Checked;
            decimal price = txtPrice.Value;
            decimal oldPrice = txtOldPrice.Value;
            decimal productCost = txtProductCost.Value;
            bool customerEntersPrice = cbCustomerEntersPrice.Checked;
            decimal minimumCustomerEnteredPrice = txtMinimumCustomerEnteredPrice.Value;
            decimal maximumCustomerEnteredPrice = txtMaximumCustomerEnteredPrice.Value;
            decimal weight = txtWeight.Value;
            decimal length = txtLength.Value;
            decimal width = txtWidth.Value;
            decimal height = txtHeight.Value;
            DateTime? availableStartDateTime = ctrlAvailableStartDateTimePicker.SelectedDate;
            DateTime? availableEndDateTime = ctrlAvailableEndDateTimePicker.SelectedDate;
            if (availableStartDateTime.HasValue)
            {
                availableStartDateTime = DateTime.SpecifyKind(availableStartDateTime.Value, DateTimeKind.Utc);
            }
            if (availableEndDateTime.HasValue)
            {
                availableEndDateTime = DateTime.SpecifyKind(availableEndDateTime.Value, DateTimeKind.Utc);
            }

            //product
            var product = new Product()
            {
                Name = name,
                ShortDescription = shortDescription,
                FullDescription = fullDescription,
                AdminComment = adminComment,
                TemplateId = templateId,
                ShowOnHomePage = showOnHomePage,
                AllowCustomerReviews = allowCustomerReviews,
                AllowCustomerRatings = allowCustomerRatings,
                Published = published,
                CreatedOn = nowDT,
                UpdatedOn = nowDT
            };

            this.ProductService.InsertProduct(product);

            //product variant
            var productVariant = new ProductVariant()
            {
                ProductId = product.ProductId,
                SKU = sku,
                ManufacturerPartNumber = manufacturerPartNumber,
                IsGiftCard = isGiftCard,
                GiftCardType = giftCardType,
                IsDownload = isDownload,
                DownloadId = productVariantDownloadId,
                UnlimitedDownloads = unlimitedDownloads,
                MaxNumberOfDownloads = maxNumberOfDownloads,
                DownloadExpirationDays = downloadExpirationDays,
                DownloadActivationType = (int)downloadActivationType,
                HasSampleDownload = hasSampleDownload,
                SampleDownloadId = productVariantSampleDownloadId,
                HasUserAgreement = hasUserAgreement,
                UserAgreementText = userAgreementText,
                IsRecurring = isRecurring,
                CycleLength = cycleLength,
                CyclePeriod = (int)cyclePeriod,
                TotalCycles = totalCycles,
                IsShipEnabled = isShipEnabled,
                IsFreeShipping = isFreeShipping,
                AdditionalShippingCharge = additionalShippingCharge,
                IsTaxExempt = isTaxExempt,
                TaxCategoryId = taxCategoryId,
                ManageInventory = manageStock,
                StockQuantity = stockQuantity,
                DisplayStockAvailability = displayStockAvailability,
                DisplayStockQuantity = displayStockQuantity,
                MinStockQuantity = minStockQuantity,
                LowStockActivityId = (int)lowStockActivity,
                NotifyAdminForQuantityBelow = notifyForQuantityBelow,
                Backorders = backorders,
                OrderMinimumQuantity = orderMinimumQuantity,
                OrderMaximumQuantity = orderMaximumQuantity,
                WarehouseId = warehouseId,
                DisableBuyButton = disableBuyButton,
                CallForPrice = callForPrice,
                Price = price,
                OldPrice = oldPrice,
                ProductCost = productCost,
                CustomerEntersPrice = customerEntersPrice,
                MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice,
                Weight = weight,
                Length = length,
                Width = width,
                Height = height,
                AvailableStartDateTime = availableStartDateTime,
                AvailableEndDateTime = availableEndDateTime,
                Published = published,
                Deleted = false,
                DisplayOrder = 1,
                CreatedOn = nowDT,
                UpdatedOn = nowDT
            };

            this.ProductService.InsertProductVariant(productVariant);

            SaveLocalizableContent(product);

            //product tags
            string[] newProductTags = ParseProductTags(txtProductTags.Text);
            foreach (string productTagName in newProductTags)
            {
                ProductTag productTag = null;
                var productTag2 = this.ProductService.GetProductTagByName(productTagName);
                if (productTag2 == null)
                {
                    //add new product tag
                    productTag = new ProductTag()
                    {
                        Name = productTagName,
                        ProductCount = 0
                    };
                    this.ProductService.InsertProductTag(productTag);
                }
                else
                {
                    productTag = productTag2;
                }
                this.ProductService.AddProductTagMapping(product.ProductId, productTag.ProductTagId);
            }

            return product;
        }
        protected void SaveLocalizableContent(Product product)
        {
            if (product == null)
                return;

            if (!this.HasLocalizableContent)
                return;

            foreach (RepeaterItem item in rptrLanguageDivs.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {
                    var txtLocalizedName = (TextBox)item.FindControl("txtLocalizedName");
                    var txtLocalizedShortDescription = (TextBox)item.FindControl("txtLocalizedShortDescription");
                    var txtLocalizedFullDescription = (FCKeditor)item.FindControl("txtLocalizedFullDescription");
                    var lblLanguageId = (Label)item.FindControl("lblLanguageId");

                    int languageId = int.Parse(lblLanguageId.Text);
                    string name = txtLocalizedName.Text;
                    string shortDescription = txtLocalizedShortDescription.Text;
                    string fullDescription = txtLocalizedFullDescription.Value;

                    bool allFieldsAreEmpty = (string.IsNullOrEmpty(name) &&
                        string.IsNullOrEmpty(shortDescription) &&
                        string.IsNullOrEmpty(fullDescription));

                    var content = this.ProductService.GetProductLocalizedByProductIdAndLanguageId(product.ProductId, languageId);
                    if (content == null)
                    {
                        if (!allFieldsAreEmpty && languageId > 0)
                        {
                            //only insert if one of the fields are filled out (avoid too many empty records in db...)
                            content = new ProductLocalized()
                            {
                                ProductId = product.ProductId,
                                LanguageId = languageId,
                                Name = name,
                                ShortDescription = shortDescription,
                                FullDescription = fullDescription
                            };
                            this.ProductService.InsertProductLocalized(content);
                        }
                    }
                    else
                    {
                        if (languageId > 0)
                        {
                            content.LanguageId = languageId;
                            content.Name = name;
                            content.ShortDescription = shortDescription;
                            content.FullDescription = fullDescription;
                            this.ProductService.UpdateProductLocalized(content);
                        }
                    }
                }
            }
        }
        protected void BindProductInfo(Product product)
        {
            string str = "";
            //产品名字
            str += Server.HtmlEncode(product.LocalizedName);
            str += "<!>";
            //产品短描述
            str += product.LocalizedFullDescription;
            str += "<!>";
            //价格
            decimal taxRate = decimal.Zero;
            decimal finalPriceWithDiscountBase =this.TaxService.GetPrice(product.ProductVariants[0], PriceHelper.GetFinalPrice(product.ProductVariants[0], true), out taxRate);
            decimal finalPriceWithDiscount = CurrencyService.ConvertCurrency(finalPriceWithDiscountBase, CurrencyService.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
            str += PriceHelper.FormatPrice(finalPriceWithDiscount);//价格
            str += "<!>";
            //产品对应的链接
            str += SEOHelper.GetProductUrl(product);
            str += "<!>";
            //产品图片
            //..............................................................
            var pictures = PictureService.GetPicturesByProductId(product.ProductId);
            if (pictures.Count > 1)
            {
                for (int i = 0; i < pictures.Count; i++)
                {
                    str += PictureService.GetPictureUrl(pictures[i], SettingManager.GetSettingValueInteger("Media.MaximumImageSize"));
                    str += "|";
                }

            }
            else if (pictures.Count == 1)
            {
                str += PictureService.GetPictureUrl(pictures[0], SettingManager.GetSettingValueInteger("Media.MaximumImageSize"));
                str += "|";
            }
            else
            {
                str += PictureService.GetDefaultPictureUrl(SettingManager.GetSettingValueInteger("Media.MaximumImageSize", 1000));
                str += "|";
            }

            //.................................................................................
            str += "<!>";
            Response.Write(str);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Product product = this.ProductService.GetProductById(this.ProductId);

                if (product != null)
                {
                    lblTitle.Text = Server.HtmlEncode(product.Name);
                    if (product.ProductVariants[0].Vendor.CustomerId !=
                            NopCommerce.BusinessLogic.NopContext.Current.User.Vendor.CustomerId)
                    {
                        //this user is not allowed to edit other items.  Redirect to their
                        //products page.
                        Response.Redirect("Products.aspx");
                    }
                }
                else
                {
                    DateTime nowDT = DateTime.UtcNow;

                    //create new product without activated set.
                    product = new Product()
                    {
                        Name = "New " + NopCommerce.BusinessLogic.NopContext.Current.User.Vendor.CompanyName + " Product ",
                        ShortDescription = String.Empty,
                        FullDescription = String.Empty,
                        AdminComment = "Created",
                        TemplateId = 5, //default for sewbie.
                        ShowOnHomePage = false,
                        AllowCustomerReviews = true,
                        AllowCustomerRatings = true,
                        Published = false,
                        Activated = false,
                        CreatedOn = DateTime.UtcNow,
                        UpdatedOn = DateTime.UtcNow
                    };

                    this.ProductService.InsertProduct(product);

                    ProductVariant prv = new ProductVariant()
                    {
                        ProductId = product.ProductId,
                        Name = product.Name,
                        SKU = String.Empty,
                        Description = String.Empty,
                        AdminComment = "Created",
                        ManufacturerPartNumber = String.Empty,
                        IsGiftCard = false,
                        GiftCardType = 0,
                        IsDownload = false,
                        DownloadId = 0,
                        UnlimitedDownloads = false,
                        MaxNumberOfDownloads = 0,
                        DownloadExpirationDays = 0,
                        DownloadActivationType = 0,
                        HasSampleDownload = false,
                        SampleDownloadId = 0,
                        HasUserAgreement = false,
                        UserAgreementText = String.Empty,
                        IsRecurring = false,
                        CycleLength = 0,
                        CyclePeriod = 0,
                        TotalCycles = 0,
                        IsShipEnabled = false,
                        IsFreeShipping = false,
                        AdditionalShippingCharge = 0,
                        IsTaxExempt = false,
                        TaxCategoryId = 0,
                        ManageInventory = 0,
                        StockQuantity = 1,
                        DisplayStockAvailability = false,
                        DisplayStockQuantity = true,
                        MinStockQuantity = 1,
                        LowStockActivityId = 0,
                        NotifyAdminForQuantityBelow = 1,
                        Backorders = 0,
                        OrderMinimumQuantity = 1,
                        OrderMaximumQuantity = 10000,
                        WarehouseId = 0,
                        DisableBuyButton = false,
                        CallForPrice = false,
                        Price = 0.01M,
                        OldPrice = 0,
                        ProductCost = 0,
                        CustomerEntersPrice = false,
                        MinimumCustomerEnteredPrice = 0,
                        MaximumCustomerEnteredPrice = 0,
                        Weight = 0,
                        Length = 0,
                        Width = 0,
                        Height = 0,
                        PictureId = 0,
                        AvailableStartDateTime = null,
                        AvailableEndDateTime = null,
                        Published = false,
                        Deleted = false,
                        DisplayOrder = 1,
                        VendorId = NopCommerce.BusinessLogic.NopContext.Current.User.CustomerId,
                        CreatedOn = nowDT,
                        UpdatedOn = nowDT
                    };

                    this.ProductService.InsertProductVariant(prv);

                    //we're going to do a redirect here so that the product id makes it into the
                    //query strnig and this page should load as if it's an edit.
                    Response.Redirect("ProductDetails.aspx?productid=" + product.ProductId);
                }
            }
        }
Example #19
0
        /// <summary>
        /// Creates a copy of product with all depended data
        /// </summary>
        /// <param name="productId">The product identifier</param>
        /// <param name="name">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 entity</returns>
        public Product DuplicateProduct(int productId, string name,
            bool isPublished, bool copyImages)
        {
            var product = GetProductById(productId);
            if (product == null)
                return null;

            Product productCopy = null;
            //uncomment this line to support transactions
            //using (var scope = new System.Transactions.TransactionScope())
            {
                // product
                productCopy = new Product()
                {
                    Name = name,
                    ShortDescription = product.ShortDescription,
                    FullDescription = product.FullDescription,
                    AdminComment = product.AdminComment,
                    TemplateId = product.TemplateId,
                    ShowOnHomePage = product.ShowOnHomePage,
                    MetaKeywords = product.MetaKeywords,
                    MetaDescription = product.MetaDescription,
                    MetaTitle = product.MetaTitle,
                    SEName = product.SEName,
                    AllowCustomerReviews = product.AllowCustomerReviews,
                    AllowCustomerRatings = product.AllowCustomerRatings,
                    Published = isPublished,
                    Deleted = product.Deleted,
                    CreatedOn = DateTime.UtcNow,
                    UpdatedOn = DateTime.UtcNow
                };
                InsertProduct(productCopy);

                if (productCopy == null)
                    return null;

                var languages = IoC.Resolve<ILanguageService>().GetAllLanguages(true);

                //localization
                foreach (var lang in languages)
                {
                    var productLocalized = GetProductLocalizedByProductIdAndLanguageId(product.ProductId, lang.LanguageId);
                    if (productLocalized != null)
                    {
                        var productLocalizedCopy = new ProductLocalized()
                        {
                            ProductId = productCopy.ProductId,
                            LanguageId = productLocalized.LanguageId,
                            Name = productLocalized.Name,
                            ShortDescription = productLocalized.ShortDescription,
                            FullDescription = productLocalized.FullDescription,
                            MetaKeywords = productLocalized.MetaKeywords,
                            MetaDescription = productLocalized.MetaDescription,
                            MetaTitle = productLocalized.MetaTitle,
                            SEName = productLocalized.SEName
                        };
                        InsertProductLocalized(productLocalizedCopy);
                    }
                }

                // product pictures
                if (copyImages)
                {
                    foreach (var productPicture in product.ProductPictures)
                    {
                        var picture = productPicture.Picture;

                        var pictureCopy = IoC.Resolve<IPictureService>().InsertPicture(picture.PictureBinary,
                            picture.MimeType,
                            picture.IsNew);

                        InsertProductPicture(new ProductPicture()
                        {
                            ProductId = productCopy.ProductId,
                            PictureId = pictureCopy.PictureId,
                            DisplayOrder = productPicture.DisplayOrder
                        });
                    }
                }

                // product <-> categories mappings
                foreach (var productCategory in product.ProductCategories)
                {
                    var productCategoryCopy = new ProductCategory()
                    {
                        ProductId = productCopy.ProductId,
                        CategoryId = productCategory.CategoryId,
                        IsFeaturedProduct = productCategory.IsFeaturedProduct,
                        DisplayOrder = productCategory.DisplayOrder
                    };

                    IoC.Resolve<ICategoryService>().InsertProductCategory(productCategoryCopy);
                }

                // product <-> manufacturers mappings
                foreach (var productManufacturers in product.ProductManufacturers)
                {
                    var productManufacturerCopy = new ProductManufacturer()
                    {
                        ProductId = productCopy.ProductId,
                        ManufacturerId = productManufacturers.ManufacturerId,
                        IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
                        DisplayOrder = productManufacturers.DisplayOrder
                    };

                    IoC.Resolve<IManufacturerService>().InsertProductManufacturer(productManufacturerCopy);
                }

                // product <-> releated products mappings
                foreach (var relatedProduct in product.RelatedProducts)
                {
                    InsertRelatedProduct(
                        new RelatedProduct()
                        {
                            ProductId1 = productCopy.ProductId,
                            ProductId2 = relatedProduct.ProductId2,
                            DisplayOrder = relatedProduct.DisplayOrder
                        });
                }

                // product specifications
                foreach (var productSpecificationAttribute in IoC.Resolve<ISpecificationAttributeService>().GetProductSpecificationAttributesByProductId(product.ProductId))
                {
                    var psaCopy = new ProductSpecificationAttribute()
                    {
                        ProductId = productCopy.ProductId,
                        SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                        AllowFiltering = productSpecificationAttribute.AllowFiltering,
                        ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                        DisplayOrder = productSpecificationAttribute.DisplayOrder
                    };
                    IoC.Resolve<ISpecificationAttributeService>().InsertProductSpecificationAttribute(psaCopy);
                }

                // product variants
                var productVariants = GetProductVariantsByProductId(product.ProductId, true);
                foreach (var productVariant in productVariants)
                {
                    // product variant picture
                    int pictureId = 0;
                    if (copyImages)
                    {
                        var picture = productVariant.Picture;
                        if (picture != null)
                        {
                            var pictureCopy = IoC.Resolve<IPictureService>().InsertPicture(picture.PictureBinary, picture.MimeType, picture.IsNew);
                            pictureId = pictureCopy.PictureId;
                        }
                    }

                    // product variant download & sample download
                    int downloadId = productVariant.DownloadId;
                    int sampleDownloadId = productVariant.SampleDownloadId;
                    if (productVariant.IsDownload)
                    {
                        var download = productVariant.Download;
                        if (download != null)
                        {
                            var downloadCopy = new Download()
                                {
                                    UseDownloadUrl = download.UseDownloadUrl,
                                    DownloadUrl = download.DownloadUrl,
                                    DownloadBinary = download.DownloadBinary,
                                    ContentType = download.ContentType,
                                    Filename = download.Filename,
                                    Extension = download.Extension,
                                    IsNew = download.IsNew
                                };
                            IoC.Resolve<IDownloadService>().InsertDownload(downloadCopy);
                            downloadId = downloadCopy.DownloadId;
                        }

                        if (productVariant.HasSampleDownload)
                        {
                            var sampleDownload = productVariant.SampleDownload;
                            if (sampleDownload != null)
                            {
                                var sampleDownloadCopy = new Download()
                                {
                                    UseDownloadUrl = sampleDownload.UseDownloadUrl,
                                    DownloadUrl = sampleDownload.DownloadUrl,
                                    DownloadBinary = sampleDownload.DownloadBinary,
                                    ContentType = sampleDownload.ContentType,
                                    Filename = sampleDownload.Filename,
                                    Extension = sampleDownload.Extension,
                                    IsNew = sampleDownload.IsNew
                                };
                                IoC.Resolve<IDownloadService>().InsertDownload(sampleDownloadCopy);
                                sampleDownloadId = sampleDownloadCopy.DownloadId;
                            }
                        }
                    }

                    // product variant
                    var productVariantCopy = new ProductVariant()
                    {
                        ProductId = productCopy.ProductId,
                        Name = productVariant.Name,
                        SKU = productVariant.SKU,
                        Description = productVariant.Description,
                        AdminComment = productVariant.AdminComment,
                        ManufacturerPartNumber = productVariant.ManufacturerPartNumber,
                        IsGiftCard = productVariant.IsGiftCard,
                        GiftCardType = productVariant.GiftCardType,
                        IsDownload = productVariant.IsDownload,
                        DownloadId = downloadId,
                        UnlimitedDownloads = productVariant.UnlimitedDownloads,
                        MaxNumberOfDownloads = productVariant.MaxNumberOfDownloads,
                        DownloadExpirationDays = productVariant.DownloadExpirationDays,
                        DownloadActivationType = productVariant.DownloadActivationType,
                        HasSampleDownload = productVariant.HasSampleDownload,
                        SampleDownloadId = sampleDownloadId,
                        HasUserAgreement = productVariant.HasUserAgreement,
                        UserAgreementText = productVariant.UserAgreementText,
                        IsRecurring = productVariant.IsRecurring,
                        CycleLength = productVariant.CycleLength,
                        CyclePeriod = productVariant.CyclePeriod,
                        TotalCycles = productVariant.TotalCycles,
                        IsShipEnabled = productVariant.IsShipEnabled,
                        IsFreeShipping = productVariant.IsFreeShipping,
                        AdditionalShippingCharge = productVariant.AdditionalShippingCharge,
                        IsTaxExempt = productVariant.IsTaxExempt,
                        TaxCategoryId = productVariant.TaxCategoryId,
                        ManageInventory = productVariant.ManageInventory,
                        StockQuantity = productVariant.StockQuantity,
                        DisplayStockAvailability = productVariant.DisplayStockAvailability,
                        DisplayStockQuantity = productVariant.DisplayStockQuantity,
                        MinStockQuantity = productVariant.MinStockQuantity,
                        LowStockActivityId = productVariant.LowStockActivityId,
                        NotifyAdminForQuantityBelow = productVariant.NotifyAdminForQuantityBelow,
                        Backorders = productVariant.Backorders,
                        OrderMinimumQuantity = productVariant.OrderMinimumQuantity,
                        OrderMaximumQuantity = productVariant.OrderMaximumQuantity,
                        WarehouseId = productVariant.WarehouseId,
                        DisableBuyButton = productVariant.DisableBuyButton,
                        CallForPrice = productVariant.CallForPrice,
                        Price = productVariant.Price,
                        OldPrice = productVariant.OldPrice,
                        ProductCost = productVariant.ProductCost,
                        CustomerEntersPrice = productVariant.CustomerEntersPrice,
                        MinimumCustomerEnteredPrice = productVariant.MinimumCustomerEnteredPrice,
                        MaximumCustomerEnteredPrice = productVariant.MaximumCustomerEnteredPrice,
                        Weight = productVariant.Weight,
                        Length = productVariant.Length,
                        Width = productVariant.Width,
                        Height = productVariant.Height,
                        PictureId = pictureId,
                        AvailableStartDateTime = productVariant.AvailableStartDateTime,
                        AvailableEndDateTime = productVariant.AvailableEndDateTime,
                        Published = productVariant.Published,
                        Deleted = productVariant.Deleted,
                        DisplayOrder = productVariant.DisplayOrder,
                        CreatedOn = DateTime.UtcNow,
                        UpdatedOn = DateTime.UtcNow
                    };

                    InsertProductVariant(productVariantCopy);

                    //localization
                    foreach (var lang in languages)
                    {
                        var productVariantLocalized = GetProductVariantLocalizedByProductVariantIdAndLanguageId(productVariant.ProductVariantId, lang.LanguageId);
                        if (productVariantLocalized != null)
                        {
                            var productVariantLocalizedCopy = new ProductVariantLocalized()
                            {
                                ProductVariantId = productVariantCopy.ProductVariantId,
                                LanguageId = productVariantLocalized.LanguageId,
                                Name = productVariantLocalized.Name,
                                Description = productVariantLocalized.Description
                            };
                            InsertProductVariantLocalized(productVariantLocalizedCopy);
                        }
                    }

                    // product variant <-> attributes mappings
                    foreach (var productVariantAttribute in IoC.Resolve<IProductAttributeService>().GetProductVariantAttributesByProductVariantId(productVariant.ProductVariantId))
                    {
                        var productVariantAttributeCopy = new ProductVariantAttribute()
                        {
                            ProductVariantId = productVariantCopy.ProductVariantId,
                            ProductAttributeId = productVariantAttribute.ProductAttributeId,
                            TextPrompt = productVariantAttribute.TextPrompt,
                            IsRequired = productVariantAttribute.IsRequired,
                            AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId,
                            DisplayOrder = productVariantAttribute.DisplayOrder
                        };
                        IoC.Resolve<IProductAttributeService>().InsertProductVariantAttribute(productVariantAttributeCopy);

                        // product variant attribute values
                        var productVariantAttributeValues = IoC.Resolve<IProductAttributeService>().GetProductVariantAttributeValues(productVariantAttribute.ProductVariantAttributeId);
                        foreach (var productVariantAttributeValue in productVariantAttributeValues)
                        {
                            var pvavCopy = new ProductVariantAttributeValue()
                            {
                                ProductVariantAttributeId = productVariantAttributeCopy.ProductVariantAttributeId,
                                Name = productVariantAttributeValue.Name,
                                PriceAdjustment = productVariantAttributeValue.PriceAdjustment,
                                WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                                IsPreSelected = productVariantAttributeValue.IsPreSelected,
                                DisplayOrder = productVariantAttributeValue.DisplayOrder
                            };
                            IoC.Resolve<IProductAttributeService>().InsertProductVariantAttributeValue(pvavCopy);

                            //localization
                            foreach (var lang in languages)
                            {
                                var pvavLocalized = IoC.Resolve<IProductAttributeService>().GetProductVariantAttributeValueLocalizedByProductVariantAttributeValueIdAndLanguageId(productVariantAttributeValue.ProductVariantAttributeValueId, lang.LanguageId);
                                if (pvavLocalized != null)
                                {
                                    var pvavLocalizedCopy = new ProductVariantAttributeValueLocalized()
                                    {
                                        ProductVariantAttributeValueId = pvavCopy.ProductVariantAttributeValueId,
                                        LanguageId = pvavLocalized.LanguageId,
                                        Name = pvavLocalized.Name
                                    };
                                    IoC.Resolve<IProductAttributeService>().InsertProductVariantAttributeValueLocalized(pvavLocalizedCopy);
                                }
                            }
                        }
                    }
                    foreach (var combination in IoC.Resolve<IProductAttributeService>().GetAllProductVariantAttributeCombinations(productVariant.ProductVariantId))
                    {
                        var combinationCopy = new ProductVariantAttributeCombination()
                        {
                            ProductVariantId = productVariantCopy.ProductVariantId,
                            AttributesXml = combination.AttributesXml,
                            StockQuantity = combination.StockQuantity,
                            AllowOutOfStockOrders = combination.AllowOutOfStockOrders
                        };
                        IoC.Resolve<IProductAttributeService>().InsertProductVariantAttributeCombination(combinationCopy);
                    }

                    // product variant tier prices
                    foreach (var tierPrice in productVariant.TierPrices)
                    {
                        InsertTierPrice(
                            new TierPrice()
                            {
                                ProductVariantId = productVariantCopy.ProductVariantId,
                                Quantity = tierPrice.Quantity,
                                Price = tierPrice.Price
                            });
                    }

                    // product variant <-> discounts mapping
                    foreach (var discount in productVariant.AllDiscounts)
                    {
                        IoC.Resolve<IDiscountService>().AddDiscountToProductVariant(productVariantCopy.ProductVariantId, discount.DiscountId);
                    }

                    // prices by customer role
                    foreach (var crpp in productVariant.CustomerRoleProductPrices)
                    {
                        this.InsertCustomerRoleProductPrice(
                            new CustomerRoleProductPrice()
                            {
                                CustomerRoleId = crpp.CustomerRoleId,
                                ProductVariantId = productVariantCopy.ProductVariantId,
                                Price = crpp.Price
                            }
                            );
                    }
                }

                //uncomment this line to support transactions
                //scope.Complete();
            }

            return productCopy;
        }
Example #20
0
        /// <summary>
        /// Sends "email a friend" message
        /// </summary>
        /// <param name="customer">Customer instance</param>
        /// <param name="languageId">Message language identifier</param>
        /// <param name="product">Product instance</param>
        /// <param name="friendsEmail">Friend's email</param>
        /// <param name="personalMessage">Personal message</param>
        /// <returns>Queued email identifier</returns>
        public int SendProductEmailAFriendMessage(Customer customer, int languageId, 
            Product product, string friendsEmail, string personalMessage)
        {
            if (customer == null)
                throw new ArgumentNullException("customer");
            if (product == null)
                throw new ArgumentNullException("product");

            string templateName = "Service.EmailAFriend";
            var localizedMessageTemplate = this.GetLocalizedMessageTemplate(templateName, languageId);
            if(localizedMessageTemplate == null || !localizedMessageTemplate.IsActive)
                return 0;

            var emailAccount = localizedMessageTemplate.EmailAccount;

            var additinalKeys = new NameValueCollection();
            additinalKeys.Add("EmailAFriend.PersonalMessage", personalMessage);
            string subject = ReplaceMessageTemplateTokens(customer, product, localizedMessageTemplate.Subject, additinalKeys);
            string body = ReplaceMessageTemplateTokens(customer, product, localizedMessageTemplate.Body, additinalKeys);
            string bcc = localizedMessageTemplate.BccEmailAddresses;
            var from = new MailAddress(emailAccount.Email, emailAccount.DisplayName);
            var to = new MailAddress(friendsEmail);
            var queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, bcc, subject, body,
                DateTime.UtcNow, 0, null, emailAccount.EmailAccountId);
            return queuedEmail.QueuedEmailId;
        }