Ejemplo n.º 1
0
        public void WriteProduct(dynamic product, string node)
        {
            if (product == null)
            {
                return;
            }

            Product entity = product.Entity;

            if (node.HasValue())
            {
                _writer.WriteStartElement(node);
            }

            decimal?basePriceAmount                 = product.BasePriceAmount;
            int?    basePriceBaseAmount             = product.BasePriceBaseAmount;
            decimal?lowestAttributeCombinationPrice = product.LowestAttributeCombinationPrice;

            _writer.Write("Id", entity.Id.ToString());
            _writer.Write("Name", (string)product.Name);
            _writer.Write("SeName", (string)product.SeName);
            _writer.Write("ShortDescription", (string)product.ShortDescription);
            _writer.Write("FullDescription", (string)product.FullDescription);
            _writer.Write("AdminComment", (string)product.AdminComment);
            _writer.Write("ProductTemplateId", entity.ProductTemplateId.ToString());
            _writer.Write("ProductTemplateViewPath", (string)product._ProductTemplateViewPath);
            _writer.Write("ShowOnHomePage", entity.ShowOnHomePage.ToString());
            _writer.Write("HomePageDisplayOrder", entity.HomePageDisplayOrder.ToString());
            _writer.Write("MetaKeywords", (string)product.MetaKeywords);
            _writer.Write("MetaDescription", (string)product.MetaDescription);
            _writer.Write("MetaTitle", (string)product.MetaTitle);
            _writer.Write("AllowCustomerReviews", entity.AllowCustomerReviews.ToString());
            _writer.Write("ApprovedRatingSum", entity.ApprovedRatingSum.ToString());
            _writer.Write("NotApprovedRatingSum", entity.NotApprovedRatingSum.ToString());
            _writer.Write("ApprovedTotalReviews", entity.ApprovedTotalReviews.ToString());
            _writer.Write("NotApprovedTotalReviews", entity.NotApprovedTotalReviews.ToString());
            _writer.Write("Published", entity.Published.ToString());
            _writer.Write("CreatedOnUtc", entity.CreatedOnUtc.ToString(_culture));
            _writer.Write("UpdatedOnUtc", entity.UpdatedOnUtc.ToString(_culture));
            _writer.Write("SubjectToAcl", entity.SubjectToAcl.ToString());
            _writer.Write("LimitedToStores", entity.LimitedToStores.ToString());
            _writer.Write("ProductTypeId", entity.ProductTypeId.ToString());
            _writer.Write("ParentGroupedProductId", entity.ParentGroupedProductId.ToString());
            _writer.Write("Sku", (string)product.Sku);
            _writer.Write("ManufacturerPartNumber", (string)product.ManufacturerPartNumber);
            _writer.Write("Gtin", (string)product.Gtin);
            _writer.Write("IsGiftCard", entity.IsGiftCard.ToString());
            _writer.Write("GiftCardTypeId", entity.GiftCardTypeId.ToString());
            _writer.Write("RequireOtherProducts", entity.RequireOtherProducts.ToString());
            _writer.Write("RequiredProductIds", entity.RequiredProductIds);
            _writer.Write("AutomaticallyAddRequiredProducts", entity.AutomaticallyAddRequiredProducts.ToString());
            _writer.Write("IsDownload", entity.IsDownload.ToString());
            _writer.Write("DownloadId", entity.DownloadId.ToString());
            _writer.Write("UnlimitedDownloads", entity.UnlimitedDownloads.ToString());
            _writer.Write("MaxNumberOfDownloads", entity.MaxNumberOfDownloads.ToString());
            _writer.Write("DownloadExpirationDays", entity.DownloadExpirationDays.HasValue ? entity.DownloadExpirationDays.Value.ToString() : "");
            _writer.Write("DownloadActivationTypeId", entity.DownloadActivationTypeId.ToString());
            _writer.Write("HasSampleDownload", entity.HasSampleDownload.ToString());
            _writer.Write("SampleDownloadId", entity.SampleDownloadId.HasValue ? entity.SampleDownloadId.Value.ToString() : "");
            _writer.Write("HasUserAgreement", entity.HasUserAgreement.ToString());
            _writer.Write("UserAgreementText", entity.UserAgreementText);
            _writer.Write("IsRecurring", entity.IsRecurring.ToString());
            _writer.Write("RecurringCycleLength", entity.RecurringCycleLength.ToString());
            _writer.Write("RecurringCyclePeriodId", entity.RecurringCyclePeriodId.ToString());
            _writer.Write("RecurringTotalCycles", entity.RecurringTotalCycles.ToString());
            _writer.Write("IsShipEnabled", entity.IsShipEnabled.ToString());
            _writer.Write("IsFreeShipping", entity.IsFreeShipping.ToString());
            _writer.Write("AdditionalShippingCharge", entity.AdditionalShippingCharge.ToString(_culture));
            _writer.Write("IsTaxExempt", entity.IsTaxExempt.ToString());
            _writer.Write("TaxCategoryId", entity.TaxCategoryId.ToString());
            _writer.Write("ManageInventoryMethodId", entity.ManageInventoryMethodId.ToString());
            _writer.Write("StockQuantity", entity.StockQuantity.ToString());
            _writer.Write("DisplayStockAvailability", entity.DisplayStockAvailability.ToString());
            _writer.Write("DisplayStockQuantity", entity.DisplayStockQuantity.ToString());
            _writer.Write("MinStockQuantity", entity.MinStockQuantity.ToString());
            _writer.Write("LowStockActivityId", entity.LowStockActivityId.ToString());
            _writer.Write("NotifyAdminForQuantityBelow", entity.NotifyAdminForQuantityBelow.ToString());
            _writer.Write("BackorderModeId", entity.BackorderModeId.ToString());
            _writer.Write("AllowBackInStockSubscriptions", entity.AllowBackInStockSubscriptions.ToString());
            _writer.Write("OrderMinimumQuantity", entity.OrderMinimumQuantity.ToString());
            _writer.Write("OrderMaximumQuantity", entity.OrderMaximumQuantity.ToString());
            _writer.Write("HideQuantityControl", entity.HideQuantityControl.ToString());
            _writer.Write("AllowedQuantities", entity.AllowedQuantities);
            _writer.Write("DisableBuyButton", entity.DisableBuyButton.ToString());
            _writer.Write("DisableWishlistButton", entity.DisableWishlistButton.ToString());
            _writer.Write("AvailableForPreOrder", entity.AvailableForPreOrder.ToString());
            _writer.Write("CallForPrice", entity.CallForPrice.ToString());
            _writer.Write("Price", entity.Price.ToString(_culture));
            _writer.Write("OldPrice", entity.OldPrice.ToString(_culture));
            _writer.Write("ProductCost", entity.ProductCost.ToString(_culture));
            _writer.Write("SpecialPrice", entity.SpecialPrice.HasValue ? entity.SpecialPrice.Value.ToString(_culture) : "");
            _writer.Write("SpecialPriceStartDateTimeUtc", entity.SpecialPriceStartDateTimeUtc.HasValue ? entity.SpecialPriceStartDateTimeUtc.Value.ToString(_culture) : "");
            _writer.Write("SpecialPriceEndDateTimeUtc", entity.SpecialPriceEndDateTimeUtc.HasValue ? entity.SpecialPriceEndDateTimeUtc.Value.ToString(_culture) : "");
            _writer.Write("CustomerEntersPrice", entity.CustomerEntersPrice.ToString());
            _writer.Write("MinimumCustomerEnteredPrice", entity.MinimumCustomerEnteredPrice.ToString(_culture));
            _writer.Write("MaximumCustomerEnteredPrice", entity.MaximumCustomerEnteredPrice.ToString(_culture));
            _writer.Write("HasTierPrices", entity.HasTierPrices.ToString());
            _writer.Write("HasDiscountsApplied", entity.HasDiscountsApplied.ToString());
            _writer.Write("Weight", ((decimal)product.Weight).ToString(_culture));
            _writer.Write("Length", ((decimal)product.Length).ToString(_culture));
            _writer.Write("Width", ((decimal)product.Width).ToString(_culture));
            _writer.Write("Height", ((decimal)product.Height).ToString(_culture));
            _writer.Write("AvailableStartDateTimeUtc", entity.AvailableStartDateTimeUtc.HasValue ? entity.AvailableStartDateTimeUtc.Value.ToString(_culture) : "");
            _writer.Write("AvailableEndDateTimeUtc", entity.AvailableEndDateTimeUtc.HasValue ? entity.AvailableEndDateTimeUtc.Value.ToString(_culture) : "");
            _writer.Write("BasePriceEnabled", ((bool)product.BasePriceEnabled).ToString());
            _writer.Write("BasePriceMeasureUnit", (string)product.BasePriceMeasureUnit);
            _writer.Write("BasePriceAmount", basePriceAmount.HasValue ? basePriceAmount.Value.ToString(_culture) : "");
            _writer.Write("BasePriceBaseAmount", basePriceBaseAmount.HasValue ? basePriceBaseAmount.Value.ToString() : "");
            _writer.Write("BasePriceHasValue", ((bool)product.BasePriceHasValue).ToString());
            _writer.Write("BasePriceInfo", (string)product._BasePriceInfo);
            _writer.Write("VisibleIndividually", entity.VisibleIndividually.ToString());
            _writer.Write("DisplayOrder", entity.DisplayOrder.ToString());
            _writer.Write("BundleTitleText", entity.BundleTitleText);
            _writer.Write("BundlePerItemPricing", entity.BundlePerItemPricing.ToString());
            _writer.Write("BundlePerItemShipping", entity.BundlePerItemShipping.ToString());
            _writer.Write("BundlePerItemShoppingCart", entity.BundlePerItemShoppingCart.ToString());
            _writer.Write("LowestAttributeCombinationPrice", lowestAttributeCombinationPrice.HasValue ? lowestAttributeCombinationPrice.Value.ToString(_culture) : "");
            _writer.Write("IsEsd", entity.IsEsd.ToString());
            _writer.Write("CustomsTariffNumber", entity.CustomsTariffNumber);

            WriteLocalized(product);

            WriteDeliveryTime(product.DeliveryTime, "DeliveryTime");

            WriteQuantityUnit(product.QuantityUnit, "QuantityUnit");

            WriteCountry(product.CountryOfOrigin, "CountryOfOrigin");

            if (product.AppliedDiscounts != null)
            {
                _writer.WriteStartElement("AppliedDiscounts");
                foreach (dynamic discount in product.AppliedDiscounts)
                {
                    Discount entityDiscount = discount.Entity;

                    _writer.WriteStartElement("AppliedDiscount");
                    _writer.Write("Id", entityDiscount.Id.ToString());
                    _writer.Write("Name", (string)discount.Name);
                    _writer.Write("DiscountTypeId", entityDiscount.DiscountTypeId.ToString());
                    _writer.Write("UsePercentage", entityDiscount.UsePercentage.ToString());
                    _writer.Write("DiscountPercentage", entityDiscount.DiscountPercentage.ToString(_culture));
                    _writer.Write("DiscountAmount", entityDiscount.DiscountAmount.ToString(_culture));
                    _writer.Write("StartDateUtc", entityDiscount.StartDateUtc.HasValue ? entityDiscount.StartDateUtc.Value.ToString(_culture) : "");
                    _writer.Write("EndDateUtc", entityDiscount.EndDateUtc.HasValue ? entityDiscount.EndDateUtc.Value.ToString(_culture) : "");
                    _writer.Write("RequiresCouponCode", entityDiscount.RequiresCouponCode.ToString());
                    _writer.Write("CouponCode", entityDiscount.CouponCode);
                    _writer.Write("DiscountLimitationId", entityDiscount.DiscountLimitationId.ToString());
                    _writer.Write("LimitationTimes", entityDiscount.LimitationTimes.ToString());
                    _writer.WriteEndElement();                  // AppliedDiscount
                }
                _writer.WriteEndElement();                      // AppliedDiscounts
            }

            if (product.TierPrices != null)
            {
                _writer.WriteStartElement("TierPrices");
                foreach (dynamic tierPrice in product.TierPrices)
                {
                    TierPrice entityTierPrice = tierPrice.Entity;

                    _writer.WriteStartElement("TierPrice");
                    _writer.Write("Id", entityTierPrice.Id.ToString());
                    _writer.Write("ProductId", entityTierPrice.ProductId.ToString());
                    _writer.Write("StoreId", entityTierPrice.StoreId.ToString());
                    _writer.Write("CustomerRoleId", entityTierPrice.CustomerRoleId.HasValue ? entityTierPrice.CustomerRoleId.Value.ToString() : "");
                    _writer.Write("Quantity", entityTierPrice.Quantity.ToString());
                    _writer.Write("Price", entityTierPrice.Price.ToString(_culture));
                    _writer.Write("CalculationMethod", ((int)entityTierPrice.CalculationMethod).ToString());
                    _writer.WriteEndElement();  // TierPrice
                }
                _writer.WriteEndElement();      // TierPrices
            }

            if (product.ProductTags != null)
            {
                _writer.WriteStartElement("ProductTags");
                foreach (dynamic tag in product.ProductTags)
                {
                    _writer.WriteStartElement("ProductTag");
                    _writer.Write("Id", ((int)tag.Id).ToString());
                    _writer.Write("Name", (string)tag.Name);
                    _writer.Write("SeName", (string)tag.SeName);

                    WriteLocalized(tag);

                    _writer.WriteEndElement();                  // ProductTag
                }
                _writer.WriteEndElement();                      // ProductTags
            }

            if (product.ProductAttributes != null)
            {
                _writer.WriteStartElement("ProductAttributes");
                foreach (dynamic pva in product.ProductAttributes)
                {
                    ProductVariantAttribute entityPva = pva.Entity;

                    _writer.WriteStartElement("ProductAttribute");
                    _writer.Write("Id", entityPva.Id.ToString());
                    _writer.Write("TextPrompt", (string)pva.TextPrompt);
                    _writer.Write("IsRequired", entityPva.IsRequired.ToString());
                    _writer.Write("AttributeControlTypeId", entityPva.AttributeControlTypeId.ToString());
                    _writer.Write("DisplayOrder", entityPva.DisplayOrder.ToString());

                    _writer.WriteStartElement("Attribute");
                    _writer.Write("Id", ((int)pva.Attribute.Id).ToString());
                    _writer.Write("Alias", (string)pva.Attribute.Alias);
                    _writer.Write("Name", (string)pva.Attribute.Name);
                    _writer.Write("Description", (string)pva.Attribute.Description);

                    WriteLocalized(pva.Attribute);

                    _writer.WriteEndElement();                          // Attribute

                    _writer.WriteStartElement("AttributeValues");
                    foreach (dynamic value in pva.Attribute.Values)
                    {
                        ProductVariantAttributeValue entityPvav = value.Entity;

                        _writer.WriteStartElement("AttributeValue");
                        _writer.Write("Id", entityPvav.Id.ToString());
                        _writer.Write("Alias", (string)value.Alias);
                        _writer.Write("Name", (string)value.Name);
                        _writer.Write("Color", (string)value.Color);
                        _writer.Write("PriceAdjustment", ((decimal)value.PriceAdjustment).ToString(_culture));
                        _writer.Write("WeightAdjustment", ((decimal)value.WeightAdjustment).ToString(_culture));
                        _writer.Write("IsPreSelected", entityPvav.IsPreSelected.ToString());
                        _writer.Write("DisplayOrder", entityPvav.DisplayOrder.ToString());
                        _writer.Write("ValueTypeId", entityPvav.ValueTypeId.ToString());
                        _writer.Write("LinkedProductId", entityPvav.LinkedProductId.ToString());
                        _writer.Write("Quantity", entityPvav.Quantity.ToString());

                        WriteLocalized(value);

                        _writer.WriteEndElement();              // AttributeValue
                    }
                    _writer.WriteEndElement();                  // AttributeValues

                    _writer.WriteEndElement();                  // ProductAttribute
                }
                _writer.WriteEndElement();                      // ProductAttributes
            }

            if (product.ProductAttributeCombinations != null)
            {
                _writer.WriteStartElement("ProductAttributeCombinations");
                foreach (dynamic combination in product.ProductAttributeCombinations)
                {
                    ProductVariantAttributeCombination entityPvac = combination.Entity;

                    _writer.WriteStartElement("ProductAttributeCombination");
                    _writer.Write("Id", entityPvac.Id.ToString());
                    _writer.Write("StockQuantity", entityPvac.StockQuantity.ToString());
                    _writer.Write("AllowOutOfStockOrders", entityPvac.AllowOutOfStockOrders.ToString());
                    _writer.Write("AttributesXml", entityPvac.AttributesXml);
                    _writer.Write("Sku", entityPvac.Sku);
                    _writer.Write("Gtin", entityPvac.Gtin);
                    _writer.Write("ManufacturerPartNumber", entityPvac.ManufacturerPartNumber);
                    _writer.Write("Price", entityPvac.Price.HasValue ? entityPvac.Price.Value.ToString(_culture) : "");
                    _writer.Write("Length", entityPvac.Length.HasValue ? entityPvac.Length.Value.ToString(_culture) : "");
                    _writer.Write("Width", entityPvac.Width.HasValue ? entityPvac.Width.Value.ToString(_culture) : "");
                    _writer.Write("Height", entityPvac.Height.HasValue ? entityPvac.Height.Value.ToString(_culture) : "");
                    _writer.Write("BasePriceAmount", entityPvac.BasePriceAmount.HasValue ? entityPvac.BasePriceAmount.Value.ToString(_culture) : "");
                    _writer.Write("BasePriceBaseAmount", entityPvac.BasePriceBaseAmount.HasValue ? entityPvac.BasePriceBaseAmount.Value.ToString() : "");
                    _writer.Write("AssignedPictureIds", entityPvac.AssignedPictureIds);
                    _writer.Write("DeliveryTimeId", entityPvac.DeliveryTimeId.HasValue ? entityPvac.DeliveryTimeId.Value.ToString() : "");
                    _writer.Write("IsActive", entityPvac.IsActive.ToString());

                    WriteDeliveryTime(combination.DeliveryTime, "DeliveryTime");

                    WriteQuantityUnit(combination.QuantityUnit, "QuantityUnit");

                    _writer.WriteStartElement("Pictures");
                    foreach (dynamic assignedPicture in combination.Pictures)
                    {
                        WritePicture(assignedPicture, "Picture");
                    }
                    _writer.WriteEndElement();             // Pictures

                    _writer.WriteEndElement();             // ProductAttributeCombination
                }
                _writer.WriteEndElement();                 // ProductAttributeCombinations
            }

            if (product.ProductPictures != null)
            {
                _writer.WriteStartElement("ProductPictures");
                foreach (dynamic productPicture in product.ProductPictures)
                {
                    ProductPicture entityProductPicture = productPicture.Entity;

                    _writer.WriteStartElement("ProductPicture");
                    _writer.Write("Id", entityProductPicture.Id.ToString());
                    _writer.Write("DisplayOrder", entityProductPicture.DisplayOrder.ToString());

                    WritePicture(productPicture.Picture, "Picture");

                    _writer.WriteEndElement();                  // ProductPicture
                }
                _writer.WriteEndElement();                      // ProductPictures
            }

            if (product.ProductCategories != null)
            {
                _writer.WriteStartElement("ProductCategories");
                foreach (dynamic productCategory in product.ProductCategories)
                {
                    ProductCategory entityProductCategory = productCategory.Entity;

                    _writer.WriteStartElement("ProductCategory");
                    _writer.Write("Id", entityProductCategory.Id.ToString());
                    _writer.Write("DisplayOrder", entityProductCategory.DisplayOrder.ToString());
                    _writer.Write("IsFeaturedProduct", entityProductCategory.IsFeaturedProduct.ToString());

                    WriteCategory(productCategory.Category, "Category");

                    _writer.WriteEndElement();                  // ProductCategory
                }
                _writer.WriteEndElement();                      // ProductCategories
            }

            if (product.ProductManufacturers != null)
            {
                _writer.WriteStartElement("ProductManufacturers");
                foreach (dynamic productManu in product.ProductManufacturers)
                {
                    ProductManufacturer entityProductManu = productManu.Entity;

                    _writer.WriteStartElement("ProductManufacturer");

                    _writer.Write("Id", entityProductManu.Id.ToString());
                    _writer.Write("DisplayOrder", entityProductManu.DisplayOrder.ToString());
                    _writer.Write("IsFeaturedProduct", entityProductManu.IsFeaturedProduct.ToString());

                    WriteManufacturer(productManu.Manufacturer, "Manufacturer");

                    _writer.WriteEndElement();                  // ProductManufacturer
                }
                _writer.WriteEndElement();                      // ProductManufacturers
            }

            if (product.ProductSpecificationAttributes != null)
            {
                _writer.WriteStartElement("ProductSpecificationAttributes");
                foreach (dynamic psa in product.ProductSpecificationAttributes)
                {
                    ProductSpecificationAttribute entityPsa = psa.Entity;

                    _writer.WriteStartElement("ProductSpecificationAttribute");

                    _writer.Write("Id", entityPsa.Id.ToString());
                    _writer.Write("ProductId", entityPsa.ProductId.ToString());
                    _writer.Write("SpecificationAttributeOptionId", entityPsa.SpecificationAttributeOptionId.ToString());
                    _writer.Write("AllowFiltering", entityPsa.AllowFiltering.ToString());
                    _writer.Write("ShowOnProductPage", entityPsa.ShowOnProductPage.ToString());
                    _writer.Write("DisplayOrder", entityPsa.DisplayOrder.ToString());

                    dynamic option = psa.SpecificationAttributeOption;
                    SpecificationAttributeOption entitySao = option.Entity;
                    SpecificationAttribute       entitySa  = option.SpecificationAttribute.Entity;

                    _writer.WriteStartElement("SpecificationAttributeOption");
                    _writer.Write("Id", entitySao.Id.ToString());
                    _writer.Write("SpecificationAttributeId", entitySao.SpecificationAttributeId.ToString());
                    _writer.Write("DisplayOrder", entitySao.DisplayOrder.ToString());
                    _writer.Write("Name", (string)option.Name);
                    _writer.Write("Alias", (string)option.Alias);

                    WriteLocalized(option);

                    _writer.WriteStartElement("SpecificationAttribute");
                    _writer.Write("Id", entitySa.Id.ToString());
                    _writer.Write("Name", (string)option.SpecificationAttribute.Name);
                    _writer.Write("Alias", (string)option.SpecificationAttribute.Alias);
                    _writer.Write("DisplayOrder", entitySa.DisplayOrder.ToString());
                    _writer.Write("AllowFiltering", entitySa.AllowFiltering.ToString());
                    _writer.Write("ShowOnProductPage", entitySa.ShowOnProductPage.ToString());
                    _writer.Write("FacetSorting", ((int)entitySa.FacetSorting).ToString());
                    _writer.Write("FacetTemplateHint", ((int)entitySa.FacetTemplateHint).ToString());

                    WriteLocalized(option.SpecificationAttribute);

                    _writer.WriteEndElement();                  // SpecificationAttribute
                    _writer.WriteEndElement();                  // SpecificationAttributeOption

                    _writer.WriteEndElement();                  // ProductSpecificationAttribute
                }
                _writer.WriteEndElement();                      // ProductSpecificationAttributes
            }

            if (product.ProductBundleItems != null)
            {
                _writer.WriteStartElement("ProductBundleItems");
                foreach (dynamic bundleItem in product.ProductBundleItems)
                {
                    ProductBundleItem entityPbi = bundleItem.Entity;

                    _writer.WriteStartElement("ProductBundleItem");
                    _writer.Write("Id", entityPbi.Id.ToString());
                    _writer.Write("ProductId", entityPbi.ProductId.ToString());
                    _writer.Write("BundleProductId", entityPbi.BundleProductId.ToString());
                    _writer.Write("Quantity", entityPbi.Quantity.ToString());
                    _writer.Write("Discount", entityPbi.Discount.HasValue ? entityPbi.Discount.Value.ToString(_culture) : "");
                    _writer.Write("DiscountPercentage", entityPbi.DiscountPercentage.ToString());
                    _writer.Write("Name", (string)bundleItem.Name);
                    _writer.Write("ShortDescription", (string)bundleItem.ShortDescription);
                    _writer.Write("FilterAttributes", entityPbi.FilterAttributes.ToString());
                    _writer.Write("HideThumbnail", entityPbi.HideThumbnail.ToString());
                    _writer.Write("Visible", entityPbi.Visible.ToString());
                    _writer.Write("Published", entityPbi.Published.ToString());
                    _writer.Write("DisplayOrder", ((int)bundleItem.DisplayOrder).ToString());
                    _writer.Write("CreatedOnUtc", entityPbi.CreatedOnUtc.ToString(_culture));
                    _writer.Write("UpdatedOnUtc", entityPbi.UpdatedOnUtc.ToString(_culture));

                    WriteLocalized(bundleItem);

                    _writer.WriteEndElement();                  // ProductBundleItem
                }
                _writer.WriteEndElement();                      // ProductBundleItems
            }

            if (node.HasValue())
            {
                _writer.WriteEndElement();
            }
        }
