public ActionResult Create(Product product)
        {
            Product prd = new Product();
            ProductCategory prdCat = new ProductCategory();
            ProductPicture picProd = new ProductPicture();
            product.ProductGuid = Guid.NewGuid();
            _productRepository.Add(product);
            prd = _productRepository.GetProductByGuid(product.ProductGuid);

            prdCat.CategoryID = product.CategoryID;
            prdCat.ProductID = prd.ID;
            if (product.CategoryID != 0)
            {
                _categoryRepository.InsertProductCategory(prdCat);
            }

            picProd.PictureID = product.PictureID;
            picProd.ProductID = prd.ID;
            picProd.DisplayOrder = 1;

            if (picProd.PictureID != 0)
            {
                _productRepository.InsertProductPicture(picProd);
            }

            return RedirectToAction("List");
        }
예제 #2
0
 public ImageMappingDto PrepareProductPictureDTO(ProductPicture productPicture)
 {
     return(PrepareProductImageDto(productPicture));
 }
예제 #3
0
        ///<inheritdoc cref="ICustomLogoService.MergeProductPictureWithLogo"/>
        public (int, string) MergeProductPictureWithLogo(
            byte[] logoBinary,
            int logoId,
            int productId,
            string uploadType,
            decimal size,
            decimal opacity,
            decimal xCoordinate,
            decimal yCoordinate,
            int targetSize       = 0,
            string storeLocation = null,
            bool overrideThumb   = false)
        {
            //Get product picture
            ProductPicture productPicture = _productPictureModifierService.GetFirstProductPicture(productId)
                                            ?? throw new ArgumentException("Product does not have any images");

            Picture productImage = productPicture.Picture;

            //Load pictures binary
            byte[] productPictureBinary = LoadPictureBinary(productPicture.Picture);

            //Validate picture binary
            if (logoBinary == null || logoBinary.Length == 0)
            {
                throw new NullReferenceException("Logo is invalid");
            }
            if (productPictureBinary == null || productPictureBinary.Length == 0)
            {
                throw new NullReferenceException("Product Picture is invalid");
            }

            //Get thumb of the image requested
            int    storeId  = _storeContext.CurrentStore.Id;
            string lastPart = GetFileExtensionFromMimeType(productImage.MimeType);
            string thumbFileName;

            if (storeId == 1)
            {
                if (targetSize == 0)
                {
                    thumbFileName = !string.IsNullOrEmpty(productImage.SeoFilename)
                        ? $"{productImage.Id:0000000}_{uploadType}_{logoId}_{productImage.SeoFilename}.{lastPart}"
                        : $"{productImage.Id:0000000}_{uploadType}_{logoId}_.{lastPart}";
                }
                else
                {
                    thumbFileName = !string.IsNullOrEmpty(productImage.SeoFilename)
                        ? $"{productImage.Id:0000000}_{uploadType}_{logoId}_{productImage.SeoFilename}_{targetSize}.{lastPart}"
                        : $"{productImage.Id:0000000}_{uploadType}_{logoId}_{targetSize}.{lastPart}";
                }
            }
            else
            {
                if (targetSize == 0)
                {
                    thumbFileName = !String.IsNullOrEmpty(productImage.SeoFilename)
                        ? $"{productImage.Id:0000000}_{uploadType}_{logoId}_{productImage.SeoFilename}_{storeId}.{lastPart}"
                        : $"{productImage.Id:0000000}_{uploadType}_{logoId}_{storeId}.{lastPart}";
                }
                else
                {
                    thumbFileName = !String.IsNullOrEmpty(productImage.SeoFilename)
                        ? $"{productImage.Id:0000000}_{uploadType}_{logoId}_{productImage.SeoFilename}_{targetSize}_{storeId}.{lastPart}"
                        : $"{productImage.Id:0000000}_{uploadType}_{logoId}_{targetSize}_{storeId}.{lastPart}";
                }
            }

            string thumbFilePath = GetThumbLocalPath(thumbFileName);

            //the named mutex helps to avoid creating the same files in different threads,
            //and does not decrease performance significantly, because the code is blocked only for the specific file.
            var mergedImage = new Picture();

            using (var mutex = new Mutex(false, thumbFileName))
            {
                if (!GeneratedThumbExists(thumbFilePath, thumbFileName) || overrideThumb)
                {
                    mutex.WaitOne();

                    //check, if the file was created, while we were waiting for the release of the mutex.
                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName) || overrideThumb)
                    {
                        byte[] pictureBinaryResized;

                        //resizing required
                        if (targetSize != 0)
                        {
                            using (var stream = new MemoryStream(logoBinary))
                            {
                                //resizing required
                                using (var originImage = Image.Load(logoBinary, out var imageFormat))
                                {
                                    using (var originImageForProduct =
                                               Image.Load(productPictureBinary, out var productImageFormat))
                                    {
                                        Image <Rgba32> image = CombineImageWithLogo(
                                            originImageForProduct, originImage, size, opacity, xCoordinate, yCoordinate);

                                        originImageForProduct.Mutate(imageProcess => imageProcess.Resize(new ResizeOptions
                                        {
                                            Mode = ResizeMode.Max,
                                            Size = CalculateDimensions(originImageForProduct.Size(), targetSize)
                                        }));

                                        pictureBinaryResized = EncodeImage(image, imageFormat);
                                    }
                                }
                            }
                        }
                        else
                        {
                            using (var originImage = Image.Load(logoBinary, out var imageFormat))
                            {
                                using (var originImageForProduct = Image.Load(productPictureBinary, out var productImageFormat))
                                {
                                    Image <Rgba32> image = CombineImageWithLogo(
                                        originImageForProduct, originImage, size, opacity, xCoordinate, yCoordinate);
                                    pictureBinaryResized = EncodeImage(image, imageFormat);
                                }
                            }
                        }

                        SaveThumb(thumbFilePath, thumbFileName, productImage.MimeType, pictureBinaryResized);

                        //We need the new image saved in picture table for pre defined logo created by admin
                        if (uploadType == ProductPictureModifierUploadType.Predefined)
                        {
                            mergedImage = InsertPicture(
                                pictureBinaryResized,
                                productImage.MimeType,
                                productImage.SeoFilename,
                                ProductPictureModifierDefault.MergedPictureAlt,
                                ProductPictureModifierDefault.MergedPictureTitle);
                        }
                    }

                    mutex.ReleaseMutex();
                }
            }
            return(mergedImage.Id, GetThumbUrl(thumbFileName, storeLocation));
        }