Ejemplo n.º 2
0
 public static ProductSpecificationAttribute ToEntity(this ProductSpecificationAttributeDTO dto, ProductSpecificationAttribute entity)
 {
     return(Mapper.Map(dto, entity));
 }
Ejemplo n.º 3
0
        private void CreateExampleProducts(CcSettings settings)
        {
            var product = new Product
            {
                ProductType       = ProductType.SimpleProduct,
                ProductTemplateId = _productTemplateService.GetAllProductTemplates().First().Id,
                Name = "Business Card",
                VisibleIndividually  = true,
                ShowOnHomePage       = true,
                AllowCustomerReviews = true,
                Price        = 10,
                Published    = true,
                CreatedOnUtc = DateTime.Now,
                UpdatedOnUtc = DateTime.Now,
                AvailableStartDateTimeUtc = new DateTime(2015, 6, 1),
                OrderMaximumQuantity      = 100,
                OrderMinimumQuantity      = 1
            };

            _productService.InsertProduct(product);
            if (settings.SampleProducts == null)
            {
                settings.SampleProducts = new List <int>();
            }
            settings.SampleProducts.Add(product.Id);

            var productDefinition = new ProductSpecificationAttribute
            {
                AllowFiltering = true,
                AttributeType  = SpecificationAttributeType.CustomText,
                SpecificationAttributeOptionId = settings.EditorDefinitionSpecificationOptionId,
                CustomValue       = @"Default editor",
                DisplayOrder      = 0,
                ProductId         = product.Id,
                ShowOnProductPage = false
            };

            _specificationAttributeService.InsertProductSpecificationAttribute(productDefinition);

            var editorConfiguration = new ProductSpecificationAttribute
            {
                AllowFiltering = true,
                AttributeType  = SpecificationAttributeType.CustomText,
                SpecificationAttributeOptionId = settings.EditorConfigurationSpecificationOptionId,
                CustomValue       = @"Default config",
                DisplayOrder      = 0,
                ProductId         = product.Id,
                ShowOnProductPage = false
            };

            _specificationAttributeService.InsertProductSpecificationAttribute(editorConfiguration);

            #region product attribute mappings
            _productAttributeService.InsertProductAttributeMapping(new ProductAttributeMapping
            {
                AttributeControlType = AttributeControlType.TextBox,
                DefaultValue         = "",
                DisplayOrder         = 100,
                ProductId            = product.Id,
                ProductAttributeId   = settings.CcIdAttributeId
            });
            #endregion

            _urlRecordService.SaveSlug(product, product.ValidateSeName(product.Name, product.Name, true), 0);
        }
        public JsonResult SaveCcAttribute(int productId, string attributeName, string attributeValue)
        {
            try
            {
                var specificationAttributes = _specificationAttributeService.GetProductSpecificationAttributes(productId);
                var prodSpecAttr            = specificationAttributes.FirstOrDefault(
                    x => x.SpecificationAttributeOption.SpecificationAttribute.Name == attributeName);
                if (prodSpecAttr == null)
                {
                    var allSpecAttrs = _specificationAttributeService.GetSpecificationAttributes();
                    var currSpecAttr = allSpecAttrs.FirstOrDefault(x => x.Name == attributeName);
                    if (currSpecAttr == null)
                    {
                        currSpecAttr              = new SpecificationAttribute();
                        currSpecAttr.Name         = attributeName;
                        currSpecAttr.DisplayOrder = 0;
                        _specificationAttributeService.InsertSpecificationAttribute(currSpecAttr);

                        var newAttrOption = new SpecificationAttributeOption();
                        newAttrOption.SpecificationAttribute = currSpecAttr;
                        newAttrOption.Name         = attributeName;
                        newAttrOption.DisplayOrder = 0;
                        _specificationAttributeService.InsertSpecificationAttributeOption(newAttrOption);
                    }

                    prodSpecAttr = new ProductSpecificationAttribute
                    {
                        AttributeType = SpecificationAttributeType.CustomText,
                        ProductId     = productId,
                        SpecificationAttributeOptionId = currSpecAttr.SpecificationAttributeOptions.First().Id,
                        DisplayOrder      = 0,
                        ShowOnProductPage = false,
                        AllowFiltering    = false,
                        CustomValue       = attributeValue,
                    };
                    _specificationAttributeService.InsertProductSpecificationAttribute(prodSpecAttr);
                }
                else
                {
                    prodSpecAttr.CustomValue       = attributeValue;
                    prodSpecAttr.ShowOnProductPage = false;
                    _specificationAttributeService.UpdateProductSpecificationAttribute(prodSpecAttr);
                }

                var productAttributeMappings = _productAttributeService.GetProductAttributeMappingsByProductId(productId);
                foreach (var attrId in _ccService.GetCcAttrIds())
                {
                    if (productAttributeMappings.All(map => map.ProductAttributeId != attrId))
                    {
                        _productAttributeService.InsertProductAttributeMapping(new ProductAttributeMapping
                        {
                            AttributeControlType = AttributeControlType.TextBox,
                            DefaultValue         = "",
                            DisplayOrder         = 100,
                            ProductId            = productId,
                            ProductAttributeId   = attrId
                        });
                    }
                }

                return(Json(new { status = "success" }));
            }
            catch (Exception ex)
            {
                var message = ex.InnerException != null ? ex.InnerException.Message : "";
                return(Json(new { status = "error", message = ex.Message + " " + message }));
            }
        }
Ejemplo n.º 5
0
 public static ProductSpecificationAttributeDTO ToModel(this ProductSpecificationAttribute entity)
 {
     return(Mapper.Map <ProductSpecificationAttribute, ProductSpecificationAttributeDTO>(entity));
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product to copy</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <returns>Product copy</returns>
        public virtual Product CopyProduct(Product product, string newName, bool isPublished, bool copyImages)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            if (String.IsNullOrEmpty(newName))
            {
                throw new ArgumentException("Product name is required");
            }


            Product productCopy = null;

            //uncomment this line to support transactions
            //using (var scope = new System.Transactions.TransactionScope())
            {
                // product
                productCopy = new Product()
                {
                    Name                 = newName,
                    ShortDescription     = product.ShortDescription,
                    FullDescription      = product.FullDescription,
                    ProductTemplateId    = product.ProductTemplateId,
                    AdminComment         = product.AdminComment,
                    ShowOnHomePage       = product.ShowOnHomePage,
                    MetaKeywords         = product.MetaKeywords,
                    MetaDescription      = product.MetaDescription,
                    MetaTitle            = product.MetaTitle,
                    AllowCustomerReviews = product.AllowCustomerReviews,
                    LimitedToStores      = product.LimitedToStores,
                    Published            = isPublished,
                    Deleted              = product.Deleted,
                    CreatedOnUtc         = DateTime.UtcNow,
                    UpdatedOnUtc         = DateTime.UtcNow
                };

                //validate search engine name
                _productService.InsertProduct(productCopy);

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

                var languages = _languageService.GetAllLanguages(true);

                //localization
                foreach (var lang in languages)
                {
                    var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(name))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
                    }

                    var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(shortDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
                    }

                    var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(fullDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
                    }

                    var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(metaKeywords))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
                    }

                    var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(metaDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
                    }

                    var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(metaTitle))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
                    }

                    //search engine name
                    _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
                }

                //product tags
                foreach (var productTag in product.ProductTags)
                {
                    productCopy.ProductTags.Add(productTag);
                }
                //ensure product is saved before updating totals
                _productService.UpdateProduct(product);
                foreach (var productTag in product.ProductTags)
                {
                    _productTagService.UpdateProductTagTotals(productTag);
                }

                // product pictures
                if (copyImages)
                {
                    foreach (var productPicture in product.ProductPictures)
                    {
                        var picture     = productPicture.Picture;
                        var pictureCopy = _pictureService.InsertPicture(
                            _pictureService.LoadPictureBinary(picture),
                            picture.MimeType,
                            _pictureService.GetPictureSeName(newName),
                            true);
                        _productService.InsertProductPicture(new ProductPicture()
                        {
                            ProductId    = productCopy.Id,
                            PictureId    = pictureCopy.Id,
                            DisplayOrder = productPicture.DisplayOrder
                        });
                    }
                }

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

                    _categoryService.InsertProductCategory(productCategoryCopy);
                }

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

                    _manufacturerService.InsertProductManufacturer(productManufacturerCopy);
                }

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

                // product <-> cross sells mappings
                foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
                {
                    _productService.InsertCrossSellProduct(
                        new CrossSellProduct()
                    {
                        ProductId1 = productCopy.Id,
                        ProductId2 = csProduct.ProductId2,
                    });
                }

                // product specifications
                foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
                {
                    var psaCopy = new ProductSpecificationAttribute()
                    {
                        ProductId = productCopy.Id,
                        SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                        AllowFiltering    = productSpecificationAttribute.AllowFiltering,
                        ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                        DisplayOrder      = productSpecificationAttribute.DisplayOrder
                    };
                    _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
                }

                //store mapping
                var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);
                foreach (var id in selectedStoreIds)
                {
                    _storeMappingService.InsertStoreMapping(productCopy, id);
                }

                // product variants
                var productVariants = product.ProductVariants;
                foreach (var productVariant in productVariants)
                {
                    CopyProductVariant(productVariant, productCopy.Id, productVariant.Name, productVariant.Published, copyImages);
                }

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

            return(productCopy);
        }