예제 #4
0
        /// <summary>
        /// Import products from XLSX file
        /// </summary>
        /// <param name="stream">Stream</param>
        public virtual void ImportProductsFromXlsx(Stream stream)
        {
            // ok, we can run the real code of the sample now
            using (var xlPackage = new ExcelPackage(stream))
            {
                // get the first worksheet in the workbook
                var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
                if (worksheet == null)
                {
                    throw new NopException("No worksheet found");
                }

                //the columns
                var properties = new[]
                {
                    "ProductTypeId",
                    "ParentGroupedProductId",
                    "VisibleIndividually",
                    "Name",
                    "ShortDescription",
                    "FullDescription",
                    "VendorId",
                    "ProductTemplateId",
                    "ShowOnHomePage",
                    "MetaKeywords",
                    "MetaDescription",
                    "MetaTitle",
                    "SeName",
                    "AllowCustomerReviews",
                    "Published",
                    "SKU",
                    "ManufacturerPartNumber",
                    "Gtin",
                    "IsGiftCard",
                    "GiftCardTypeId",
                    "OverriddenGiftCardAmount",
                    "RequireOtherProducts",
                    "RequiredProductIds",
                    "AutomaticallyAddRequiredProducts",
                    "IsDownload",
                    "DownloadId",
                    "UnlimitedDownloads",
                    "MaxNumberOfDownloads",
                    "DownloadActivationTypeId",
                    "HasSampleDownload",
                    "SampleDownloadId",
                    "HasUserAgreement",
                    "UserAgreementText",
                    "IsRecurring",
                    "RecurringCycleLength",
                    "RecurringCyclePeriodId",
                    "RecurringTotalCycles",
                    "IsRental",
                    "RentalPriceLength",
                    "RentalPricePeriodId",
                    "IsShipEnabled",
                    "IsFreeShipping",
                    "ShipSeparately",
                    "AdditionalShippingCharge",
                    "DeliveryDateId",
                    "IsTaxExempt",
                    "TaxCategoryId",
                    "IsTelecommunicationsOrBroadcastingOrElectronicServices",
                    "ManageInventoryMethodId",
                    "UseMultipleWarehouses",
                    "WarehouseId",
                    "StockQuantity",
                    "DisplayStockAvailability",
                    "DisplayStockQuantity",
                    "MinStockQuantity",
                    "LowStockActivityId",
                    "NotifyAdminForQuantityBelow",
                    "BackorderModeId",
                    "AllowBackInStockSubscriptions",
                    "OrderMinimumQuantity",
                    "OrderMaximumQuantity",
                    "AllowedQuantities",
                    "AllowAddingOnlyExistingAttributeCombinations",
                    "DisableBuyButton",
                    "DisableWishlistButton",
                    "AvailableForPreOrder",
                    "PreOrderAvailabilityStartDateTimeUtc",
                    "CallForPrice",
                    "Price",
                    "OldPrice",
                    "ProductCost",
                    "SpecialPrice",
                    "SpecialPriceStartDateTimeUtc",
                    "SpecialPriceEndDateTimeUtc",
                    "CustomerEntersPrice",
                    "MinimumCustomerEnteredPrice",
                    "MaximumCustomerEnteredPrice",
                    "BasepriceEnabled",
                    "BasepriceAmount",
                    "BasepriceUnitId",
                    "BasepriceBaseAmount",
                    "BasepriceBaseUnitId",
                    "MarkAsNew",
                    "MarkAsNewStartDateTimeUtc",
                    "MarkAsNewEndDateTimeUtc",
                    "Weight",
                    "Length",
                    "Width",
                    "Height",
                    "CreatedOnUtc",
                    "CategoryIds",
                    "ManufacturerIds",
                    "Picture1",
                    "Picture2",
                    "Picture3"
                };


                int iRow = 2;
                while (true)
                {
                    bool allColumnsAreEmpty = true;
                    for (var i = 1; i <= properties.Length; i++)
                    {
                        if (worksheet.Cells[iRow, i].Value != null && !String.IsNullOrEmpty(worksheet.Cells[iRow, i].Value.ToString()))
                        {
                            allColumnsAreEmpty = false;
                            break;
                        }
                    }
                    if (allColumnsAreEmpty)
                    {
                        break;
                    }

                    int     productTypeId          = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTypeId")].Value);
                    int     parentGroupedProductId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ParentGroupedProductId")].Value);
                    bool    visibleIndividually    = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "VisibleIndividually")].Value);
                    string  name                 = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Name")].Value);
                    string  shortDescription     = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ShortDescription")].Value);
                    string  fullDescription      = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "FullDescription")].Value);
                    int     vendorId             = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "VendorId")].Value);
                    int     productTemplateId    = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTemplateId")].Value);
                    bool    showOnHomePage       = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShowOnHomePage")].Value);
                    string  metaKeywords         = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaKeywords")].Value);
                    string  metaDescription      = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaDescription")].Value);
                    string  metaTitle            = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaTitle")].Value);
                    string  seName               = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "SeName")].Value);
                    bool    allowCustomerReviews = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowCustomerReviews")].Value);
                    bool    published            = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "Published")].Value);
                    string  sku = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "SKU")].Value);
                    string  manufacturerPartNumber = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerPartNumber")].Value);
                    string  gtin                          = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Gtin")].Value);
                    bool    isGiftCard                    = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsGiftCard")].Value);
                    int     giftCardTypeId                = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "GiftCardTypeId")].Value);
                    decimal?overriddenGiftCardAmount      = null;
                    var     overriddenGiftCardAmountExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "OverriddenGiftCardAmount")].Value;
                    if (overriddenGiftCardAmountExcel != null)
                    {
                        overriddenGiftCardAmount = Convert.ToDecimal(overriddenGiftCardAmountExcel);
                    }
                    bool     requireOtherProducts             = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "RequireOtherProducts")].Value);
                    string   requiredProductIds               = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "RequiredProductIds")].Value);
                    bool     automaticallyAddRequiredProducts = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AutomaticallyAddRequiredProducts")].Value);
                    bool     isDownload               = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsDownload")].Value);
                    int      downloadId               = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadId")].Value);
                    bool     unlimitedDownloads       = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UnlimitedDownloads")].Value);
                    int      maxNumberOfDownloads     = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MaxNumberOfDownloads")].Value);
                    int      downloadActivationTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadActivationTypeId")].Value);
                    bool     hasSampleDownload        = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasSampleDownload")].Value);
                    int      sampleDownloadId         = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "SampleDownloadId")].Value);
                    bool     hasUserAgreement         = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasUserAgreement")].Value);
                    string   userAgreementText        = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "UserAgreementText")].Value);
                    bool     isRecurring              = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRecurring")].Value);
                    int      recurringCycleLength     = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCycleLength")].Value);
                    int      recurringCyclePeriodId   = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCyclePeriodId")].Value);
                    int      recurringTotalCycles     = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringTotalCycles")].Value);
                    bool     isRental                 = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRental")].Value);
                    int      rentalPriceLength        = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RentalPriceLength")].Value);
                    int      rentalPricePeriodId      = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RentalPricePeriodId")].Value);
                    bool     isShipEnabled            = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsShipEnabled")].Value);
                    bool     isFreeShipping           = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsFreeShipping")].Value);
                    bool     shipSeparately           = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShipSeparately")].Value);
                    decimal  additionalShippingCharge = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "AdditionalShippingCharge")].Value);
                    int      deliveryDateId           = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DeliveryDateId")].Value);
                    bool     isTaxExempt              = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTaxExempt")].Value);
                    int      taxCategoryId            = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "TaxCategoryId")].Value);
                    bool     isTelecommunicationsOrBroadcastingOrElectronicServices = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTelecommunicationsOrBroadcastingOrElectronicServices")].Value);
                    int      manageInventoryMethodId       = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ManageInventoryMethodId")].Value);
                    bool     useMultipleWarehouses         = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UseMultipleWarehouses")].Value);
                    int      warehouseId                   = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "WarehouseId")].Value);
                    int      stockQuantity                 = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "StockQuantity")].Value);
                    bool     displayStockAvailability      = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockAvailability")].Value);
                    bool     displayStockQuantity          = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockQuantity")].Value);
                    int      minStockQuantity              = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MinStockQuantity")].Value);
                    int      lowStockActivityId            = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "LowStockActivityId")].Value);
                    int      notifyAdminForQuantityBelow   = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "NotifyAdminForQuantityBelow")].Value);
                    int      backorderModeId               = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BackorderModeId")].Value);
                    bool     allowBackInStockSubscriptions = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowBackInStockSubscriptions")].Value);
                    int      orderMinimumQuantity          = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMinimumQuantity")].Value);
                    int      orderMaximumQuantity          = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMaximumQuantity")].Value);
                    string   allowedQuantities             = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowedQuantities")].Value);
                    bool     allowAddingOnlyExistingAttributeCombinations = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowAddingOnlyExistingAttributeCombinations")].Value);
                    bool     disableBuyButton      = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableBuyButton")].Value);
                    bool     disableWishlistButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableWishlistButton")].Value);
                    bool     availableForPreOrder  = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AvailableForPreOrder")].Value);
                    DateTime?preOrderAvailabilityStartDateTimeUtc      = null;
                    var      preOrderAvailabilityStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "PreOrderAvailabilityStartDateTimeUtc")].Value;
                    if (preOrderAvailabilityStartDateTimeUtcExcel != null)
                    {
                        preOrderAvailabilityStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(preOrderAvailabilityStartDateTimeUtcExcel));
                    }
                    bool    callForPrice      = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CallForPrice")].Value);
                    decimal price             = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Price")].Value);
                    decimal oldPrice          = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "OldPrice")].Value);
                    decimal productCost       = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductCost")].Value);
                    decimal?specialPrice      = null;
                    var     specialPriceExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPrice")].Value;
                    if (specialPriceExcel != null)
                    {
                        specialPrice = Convert.ToDecimal(specialPriceExcel);
                    }
                    DateTime?specialPriceStartDateTimeUtc      = null;
                    var      specialPriceStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceStartDateTimeUtc")].Value;
                    if (specialPriceStartDateTimeUtcExcel != null)
                    {
                        specialPriceStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceStartDateTimeUtcExcel));
                    }
                    DateTime?specialPriceEndDateTimeUtc      = null;
                    var      specialPriceEndDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceEndDateTimeUtc")].Value;
                    if (specialPriceEndDateTimeUtcExcel != null)
                    {
                        specialPriceEndDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceEndDateTimeUtcExcel));
                    }

                    bool     customerEntersPrice         = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CustomerEntersPrice")].Value);
                    decimal  minimumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MinimumCustomerEnteredPrice")].Value);
                    decimal  maximumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MaximumCustomerEnteredPrice")].Value);
                    bool     basepriceEnabled            = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceEnabled")].Value);
                    decimal  basepriceAmount             = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceAmount")].Value);
                    int      basepriceUnitId             = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceUnitId")].Value);
                    decimal  basepriceBaseAmount         = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceBaseAmount")].Value);
                    int      basepriceBaseUnitId         = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceBaseUnitId")].Value);
                    bool     markAsNew = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "MarkAsNew")].Value);
                    DateTime?markAsNewStartDateTimeUtc      = null;
                    var      markAsNewStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "MarkAsNewStartDateTimeUtc")].Value;
                    if (markAsNewStartDateTimeUtcExcel != null)
                    {
                        markAsNewStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(markAsNewStartDateTimeUtcExcel));
                    }
                    DateTime?markAsNewEndDateTimeUtc      = null;
                    var      markAsNewEndDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "MarkAsNewEndDateTimeUtc")].Value;
                    if (markAsNewEndDateTimeUtcExcel != null)
                    {
                        markAsNewEndDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(markAsNewEndDateTimeUtcExcel));
                    }
                    decimal  weight          = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Weight")].Value);
                    decimal  length          = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Length")].Value);
                    decimal  width           = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Width")].Value);
                    decimal  height          = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Height")].Value);
                    DateTime createdOnUtc    = DateTime.FromOADate(Convert.ToDouble(worksheet.Cells[iRow, GetColumnIndex(properties, "CreatedOnUtc")].Value));
                    string   categoryIds     = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "CategoryIds")].Value);
                    string   manufacturerIds = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerIds")].Value);
                    string   picture1        = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture1")].Value);
                    string   picture2        = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture2")].Value);
                    string   picture3        = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture3")].Value);



                    var  product    = _productService.GetProductBySku(sku);
                    bool newProduct = false;
                    if (product == null)
                    {
                        product    = new Product();
                        newProduct = true;
                    }
                    product.ProductTypeId          = productTypeId;
                    product.ParentGroupedProductId = parentGroupedProductId;
                    product.VisibleIndividually    = visibleIndividually;
                    product.Name                 = name;
                    product.ShortDescription     = shortDescription;
                    product.FullDescription      = fullDescription;
                    product.VendorId             = vendorId;
                    product.ProductTemplateId    = productTemplateId;
                    product.ShowOnHomePage       = showOnHomePage;
                    product.MetaKeywords         = metaKeywords;
                    product.MetaDescription      = metaDescription;
                    product.MetaTitle            = metaTitle;
                    product.AllowCustomerReviews = allowCustomerReviews;
                    product.Sku = sku;
                    product.ManufacturerPartNumber = manufacturerPartNumber;
                    product.Gtin                             = gtin;
                    product.IsGiftCard                       = isGiftCard;
                    product.GiftCardTypeId                   = giftCardTypeId;
                    product.OverriddenGiftCardAmount         = overriddenGiftCardAmount;
                    product.RequireOtherProducts             = requireOtherProducts;
                    product.RequiredProductIds               = requiredProductIds;
                    product.AutomaticallyAddRequiredProducts = automaticallyAddRequiredProducts;
                    product.IsDownload                       = isDownload;
                    product.DownloadId                       = downloadId;
                    product.UnlimitedDownloads               = unlimitedDownloads;
                    product.MaxNumberOfDownloads             = maxNumberOfDownloads;
                    product.DownloadActivationTypeId         = downloadActivationTypeId;
                    product.HasSampleDownload                = hasSampleDownload;
                    product.SampleDownloadId                 = sampleDownloadId;
                    product.HasUserAgreement                 = hasUserAgreement;
                    product.UserAgreementText                = userAgreementText;
                    product.IsRecurring                      = isRecurring;
                    product.RecurringCycleLength             = recurringCycleLength;
                    product.RecurringCyclePeriodId           = recurringCyclePeriodId;
                    product.RecurringTotalCycles             = recurringTotalCycles;
                    product.IsRental                         = isRental;
                    product.RentalPriceLength                = rentalPriceLength;
                    product.RentalPricePeriodId              = rentalPricePeriodId;
                    product.IsShipEnabled                    = isShipEnabled;
                    product.IsFreeShipping                   = isFreeShipping;
                    product.ShipSeparately                   = shipSeparately;
                    product.AdditionalShippingCharge         = additionalShippingCharge;
                    product.DeliveryDateId                   = deliveryDateId;
                    product.IsTaxExempt                      = isTaxExempt;
                    product.TaxCategoryId                    = taxCategoryId;
                    product.IsTelecommunicationsOrBroadcastingOrElectronicServices = isTelecommunicationsOrBroadcastingOrElectronicServices;
                    product.ManageInventoryMethodId       = manageInventoryMethodId;
                    product.UseMultipleWarehouses         = useMultipleWarehouses;
                    product.WarehouseId                   = warehouseId;
                    product.StockQuantity                 = stockQuantity;
                    product.DisplayStockAvailability      = displayStockAvailability;
                    product.DisplayStockQuantity          = displayStockQuantity;
                    product.MinStockQuantity              = minStockQuantity;
                    product.LowStockActivityId            = lowStockActivityId;
                    product.NotifyAdminForQuantityBelow   = notifyAdminForQuantityBelow;
                    product.BackorderModeId               = backorderModeId;
                    product.AllowBackInStockSubscriptions = allowBackInStockSubscriptions;
                    product.OrderMinimumQuantity          = orderMinimumQuantity;
                    product.OrderMaximumQuantity          = orderMaximumQuantity;
                    product.AllowedQuantities             = allowedQuantities;
                    product.AllowAddingOnlyExistingAttributeCombinations = allowAddingOnlyExistingAttributeCombinations;
                    product.DisableBuyButton      = disableBuyButton;
                    product.DisableWishlistButton = disableWishlistButton;
                    product.AvailableForPreOrder  = availableForPreOrder;
                    product.PreOrderAvailabilityStartDateTimeUtc = preOrderAvailabilityStartDateTimeUtc;
                    product.CallForPrice = callForPrice;
                    product.Price        = price;
                    product.OldPrice     = oldPrice;
                    product.ProductCost  = productCost;
                    product.SpecialPrice = specialPrice;
                    product.SpecialPriceStartDateTimeUtc = specialPriceStartDateTimeUtc;
                    product.SpecialPriceEndDateTimeUtc   = specialPriceEndDateTimeUtc;
                    product.CustomerEntersPrice          = customerEntersPrice;
                    product.MinimumCustomerEnteredPrice  = minimumCustomerEnteredPrice;
                    product.MaximumCustomerEnteredPrice  = maximumCustomerEnteredPrice;
                    product.BasepriceEnabled             = basepriceEnabled;
                    product.BasepriceAmount           = basepriceAmount;
                    product.BasepriceUnitId           = basepriceUnitId;
                    product.BasepriceBaseAmount       = basepriceBaseAmount;
                    product.BasepriceBaseUnitId       = basepriceBaseUnitId;
                    product.MarkAsNew                 = markAsNew;
                    product.MarkAsNewStartDateTimeUtc = markAsNewStartDateTimeUtc;
                    product.MarkAsNewEndDateTimeUtc   = markAsNewEndDateTimeUtc;
                    product.Weight       = weight;
                    product.Length       = length;
                    product.Width        = width;
                    product.Height       = height;
                    product.Published    = published;
                    product.CreatedOnUtc = createdOnUtc;
                    product.UpdatedOnUtc = DateTime.UtcNow;
                    if (newProduct)
                    {
                        _productService.InsertProduct(product);
                    }
                    else
                    {
                        _productService.UpdateProduct(product);
                    }

                    var _seName = product.ValidateSeName(seName, product.Name, true);
                    //search engine name
                    _urlRecordService.SaveSlug(product, _seName, 0);
                    product.SeName = _seName;
                    _productService.UpdateProduct(product);
                    //category mappings
                    if (!String.IsNullOrEmpty(categoryIds))
                    {
                        foreach (var id in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim())))
                        {
                            if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null)
                            {
                                //ensure that category exists
                                var category = _categoryService.GetCategoryById(id);
                                if (category != null)
                                {
                                    var productCategory = new ProductCategory
                                    {
                                        _id               = ObjectId.GenerateNewId().ToString(),
                                        Id                = product.ProductCategories.Count > 0 ? product.ProductCategories.Max(x => x.Id) + 1 : 1,
                                        ProductId         = product.Id,
                                        CategoryId        = category.Id,
                                        IsFeaturedProduct = false,
                                        DisplayOrder      = 1
                                    };
                                    _categoryService.InsertProductCategory(productCategory);
                                }
                            }
                        }
                    }

                    //manufacturer mappings
                    if (!String.IsNullOrEmpty(manufacturerIds))
                    {
                        foreach (var id in manufacturerIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim())))
                        {
                            if (product.ProductManufacturers.FirstOrDefault(x => x.ManufacturerId == id) == null)
                            {
                                //ensure that manufacturer exists
                                var manufacturer = _manufacturerService.GetManufacturerById(id);
                                if (manufacturer != null)
                                {
                                    var productManufacturer = new ProductManufacturer
                                    {
                                        _id               = ObjectId.GenerateNewId().ToString(),
                                        Id                = product.ProductManufacturers.Count > 0 ? product.ProductManufacturers.Max(x => x.Id) + 1 : 1,
                                        ProductId         = product.Id,
                                        ManufacturerId    = manufacturer.Id,
                                        IsFeaturedProduct = false,
                                        DisplayOrder      = 1
                                    };
                                    _manufacturerService.InsertProductManufacturer(productManufacturer);
                                }
                            }
                        }
                    }

                    //pictures
                    foreach (var picturePath in new[] { picture1, picture2, picture3 })
                    {
                        if (String.IsNullOrEmpty(picturePath))
                        {
                            continue;
                        }

                        var mimeType             = GetMimeTypeFromFilePath(picturePath);
                        var newPictureBinary     = File.ReadAllBytes(picturePath);
                        var pictureAlreadyExists = false;
                        if (!newProduct)
                        {
                            //compare with existing product pictures
                            var existingPictures = product.ProductPictures; // _pictureService.GetPicturesByProductId(product.Id);
                            foreach (var existingPicture in existingPictures)
                            {
                                var pp             = _pictureService.GetPictureById(existingPicture.PictureId);
                                var existingBinary = _pictureService.LoadPictureBinary(pp);
                                //picture binary after validation (like in database)
                                var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
                                if (existingBinary.SequenceEqual(validatedPictureBinary) || existingBinary.SequenceEqual(newPictureBinary))
                                {
                                    //the same picture content
                                    pictureAlreadyExists = true;
                                    break;
                                }
                            }
                        }

                        if (!pictureAlreadyExists)
                        {
                            var picture        = _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(name));
                            var productPicture = new ProductPicture
                            {
                                Id           = product.ProductPictures.Count > 0 ? product.ProductPictures.Max(x => x.Id) + 1 : 1,
                                _id          = ObjectId.GenerateNewId().ToString(),
                                PictureId    = picture.Id,
                                ProductId    = product.Id,
                                DisplayOrder = 1,
                            };
                            //product.ProductPictures.Add(;
                            _productService.InsertProductPicture(productPicture);
                        }
                    }

                    //update "HasTierPrices" and "HasDiscountsApplied" properties
                    _productService.UpdateHasTierPricesProperty(product.Id);
                    _productService.UpdateHasDiscountsApplied(product.Id);



                    //next product
                    iRow++;
                }
            }
        }
예제 #5
0
 public void Create(ProductPicture productPicture)
 {
     context.ProductPictures.Add(productPicture);
     context.SaveChanges();
 }
예제 #6
0
        /// <summary>
        /// Updates a product picture
        /// </summary>
        /// <param name="productPicture">Product picture</param>
        public virtual void UpdateProductPicture(ProductPicture productPicture)
        {
            Guard.NotNull(productPicture, nameof(productPicture));

            _productPictureRepository.Update(productPicture);
        }
예제 #7
0
        public void CreateProduct()
        {
            int    productID   = GetTopProductID() + 1;
            int    categoryID  = GetCategory();
            string brand       = GetBrand();
            string productName = GetName(categoryID, brand);

            Product product = new Product()
            {
                CategoryID         = categoryID,
                ProductName        = productName,
                Brand              = brand,
                UnitPrice          = GetPrice(),
                QtAvailable        = GetRandom(0, 100),
                ProducerCode       = GetCode(),
                ProductDescription = GetDescription()
            };

            __Context.Product.Add(product);
            if (!(__Context.SaveChanges() == 1))
            {
                Console.WriteLine($"An error occured while trying to save a Product type into the DB\n" +
                                  $"Product ID = {product.ProductID}");
            }
            else
            {
                Console.WriteLine($"> Product {product.ProductID} saved.");
            }

            List <ProductParameter> productParameters = new List <ProductParameter>();
            ProductPicture          productPicture    = new ProductPicture();

            switch (product.CategoryID)
            {
            case 1:     //CPU
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 1, ProductID = productID, ParameterDecimal = GetRandomDecimal(10), ParameterValueText = "GHz"
                });
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 2, ProductID = productID, ParameterValueText = $"Socket {GetRandom(100, 2000)}"
                });
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 4, ProductID = productID, ParameterValueInt = GetRandom(4, 20)
                });
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 5, ProductID = productID, ParameterValueInt = GetRandom(6, 12)
                });
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 6, ProductID = productID, ParameterValueInt = GetRandom(100, 140), ParameterValueText = "Watt"
                });
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/cpu.jpg"
                };
                break;

            case 2:     //GPU
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 1, ProductID = productID, ParameterDecimal = GetRandomDecimal(10), ParameterValueText = "MHz"
                });                                                                                                                                                                 //taktowanie
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 3, ProductID = productID, ParameterDecimal = GetRandom(600, 900), ParameterValueText = "MB"
                });                                                                                                                                                                 //ram
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 6, ProductID = productID, ParameterValueInt = GetRandom(300, 360), ParameterValueText = "Watt"
                });
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 9, ProductID = productID, ParameterValueText = "HDMI, VGA, DVI"
                });                                                                                                                                                                 //slot
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 10, ProductID = productID, ParameterValueInt = GetRandom(300, 360), ParameterValueText = "mm"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 11, ProductID = productID, ParameterValueInt = GetRandom(100, 160), ParameterValueText = "mm"
                });                                                                                                                                                                 //szer
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 12, ProductID = productID, ParameterValueInt = GetRandom(10, 30), ParameterValueText = "mm"
                });                                                                                                                                                                 //wys
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/gpu.jpg"
                };
                break;

            case 3:     //MOTHERBOARD
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 2, ProductID = productID, ParameterValueText = $"Socket {GetRandom(100, 2000)}"
                });
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 6, ProductID = productID, ParameterValueInt = GetRandom(100, 140), ParameterValueText = "Watt"
                });
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 10, ProductID = productID, ParameterValueInt = GetRandom(250, 300), ParameterValueText = "mm"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 11, ProductID = productID, ParameterValueInt = GetRandom(250, 300), ParameterValueText = "mm"
                });                                                                                                                                                                 //szer
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 12, ProductID = productID, ParameterValueInt = GetRandom(10, 35), ParameterValueText = "mm"
                });                                                                                                                                                                 //wys
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/motherboard.jpg"
                };
                break;

            case 4:     //RAM
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 1, ProductID = productID, ParameterDecimal = GetRandomDecimal(10), ParameterValueText = "MHz"
                });                                                                                                                                                                 //taktowanie
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 3, ProductID = productID, ParameterDecimal = GetRandom(600, 900), ParameterValueText = "MB"
                });                                                                                                                                                                 //ram
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 8, ProductID = productID, ParameterValueInt = GetRandom(100, 140), ParameterValueText = "DDR4"
                });                                                                                                                                                                 //mem type
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/ram.jpg"
                };
                break;

            case 5:     //HDD
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 7, ProductID = productID, ParameterValueInt = GetRandom(512, 4096), ParameterValueText = "GB"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 10, ProductID = productID, ParameterValueInt = GetRandom(190, 220), ParameterValueText = "mm"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 11, ProductID = productID, ParameterValueInt = GetRandom(100, 150), ParameterValueText = "mm"
                });                                                                                                                                                                 //szer
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 12, ProductID = productID, ParameterValueInt = GetRandom(10, 30), ParameterValueText = "mm"
                });                                                                                                                                                                 //wys
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/hdd.jpg"
                };
                break;

            case 6:     //SSD
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 7, ProductID = productID, ParameterValueInt = GetRandom(512, 1024), ParameterValueText = "GB"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 10, ProductID = productID, ParameterValueInt = GetRandom(190, 220), ParameterValueText = "mm"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 11, ProductID = productID, ParameterValueInt = GetRandom(100, 150), ParameterValueText = "mm"
                });                                                                                                                                                                 //szer
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 12, ProductID = productID, ParameterValueInt = GetRandom(10, 30), ParameterValueText = "mm"
                });                                                                                                                                                                 //wy
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/ssd.jpg"
                };
                break;

            case 7:     //COOLING
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 9, ProductID = productID, ParameterValueText = "4-pin PWM"
                });                                                                                                                                                            //slot
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/cooling.jpg"
                };
                break;

            case 8:     //POWER SUPPLY
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 10, ProductID = productID, ParameterValueInt = GetRandom(200, 240), ParameterValueText = "mm"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 11, ProductID = productID, ParameterValueInt = GetRandom(200, 240), ParameterValueText = "mm"
                });                                                                                                                                                                 //szer
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 12, ProductID = productID, ParameterValueInt = GetRandom(100, 120), ParameterValueText = "mm"
                });                                                                                                                                                                   //wys
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 14, ProductID = productID, ParameterValueText = "80 PLUS GOLD"
                });                                                                                                                                  //cert
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 15, ProductID = productID, ParameterValueText = "89%"
                });                                                                                                                         //wyd
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 16, ProductID = productID, ParameterValueInt = GetRandom(500, 750), ParameterValueText = "Watt"
                });                                                                                                                                                                    //max power
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/powersupply.jpg"
                };
                break;

            case 9:     //CASE
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 10, ProductID = productID, ParameterValueInt = GetRandom(300, 560), ParameterValueText = "mm"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 11, ProductID = productID, ParameterValueInt = GetRandom(200, 280), ParameterValueText = "mm"
                });                                                                                                                                                                 //szer
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 12, ProductID = productID, ParameterValueInt = GetRandom(300, 500), ParameterValueText = "mm"
                });                                                                                                                                                                   //wys
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/case.jpg"
                };
                break;

            case 10:        //SPEAKERS
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 6, ProductID = productID, ParameterValueInt = GetRandom(10, 25), ParameterValueText = "Watt"
                });
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 10, ProductID = productID, ParameterValueInt = GetRandom(200, 250), ParameterValueText = "mm"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 11, ProductID = productID, ParameterValueInt = GetRandom(100, 250), ParameterValueText = "mm"
                });                                                                                                                                                                 //szer
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 12, ProductID = productID, ParameterValueInt = GetRandom(100, 250), ParameterValueText = "mm"
                });                                                                                                                                                                   //wys
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 13, ProductID = productID, ParameterValueText = "Black/Gray/Red"
                });                                                                                                                                     //color
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/speakers.jpg"
                };
                break;

            case 11:        //HEADPHONES
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 13, ProductID = productID, ParameterValueText = "Black/Magenta"
                });                                                                                                                                    //color
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/headphones.jpg"
                };
                break;

            case 12:        //MOUSE
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 13, ProductID = productID, ParameterValueText = "White/Black"
                });                                                                                                                                  //color
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/mouse.jpg"
                };
                break;

            case 13:        //KEYBOARD
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 13, ProductID = productID, ParameterValueText = "Black/White/Dark Gray"
                });                                                                                                                                            //color
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/keyboard.jpg"
                };
                break;

            case 14:        //MONITOR
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 10, ProductID = productID, ParameterValueInt = GetRandom(300, 360), ParameterValueText = "mm"
                });                                                                                                                                                                 //dł
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 11, ProductID = productID, ParameterValueInt = GetRandom(100, 160), ParameterValueText = "mm"
                });                                                                                                                                                                 //szer
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 12, ProductID = productID, ParameterValueInt = GetRandom(10, 30), ParameterValueText = "mm"
                });                                                                                                                                                                 //wys
                productParameters.Add(new ProductParameter()
                {
                    ParameterID = 13, ProductID = productID, ParameterValueText = "Black/White/Dark Gray"
                });
                productPicture = new ProductPicture()
                {
                    ProductID = productID, PicturePath = "Resources/monitor.jpg"
                };
                break;
            }

            __Context.ProductPicture.Add(productPicture);
            if (!(__Context.SaveChanges() == 1))
            {
                Console.WriteLine($"An error occured while trying to save a ProductPicture type into the DB");
            }
            else
            {
                Console.WriteLine($"> ProductPicture saved.");
            }

            foreach (ProductParameter pp in productParameters)
            {
                __Context.ProductParameter.Add(pp);
                if (!(__Context.SaveChanges() == 1))
                {
                    Console.WriteLine($"An error occured while trying to save a ProductParameter type into the DB");
                }
                else
                {
                    Console.WriteLine($"> ProductParameter {pp.ParameterID} saved.");
                }
            }

            productParameters.Clear();
        }
예제 #8
0
        private void ProcessProductPictures(ICollection <ImportRow <Product> > batch, ImportResult result)
        {
            // true, cause pictures must be saved and assigned an id
            // prior adding a mapping.
            _rsProductPicture.AutoCommitEnabled = true;

            ProductPicture lastInserted = null;

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

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

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

                        var currentPictures = _rsProductPicture.TableUntracked.Where(x => x.ProductId == row.Entity.Id);
                        var pictureBinary   = FindEqualPicture(picture, currentPictures);

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

            // Perf: notify only about LAST insertion and update
            if (lastInserted != null)
            {
                _eventPublisher.EntityInserted(lastInserted);
            }
        }
예제 #9
0
        public async Task <IActionResult> Edit(Product model)
        {
            model.UserId = (await userManager.FindByNameAsync(User.Identity.Name)).Id;

            if (model.PictureFile != null)
            {
                using (var image = Image.Load(model.PictureFile.OpenReadStream()))
                {
                    image.Mutate(p =>
                    {
                        p.Resize(new ResizeOptions
                        {
                            Size = new Size(800, 800),
                            Mode = ResizeMode.Crop
                        })
                        .BackgroundColor(Color.White);
                    });
                    model.Picture = image.ToBase64String(JpegFormat.Instance);
                }
            }

            if (model.PictureFiles != null)
            {
                foreach (var pictureFile in model.PictureFiles)
                {
                    using (var image = Image.Load(pictureFile.OpenReadStream()))
                    {
                        image.Mutate(p =>
                        {
                            p.Resize(new ResizeOptions
                            {
                                Size = new Size(800, 800),
                                Mode = ResizeMode.Crop
                            })
                            .BackgroundColor(Color.White);
                        });
                        var picture        = image.ToBase64String(JpegFormat.Instance);
                        var productPicture = new ProductPicture
                        {
                            Date    = DateTime.Now,
                            Enabled = true,
                            Picture = picture,
                            UserId  = model.UserId
                        };
                        model.ProductPictures.Add(productPicture);
                        context.Entry(productPicture).State = EntityState.Added;
                    }
                }
            }

            if (model.PictureFilesToDeleted != null)
            {
                foreach (var pictureFileId in model.PictureFilesToDeleted)
                {
                    var pictureFile = await context.ProductPictures.FindAsync(pictureFileId);

                    context.Entry(pictureFile).State = EntityState.Deleted;
                }
            }

            model.Price = decimal.Parse(model.PriceText, CultureInfo.CreateSpecificCulture("tr-TR"));

            var currentCategories = await context.CategoryProducts.Where(p => p.ProductId == model.Id).Select(p => p.CategoryId).ToArrayAsync();

            if (model.SelectedCategories != null)
            {
                model.SelectedCategories
                .ToList()
                .ForEach(p =>
                {
                    if (!currentCategories.Any(q => q == p))
                    {
                        var categoryProduct = new CategoryProduct {
                            CategoryId = p
                        };
                        model.CategoryProducts.Add(categoryProduct);
                        context.Entry(categoryProduct).State = EntityState.Added;
                    }
                });

                currentCategories
                .Except(model.SelectedCategories)
                .ToList()
                .ForEach(p =>
                {
                    var categoryProduct = context.CategoryProducts.SingleOrDefault(q => q.ProductId == model.Id && q.CategoryId == p);
                    context.Entry(categoryProduct).State = EntityState.Deleted;
                });
            }

            context.Entry(model).State = EntityState.Modified;
            try
            {
                await context.SaveChangesAsync();

                TempData["success"] = $"{entity} güncelleme işlemi başarıyla tamamlanmıştır.";
                return(RedirectToAction("Index"));
            }
            catch (DbUpdateException)
            {
                TempData["error"] = $"Aynı isimli birden fazla {entity.ToLower()} olamaz.";
                await PopulateDropdowns();

                return(View(model));
            }
        }