Ejemplo n.º 7
0
 public ProductSpecificationAttributeDto PrepareProductSpecificationAttributeDto(ProductSpecificationAttribute productSpecificationAttribute)
 {
     return(productSpecificationAttribute.ToDto());
 }
 /// <summary>
 /// Updates the product specification attribute mapping
 /// </summary>
 /// <param name="productSpecificationAttribute">Product specification attribute mapping</param>
 public virtual async Task UpdateProductSpecificationAttributeAsync(ProductSpecificationAttribute productSpecificationAttribute)
 {
     await _productSpecificationAttributeRepository.UpdateAsync(productSpecificationAttribute);
 }
Ejemplo n.º 9
0
 public PartialViewResult Delete(ProductSpecificationAttribute option)
 {
     return(PartialView(option));
 }
Ejemplo n.º 10
0
        public async Task <ActionResult> CallApi(ConfigurationModel model)
        {
            var storeScope      = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var mappingSettings = _settingService.LoadSetting <ProductMappingSettings>(storeScope);

            var tokenebay = EbayExtensions.GetToken();

            var categoryWorldBuy = _categoryMappingRecord.Table.Where(u => u.CategoryId == model.CategoryId && u.SourceId == (int)Source.Ebay).ToList();

            if (categoryWorldBuy != null)
            {
                foreach (var cateIds in categoryWorldBuy)
                {
                    var clientapi1 = new HttpClient();
                    clientapi1.BaseAddress = new Uri("https://api.ebay.com/");
                    clientapi1.DefaultRequestHeaders.Clear();
                    clientapi1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    clientapi1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenebay);
                    clientapi1.Timeout = TimeSpan.FromMinutes(60);

                    var getCategoryId = _affiliateEbayService.Get(cateIds.CategorySourceId).EbayId.ToString();

                    string str = "buy/browse/v1/item_summary/search?limit=200&category_ids=" + getCategoryId;
                    if (!string.IsNullOrEmpty(model.KeyWord))
                    {
                        str = str + "&q=" + model.KeyWord;
                    }

                    HttpResponseMessage Res1 = await clientapi1.GetAsync(str);

                    if (Res1.IsSuccessStatusCode)
                    {
                        var EmpResponse1 = Res1.Content.ReadAsStringAsync().Result;
                        var result1      = JsonConvert.DeserializeObject <SearchOutput>(EmpResponse1);

                        int temp  = int.Parse(result1.total);
                        int value = 0;
                        while (temp > 0)
                        {
                            str = str + "&offset=" + value;
                            HttpResponseMessage Res2 = await clientapi1.GetAsync(str);

                            if (Res2.IsSuccessStatusCode)
                            {
                                var EmpResponse2 = Res2.Content.ReadAsStringAsync().Result;
                                var result2      = JsonConvert.DeserializeObject <SearchOutput>(EmpResponse2);

                                if (result2.itemSummaries != null)
                                {
                                    foreach (var item in result2.itemSummaries)
                                    {
                                        var checkProduct = _affiliateEbayService.GetProductBySourceId(productSourceId: item.itemId, source: (int)Source.Ebay);
                                        if (checkProduct.Id == 0)
                                        {
                                            var clientapi = new HttpClient();
                                            clientapi.BaseAddress = new Uri("https://api.ebay.com/");
                                            clientapi.DefaultRequestHeaders.Clear();
                                            clientapi.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                                            clientapi.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenebay);
                                            clientapi.Timeout = TimeSpan.FromMinutes(60);

                                            HttpResponseMessage Res = await clientapi.GetAsync("buy/browse/v1/item/" + item.itemId);

                                            if (Res.IsSuccessStatusCode)
                                            {
                                                var EmpResponse = Res.Content.ReadAsStringAsync().Result;
                                                var result      = JsonConvert.DeserializeObject <ProductModelApi>(EmpResponse);

                                                if (result.price != null)
                                                {
                                                    var price   = Convert.ToDecimal(result.price.value);
                                                    var product = new Product();
                                                    product.Name = result.title;
                                                    var currencyService = EngineContext.Current.Resolve <ICurrencyService>();
                                                    product.Price = Round(currencyService.ConvertToPrimaryStoreCurrency(price * (1 + mappingSettings.AdditionalCostPercent / 100), currencyService.GetCurrencyByCode("USD")), -3);
                                                    //if(result.marketingPrice == null)
                                                    //{
                                                    //    product.OldPrice = 0;
                                                    //}
                                                    //else
                                                    //{
                                                    //    if(result.marketingPrice.originalPrice == null)
                                                    //        product.OldPrice = 0;
                                                    //    else
                                                    //        product.OldPrice = Convert.ToDecimal(result.marketingPrice.originalPrice.value);
                                                    //}
                                                    product.ShortDescription = result.shortDescription;
                                                    product.FullDescription  = result.description;

                                                    product.VisibleIndividually         = true;
                                                    product.AllowCustomerReviews        = true;
                                                    product.UnlimitedDownloads          = true;
                                                    product.MaxNumberOfDownloads        = 10;
                                                    product.RecurringCycleLength        = 100;
                                                    product.RecurringTotalCycles        = 10;
                                                    product.RentalPriceLength           = 1;
                                                    product.IsShipEnabled               = true;
                                                    product.NotifyAdminForQuantityBelow = 1;
                                                    product.StockQuantity               = 1000;
                                                    product.OrderMaximumQuantity        = 1000;
                                                    product.OrderMinimumQuantity        = 1;
                                                    product.CreatedOnUtc = DateTime.UtcNow;
                                                    product.UpdatedOnUtc = DateTime.UtcNow;
                                                    _productService.InsertProduct(product);

                                                    var productMapping = new ProductMapping();
                                                    productMapping.ProductSourceId   = item.itemId;
                                                    productMapping.ProductSourceLink = item.itemWebUrl;
                                                    productMapping.SourceId          = (int)Source.Ebay;
                                                    productMapping.ProductId         = product.Id;
                                                    productMapping.Price             = price;
                                                    _productMappingService.InsertProduct(productMapping);

                                                    // Thêm hình chính
                                                    var imageMain = result.image.imageUrl.Split('?')[0];
                                                    System.Drawing.Image imageKey = EbayExtensions.DownloadImage(imageMain);
                                                    if (imageKey != null)
                                                    {
                                                        var contentTypeMain         = "";
                                                        var vendorPictureBinaryMain = EbayExtensions.ImageToByte(imageKey);

                                                        var fileExtensionMain = Path.GetExtension(imageMain);
                                                        if (!String.IsNullOrEmpty(fileExtensionMain))
                                                        {
                                                            fileExtensionMain = fileExtensionMain.ToLowerInvariant();
                                                        }
                                                        if (String.IsNullOrEmpty(contentTypeMain))
                                                        {
                                                            switch (fileExtensionMain)
                                                            {
                                                            case ".bmp":
                                                                contentTypeMain = MimeTypes.ImageBmp;
                                                                break;

                                                            case ".gif":
                                                                contentTypeMain = MimeTypes.ImageGif;
                                                                break;

                                                            case ".jpeg":
                                                            case ".jpg":
                                                            case ".jpe":
                                                            case ".jfif":
                                                            case ".pjpeg":
                                                            case ".pjp":
                                                                contentTypeMain = MimeTypes.ImageJpeg;
                                                                break;

                                                            case ".png":
                                                                contentTypeMain = MimeTypes.ImagePng;
                                                                break;

                                                            case ".tiff":
                                                            case ".tif":
                                                                contentTypeMain = MimeTypes.ImageTiff;
                                                                break;

                                                            default:
                                                                break;
                                                            }
                                                        }
                                                        var pictureMain = _pictureService.InsertPicture(vendorPictureBinaryMain, contentTypeMain, null);
                                                        _productService.InsertProductPicture(new ProductPicture
                                                        {
                                                            PictureId    = pictureMain.Id,
                                                            ProductId    = product.Id,
                                                            DisplayOrder = 0,
                                                        });
                                                    }

                                                    int display = 1;
                                                    if (result.additionalImages != null)
                                                    {
                                                        foreach (var ite in result.additionalImages)
                                                        {
                                                            var ima = ite.imageUrl.Split('?')[0];
                                                            System.Drawing.Image image = EbayExtensions.DownloadImage(ima);
                                                            if (image != null)
                                                            {
                                                                var contentType         = "";
                                                                var vendorPictureBinary = EbayExtensions.ImageToByte(image);

                                                                var fileExtension = Path.GetExtension(ima);
                                                                if (!String.IsNullOrEmpty(fileExtension))
                                                                {
                                                                    fileExtension = fileExtension.ToLowerInvariant();
                                                                }
                                                                if (String.IsNullOrEmpty(contentType))
                                                                {
                                                                    switch (fileExtension)
                                                                    {
                                                                    case ".bmp":
                                                                        contentType = MimeTypes.ImageBmp;
                                                                        break;

                                                                    case ".gif":
                                                                        contentType = MimeTypes.ImageGif;
                                                                        break;

                                                                    case ".jpeg":
                                                                    case ".jpg":
                                                                    case ".jpe":
                                                                    case ".jfif":
                                                                    case ".pjpeg":
                                                                    case ".pjp":
                                                                        contentType = MimeTypes.ImageJpeg;
                                                                        break;

                                                                    case ".png":
                                                                        contentType = MimeTypes.ImagePng;
                                                                        break;

                                                                    case ".tiff":
                                                                    case ".tif":
                                                                        contentType = MimeTypes.ImageTiff;
                                                                        break;

                                                                    default:
                                                                        break;
                                                                    }
                                                                }
                                                                var picture = _pictureService.InsertPicture(vendorPictureBinary, contentType, null);
                                                                _productService.InsertProductPicture(new ProductPicture
                                                                {
                                                                    PictureId    = picture.Id,
                                                                    ProductId    = product.Id,
                                                                    DisplayOrder = display++,
                                                                });
                                                            }
                                                        }
                                                    }

                                                    //Product specification attributes
                                                    if (result.localizedAspects != null)
                                                    {
                                                        foreach (var attributes in result.localizedAspects)
                                                        {
                                                            var getAttribute                 = _affiliateEbayService.GetSpecificationAttributeByName(attributes.name);
                                                            var specificationAttribute       = new SpecificationAttribute();
                                                            var specificationAttributeOption = new SpecificationAttributeOption();
                                                            if (getAttribute == null)
                                                            {
                                                                specificationAttribute.Name         = attributes.name;
                                                                specificationAttribute.DisplayOrder = 0;
                                                                _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute);

                                                                specificationAttributeOption.DisplayOrder             = 0;
                                                                specificationAttributeOption.ColorSquaresRgb          = null;
                                                                specificationAttributeOption.Name                     = attributes.value;
                                                                specificationAttributeOption.SpecificationAttributeId = specificationAttribute.Id;
                                                                _specificationAttributeService.InsertSpecificationAttributeOption(specificationAttributeOption);
                                                            }

                                                            var productSpecificationAttribute = new ProductSpecificationAttribute();
                                                            productSpecificationAttribute.AttributeTypeId = (int)SpecificationAttributeType.CustomText;
                                                            if (getAttribute == null)
                                                            {
                                                                productSpecificationAttribute.SpecificationAttributeOptionId = specificationAttributeOption.Id;
                                                            }
                                                            else
                                                            {
                                                                var options = _specificationAttributeService.GetSpecificationAttributeOptionsBySpecificationAttribute(getAttribute.Id);
                                                                productSpecificationAttribute.SpecificationAttributeOptionId = options.FirstOrDefault().Id;
                                                            }
                                                            productSpecificationAttribute.ProductId         = product.Id;
                                                            productSpecificationAttribute.CustomValue       = attributes.value;
                                                            productSpecificationAttribute.AllowFiltering    = false;
                                                            productSpecificationAttribute.ShowOnProductPage = true;
                                                            productSpecificationAttribute.DisplayOrder      = 1;
                                                            _specificationAttributeService.InsertProductSpecificationAttribute(productSpecificationAttribute);
                                                        }
                                                    }

                                                    //categories
                                                    SaveCategoryMappings(product, new List <int>()
                                                    {
                                                        model.CategoryId
                                                    });
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            value = value + 200;
                            temp  = temp - 200;
                        }
                    }
                }
                SuccessNotification(_localizationService.GetResource("Admin.Catalog.Products.Added"));
            }
            else
            {
                ErrorNotification(_localizationService.GetResource("Plugins.AffiliateEbay.CallApi.Error"));
            }

            return(CallApi());
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Inserts a product specification attribute mapping
 /// </summary>
 /// <param name="productSpecificationAttribute">Product specification attribute mapping</param>
 public virtual async Task InsertProductSpecificationAttributeAsync(ProductSpecificationAttribute productSpecificationAttribute)
 {
     await _productSpecificationAttributeRepository.InsertAsync(productSpecificationAttribute);
 }
Ejemplo n.º 12
0
        internal static void Import(КоммерческаяИнформация source,
                                    ICategoryService categoryService,
                                    ISpecificationAttributeService specificationAttributeService,
                                    IManufacturerService manufacturerService,
                                    IProductService productService,
                                    IUrlRecordService urlRecordService,
                                    IPictureService pictureService,
                                    List <Category> categories,
                                    Dictionary <string, int> categoryMappings,
                                    List <SpecificationAttribute> attributes,
                                    Dictionary <string, int> attributesMappings,
                                    List <Manufacturer> manufacturers,
                                    Dictionary <string, int> manufacturersMappings,
                                    string mappingsFile,
                                    string logFile,
                                    ImportCatalogSettings importSettings)

        {
            logFile.Log("Начало импорта товаров");
            var stats = new[] { 0, 0 };

            var mappings = File.Exists(mappingsFile)
                ? JsonConvert.DeserializeObject <Dictionary <string, int> >(File.ReadAllText(mappingsFile))
                : new Dictionary <string, int>();

            foreach (var prod in source.Каталог.Товары)
            {
                try
                {
                    var product = mappings.ContainsKey(prod.Ид)
                        ? productService.GetProductById(mappings[prod.Ид])
                        : null;

                    var deleted = prod.Статус == "Удален";
                    if (product == null)
                    {
                        product = new Product
                        {
                            CreatedOnUtc        = DateTime.Now,
                            UpdatedOnUtc        = DateTime.Now,
                            ProductType         = ProductType.SimpleProduct,
                            ProductTemplateId   = 1,
                            VisibleIndividually = true,
                            Name                 = prod.Наименование,
                            Sku                  = prod.Артикул,
                            ShortDescription     = prod.Описание,
                            FullDescription      = prod.Описание,
                            AllowCustomerReviews = true,
                            Deleted              = deleted,
                            Published            = !deleted,
                            OrderMinimumQuantity = 1,
                            OrderMaximumQuantity = 10000
                        };
                        productService.InsertProduct(product);
                        var seName = product.ValidateSeName(null, product.Name, true);
                        urlRecordService.SaveSlug(product, seName, 0);
                        //logFile.Log($"Новый товар {product.Name} ({product.Id}): {prod.Ид}");
                        stats[0]++;
                    }
                    else
                    {
                        if (!importSettings.UpdateExisting)
                        {
                            //logFile.Log($"Пропущен товар {product.Name} ({product.Id}): {prod.Ид}");
                            stats[1]++;
                            continue;
                        }
                        product.UpdatedOnUtc = DateTime.Now;
                        product.Deleted      = deleted;
                        product.Published    = !deleted;
                        productService.UpdateProduct(product);
                        //logFile.Log($"Обновлен товар {product.Name} ({product.Id}): {prod.Ид}");
                        stats[1]++;
                    }
                    mappings[prod.Ид] = product.Id;

                    if (importSettings.OverwriteManufacturers)
                    {
                        foreach (var manufacturer in product.ProductManufacturers.ToList())
                        {
                            manufacturerService.DeleteProductManufacturer(manufacturer);
                        }
                    }
                    if (prod.Изготовитель != null && manufacturersMappings.ContainsKey(prod.Изготовитель.Ид))
                    {
                        var manufacturerId = manufacturersMappings[prod.Изготовитель.Ид];
                        var manufacturer   = product.ProductManufacturers.FirstOrDefault(m => m.ManufacturerId == manufacturerId);
                        if (manufacturer == null)
                        {
                            manufacturer = new ProductManufacturer
                            {
                                ProductId      = product.Id,
                                ManufacturerId = manufacturerId
                            };
                            manufacturerService.InsertProductManufacturer(manufacturer);
                            product.ProductManufacturers.Add(manufacturer);
                        }
                    }

                    if (importSettings.OverwriteCategories)
                    {
                        foreach (var category in product.ProductCategories.ToList())
                        {
                            categoryService.DeleteProductCategory(category);
                        }
                    }
                    if (prod.Группы != null && categoryMappings.ContainsKey(prod.Группы.Ид))
                    {
                        var categoryId = categoryMappings[prod.Группы.Ид];
                        var category   = product.ProductCategories.FirstOrDefault(c => c.CategoryId == categoryId);
                        if (category == null)
                        {
                            category = new ProductCategory
                            {
                                ProductId  = product.Id,
                                CategoryId = categoryId
                            };
                            categoryService.InsertProductCategory(category);
                            product.ProductCategories.Add(category);
                        }
                    }

                    if (importSettings.ImportSpecificationAttributes && prod.ЗначенияСвойств != null)
                    {
                        foreach (var attr in prod.ЗначенияСвойств)
                        {
                            if (attributesMappings.ContainsKey(attr.Ид))
                            {
                                var emptyOptionKey = $"{attr.Ид}.";
                                if (attributesMappings.ContainsKey(emptyOptionKey))
                                {
                                    var option = product.ProductSpecificationAttributes
                                                 .FirstOrDefault(a => a.SpecificationAttributeOptionId == attributesMappings[emptyOptionKey]);
                                    if (option == null)
                                    {
                                        option = new ProductSpecificationAttribute
                                        {
                                            ProductId         = product.Id,
                                            ShowOnProductPage = true,
                                            AllowFiltering    = false,
                                            SpecificationAttributeOptionId = attributesMappings[emptyOptionKey],
                                            AttributeType = SpecificationAttributeType.CustomText,
                                            CustomValue   = attr.Значение
                                        };
                                        specificationAttributeService.InsertProductSpecificationAttribute(option);
                                        product.ProductSpecificationAttributes.Add(option);
                                    }
                                    else if (option.CustomValue != attr.Значение)
                                    {
                                        option.CustomValue = attr.Значение;
                                        specificationAttributeService.UpdateProductSpecificationAttribute(option);
                                    }
                                }
                                else
                                {
                                    var optionKey = $"{attr.Ид}.{attr.Значение}";

                                    var option = product.ProductSpecificationAttributes
                                                 .FirstOrDefault(o => o.SpecificationAttributeOptionId == attributesMappings[optionKey]);
                                    if (option == null)
                                    {
                                        var attribute = attributes.FirstOrDefault(a => a.Id == attributesMappings[attr.Ид]);
                                        var optionIds = attribute.SpecificationAttributeOptions.Select(o => o.Id);
                                        var options   = product.ProductSpecificationAttributes
                                                        .Where(a => optionIds.Contains(a.SpecificationAttributeOptionId)).ToList();
                                        if (options != null && options.Count > 0)
                                        {
                                            foreach (var opt in options)
                                            {
                                                product.ProductSpecificationAttributes.Remove(opt);
                                                specificationAttributeService.DeleteProductSpecificationAttribute(opt);
                                            }
                                        }

                                        option = new ProductSpecificationAttribute
                                        {
                                            ProductId         = product.Id,
                                            ShowOnProductPage = true,
                                            AllowFiltering    = true,
                                            SpecificationAttributeOptionId = attributesMappings[optionKey],
                                            AttributeType = SpecificationAttributeType.Option
                                        };
                                        specificationAttributeService.InsertProductSpecificationAttribute(option);
                                        product.ProductSpecificationAttributes.Add(option);
                                    }
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(prod.Картинка))
                    {
                        // todo: compare with existing images
                        var picturePath = HttpContext.Current.Request.MapPath($"~/Content/{prod.Картинка}");
                        var picture     = LoadPicture(pictureService, picturePath, product.Name);
                        if (picture != null)
                        {
                            product.ProductPictures.Add(new ProductPicture
                            {
                                DisplayOrder = 1,
                                PictureId    = picture.Id,
                                ProductId    = product.Id
                            });
                        }
                    }

                    File.WriteAllText(mappingsFile, JsonConvert.SerializeObject(mappings, Formatting.Indented), Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    logFile.Log($"Ошибка при обработке товара {prod.Ид} ({prod.Наименование}): {ex}");
                }
            }

            logFile.Log($"Импорт товаров завершен. Добавлено: {stats[0]}. Обновлено: {stats[1]}.");
        }
 public JsonResult RemoveSpecification(ProductSpecificationAttribute attribute, int categoryId)
 {
     return(Json(_ecommerceSearchablePageAdminService.RemoveSpecificationFromHidden(attribute, categoryId)));
 }
Ejemplo n.º 14
0
 public void DeleteSpecificationAttribute(ProductSpecificationAttribute option)
 {
     _session.Transact(session => session.Delete(option));
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Creates a copy of product with all depended data
        /// </summary>
        /// <param name="productId">The product identifier</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <returns>Product entity</returns>
        public Product CopyProduct(int productId, string newName, bool isPublished, bool copyImages)
        {
            var product = _productService.GetProductById(productId);

            if (product == null)
            {
                throw new ArgumentException("No product found with the specified id", "productId");
            }

            Product productCopy = null;

            //uncomment this line to support transactions
            //using (var scope = new System.Transactions.TransactionScope())
            {
                // product
                productCopy = new Product()
                {
                    Name                 = newName,
                    ShortDescription     = product.ShortDescription,
                    FullDescription      = product.FullDescription,
                    ProductTemplateId    = product.ProductTemplateId,
                    AdminComment         = product.AdminComment,
                    ShowOnHomePage       = product.ShowOnHomePage,
                    MetaKeywords         = product.MetaKeywords,
                    MetaDescription      = product.MetaDescription,
                    MetaTitle            = product.MetaTitle,
                    AllowCustomerReviews = product.AllowCustomerReviews,
                    Published            = isPublished,
                    Deleted              = product.Deleted,
                    CreatedOnUtc         = DateTime.UtcNow,
                    UpdatedOnUtc         = DateTime.UtcNow
                };

                //validate search engine name
                _productService.InsertProduct(productCopy);

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

                var languages = _languageService.GetAllLanguages(true);

                //localization
                foreach (var lang in languages)
                {
                    var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(name))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
                    }

                    var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(shortDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
                    }

                    var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(fullDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
                    }

                    var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(metaKeywords))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
                    }

                    var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(metaDescription))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
                    }

                    var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                    if (!String.IsNullOrEmpty(metaTitle))
                    {
                        _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
                    }

                    //search engine name
                    _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
                }

                //product tags
                foreach (var productTag in product.ProductTags)
                {
                    productCopy.ProductTags.Add(productTag);
                }
                //ensure product is saved before updating totals
                _productService.UpdateProduct(product);
                foreach (var productTag in product.ProductTags)
                {
                    _productTagService.UpdateProductTagTotals(productTag);
                }

                // product pictures
                if (copyImages)
                {
                    foreach (var productPicture in product.ProductPictures)
                    {
                        var picture     = productPicture.Picture;
                        var pictureCopy = _pictureService.InsertPicture(
                            _pictureService.LoadPictureBinary(picture),
                            picture.MimeType,
                            _pictureService.GetPictureSeName(newName),
                            true);
                        _productService.InsertProductPicture(new ProductPicture()
                        {
                            ProductId    = productCopy.Id,
                            PictureId    = pictureCopy.Id,
                            DisplayOrder = productPicture.DisplayOrder
                        });
                    }
                }

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

                    _categoryService.InsertProductCategory(productCategoryCopy);
                }

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

                    _manufacturerService.InsertProductManufacturer(productManufacturerCopy);
                }

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

                // product <-> cross sells mappings
                foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
                {
                    _productService.InsertCrossSellProduct(
                        new CrossSellProduct()
                    {
                        ProductId1 = productCopy.Id,
                        ProductId2 = csProduct.ProductId2,
                    });
                }

                // product specifications
                foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
                {
                    var psaCopy = new ProductSpecificationAttribute()
                    {
                        ProductId = productCopy.Id,
                        SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                        AllowFiltering    = productSpecificationAttribute.AllowFiltering,
                        ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                        DisplayOrder      = productSpecificationAttribute.DisplayOrder
                    };
                    _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
                }

                // product variants
                var productVariants = product.ProductVariants;
                foreach (var productVariant in productVariants)
                {
                    // product variant picture
                    int pictureId = 0;
                    if (copyImages)
                    {
                        var picture = _pictureService.GetPictureById(productVariant.PictureId);
                        if (picture != null)
                        {
                            var pictureCopy = _pictureService.InsertPicture(
                                _pictureService.LoadPictureBinary(picture),
                                picture.MimeType,
                                _pictureService.GetPictureSeName(productVariant.Name),
                                true);
                            pictureId = pictureCopy.Id;
                        }
                    }

                    // product variant download & sample download
                    int downloadId       = productVariant.DownloadId;
                    int sampleDownloadId = productVariant.SampleDownloadId;
                    if (productVariant.IsDownload)
                    {
                        var download = _downloadService.GetDownloadById(productVariant.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 (productVariant.HasSampleDownload)
                        {
                            var sampleDownload = _downloadService.GetDownloadById(productVariant.SampleDownloadId);
                            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 variant
                    var productVariantCopy = new ProductVariant()
                    {
                        ProductId                 = productCopy.Id,
                        Name                      = productVariant.Name,
                        Sku                       = productVariant.Sku,
                        Description               = productVariant.Description,
                        AdminComment              = productVariant.AdminComment,
                        ManufacturerPartNumber    = productVariant.ManufacturerPartNumber,
                        Gtin                      = productVariant.Gtin,
                        IsGiftCard                = productVariant.IsGiftCard,
                        GiftCardType              = productVariant.GiftCardType,
                        RequireOtherProducts      = productVariant.RequireOtherProducts,
                        RequiredProductVariantIds = productVariant.RequiredProductVariantIds,
                        AutomaticallyAddRequiredProductVariants = productVariant.AutomaticallyAddRequiredProductVariants,
                        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,
                        RecurringCycleLength          = productVariant.RecurringCycleLength,
                        RecurringCyclePeriod          = productVariant.RecurringCyclePeriod,
                        RecurringTotalCycles          = productVariant.RecurringTotalCycles,
                        IsShipEnabled                 = productVariant.IsShipEnabled,
                        IsFreeShipping                = productVariant.IsFreeShipping,
                        AdditionalShippingCharge      = productVariant.AdditionalShippingCharge,
                        IsTaxExempt                   = productVariant.IsTaxExempt,
                        TaxCategoryId                 = productVariant.TaxCategoryId,
                        ManageInventoryMethod         = productVariant.ManageInventoryMethod,
                        StockQuantity                 = productVariant.StockQuantity,
                        DisplayStockAvailability      = productVariant.DisplayStockAvailability,
                        DisplayStockQuantity          = productVariant.DisplayStockQuantity,
                        MinStockQuantity              = productVariant.MinStockQuantity,
                        LowStockActivityId            = productVariant.LowStockActivityId,
                        NotifyAdminForQuantityBelow   = productVariant.NotifyAdminForQuantityBelow,
                        BackorderMode                 = productVariant.BackorderMode,
                        AllowBackInStockSubscriptions = productVariant.AllowBackInStockSubscriptions,
                        OrderMinimumQuantity          = productVariant.OrderMinimumQuantity,
                        OrderMaximumQuantity          = productVariant.OrderMaximumQuantity,
                        AllowedQuantities             = productVariant.AllowedQuantities,
                        DisableBuyButton              = productVariant.DisableBuyButton,
                        DisableWishlistButton         = productVariant.DisableWishlistButton,
                        CallForPrice                  = productVariant.CallForPrice,
                        Price        = productVariant.Price,
                        OldPrice     = productVariant.OldPrice,
                        ProductCost  = productVariant.ProductCost,
                        SpecialPrice = productVariant.SpecialPrice,
                        SpecialPriceStartDateTimeUtc = productVariant.SpecialPriceStartDateTimeUtc,
                        SpecialPriceEndDateTimeUtc   = productVariant.SpecialPriceEndDateTimeUtc,
                        CustomerEntersPrice          = productVariant.CustomerEntersPrice,
                        MinimumCustomerEnteredPrice  = productVariant.MinimumCustomerEnteredPrice,
                        MaximumCustomerEnteredPrice  = productVariant.MaximumCustomerEnteredPrice,
                        Weight    = productVariant.Weight,
                        Length    = productVariant.Length,
                        Width     = productVariant.Width,
                        Height    = productVariant.Height,
                        PictureId = pictureId,
                        AvailableStartDateTimeUtc = productVariant.AvailableStartDateTimeUtc,
                        AvailableEndDateTimeUtc   = productVariant.AvailableEndDateTimeUtc,
                        Published    = productVariant.Published,
                        Deleted      = productVariant.Deleted,
                        DisplayOrder = productVariant.DisplayOrder,
                        CreatedOnUtc = DateTime.UtcNow,
                        UpdatedOnUtc = DateTime.UtcNow
                    };

                    _productService.InsertProductVariant(productVariantCopy);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productVariant.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(productVariantCopy, x => x.Name, name, lang.Id);
                        }

                        var description = productVariant.GetLocalized(x => x.Description, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(description))
                        {
                            _localizedEntityService.SaveLocalizedValue(productVariantCopy, x => x.Description, description, lang.Id);
                        }
                    }

                    // product variant <-> attributes mappings
                    var associatedAttributes      = new Dictionary <int, int>();
                    var associatedAttributeValues = new Dictionary <int, int>();
                    foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductVariantId(productVariant.Id))
                    {
                        var productVariantAttributeCopy = new ProductVariantAttribute()
                        {
                            ProductVariantId       = productVariantCopy.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,
                                PriceAdjustment  = productVariantAttributeValue.PriceAdjustment,
                                WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                                IsPreSelected    = productVariantAttributeValue.IsPreSelected,
                                DisplayOrder     = productVariantAttributeValue.DisplayOrder
                            };
                            _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);
                                }
                            }
                        }
                    }
                    foreach (var combination in _productAttributeService.GetAllProductVariantAttributeCombinations(productVariant.Id))
                    {
                        //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()
                        {
                            ProductVariantId      = productVariantCopy.Id,
                            AttributesXml         = newAttributesXml,
                            StockQuantity         = combination.StockQuantity,
                            AllowOutOfStockOrders = combination.AllowOutOfStockOrders
                        };
                        _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy);
                    }

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

                    // product variant <-> discounts mapping
                    foreach (var discount in productVariant.AppliedDiscounts)
                    {
                        productVariantCopy.AppliedDiscounts.Add(discount);
                        _productService.UpdateProductVariant(productVariantCopy);
                    }


                    //update "HasTierPrices" and "HasDiscountsApplied" properties
                    _productService.UpdateHasTierPricesProperty(productVariantCopy);
                    _productService.UpdateHasDiscountsApplied(productVariantCopy);
                }

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

            return(productCopy);
        }