예제 #10
0
        /// <summary>
        /// 删除,按主键ID;
        /// </summary>
        /// <param name="identify">实体的主键</param>
        public void PictureDelete(int identify)
        {
            ProductPicture pp = this.PictureSingle(identify);

            this.PictureDelete(pp);
        }
예제 #11
0
 /// <summary>
 /// 删除图片文件
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="tran">数据库操作事务</param>
 private void _PictureDelete(ProductPicture entity, DbTransaction tran)
 {
     Song.CustomControl.FileUpload.Delete("Product", entity.Pp_File);
     Gateway.Default.Delete <ProductPicture>(ProductPicture._.Pp_Id == entity.Pp_Id, tran);
 }
예제 #12
0
        private void ProcessProductPicturesOld(IImportExecuteContext context, ImportRow <Product>[] batch)
        {
            // true, cause pictures must be saved and assigned an id prior adding a mapping.
            _productPictureRepository.AutoCommitEnabled = true;

            ProductPicture lastInserted   = null;
            var            equalPictureId = 0;

            foreach (var row in batch)
            {
                var count      = -1;
                var thumbPaths = row.GetDataValue <List <string> >("PictureThumbPaths");

                if (thumbPaths == null)
                {
                    continue;
                }

                foreach (var path in thumbPaths.Where(x => x.HasValue() && File.Exists(x)))
                {
                    try
                    {
                        var currentProductPictures = _productPictureRepository.TableUntracked.Expand(x => x.Picture)
                                                     .Where(x => x.ProductId == row.Entity.Id)
                                                     .ToList();

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

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

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

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

                                _productPictureRepository.Insert(mapping);
                                lastInserted = mapping;
                            }
                        }
                        else
                        {
                            var idx = thumbPaths.IndexOf(path) + 1;
                            context.Result.AddInfo("Found equal picture in data store. Skipping field.", row.GetRowInfo(), "PictureThumbPaths" + idx.ToString());
                        }
                    }
                    catch (Exception exception)
                    {
                        var idx = thumbPaths.IndexOf(path) + 1;
                        context.Result.AddWarning(exception.Message, row.GetRowInfo(), "PictureThumbPaths" + idx.ToString());
                    }
                }
            }

            // Perf: notify only about LAST insertion and update
            if (lastInserted != null)
            {
                _services.EventPublisher.EntityInserted(lastInserted);
            }
        }
예제 #13
0
 public ProductPictureEntity(ProductPicture ProductPicture, params object[] args) : base(ProductPicture)
 {
 }
예제 #14
0
        private void BindData()
        {
            if (product != null)
            {
                string productURL = SEOHelper.GetProductUrl(product);

                LWG.Business.CatalogBiz catalogBiz = new LWG.Business.CatalogBiz();
                lwg_Catalog             catalog    = catalogBiz.GetByID(product.ProductId);

                hlCatalogNo.Text      = Server.HtmlEncode(catalog.CatalogNumber);
                hlProduct.NavigateUrl = hlCatalogNo.NavigateUrl = productURL;
                hlProduct.Text        = Server.HtmlEncode(product.Name);

                ProductPicture productPicture = product.DefaultProductPicture;
                if (productPicture != null)
                {
                    hlImageLink.ImageUrl = PictureManager.GetPictureUrl(productPicture.Picture, this.ProductImageSize, true);
                    hlImageLink.ToolTip  = String.Format(GetLocaleResourceString("Media.Product.ImageLinkTitleFormat"), product.Name);
                    hlImageLink.Text     = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.Name);
                }
                else
                {
                    hlImageLink.ImageUrl = PictureManager.GetDefaultPictureUrl(this.ProductImageSize);
                    hlImageLink.ToolTip  = String.Format(GetLocaleResourceString("Media.Product.ImageLinkTitleFormat"), product.Name);
                    hlImageLink.Text     = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.Name);
                }
                hlImageLink.NavigateUrl = productURL;

                lShortDescription.Text = product.ShortDescription;

                var productVariantCollection = product.ProductVariants;

                if (productVariantCollection.Count > 0)
                {
                    if (!product.HasMultipleVariants)
                    {
                        var productVariant = productVariantCollection[0];
                        btnAddToCart.Visible = (!productVariant.DisableBuyButton);
                        if (!SettingManager.GetSettingValueBoolean("Common.HidePricesForNonRegistered") ||
                            (NopContext.Current.User != null &&
                             !NopContext.Current.User.IsGuest))
                        {
                            if (productVariant.CustomerEntersPrice)
                            {
                                lblOldPrice.Visible = false;
                                lblPrice.Visible    = false;
                            }
                            else
                            {
                                decimal oldPriceBase = TaxManager.GetPrice(productVariant, productVariant.OldPrice);
                                decimal finalPriceWithoutDiscountBase = TaxManager.GetPrice(productVariant, PriceHelper.GetFinalPrice(productVariant, false));

                                decimal oldPrice = CurrencyManager.ConvertCurrency(oldPriceBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                                decimal finalPriceWithoutDiscount = CurrencyManager.ConvertCurrency(finalPriceWithoutDiscountBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);

                                if (finalPriceWithoutDiscountBase != oldPriceBase && oldPriceBase != decimal.Zero)
                                {
                                    lblOldPrice.Text = PriceHelper.FormatPrice(oldPrice);
                                    lblPrice.Text    = PriceHelper.FormatPrice(finalPriceWithoutDiscount);
                                }
                                else
                                {
                                    lblOldPrice.Visible = false;
                                    lblPrice.Text       = PriceHelper.FormatPrice(finalPriceWithoutDiscount);
                                }
                            }
                        }
                        else
                        {
                            lblOldPrice.Visible  = false;
                            lblPrice.Visible     = false;
                            btnAddToCart.Visible = false;
                        }
                        ddlVariantPrice.Visible = false;
                    }
                    else
                    {
                        lblOldPrice.Visible  = false;
                        lblPrice.Visible     = false;
                        btnAddToCart.Visible = false;

                        ddlVariantPrice.Visible    = true;
                        ddlVariantPrice.DataSource = productVariantCollection.OrderBy(pv => pv.Price);
                        ddlVariantPrice.DataBind();
                        #region comment built-in code
                        //var productVariant = product.MinimalPriceProductVariant;
                        //if (productVariant != null)
                        //{
                        //    if (!SettingManager.GetSettingValueBoolean("Common.HidePricesForNonRegistered") ||
                        //        (NopContext.Current.User != null &&
                        //        !NopContext.Current.User.IsGuest))
                        //    {
                        //        if (productVariant.CustomerEntersPrice)
                        //        {
                        //            lblOldPrice.Visible = false;
                        //            lblPrice.Visible = false;
                        //        }
                        //        else
                        //        {
                        //            decimal fromPriceBase = TaxManager.GetPrice(productVariant, PriceHelper.GetFinalPrice(productVariant, false));
                        //            decimal fromPrice = CurrencyManager.ConvertCurrency(fromPriceBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                        //            lblOldPrice.Visible = false;
                        //            lblPrice.Text = String.Format(GetLocaleResourceString("Products.PriceRangeFromText"), PriceHelper.FormatPrice(fromPrice));
                        //        }
                        //    }
                        //    else
                        //    {
                        //        lblOldPrice.Visible = false;
                        //        lblPrice.Visible = false;
                        //        btnAddToCart.Visible = false;
                        //    }
                        //}

                        //btnAddToCart.Visible = false;
                        #endregion
                    }
                }
                else
                {
                    lblOldPrice.Visible  = false;
                    lblPrice.Visible     = false;
                    btnAddToCart.Visible = false;
                }
            }
        }
예제 #15
0
        public static IEnumerable <ProductOverviewModel> PrepareProductOverviewModels(this Controller controller,
                                                                                      IWorkContext workContext,
                                                                                      IStoreContext storeContext,
                                                                                      ICategoryService categoryService,
                                                                                      IProductService productService,
                                                                                      ISpecificationAttributeService specificationAttributeService,
                                                                                      IPriceCalculationService priceCalculationService,
                                                                                      IPriceFormatter priceFormatter,
                                                                                      IPermissionService permissionService,
                                                                                      ILocalizationService localizationService,
                                                                                      ITaxService taxService,
                                                                                      ICurrencyService currencyService,
                                                                                      IPictureService pictureService,
                                                                                      IMeasureService measureService,
                                                                                      IWebHelper webHelper,
                                                                                      ICacheManager cacheManager,
                                                                                      CatalogSettings catalogSettings,
                                                                                      MediaSettings mediaSettings,
                                                                                      IEnumerable <Product> products,
                                                                                      bool preparePriceModel                 = true, bool preparePictureModel = true,
                                                                                      int?productThumbPictureSize            = null, bool prepareSpecificationAttributes = false,
                                                                                      bool forceRedirectionAfterAddingToCart = false)
        {
            if (products == null)
            {
                throw new ArgumentNullException("products");
            }

            var models = new List <ProductOverviewModel>();

            foreach (var product in products)
            {
                var model = new ProductOverviewModel
                {
                    Id               = product.Id,
                    Name             = product.GetLocalized(x => x.Name),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription  = product.GetLocalized(x => x.FullDescription),
                    SeName           = product.GetSeName(),
                    ProductType      = product.ProductType,
                    MarkAsNew        = product.MarkAsNew &&
                                       (!product.MarkAsNewStartDateTimeUtc.HasValue || product.MarkAsNewStartDateTimeUtc.Value < DateTime.UtcNow) &&
                                       (!product.MarkAsNewEndDateTimeUtc.HasValue || product.MarkAsNewEndDateTimeUtc.Value > DateTime.UtcNow)
                };
                //price
                if (preparePriceModel)
                {
                    #region Prepare product price

                    var priceModel = new ProductOverviewModel.ProductPriceModel
                    {
                        ForceRedirectionAfterAddingToCart = forceRedirectionAfterAddingToCart
                    };

                    switch (product.ProductType)
                    {
                    case ProductType.GroupedProduct:
                    {
                        #region Grouped product

                        var associatedProducts = productService.GetAssociatedProducts(product.Id, storeContext.CurrentStore.Id);

                        //add to cart button (ignore "DisableBuyButton" property for grouped products)
                        priceModel.DisableBuyButton = !permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart) ||
                                                      !permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //add to wishlist button (ignore "DisableWishlistButton" property for grouped products)
                        priceModel.DisableWishlistButton = !permissionService.Authorize(StandardPermissionProvider.EnableWishlist) ||
                                                           !permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //compare products
                        priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled;

                        switch (associatedProducts.Count)
                        {
                        case 0:
                        {
                        }
                        break;

                        default:
                        {
                            //we have at least one associated product
                            //compare products
                            priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled;
                            //priceModel.AvailableForPreOrder = false;

                            if (permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                            {
                                //find a minimum possible price
                                decimal?minPossiblePrice = null;
                                Product minPriceProduct  = null;
                                foreach (var associatedProduct in associatedProducts)
                                {
                                    //calculate for the maximum quantity (in case if we have tier prices)
                                    var tmpPrice = priceCalculationService.GetFinalPrice(associatedProduct,
                                                                                         workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);
                                    if (!minPossiblePrice.HasValue || tmpPrice < minPossiblePrice.Value)
                                    {
                                        minPriceProduct  = associatedProduct;
                                        minPossiblePrice = tmpPrice;
                                    }
                                }
                                if (minPriceProduct != null && !minPriceProduct.CustomerEntersPrice)
                                {
                                    if (minPriceProduct.CallForPrice)
                                    {
                                        priceModel.OldPrice = null;
                                        priceModel.Price    = localizationService.GetResource("Products.CallForPrice");
                                    }
                                    else if (minPossiblePrice.HasValue)
                                    {
                                        //calculate prices
                                        decimal taxRate;
                                        decimal finalPriceBase = taxService.GetProductPrice(minPriceProduct, minPossiblePrice.Value, out taxRate);
                                        decimal finalPrice     = currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, workContext.WorkingCurrency);

                                        priceModel.OldPrice   = null;
                                        priceModel.Price      = String.Format(localizationService.GetResource("Products.PriceRangeFrom"), priceFormatter.FormatPrice(finalPrice));
                                        priceModel.PriceValue = finalPrice;

                                        //PAngV baseprice (used in Germany)
                                        priceModel.BasePricePAngV = product.FormatBasePrice(finalPrice,
                                                                                            localizationService, measureService, currencyService, workContext, priceFormatter);
                                    }
                                    else
                                    {
                                        //Actually it's not possible (we presume that minimalPrice always has a value)
                                        //We never should get here
                                        Debug.WriteLine("Cannot calculate minPrice for product #{0}", product.Id);
                                    }
                                }
                            }
                            else
                            {
                                //hide prices
                                priceModel.OldPrice = null;
                                priceModel.Price    = null;
                            }
                        }
                        break;
                        }

                        #endregion
                    }
                    break;

                    case ProductType.SimpleProduct:
                    default:
                    {
                        #region Simple product

                        //add to cart button
                        priceModel.DisableBuyButton = product.DisableBuyButton ||
                                                      !permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart) ||
                                                      !permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //add to wishlist button
                        priceModel.DisableWishlistButton = product.DisableWishlistButton ||
                                                           !permissionService.Authorize(StandardPermissionProvider.EnableWishlist) ||
                                                           !permissionService.Authorize(StandardPermissionProvider.DisplayPrices);
                        //compare products
                        priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled;

                        //rental
                        priceModel.IsRental = product.IsRental;

                        //pre-order
                        if (product.AvailableForPreOrder)
                        {
                            priceModel.AvailableForPreOrder = !product.PreOrderAvailabilityStartDateTimeUtc.HasValue ||
                                                              product.PreOrderAvailabilityStartDateTimeUtc.Value >= DateTime.UtcNow;
                            priceModel.PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc;
                        }

                        //prices
                        if (permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                        {
                            if (!product.CustomerEntersPrice)
                            {
                                if (product.CallForPrice)
                                {
                                    //call for price
                                    priceModel.OldPrice = null;
                                    priceModel.Price    = localizationService.GetResource("Products.CallForPrice");
                                }
                                else
                                {
                                    //prices

                                    //calculate for the maximum quantity (in case if we have tier prices)
                                    decimal minPossiblePrice = priceCalculationService.GetFinalPrice(product,
                                                                                                     workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);

                                    decimal taxRate;
                                    decimal oldPriceBase   = taxService.GetProductPrice(product, product.OldPrice, out taxRate);
                                    decimal finalPriceBase = taxService.GetProductPrice(product, minPossiblePrice, out taxRate);

                                    decimal oldPrice   = currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase, workContext.WorkingCurrency);
                                    decimal finalPrice = currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, workContext.WorkingCurrency);

                                    //do we have tier prices configured?
                                    var tierPrices = new List <TierPrice>();
                                    if (product.HasTierPrices)
                                    {
                                        tierPrices.AddRange(product.TierPrices
                                                            .OrderBy(tp => tp.Quantity)
                                                            .ToList()
                                                            .FilterByStore(storeContext.CurrentStore.Id)
                                                            .FilterForCustomer(workContext.CurrentCustomer)
                                                            .RemoveDuplicatedQuantities());
                                    }
                                    //When there is just one tier (with  qty 1),
                                    //there are no actual savings in the list.
                                    bool displayFromMessage = tierPrices.Any() &&
                                                              !(tierPrices.Count == 1 && tierPrices[0].Quantity <= 1);
                                    if (displayFromMessage)
                                    {
                                        priceModel.OldPrice   = null;
                                        priceModel.Price      = String.Format(localizationService.GetResource("Products.PriceRangeFrom"), priceFormatter.FormatPrice(finalPrice));
                                        priceModel.PriceValue = finalPrice;
                                    }
                                    else
                                    {
                                        if (finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero)
                                        {
                                            priceModel.OldPrice   = priceFormatter.FormatPrice(oldPrice);
                                            priceModel.Price      = priceFormatter.FormatPrice(finalPrice);
                                            priceModel.PriceValue = finalPrice;
                                        }
                                        else
                                        {
                                            priceModel.OldPrice   = null;
                                            priceModel.Price      = priceFormatter.FormatPrice(finalPrice);
                                            priceModel.PriceValue = finalPrice;
                                        }
                                    }
                                    if (product.IsRental)
                                    {
                                        //rental product
                                        priceModel.OldPrice = priceFormatter.FormatRentalProductPeriod(product, priceModel.OldPrice);
                                        priceModel.Price    = priceFormatter.FormatRentalProductPeriod(product, priceModel.Price);
                                    }


                                    //property for German market
                                    //we display tax/shipping info only with "shipping enabled" for this product
                                    //we also ensure this it's not free shipping
                                    priceModel.DisplayTaxShippingInfo = catalogSettings.DisplayTaxShippingInfoProductBoxes &&
                                                                        product.IsShipEnabled &&
                                                                        !product.IsFreeShipping;

                                    //PAngV baseprice (used in Germany)
                                    priceModel.BasePricePAngV = product.FormatBasePrice(finalPrice,
                                                                                        localizationService, measureService, currencyService, workContext, priceFormatter);
                                }
                            }
                        }
                        else
                        {
                            //hide prices
                            priceModel.OldPrice = null;
                            priceModel.Price    = null;
                        }

                        #endregion
                    }
                    break;
                    }

                    model.ProductPrice = priceModel;

                    #endregion
                }

                //picture
                if (preparePictureModel)
                {
                    #region Prepare product picture

                    //If a size has been set in the view, we use it in priority
                    int pictureSize = productThumbPictureSize.HasValue ? productThumbPictureSize.Value : mediaSettings.ProductThumbPictureSize;
                    //prepare picture model
                    var defaultProductPictureCacheKey = string.Format(ModelCacheEventConsumer.PRODUCT_DEFAULTPICTURE_MODEL_KEY, product.Id, pictureSize, true, workContext.WorkingLanguage.Id, webHelper.IsCurrentConnectionSecured(), storeContext.CurrentStore.Id);
                    model.DefaultPictureModel = cacheManager.Get(defaultProductPictureCacheKey, () =>
                    {
                        var picture = product.ProductPictures.FirstOrDefault(); //pictureService.GetPicturesByProductId(product.Id, 1).FirstOrDefault();
                        if (picture == null)
                        {
                            picture = new ProductPicture();
                        }

                        var pictureModel = new PictureModel
                        {
                            ImageUrl         = pictureService.GetPictureUrl(picture.PictureId, pictureSize),
                            FullSizeImageUrl = pictureService.GetPictureUrl(picture.PictureId)
                        };
                        //"title" attribute
                        pictureModel.Title = (picture != null && !string.IsNullOrEmpty(picture.TitleAttribute)) ?
                                             picture.TitleAttribute :
                                             string.Format(localizationService.GetResource("Media.Product.ImageLinkTitleFormat"), model.Name);
                        //"alt" attribute
                        pictureModel.AlternateText = (picture != null && !string.IsNullOrEmpty(picture.AltAttribute)) ?
                                                     picture.AltAttribute :
                                                     string.Format(localizationService.GetResource("Media.Product.ImageAlternateTextFormat"), model.Name);

                        return(pictureModel);
                    });

                    #endregion
                }

                //specs
                if (prepareSpecificationAttributes)
                {
                    model.SpecificationAttributeModels = PrepareProductSpecificationModel(controller, workContext,
                                                                                          specificationAttributeService, cacheManager, product);
                }

                //reviews
                model.ReviewOverviewModel = controller.PrepareProductReviewOverviewModel(productService, storeContext, catalogSettings, cacheManager, product);

                models.Add(model);
            }
            return(models);
        }
예제 #16
0
 public static ProductPictureModel ToModel(this ProductPicture entity)
 {
     return(entity.MapTo <ProductPicture, ProductPictureModel>());
 }
        protected IEnumerable <ProductOverviewModel> PrepareProductOverviewModels(IEnumerable <Product> products,
                                                                                  bool preparePriceModel                 = true, bool preparePictureModel = true,
                                                                                  int?productThumbPictureSize            = null, bool prepareSpecificationAttributes = false,
                                                                                  bool forceRedirectionAfterAddingToCart = false)
        {
            if (products == null)
            {
                throw new ArgumentNullException("products");
            }

            var models = new List <ProductOverviewModel>();

            foreach (var product in products)
            {
                var model = new ProductOverviewModel
                {
                    Id               = product.Id,
                    Name             = product.GetLocalized(x => x.Name),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription  = product.GetLocalized(x => x.FullDescription),
                    SeName           = product.GetSeName(),
                };
                //price
                if (preparePriceModel)
                {
                    #region Prepare product price

                    var priceModel = new ProductOverviewModel.ProductPriceModel();

                    switch (product.ProductType)
                    {
                    case ProductType.GroupedProduct:
                    {
                        #region Grouped product

                        var associatedProducts = _productService.GetAssociatedProducts(product.Id, _storeContext.CurrentStore.Id);

                        switch (associatedProducts.Count)
                        {
                        case 0:
                        {
                            //no associated products
                            priceModel.OldPrice              = null;
                            priceModel.Price                 = null;
                            priceModel.DisableBuyButton      = true;
                            priceModel.DisableWishlistButton = true;
                            priceModel.AvailableForPreOrder  = false;
                        }
                        break;

                        default:
                        {
                            //we have at least one associated product
                            priceModel.DisableBuyButton      = true;
                            priceModel.DisableWishlistButton = true;
                            priceModel.AvailableForPreOrder  = false;

                            if (_permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                            {
                                //find a minimum possible price
                                decimal?minPossiblePrice = null;
                                Product minPriceProduct  = null;
                                foreach (var associatedProduct in associatedProducts)
                                {
                                    //calculate for the maximum quantity (in case if we have tier prices)
                                    var tmpPrice = _priceCalculationService.GetFinalPrice(associatedProduct,
                                                                                          _workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);
                                    if (!minPossiblePrice.HasValue || tmpPrice < minPossiblePrice.Value)
                                    {
                                        minPriceProduct  = associatedProduct;
                                        minPossiblePrice = tmpPrice;
                                    }
                                }
                                if (minPriceProduct != null && !minPriceProduct.CustomerEntersPrice)
                                {
                                    if (minPriceProduct.CallForPrice)
                                    {
                                        priceModel.OldPrice = null;
                                        priceModel.Price    = _localizationService.GetResource("Products.CallForPrice");
                                    }
                                    else if (minPossiblePrice.HasValue)
                                    {
                                        //calculate prices
                                        decimal taxRate;
                                        decimal finalPriceBase = _taxService.GetProductPrice(minPriceProduct, minPossiblePrice.Value, out taxRate);
                                        decimal finalPrice     = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, _workContext.WorkingCurrency);

                                        priceModel.OldPrice = null;
                                        priceModel.Price    = String.Format(_localizationService.GetResource("Products.PriceRangeFrom"), _priceFormatter.FormatPrice(finalPrice));
                                    }
                                    else
                                    {
                                        //Actually it's not possible (we presume that minimalPrice always has a value)
                                        //We never should get here
                                        Debug.WriteLine("Cannot calculate minPrice for product #{0}", product.Id);
                                    }
                                }
                            }
                            else
                            {
                                //hide prices
                                priceModel.OldPrice = null;
                                priceModel.Price    = null;
                            }
                        }
                        break;
                        }

                        #endregion
                    }
                    break;

                    case ProductType.SimpleProduct:
                    default:
                    {
                        #region Simple product

                        //add to cart button
                        priceModel.DisableBuyButton = product.DisableBuyButton ||
                                                      !_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart) ||
                                                      !_permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //add to wishlist button
                        priceModel.DisableWishlistButton = product.DisableWishlistButton ||
                                                           !_permissionService.Authorize(StandardPermissionProvider.EnableWishlist) ||
                                                           !_permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //rental
                        priceModel.IsRental = product.IsRental;

                        //pre-order
                        if (product.AvailableForPreOrder)
                        {
                            priceModel.AvailableForPreOrder = !product.PreOrderAvailabilityStartDateTimeUtc.HasValue ||
                                                              product.PreOrderAvailabilityStartDateTimeUtc.Value >= DateTime.UtcNow;
                            priceModel.PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc;
                        }

                        //prices
                        if (_permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                        {
                            if (!product.CustomerEntersPrice)
                            {
                                if (product.CallForPrice)
                                {
                                    //call for price
                                    priceModel.OldPrice = null;
                                    priceModel.Price    = _localizationService.GetResource("Products.CallForPrice");
                                }
                                else
                                {
                                    //prices

                                    //calculate for the maximum quantity (in case if we have tier prices)
                                    decimal minPossiblePrice = _priceCalculationService.GetFinalPrice(product,
                                                                                                      _workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);

                                    decimal taxRate;
                                    decimal oldPriceBase   = _taxService.GetProductPrice(product, product.OldPrice, out taxRate);
                                    decimal finalPriceBase = _taxService.GetProductPrice(product, minPossiblePrice, out taxRate);

                                    decimal oldPrice   = _currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase, _workContext.WorkingCurrency);
                                    decimal finalPrice = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, _workContext.WorkingCurrency);

                                    //do we have tier prices configured?
                                    var tierPrices = new List <TierPrice>();
                                    if (product.HasTierPrices)
                                    {
                                        tierPrices.AddRange(product.TierPrices
                                                            .OrderBy(tp => tp.Quantity)
                                                            .ToList()
                                                            .FilterByStore(_storeContext.CurrentStore.Id)
                                                            .FilterForCustomer(_workContext.CurrentCustomer)
                                                            .RemoveDuplicatedQuantities());
                                    }
                                    //When there is just one tier (with  qty 1),
                                    //there are no actual savings in the list.
                                    bool displayFromMessage = tierPrices.Count > 0 &&
                                                              !(tierPrices.Count == 1 && tierPrices[0].Quantity <= 1);
                                    if (displayFromMessage)
                                    {
                                        priceModel.OldPrice = null;
                                        priceModel.Price    = String.Format(_localizationService.GetResource("Products.PriceRangeFrom"), _priceFormatter.FormatPrice(finalPrice));
                                    }
                                    else
                                    {
                                        if (finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero)
                                        {
                                            priceModel.OldPrice = _priceFormatter.FormatPrice(oldPrice);
                                            priceModel.Price    = _priceFormatter.FormatPrice(finalPrice);
                                        }
                                        else
                                        {
                                            priceModel.OldPrice = null;
                                            priceModel.Price    = _priceFormatter.FormatPrice(finalPrice);
                                        }
                                    }
                                    if (product.IsRental)
                                    {
                                        //rental product
                                        priceModel.OldPrice = _priceFormatter.FormatRentalProductPeriod(product, priceModel.OldPrice);
                                        priceModel.Price    = _priceFormatter.FormatRentalProductPeriod(product, priceModel.Price);
                                    }
                                }
                            }
                        }
                        else
                        {
                            //hide prices
                            priceModel.OldPrice = null;
                            priceModel.Price    = null;
                        }

                        #endregion
                    }
                    break;
                    }

                    model.ProductPrice = priceModel;

                    #endregion
                }

                //picture
                if (preparePictureModel)
                {
                    #region Prepare product picture

                    //If a size has been set in the view, we use it in priority
                    int pictureSize = productThumbPictureSize.HasValue ? productThumbPictureSize.Value : 125;
                    //prepare picture model
                    //var picture = _pictureService.GetPicturesByProductId(product.Id, 1).FirstOrDefault();
                    var picture = product.ProductPictures.FirstOrDefault(); //_pictureService.GetPictureById(product.prodId, 1).FirstOrDefault();
                    if (picture == null)
                    {
                        picture = new ProductPicture();
                    }
                    model.DefaultPictureModel = new PictureModel
                    {
                        ImageUrl         = _pictureService.GetPictureUrl(picture.PictureId, pictureSize),
                        FullSizeImageUrl = _pictureService.GetPictureUrl(picture.PictureId)
                    };
                    //"title" attribute
                    model.DefaultPictureModel.Title = (picture != null && !string.IsNullOrEmpty(picture.TitleAttribute)) ?
                                                      picture.TitleAttribute :
                                                      string.Format(_localizationService.GetResource("Media.Product.ImageLinkTitleFormat"), model.Name);
                    //"alt" attribute
                    model.DefaultPictureModel.AlternateText = (picture != null && !string.IsNullOrEmpty(picture.AltAttribute)) ?
                                                              picture.AltAttribute :
                                                              string.Format(_localizationService.GetResource("Media.Product.ImageAlternateTextFormat"), model.Name);

                    #endregion
                }

                models.Add(model);
            }
            return(models);
        }