Ejemplo n.º 16
0
 public RedirectToRouteResult Delete_POST(ProductSpecificationAttribute option)
 {
     _productOptionManager.DeleteSpecificationAttribute(option);
     return(RedirectToAction("Index"));
 }
Ejemplo n.º 17
0
 public static ProductSpecificationAttributeDto ToDto(this ProductSpecificationAttribute productSpecificationAttribute)
 {
     return(productSpecificationAttribute.MapTo <ProductSpecificationAttribute, ProductSpecificationAttributeDto>());
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Inserts a product specification attribute mapping
 /// </summary>
 /// <param name="productSpecificationAttribute">Product specification attribute mapping</param>
 public virtual void InsertProductSpecificationAttribute(ProductSpecificationAttribute productSpecificationAttribute)
 {
     _productSpecificationAttributeRepository.Insert(productSpecificationAttribute);
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product to copy</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
        /// <returns>Product copy</returns>
        public virtual Product CopyProduct(Product product, string newName,
                                           bool isPublished = true, bool copyImages = true, bool copyAssociatedProducts = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            if (String.IsNullOrEmpty(newName))
            {
                throw new ArgumentException("Product name is required");
            }

            //product download & sample download
            int downloadId       = product.DownloadId;
            int sampleDownloadId = product.SampleDownloadId;

            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);
                    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
            var productCopy = new Product
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                VendorId             = product.VendorId,
                ProductTemplateId    = product.ProductTemplateId,
                AdminComment         = product.AdminComment,
                ShowOnHomePage       = product.ShowOnHomePage,
                MetaKeywords         = product.MetaKeywords,
                MetaDescription      = product.MetaDescription,
                MetaTitle            = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores      = product.LimitedToStores,
                Sku = product.Sku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin                             = product.Gtin,
                IsGiftCard                       = product.IsGiftCard,
                GiftCardType                     = product.GiftCardType,
                OverriddenGiftCardAmount         = product.OverriddenGiftCardAmount,
                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,
                IsRental                         = product.IsRental,
                RentalPriceLength                = product.RentalPriceLength,
                RentalPricePeriod                = product.RentalPricePeriod,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                ShipSeparately                   = product.ShipSeparately,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                DeliveryDateId                   = product.DeliveryDateId,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                IsTelecommunicationsOrBroadcastingOrElectronicServices = product.IsTelecommunicationsOrBroadcastingOrElectronicServices,
                ManageInventoryMethod         = product.ManageInventoryMethod,
                UseMultipleWarehouses         = product.UseMultipleWarehouses,
                WarehouseId                   = product.WarehouseId,
                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,
                AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations,
                DisableBuyButton      = product.DisableBuyButton,
                DisableWishlistButton = product.DisableWishlistButton,
                AvailableForPreOrder  = product.AvailableForPreOrder,
                PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc,
                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,
                BasepriceEnabled             = product.BasepriceEnabled,
                BasepriceAmount           = product.BasepriceAmount,
                BasepriceUnitId           = product.BasepriceUnitId,
                BasepriceBaseAmount       = product.BasepriceBaseAmount,
                BasepriceBaseUnitId       = product.BasepriceBaseUnitId,
                MarkAsNew                 = product.MarkAsNew,
                MarkAsNewStartDateTimeUtc = product.MarkAsNewStartDateTimeUtc,
                MarkAsNewEndDateTimeUtc   = product.MarkAsNewEndDateTimeUtc,
                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 = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow
            };

            //validate search engine name
            _productService.InsertProduct(productCopy);

            //search engine name
            _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

            var languages = _languageService.GetAllLanguages(true);

            //localization
            foreach (var lang in languages)
            {
                var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                if (!String.IsNullOrEmpty(name))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
                }

                var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(shortDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
                }

                var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(fullDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
                }

                var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaKeywords))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
                }

                var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
                }

                var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaTitle))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
                }

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
            }

            //product tags
            foreach (var productTag in product.ProductTags)
            {
                productCopy.ProductTags.Add(productTag);
            }
            _productService.UpdateProduct(productCopy);

            //product pictures
            //variable to store original and new picture identifiers
            var originalNewPictureIdentifiers = new Dictionary <int, int>();

            if (copyImages)
            {
                foreach (var productPicture in product.ProductPictures)
                {
                    var picture     = productPicture.Picture;
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(newName),
                        picture.AltAttribute,
                        picture.TitleAttribute);
                    _productService.InsertProductPicture(new ProductPicture
                    {
                        ProductId    = productCopy.Id,
                        PictureId    = pictureCopy.Id,
                        DisplayOrder = productPicture.DisplayOrder
                    });
                    originalNewPictureIdentifiers.Add(picture.Id, pictureCopy.Id);
                }
            }

            // product <-> warehouses mappings
            foreach (var pwi in product.ProductWarehouseInventory)
            {
                var pwiCopy = new ProductWarehouseInventory
                {
                    ProductId        = productCopy.Id,
                    WarehouseId      = pwi.WarehouseId,
                    StockQuantity    = pwi.StockQuantity,
                    ReservedQuantity = 0,
                };

                productCopy.ProductWarehouseInventory.Add(pwiCopy);
            }
            _productService.UpdateProduct(productCopy);

            // 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,
                    AttributeTypeId = productSpecificationAttribute.AttributeTypeId,
                    SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                    CustomValue       = productSpecificationAttribute.CustomValue,
                    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 productAttributeMapping in _productAttributeService.GetProductAttributeMappingsByProductId(product.Id))
            {
                var productAttributeMappingCopy = new ProductAttributeMapping
                {
                    ProductId                       = productCopy.Id,
                    ProductAttributeId              = productAttributeMapping.ProductAttributeId,
                    TextPrompt                      = productAttributeMapping.TextPrompt,
                    IsRequired                      = productAttributeMapping.IsRequired,
                    AttributeControlTypeId          = productAttributeMapping.AttributeControlTypeId,
                    DisplayOrder                    = productAttributeMapping.DisplayOrder,
                    ValidationMinLength             = productAttributeMapping.ValidationMinLength,
                    ValidationMaxLength             = productAttributeMapping.ValidationMaxLength,
                    ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions,
                    ValidationFileMaximumSize       = productAttributeMapping.ValidationFileMaximumSize,
                    DefaultValue                    = productAttributeMapping.DefaultValue,
                    //UNDONE copy ConditionAttributeXml (we should replace attribute IDs with new values)
                };
                _productAttributeService.InsertProductAttributeMapping(productAttributeMappingCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productAttributeMapping.Id, productAttributeMappingCopy.Id);

                // product attribute values
                var productAttributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id);
                foreach (var productAttributeValue in productAttributeValues)
                {
                    int attributeValuePictureId = 0;
                    if (originalNewPictureIdentifiers.ContainsKey(productAttributeValue.PictureId))
                    {
                        attributeValuePictureId = originalNewPictureIdentifiers[productAttributeValue.PictureId];
                    }
                    var attributeValueCopy = new ProductAttributeValue
                    {
                        ProductAttributeMappingId = productAttributeMappingCopy.Id,
                        AttributeValueTypeId      = productAttributeValue.AttributeValueTypeId,
                        AssociatedProductId       = productAttributeValue.AssociatedProductId,
                        Name             = productAttributeValue.Name,
                        ColorSquaresRgb  = productAttributeValue.ColorSquaresRgb,
                        PriceAdjustment  = productAttributeValue.PriceAdjustment,
                        WeightAdjustment = productAttributeValue.WeightAdjustment,
                        Cost             = productAttributeValue.Cost,
                        Quantity         = productAttributeValue.Quantity,
                        IsPreSelected    = productAttributeValue.IsPreSelected,
                        DisplayOrder     = productAttributeValue.DisplayOrder,
                        PictureId        = attributeValuePictureId,
                    };
                    _productAttributeService.InsertProductAttributeValue(attributeValueCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productAttributeValue.Id, attributeValueCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(attributeValueCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }
            //attribute combinations
            foreach (var combination in _productAttributeService.GetAllProductAttributeCombinations(product.Id))
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml        = "";
                var    parsedProductAttributes = _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml);
                foreach (var oldAttribute in parsedProductAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldAttribute.Id))
                    {
                        var newAttribute = _productAttributeService.GetProductAttributeMappingById(associatedAttributes[oldAttribute.Id]);
                        if (newAttribute != null)
                        {
                            var oldAttributeValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldAttribute.Id);
                            foreach (var oldAttributeValueStr in oldAttributeValuesStr)
                            {
                                if (newAttribute.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldAttributeValue = int.Parse(oldAttributeValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldAttributeValue))
                                    {
                                        var newAttributeValue = _productAttributeService.GetProductAttributeValueById(associatedAttributeValues[oldAttributeValue]);
                                        if (newAttributeValue != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                           newAttribute, newAttributeValue.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                   newAttribute, oldAttributeValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductAttributeCombination
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,
                    Sku = combination.Sku,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Gtin                        = combination.Gtin,
                    OverriddenPrice             = combination.OverriddenPrice,
                    NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow
                };
                _productAttributeService.InsertProductAttributeCombination(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.UpdateHasDiscountsApplied(productCopy);


            //associated products
            if (copyAssociatedProducts)
            {
                var associatedProducts = _productService.GetAssociatedProducts(product.Id, showHidden: true);
                foreach (var associatedProduct in associatedProducts)
                {
                    var associatedProductCopy = CopyProduct(associatedProduct, string.Format("Copy of {0}", associatedProduct.Name),
                                                            isPublished, copyImages, false);
                    associatedProductCopy.ParentGroupedProductId = productCopy.Id;
                    _productService.UpdateProduct(productCopy);
                }
            }

            return(productCopy);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Updates the product specification attribute mapping
 /// </summary>
 /// <param name="productSpecificationAttribute">Product specification attribute mapping</param>
 public virtual void UpdateProductSpecificationAttribute(ProductSpecificationAttribute productSpecificationAttribute)
 {
     _productSpecificationAttributeRepository.Update(productSpecificationAttribute);
 }
Ejemplo n.º 21
0
        /// <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       = product.DownloadId;
            int?sampleDownloadId = product.SampleDownloadId;

            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,
                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);
                    _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
            foreach (var combination in _productAttributeService.GetAllProductVariantAttributeCombinations(product.Id))
            {
                //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()
                {
                    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);
        }
Ejemplo n.º 22
0
        // Value Spec Mod
        protected void rptrProductSpecification_DataBound(object sender, RepeaterItemEventArgs e)
        {
            ProductSpecificationAttribute theSpecAttribute = (ProductSpecificationAttribute)e.Item.DataItem;
            PlaceHolder specPH1 = (PlaceHolder)e.Item.FindControl("specPH1");

            switch (theSpecAttribute.SpecificationAttributeOption.Name)
            {
            case "Value":
            {
                Label theLabel = new Label();
                theLabel.Text = Server.HtmlEncode(theSpecAttribute.Value);
                specPH1.Controls.Add(theLabel);
                break;
            }

            case "Image":
            {
                Image theImage = new Image();
                theImage.ImageUrl = Server.HtmlEncode(theSpecAttribute.Value);
                specPH1.Controls.Add(theImage);
                break;
            }

            case "File":
            {
                // Just grab the file name and pull out the extension then
                // Show the proper file icon

                // Get just the file Name
                string[] file     = theSpecAttribute.Value.Split('/');
                string   fileName = file[file.Length - 1];

                // Get just the file extension
                string fileExt = fileName.Substring(fileName.Length - 4);

                // remove the file extension
                string fnNoExt = fileName.Replace(fileExt, "");


                // Show the correct file image based on the file extension
                switch (fileExt)
                {
                case ".pdf":
                {
                    Image extImage = new Image();
                    extImage.ImageUrl = Server.HtmlEncode("~/images/adobeFileIcon.jpg");
                    specPH1.Controls.Add(extImage);
                    break;
                }

                default:
                {
                    break;
                }
                }


                HyperLink theLink = new HyperLink();
                theLink.NavigateUrl = Server.HtmlEncode(theSpecAttribute.Value);
                theLink.Text        = Server.HtmlEncode(fnNoExt);
                specPH1.Controls.Add(theLink);
                break;
            }

            case "Html":
            {
                Literal theLiteral = new Literal();
                theLiteral.Text = theSpecAttribute.Value;
                specPH1.Controls.Add(theLiteral);
                break;
            }

            default:
            {
                // spec value is nops just add the label control to the placeholder, but pull the
                // value from the actual spec att option name
                Label theLabel = new Label();
                theLabel.Text = Server.HtmlEncode(theSpecAttribute.SpecificationAttributeOption.Name);
                specPH1.Controls.Add(theLabel);
                break;
            }
            }
        }