예제 #18
0
 protected string GetPictureUrl(ProductPicture picture, int size)
 {
     return PictureManager.GetPictureUrl(picture.PictureID, size);
 }
예제 #19
0
        public void CreateProduct(AdminProductDto productDto)
        {
            var product = _mapper.Map <Product>(productDto);

            product.Id = Guid.NewGuid().ToString();
            var picture = _mapper.Map <List <Picture> >(productDto.PictureList);

            var categories   = _mapper.Map <List <Category> >(productDto.CategoryViews);
            var id           = _appDbContext.Products.Select(a => a.Id).FirstOrDefault();
            var siezesPrices = GetAllSizesWithPrice(id);
            var sizes        = _mapper.Map <List <Size> >(productDto.SizesPricesList);

            foreach (var pic in picture)
            {
                var doesPicExist = _appDbContext.Pictures.Where(a => a.Path == pic.Path).Any();
                if (!doesPicExist)
                {
                    _appDbContext.Pictures.Add(pic);
                    _appDbContext.SaveChanges();
                }

                var productPicture = new ProductPicture()
                {
                    PictureId = pic.Id, ProductId = product.Id
                };
                product.ProductPictures.Add(productPicture);
            }
            foreach (var size in siezesPrices)
            {
                var sizesAndPrices = new ProductSize()
                {
                    ProductId = product.Id, SizeId = size.Id, Price = size.Price
                };
                product.ProductSizes.Add(sizesAndPrices);
            }
            foreach (var c in categories)
            {
                if (!_appDbContext.Categories.Where(a => a.Name == c.Name).Any())
                {
                    var category = new Category()
                    {
                        Name = c.Name
                    };
                    _appDbContext.Categories.Add(category);
                    _appDbContext.SaveChanges();
                }

                var doesCategoryExistsForProduct = _appDbContext.ProductCategories.Where(a => a.ProductId == id && a.Category.Name == c.Name).Any();
                if (!doesCategoryExistsForProduct)
                {
                    var cId = _appDbContext.Categories.Where(a => a.Name == c.Name).Select(a => a.Id).FirstOrDefault();
                    var pC  = new ProductCategory()
                    {
                        CategoryId = cId, ProductId = product.Id
                    };
                    product.ProductCategories.Add(pC);
                }
            }
            if (siezesPrices.Count == 0)
            {
                var allGenericSizes = _appDbContext.Sizes.ToList();
                foreach (var size in allGenericSizes)
                {
                    var genericSizesWithPrice = new ProductSize {
                        ProductId = product.Id, SizeId = size.Id, Price = size.Price
                    };
                    product.ProductSizes.Add(genericSizesWithPrice);
                }
            }


            _appDbContext.Products.Add(product);
            _appDbContext.SaveChanges();
        }
예제 #20
0
 public void InsertProductPicture(ProductPicture productPicture)
 {
     _productPictureRepository.Insert(productPicture);
 }
예제 #21
0
        public virtual void InsertProductPicture(ProductPicture productPicture)
        {
            Guard.NotNull(productPicture, nameof(productPicture));

            _productPictureRepository.Insert(productPicture);
        }
예제 #22
0
 public void UpdateProductPicture(ProductPicture productPicture)
 {
     _productPictureRepository.Update(productPicture);
 }
예제 #23
0
        protected override void Seed(ApplicationDbContext context)
        {
            if (System.Diagnostics.Debugger.IsAttached == false)
            {
                // System.Diagnostics.Debugger.Launch();
            }
            // This method will be called after migrating to the latest version.
            context.Configuration.LazyLoadingEnabled = true;

            // Generation configuration
            int companyCount             = 3;
            int uniqueAddressStreetCount = 2;
            int uniqueAddressCityCount   = 5;

            int userCount              = 5;
            int uniqueUserNameCount    = 5;
            int uniqueUserSurnameCount = 10;

            int productCount         = 20;
            int employeeCount        = 5;
            int productRatingCount   = 10;
            int productCommentCount  = 10;
            int companyReportCount   = 10;
            int watchedProductCount  = 20;
            int existingProductCount = 40;
            //int qrCodeCount = 10;
            int companyStatisticsCountPerCompany = 10;
            int scanCount = 20;

            Random random = new Random();

            // delete everything
            context.CompanyStatistics.RemoveRange(context.CompanyStatistics);
            context.SaveChanges();

            context.QRs.RemoveRange(context.QRs);
            context.SaveChanges();

            context.ProductComments.RemoveRange(context.ProductComments);
            context.SaveChanges();

            context.ExistingProducts.RemoveRange(context.ExistingProducts);
            context.SaveChanges();

            context.ProductRatings.RemoveRange(context.ProductRatings);
            context.SaveChanges();

            context.Employees.RemoveRange(context.Employees);
            context.SaveChanges();

            context.WatchedProducts.RemoveRange(context.WatchedProducts);
            context.SaveChanges();

            ((DbSet <ApplicationUser>)context.Users).RemoveRange(context.Users);
            context.SaveChanges();


            context.ProductPictures.RemoveRange(context.ProductPictures);
            context.SaveChanges();


            context.Companies.RemoveRange(context.Companies);
            context.SaveChanges();

            context.Products.RemoveRange(context.Products);
            context.SaveChanges();

            ((DbSet <IdentityRole>)context.Roles).RemoveRange(context.Roles);
            context.SaveChanges();
            context.Statistics.RemoveRange(context.Statistics);
            context.SaveChanges();

            context.Scans.RemoveRange(context.Scans);
            context.SaveChanges();

            // UserRoles
            context.Roles.Add(new IdentityRole("User"));
            context.Roles.Add(new IdentityRole("Employee"));
            context.Roles.Add(new IdentityRole("Administrator"));
            context.SaveChanges();

            // Company
            for (int i = 0; i < companyCount; ++i)
            {
                List <int> nipDigits  = new List <int>(new int[10]);
                List <int> nipWeights = new List <int>(new int[9] {
                    6, 5, 7, 2, 3, 4, 5, 6, 7
                });
                int nipLastDigit = 0;
                for (int j = 0; j < nipWeights.Count; j++)
                {
                    nipDigits[j]  = random.Next(10);
                    nipLastDigit += nipDigits[j] * nipWeights[j];
                }
                nipLastDigit = nipLastDigit % 11;
                nipDigits[9] = nipLastDigit;

                Company company = new Company
                {
                    Name           = "companyName" + i,
                    Kind           = ((random.Next(2) == 0) ? "Production" : "Services"),
                    AddressStreet  = "addressStreet" + random.Next(uniqueAddressStreetCount),
                    AddressZipCode = "CT-" + random.Next(99999),
                    AddressCity    = "addressCity" + random.Next(uniqueAddressCityCount),
                    Email          = "companyName" + i + "@mail.com",
                    NIP            = String.Join("", nipDigits),
                    REGON          = random.Next(999999999).ToString(),
                    JoinDate       = new DateTime(random.Next(2015, 2017), random.Next(12) + 1, random.Next(25) + 1)
                };
                context.Companies.AddOrUpdate(c => c.Name, company);
            }
            context.SaveChanges();

            // User
            var store   = new UserStore <ApplicationUser>(context);
            var manager = new ApplicationUserManager(store);

            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 1,
                RequireNonLetterOrDigit = false,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireUppercase        = false,
            };
            for (int i = 0; i < userCount; i++)
            {
                List <int> phoneNumber = new List <int>(new int[10]);
                for (int j = 0; j < phoneNumber.Count; j++)
                {
                    phoneNumber[j] = random.Next(10);
                }
                ApplicationUser user = new ApplicationUser
                {
                    Name    = "name" + i,
                    Surname = "surname" + random.Next(uniqueUserSurnameCount),

                    Email          = "user" + i + "@email.com",
                    UserName       = "******" + i + "@email.com",
                    EmailConfirmed = true,

                    PasswordHash = ("user" + i).GetHashCode().ToString(),

                    SecurityStamp = "?",

                    PhoneNumber = String.Join("", phoneNumber.ToArray()),

                    TwoFactorEnabled = false,

                    LockoutEnabled = false,

                    AccessFailedCount = 0
                };
                manager.CreateAsync(user, user.Name).Wait();

                if (i == 0)
                {
                    manager.AddToRoleAsync(user.Id, "Administrator").Wait();
                }
            }

            // Employee
            List <Employee> employees = new List <Employee>(employeeCount);

            for (int i = 0; i < employeeCount; i++)
            {
                Employee employee = new Employee
                {
                    UserId    = context.Users.ToList()[random.Next(context.Users.Count())].Id,
                    JoinDate  = new DateTime(random.Next(2015, 2018), random.Next(12) + 1, random.Next(25) + 1),
                    CompanyId = context.Companies.ToList()[random.Next(context.Companies.Count())].Id
                };
                employees.Add(employee);
                manager.AddToRoleAsync(employee.UserId, "Employee").Wait();
            }
            var distinceEmployees = employees.Distinct(new EmployeeEqualityComparer()).ToArray();

            context.Employees.AddOrUpdate(e => e.UserId, distinceEmployees);
            context.SaveChanges();

            // Product
            var products = new List <Product>(productCount);

            for (int i = 0; i < productCount; i++)
            {
                Product product = new Product
                {
                    Name            = "product" + i,
                    Barcode         = random.Next(9999999).ToString() + random.Next(999999),
                    Description     = "description" + i,
                    CreationDate    = new DateTime(random.Next(2015, 2017), random.Next(12) + 1, random.Next(25) + 1),//new DateTime(random.Next(2018, 2019), random.Next(1, 13), random.Next(25) + 1),
                    CountryOfOrigin = "country" + random.Next(10),
                    SuggestedPrice  = (decimal)random.Next(201),
                    CompanyId       = context.Companies.ToList()[random.Next(context.Companies.Count())].Id
                };
                products.Add(product);
            }
            context.Products.AddRange(products);
            context.SaveChanges();

            // Product picture
            string[] filePaths;
            try
            {
                string appDataPath  = AppDomain.CurrentDomain.BaseDirectory + "/App_Data";
                var    picturesPath = Path.Combine(appDataPath, "products");
                filePaths = Directory.GetFiles(picturesPath);
            }
            catch (Exception e)
            {
                string appDataPath  = AppDomain.CurrentDomain.BaseDirectory + "/.../App_Data";
                var    picturesPath = Path.Combine(appDataPath, "products");
                filePaths = Directory.GetFiles(picturesPath);
            }
            var pictures = new List <byte[]>();

            foreach (var path in filePaths)
            {
                var bytes = File.ReadAllBytes(path);
                pictures.Add(bytes);
            }

            var productPictures = new List <ProductPicture>(productCount);

            for (int i = 0; i < productCount; ++i)
            {
                var productPicture = new ProductPicture()
                {
                    ProductId = products[i].Id,
                    Content   = pictures[random.Next(pictures.Count)]
                };
                productPictures.Add(productPicture);
            }
            context.ProductPictures.AddRange(productPictures);
            context.SaveChanges();

            // ProductRating
            List <ProductRating> productRatings = new List <ProductRating>(productRatingCount);

            for (int i = 0; i < productRatingCount; i++)
            {
                int[]         rateArray     = new[] { 1, 2, 3, 4, 5 };
                ProductRating productRating = new ProductRating
                {
                    Rating    = random.Next(1, rateArray.Length),
                    UserId    = context.Users.ToList()[random.Next(context.Users.Count())].Id,
                    ProductId = context.Products.ToList()[random.Next(context.Products.Count())].Id,
                    Added     = new DateTime(2018, 12, random.Next(28) + 1)
                };
                if (!productRatings.Any(pr => pr.UserId.Equals(productRating.UserId) && pr.ProductId.Equals(productRating.ProductId)))
                {
                    productRatings.Add(productRating);
                }
            }
            context.ProductRatings.AddOrUpdate(pr => pr.UserId, productRatings.ToArray());
            context.SaveChanges();

            // WatchedProduct
            var watchedProductList = new List <WatchedProduct>(watchedProductCount);

            for (int i = 0; i < watchedProductCount; i++)
            {
                WatchedProduct watchedProduct = new WatchedProduct
                {
                    ApplicationUserId = context.Users.ToList()[random.Next(context.Users.Count())].Id,
                    ProductId         = context.Products.ToList()[random.Next(context.Products.Count())].Id
                };
                if (watchedProductList.Any(wp => wp.ApplicationUserId == watchedProduct.ApplicationUserId && wp.ProductId == watchedProduct.ProductId) == false)
                {
                    watchedProductList.Add(watchedProduct);
                }
            }
            context.WatchedProducts.AddRange(watchedProductList);
            context.SaveChanges();

            // ProductComment
            for (int i = 0; i < productCommentCount; i++)
            {
                var productComment = new ProductComment
                {
                    ApplicationUserId = context.Users.ToList()[random.Next(context.Users.Count())].Id,
                    ProductId         = context.Products.ToList()[random.Next(context.Products.Count())].Id,
                    Comment           = "Comment" + i,
                    Date = new DateTime(random.Next(2016, 2018), random.Next(12) + 1, random.Next(25) + 1)
                };
                context.ProductComments.AddOrUpdate(productComment);
            }
            context.SaveChanges();

            // CompanyReport
            for (int i = 0; i < companyReportCount; i++)
            {
                CompanyReport companyReport = new CompanyReport
                {
                    Content   = "content" + i,
                    CompanyId = context.Companies.ToList()[random.Next(context.Companies.Count())].Id
                };
                context.CompanyReports.AddOrUpdate(cr => cr.Content, companyReport);
            }
            context.SaveChanges();

            // ExistingProduct
            for (int i = 0; i < existingProductCount; i++)
            {
                ExistingProduct existingProduct = new ExistingProduct
                {
                    ExpirationDate = new DateTime(random.Next(2018, 2030), random.Next(12) + 1, random.Next(25) + 1),
                    CreationDate   = new DateTime(random.Next(2018, 2019), random.Next(1, 13), random.Next(25) + 1),
                    ProductId      = context.Products.ToList()[random.Next(context.Products.Count())].Id
                };
                existingProduct.GenerateSecret();
                context.ExistingProducts.AddOrUpdate(existingProduct);
            }
            context.SaveChanges();

            // QR

            /*List<QR> qrs = new List<QR>(qrCodeCount);
             * for (int i = 0; i < qrCodeCount; i++)
             * {
             *  QR qr = new QR
             *  {
             *      ExistingProductId = context.ExistingProducts.ToList()[random.Next(context.ExistingProducts.Count())].Id,
             *      Version = 1,
             *      Content = new byte[10]
             *  };
             *  qrs.Add(qr);
             *  //context.QRs.AddOrUpdate(q => q.ExistingProductId, qr);
             * }
             * var distinctQrs = qrs.Distinct(new QREqualityComparer()).ToArray();
             * context.QRs.AddOrUpdate(q => q.ExistingProductId, distinctQrs);
             * context.SaveChanges();*/

            // CompanyStatistics
            var companyStatistics = new List <CompanyStatistics>(companyCount * companyStatisticsCountPerCompany);

            foreach (var company in context.Companies)
            {
                for (int j = 0; j < companyStatisticsCountPerCompany; j++)
                {
                    var statistics = new CompanyStatistics()
                    {
                        CompanyId         = company.Id,
                        Date              = DateTime.Now.AddDays(-j).Date,
                        RegistredProducts = random.Next(10),
                    };
                    companyStatistics.Add(statistics);
                }
            }
            context.CompanyStatistics.AddRange(companyStatistics);
            context.SaveChanges();

            // Statistics
            var currentMonth          = DateTime.Now.Month;
            var currentYear           = DateTime.Now.Year;
            var currentMonthBeginning = new DateTime(currentYear, currentMonth, 1);

            context.Statistics.Add(new Statistics
            {
                LastMonthCompanyCount = context.Companies.Where(c => c.JoinDate < currentMonthBeginning).ToList().Count(),
                LastMonthProductCount = context.Products.Where(p => p.CreationDate < currentMonthBeginning).ToList().Count()
            });
            context.SaveChanges();

            // Scans
            var scans = new List <Scan>(scanCount);

            for (int i = 0; i < scanCount; ++i)
            {
                var scan = new Scan()
                {
                    UserId            = context.Users.ToList()[random.Next(context.Users.Count())].Id,
                    ExistingProductId = context.ExistingProducts.ToList()[random.Next(context.ExistingProducts.Count())].Id,
                    Date = DateTime.Now.AddDays(-i).Date,
                };
                if (scans.Any(s => s.UserId == scan.UserId && s.ExistingProductId == scan.ExistingProductId))
                {
                    continue;
                }
                scans.Add(scan);
            }
            context.Scans.AddRange(scans);
            context.SaveChanges();
        }
예제 #24
0
 public void AddProductPicture(ProductPicture picture)
 {
     db.AddToProductPictures(picture);
 }
 public void DeleteProductPicture(ProductPicture productPicture)
 {
     _context.ProductPictures.Remove(productPicture);
 }
예제 #26
0
        private void OnUpload(HttpContext context)
        {
            string errorMsg = "";

            try
            {
                int  effect              = 0;
                bool isCreateThumbnail   = ConfigHelper.GetValueByKey("IsCteateProductPictureThumbnail") == "1";
                UploadFilesHelper  ufh   = new UploadFilesHelper();
                HttpFileCollection files = context.Request.Files;
                foreach (string item in files.AllKeys)
                {
                    if (files[item] == null || files[item].ContentLength == 0)
                    {
                        continue;
                    }
                    string[]           paths   = ufh.Upload(files[item], "ProductPictures", isCreateThumbnail);
                    ProductPicture     ppBll   = new ProductPicture();
                    ProductPictureInfo ppModel = new ProductPictureInfo();

                    string originalPicturePath = "";
                    string bPicturePath        = "";
                    string mPicturePath        = "";
                    string sPicturePath        = "";
                    string otherPicturePath    = "";
                    for (int i = 0; i < paths.Length; i++)
                    {
                        switch (i)
                        {
                        case 0:
                            originalPicturePath = paths[i].Replace("~", "");
                            break;

                        case 1:
                            bPicturePath = paths[i].Replace("~", "");
                            break;

                        case 2:
                            mPicturePath = paths[i].Replace("~", "");
                            break;

                        case 3:
                            sPicturePath = paths[i].Replace("~", "");
                            break;

                        case 4:
                            otherPicturePath = paths[i].Replace("~", "");
                            break;

                        default:
                            break;
                        }
                    }
                    ppModel.OriginalPicture = originalPicturePath;
                    ppModel.BPicture        = bPicturePath;
                    ppModel.MPicture        = mPicturePath;
                    ppModel.SPicture        = sPicturePath;
                    ppModel.OtherPicture    = otherPicturePath;
                    ppModel.LastUpdatedDate = DateTime.Now;
                    ppBll.Insert(ppModel);
                    effect++;
                }

                if (effect == 0)
                {
                    context.Response.Write("{\"success\": false,\"message\": \"未找到任何可上传的文件,请检查!\"}");
                    return;
                }

                context.Response.Write("{\"success\": true,\"message\": \"已成功上传文件数:" + effect + "个\"}");
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
            }

            if (errorMsg != "")
            {
                context.Response.Write("{\"success\": false,\"message\": \"" + errorMsg + "\"}");
            }
        }
    public void RaiseCallbackEvent(string eventArgument)
    {
        Guid id;
        TemporaryAttachment ta;

        if (eventArgument == "refreshBinder")
        {
            switch (action)
            {
            case OperateType.Add:
                result = BindAttachment();
                break;

            case OperateType.Edit:
                result = BindPictures();
                break;
            }
        }
        if (eventArgument.StartsWith("deleteAttach"))
        {
            try
            {
                switch (action)
                {
                case OperateType.Add:
                    id = new Guid(eventArgument.Split(':')[1]);
                    TemporaryAttachments.Delete(id);
                    break;

                case OperateType.Edit:
                    ProductPictures.Delete(int.Parse(eventArgument.Split(':')[1]));
                    break;
                }
                result = "0";
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
        }
        if (eventArgument.StartsWith("setDefault"))
        {
            try
            {
                switch (action)
                {
                case OperateType.Add:
                    id = new Guid(eventArgument.Split(':')[1]);
                    ta = TemporaryAttachments.GetTemporaryAttachments(Profile.AccountInfo.UserID, AttachmentType.ProductPhoto)[0];
                    ta.DisplayOrder = 100;
                    TemporaryAttachments.Update(ta);

                    ta = TemporaryAttachments.GetTemporaryAttachment(id);
                    ta.DisplayOrder = 0;
                    TemporaryAttachments.Update(ta);

                    result = BindAttachment();
                    break;

                case OperateType.Edit:
                    int            picId = int.Parse(eventArgument.Split(':')[1]);
                    ProductPicture pics  = ProductPictures.GetPictures(productID)[0];
                    pics.DisplayOrder = 100;
                    ProductPictures.Update(pics);

                    pics = ProductPictures.GetPicture(picId);
                    pics.DisplayOrder = 0;
                    ProductPictures.Update(pics);

                    result = BindPictures();
                    break;
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
        }
    }
예제 #28
0
        public ActionResult Edit(Product product)
        {
            Product prd = new Product();
            ProductCategory prdCat = new ProductCategory();
            ProductPicture picProd = new ProductPicture();
            _productRepository.Update(product);

            prdCat.ProductID = product.ID;
            prdCat.CategoryID = product.CategoryID;

            if(product.CategoryID != 0)
            _categoryRepository.UpdateProductCategory(prdCat);

            picProd.PictureID = product.PictureID;
            picProd.ProductID = product.ID;
            if(product.PictureID != 0)
            _productRepository.UpdateProductPicture(picProd);

            return RedirectToAction("List");
        }
예제 #29
0
        protected virtual void ProcessProductPictures(ImportExecuteContext context, IEnumerable <ImportRow <Product> > batch)
        {
            // true, cause pictures must be saved and assigned an id prior adding a mapping.
            _productPictureRepository.AutoCommitEnabled = true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Perf: notify only about LAST insertion and update
            if (lastInserted != null)
            {
                _services.EventPublisher.EntityInserted(lastInserted);
            }
        }
예제 #30
0
        /// <summary>
        /// Import products from XLSX file
        /// </summary>
        /// <param name="stream">Stream</param>
        public virtual void ImportProductsFromXlsx(Stream stream)
        {
            // ok, we can run the real code of the sample now
            using (var xlPackage = new ExcelPackage(stream))
            {
                // get the first worksheet in the workbook
                var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
                if (worksheet == null)
                {
                    throw new NopException("No worksheet found");
                }


                //the columns
                var properties = new List <PropertyByName <Product> >();
                var poz        = 1;
                while (true)
                {
                    try
                    {
                        var cell = worksheet.Cells[1, poz];

                        if (cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString()))
                        {
                            break;
                        }

                        poz += 1;
                        properties.Add(new PropertyByName <Product>(cell.Value.ToString().ToLower()));
                    }
                    catch
                    {
                        break;
                    }
                }

                var manager = new PropertyManager <Product>(properties.ToArray());


                int iRow = 2;
                while (true)
                {
                    var allColumnsAreEmpty = manager.GetProperties
                                             .Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition])
                                             .All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString()));

                    if (allColumnsAreEmpty)
                    {
                        break;
                    }

                    manager.ReadFromXlsx(worksheet, iRow);
                    var sku = manager.GetProperty("sku") != null?manager.GetProperty("sku").StringValue : string.Empty;

                    var productid = manager.GetProperty("id") != null?manager.GetProperty("id").StringValue : string.Empty;

                    Product product = null;

                    if (!String.IsNullOrEmpty(sku))
                    {
                        product = _productService.GetProductBySku(sku);
                    }

                    if (!String.IsNullOrEmpty(productid))
                    {
                        product = _productService.GetProductById(productid);
                    }

                    var isNew = product == null;

                    product = product ?? new Product();

                    if (isNew)
                    {
                        product.CreatedOnUtc = DateTime.UtcNow;
                    }


                    foreach (var property in manager.GetProperties)
                    {
                        switch (property.PropertyName.ToLower())
                        {
                        case "producttypeid":
                            product.ProductTypeId = property.IntValue;
                            break;

                        case "parentgroupedproductid":
                            product.ParentGroupedProductId = property.StringValue;
                            break;

                        case "visibleindividually":
                            product.VisibleIndividually = property.BooleanValue;
                            break;

                        case "name":
                            product.Name = property.StringValue;
                            break;

                        case "shortdescription":
                            product.ShortDescription = property.StringValue;
                            break;

                        case "fulldescription":
                            product.FullDescription = property.StringValue;
                            break;

                        case "vendorid":
                            product.VendorId = property.StringValue;
                            break;

                        case "producttemplateid":
                            product.ProductTemplateId = property.StringValue;
                            break;

                        case "showonhomepage":
                            product.ShowOnHomePage = property.BooleanValue;
                            break;

                        case "metakeywords":
                            product.MetaKeywords = property.StringValue;
                            break;

                        case "metadescription":
                            product.MetaDescription = property.StringValue;
                            break;

                        case "metatitle":
                            product.MetaTitle = property.StringValue;
                            break;

                        case "allowcustomerreviews":
                            product.AllowCustomerReviews = property.BooleanValue;
                            break;

                        case "published":
                            product.Published = property.BooleanValue;
                            break;

                        case "sku":
                            product.Sku = property.StringValue;
                            break;

                        case "manufacturerpartnumber":
                            product.ManufacturerPartNumber = property.StringValue;
                            break;

                        case "gtin":
                            product.Gtin = property.StringValue;
                            break;

                        case "isgiftcard":
                            product.IsGiftCard = property.BooleanValue;
                            break;

                        case "giftcardtypeid":
                            product.GiftCardTypeId = property.IntValue;
                            break;

                        case "overriddengiftcardamount":
                            product.OverriddenGiftCardAmount = property.DecimalValue;
                            break;

                        case "requireotherproducts":
                            product.RequireOtherProducts = property.BooleanValue;
                            break;

                        case "requiredproductids":
                            product.RequiredProductIds = property.StringValue;
                            break;

                        case "automaticallyaddrequiredproducts":
                            product.AutomaticallyAddRequiredProducts = property.BooleanValue;
                            break;

                        case "isdownload":
                            product.IsDownload = property.BooleanValue;
                            break;

                        case "downloadid":
                            product.DownloadId = property.StringValue;
                            break;

                        case "unlimiteddownloads":
                            product.UnlimitedDownloads = property.BooleanValue;
                            break;

                        case "maxnumberofdownloads":
                            product.MaxNumberOfDownloads = property.IntValue;
                            break;

                        case "downloadactivationtypeid":
                            product.DownloadActivationTypeId = property.IntValue;
                            break;

                        case "hassampledownload":
                            product.HasSampleDownload = property.BooleanValue;
                            break;

                        case "sampledownloadid":
                            product.SampleDownloadId = property.StringValue;
                            break;

                        case "hasuseragreement":
                            product.HasUserAgreement = property.BooleanValue;
                            break;

                        case "useragreementtext":
                            product.UserAgreementText = property.StringValue;
                            break;

                        case "isrecurring":
                            product.IsRecurring = property.BooleanValue;
                            break;

                        case "recurringcyclelength":
                            product.RecurringCycleLength = property.IntValue;
                            break;

                        case "recurringcycleperiodid":
                            product.RecurringCyclePeriodId = property.IntValue;
                            break;

                        case "recurringtotalcycles":
                            product.RecurringTotalCycles = property.IntValue;
                            break;

                        case "isrental":
                            product.IsRental = property.BooleanValue;
                            break;

                        case "rentalpricelength":
                            product.RentalPriceLength = property.IntValue;
                            break;

                        case "rentalpriceperiodid":
                            product.RentalPricePeriodId = property.IntValue;
                            break;

                        case "isshipenabled":
                            product.IsShipEnabled = property.BooleanValue;
                            break;

                        case "isfreeshipping":
                            product.IsFreeShipping = property.BooleanValue;
                            break;

                        case "shipseparately":
                            product.ShipSeparately = property.BooleanValue;
                            break;

                        case "additionalshippingcharge":
                            product.AdditionalShippingCharge = property.DecimalValue;
                            break;

                        case "deliverydateId":
                            product.DeliveryDateId = property.StringValue;
                            break;

                        case "istaxexempt":
                            product.IsTaxExempt = property.BooleanValue;
                            break;

                        case "taxcategoryid":
                            product.TaxCategoryId = property.StringValue;
                            break;

                        case "istelecommunicationsorbroadcastingorelectronicservices":
                            product.IsTelecommunicationsOrBroadcastingOrElectronicServices = property.BooleanValue;
                            break;

                        case "manageinventorymethodid":
                            product.ManageInventoryMethodId = property.IntValue;
                            break;

                        case "usemultiplewarehouses":
                            product.UseMultipleWarehouses = property.BooleanValue;
                            break;

                        case "warehouseid":
                            product.WarehouseId = property.StringValue;
                            break;

                        case "stockquantity":
                            product.StockQuantity = property.IntValue;
                            break;

                        case "displaystockavailability":
                            product.DisplayStockAvailability = property.BooleanValue;
                            break;

                        case "displaystockquantity":
                            product.DisplayStockQuantity = property.BooleanValue;
                            break;

                        case "minstockquantity":
                            product.MinStockQuantity = property.IntValue;
                            break;

                        case "lowstockactivityid":
                            product.LowStockActivityId = property.IntValue;
                            break;

                        case "notifyadminforquantitybelow":
                            product.NotifyAdminForQuantityBelow = property.IntValue;
                            break;

                        case "backordermodeid":
                            product.BackorderModeId = property.IntValue;
                            break;

                        case "allowbackinstocksubscriptions":
                            product.AllowBackInStockSubscriptions = property.BooleanValue;
                            break;

                        case "orderminimumquantity":
                            product.OrderMinimumQuantity = property.IntValue;
                            break;

                        case "ordermaximumquantity":
                            product.OrderMaximumQuantity = property.IntValue;
                            break;

                        case "allowedquantities":
                            product.AllowedQuantities = property.StringValue;
                            break;

                        case "allowaddingonlyexistingattributecombinations":
                            product.AllowAddingOnlyExistingAttributeCombinations = property.BooleanValue;
                            break;

                        case "disablebuybutton":
                            product.DisableBuyButton = property.BooleanValue;
                            break;

                        case "disablewishlistbutton":
                            product.DisableWishlistButton = property.BooleanValue;
                            break;

                        case "availableforpreorder":
                            product.AvailableForPreOrder = property.BooleanValue;
                            break;

                        case "preorderavailabilitystartdatetimeutc":
                            product.PreOrderAvailabilityStartDateTimeUtc = property.DateTimeNullable;
                            break;

                        case "callforprice":
                            product.CallForPrice = property.BooleanValue;
                            break;

                        case "price":
                            product.Price = property.DecimalValue;
                            break;

                        case "oldprice":
                            product.OldPrice = property.DecimalValue;
                            break;

                        case "productcost":
                            product.ProductCost = property.DecimalValue;
                            break;

                        case "specialprice":
                            product.SpecialPrice = property.DecimalValueNullable;
                            break;

                        case "specialpricestartdatetimeutc":
                            product.SpecialPriceStartDateTimeUtc = property.DateTimeNullable;
                            break;

                        case "specialpriceenddatetimeutc":
                            product.SpecialPriceEndDateTimeUtc = property.DateTimeNullable;
                            break;

                        case "customerentersprice":
                            product.CustomerEntersPrice = property.BooleanValue;
                            break;

                        case "minimumcustomerenteredprice":
                            product.MinimumCustomerEnteredPrice = property.DecimalValue;
                            break;

                        case "maximumcustomerenteredprice":
                            product.MaximumCustomerEnteredPrice = property.DecimalValue;
                            break;

                        case "basepriceenabled":
                            product.BasepriceEnabled = property.BooleanValue;
                            break;

                        case "basepriceamount":
                            product.BasepriceAmount = property.DecimalValue;
                            break;

                        case "basepriceunitid":
                            product.BasepriceUnitId = property.StringValue;
                            break;

                        case "basepricebaseamount":
                            product.BasepriceBaseAmount = property.DecimalValue;
                            break;

                        case "basepricebaseunitid":
                            product.BasepriceBaseUnitId = property.StringValue;
                            break;

                        case "markasnew":
                            product.MarkAsNew = property.BooleanValue;
                            break;

                        case "markasnewstartdatetimeutc":
                            product.MarkAsNewStartDateTimeUtc = property.DateTimeNullable;
                            break;

                        case "markasnewenddatetimeutc":
                            product.MarkAsNewEndDateTimeUtc = property.DateTimeNullable;
                            break;

                        case "unitid":
                            product.UnitId = property.StringValue;
                            break;

                        case "weight":
                            product.Weight = property.DecimalValue;
                            break;

                        case "length":
                            product.Length = property.DecimalValue;
                            break;

                        case "width":
                            product.Width = property.DecimalValue;
                            break;

                        case "height":
                            product.Height = property.DecimalValue;
                            break;
                        }
                    }

                    if (isNew && properties.All(p => p.PropertyName.ToLower() != "producttypeid"))
                    {
                        product.ProductType = ProductType.SimpleProduct;
                    }

                    var categoryIds = manager.GetProperty("categoryids") != null?manager.GetProperty("categoryids").StringValue : string.Empty;

                    var manufacturerIds = manager.GetProperty("manufacturerids") != null?manager.GetProperty("manufacturerids").StringValue : string.Empty;

                    var picture1 = manager.GetProperty("picture1") != null?manager.GetProperty("picture1").StringValue : string.Empty;

                    var picture2 = manager.GetProperty("picture2") != null?manager.GetProperty("picture2").StringValue : string.Empty;

                    var picture3 = manager.GetProperty("picture3") != null?manager.GetProperty("picture3").StringValue : string.Empty;

                    product.UpdatedOnUtc = DateTime.UtcNow;

                    if (isNew)
                    {
                        _productService.InsertProduct(product);
                    }
                    else
                    {
                        _productService.UpdateProduct(product);
                    }

                    //search engine name
                    var seName = manager.GetProperty("sename") != null?manager.GetProperty("sename").StringValue : product.Name;

                    _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), "");
                    var _seName = product.ValidateSeName(seName, product.Name, true);
                    //search engine name
                    _urlRecordService.SaveSlug(product, _seName, "");
                    product.SeName = _seName;
                    _productService.UpdateProduct(product);
                    //category mappings
                    if (!String.IsNullOrEmpty(categoryIds))
                    {
                        foreach (var id in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()))
                        {
                            if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null)
                            {
                                //ensure that category exists
                                var category = _categoryService.GetCategoryById(id);
                                if (category != null)
                                {
                                    var productCategory = new ProductCategory
                                    {
                                        ProductId         = product.Id,
                                        CategoryId        = category.Id,
                                        IsFeaturedProduct = false,
                                        DisplayOrder      = 1
                                    };
                                    _categoryService.InsertProductCategory(productCategory);
                                }
                            }
                        }
                    }

                    //manufacturer mappings
                    if (!String.IsNullOrEmpty(manufacturerIds))
                    {
                        foreach (var id in manufacturerIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()))
                        {
                            if (product.ProductManufacturers.FirstOrDefault(x => x.ManufacturerId == id) == null)
                            {
                                //ensure that manufacturer exists
                                var manufacturer = _manufacturerService.GetManufacturerById(id);
                                if (manufacturer != null)
                                {
                                    var productManufacturer = new ProductManufacturer
                                    {
                                        ProductId         = product.Id,
                                        ManufacturerId    = manufacturer.Id,
                                        IsFeaturedProduct = false,
                                        DisplayOrder      = 1
                                    };
                                    _manufacturerService.InsertProductManufacturer(productManufacturer);
                                }
                            }
                        }
                    }

                    //pictures
                    foreach (var picturePath in new[] { picture1, picture2, picture3 })
                    {
                        if (String.IsNullOrEmpty(picturePath))
                        {
                            continue;
                        }

                        var mimeType             = GetMimeTypeFromFilePath(picturePath);
                        var newPictureBinary     = File.ReadAllBytes(picturePath);
                        var pictureAlreadyExists = false;
                        if (!isNew)
                        {
                            //compare with existing product pictures
                            var existingPictures = product.ProductPictures;
                            foreach (var existingPicture in existingPictures)
                            {
                                var pp             = _pictureService.GetPictureById(existingPicture.PictureId);
                                var existingBinary = _pictureService.LoadPictureBinary(pp);
                                //picture binary after validation (like in database)
                                var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
                                if (existingBinary.SequenceEqual(validatedPictureBinary) || existingBinary.SequenceEqual(newPictureBinary))
                                {
                                    //the same picture content
                                    pictureAlreadyExists = true;
                                    break;
                                }
                            }
                        }

                        if (!pictureAlreadyExists)
                        {
                            var picture        = _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.Name));
                            var productPicture = new ProductPicture
                            {
                                PictureId    = picture.Id,
                                ProductId    = product.Id,
                                DisplayOrder = 1,
                            };
                            _productService.InsertProductPicture(productPicture);
                        }
                    }

                    //update "HasTierPrices" and "HasDiscountsApplied" properties
                    _productService.UpdateHasTierPricesProperty(product.Id);
                    _productService.UpdateHasDiscountsApplied(product.Id);



                    //next product
                    iRow++;
                }
            }
        }
예제 #31
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();
            }
        }
예제 #32
0
 public static ProductPicture ToEntity(this ProductPictureModel model, ProductPicture destination)
 {
     return(model.MapTo(destination));
 }