public void Execute(IImportExecuteContext context)
        {
            var utcNow         = DateTime.UtcNow;
            var currentStoreId = _services.StoreContext.CurrentStore.Id;

            var toAdd    = new List <NewsLetterSubscription>();
            var toUpdate = new List <NewsLetterSubscription>();

            using (var scope = new DbContextScope(ctx: _services.DbContext, autoDetectChanges: false, proxyCreation: false, validateOnSave: false, autoCommit: false))
            {
                var segmenter = context.GetSegmenter <NewsLetterSubscription>();

                context.Result.TotalRecords = segmenter.TotalRows;

                while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                {
                    var batch = segmenter.CurrentBatch;

                    _subscriptionRepository.Context.DetachAll(false);

                    context.SetProgress(segmenter.CurrentSegmentFirstRowIndex - 1, segmenter.TotalRows);

                    foreach (var row in batch)
                    {
                        try
                        {
                            var email   = row.GetDataValue <string>("Email");
                            var active  = row.GetDataValue <bool>("Active");
                            var storeId = row.GetDataValue <int>("StoreId");

                            if (storeId == 0)
                            {
                                storeId = currentStoreId;
                            }

                            if (email.IsEmpty())
                            {
                                context.Result.AddWarning("Skipped empty email address", row.GetRowInfo(), "Email");
                                continue;
                            }

                            if (email.Length > 255)
                            {
                                context.Result.AddWarning("Skipped email address '{0}'. It exceeds the maximum allowed length of 255".FormatInvariant(email), row.GetRowInfo(), "Email");
                                continue;
                            }

                            if (!email.IsEmail())
                            {
                                context.Result.AddWarning("Skipped invalid email address '{0}'".FormatInvariant(email), row.GetRowInfo(), "Email");
                                continue;
                            }

                            NewsLetterSubscription subscription = null;

                            foreach (var keyName in context.KeyFieldNames)
                            {
                                switch (keyName)
                                {
                                case "Email":
                                    subscription = _subscriptionRepository.Table
                                                   .OrderBy(x => x.Id)
                                                   .FirstOrDefault(x => x.Email == email && x.StoreId == storeId);
                                    break;
                                }

                                if (subscription != null)
                                {
                                    break;
                                }
                            }

                            if (subscription == null)
                            {
                                if (context.UpdateOnly)
                                {
                                    ++context.Result.SkippedRecords;
                                    continue;
                                }

                                subscription = new NewsLetterSubscription
                                {
                                    Active       = active,
                                    CreatedOnUtc = utcNow,
                                    Email        = email,
                                    NewsLetterSubscriptionGuid = Guid.NewGuid(),
                                    StoreId = storeId
                                };

                                toAdd.Add(subscription);
                                ++context.Result.NewRecords;
                            }
                            else
                            {
                                subscription.Active = active;

                                toUpdate.Add(subscription);
                                ++context.Result.ModifiedRecords;
                            }

                            // insert new subscribers
                            _subscriptionRepository.AutoCommitEnabled = true;
                            _subscriptionRepository.InsertRange(toAdd, 500);
                            toAdd.Clear();

                            // update modified subscribers
                            _subscriptionRepository.UpdateRange(toUpdate);
                            toUpdate.Clear();
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception.ToAllMessages(), row.GetRowInfo());
                        }
                    }
                }
            }
        }
Beispiel #2
0
        protected override void Import(IImportExecuteContext context)
        {
            var srcToDestId = new Dictionary <int, ImportCategoryMapping>();

            var templateViewPaths = _categoryTemplateService.GetAllCategoryTemplates()
                                    .GroupBy(x => x.ViewPath, StringComparer.OrdinalIgnoreCase)
                                    .ToDictionary(x => x.Key, x => x.First().Id);

            using (var scope = new DbContextScope(ctx: _categoryRepository.Context, autoDetectChanges: false, proxyCreation: false, validateOnSave: false))
            {
                var segmenter = context.GetSegmenter <Category>();

                Init(context, _dataExchangeSettings);

                context.Result.TotalRecords = segmenter.TotalRows;

                while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                {
                    var batch = segmenter.CurrentBatch;

                    // Perf: detach all entities
                    _categoryRepository.Context.DetachAll(false);

                    context.SetProgress(segmenter.CurrentSegmentFirstRowIndex - 1, segmenter.TotalRows);

                    try
                    {
                        ProcessCategories(context, batch, templateViewPaths, srcToDestId);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessCategories");
                    }

                    // reduce batch to saved (valid) products.
                    // No need to perform import operations on errored products.
                    batch = batch.Where(x => x.Entity != null && !x.IsTransient).ToArray();

                    // update result object
                    context.Result.NewRecords      += batch.Count(x => x.IsNew && !x.IsTransient);
                    context.Result.ModifiedRecords += batch.Count(x => !x.IsNew && !x.IsTransient);

                    // process slugs
                    if (segmenter.HasColumn("SeName") || batch.Any(x => x.IsNew || x.NameChanged))
                    {
                        try
                        {
                            _categoryRepository.Context.AutoDetectChangesEnabled = true;
                            ProcessSlugs(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessSlugs");
                        }
                        finally
                        {
                            _categoryRepository.Context.AutoDetectChangesEnabled = false;
                        }
                    }

                    // process store mappings
                    if (segmenter.HasColumn("LimitedToStores") && segmenter.HasColumn("StoreIds"))
                    {
                        try
                        {
                            _categoryRepository.Context.AutoDetectChangesEnabled = true;
                            ProcessStoreMappings(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessStoreMappings");
                        }
                        finally
                        {
                            _categoryRepository.Context.AutoDetectChangesEnabled = false;
                        }
                    }

                    // localizations
                    try
                    {
                        ProcessLocalizations(context, batch);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessLocalizedProperties");
                    }

                    // process pictures
                    if (srcToDestId.Any() && segmenter.HasColumn("ImageUrl"))
                    {
                        try
                        {
                            _categoryRepository.Context.AutoDetectChangesEnabled = true;
                            ProcessPictures(context, batch, srcToDestId);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessPictures");
                        }
                        finally
                        {
                            _categoryRepository.Context.AutoDetectChangesEnabled = false;
                        }
                    }
                }

                // map parent id of inserted categories
                if (srcToDestId.Any() && segmenter.HasColumn("Id") && segmenter.HasColumn("ParentCategoryId"))
                {
                    segmenter.Reset();

                    while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                    {
                        var batch = segmenter.CurrentBatch;

                        _categoryRepository.Context.DetachAll(false);

                        try
                        {
                            ProcessParentMappings(context, batch, srcToDestId);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessParentMappings");
                        }
                    }
                }
            }
        }
        protected override void Import(IImportExecuteContext context)
        {
            var customer = _services.WorkContext.CurrentCustomer;
            var allowManagingCustomerRoles = _services.Permissions.Authorize(StandardPermissionProvider.ManageCustomerRoles, customer);

            var allCustomerRoles = _customerService.GetAllCustomerRoles(true);

            var allAffiliateIds = _affiliateService.GetAllAffiliates(true)
                                  .Select(x => x.Id)
                                  .ToList();

            var allCountryIds = _countryService.GetAllCountries(true)
                                .Select(x => x.Id)
                                .ToList();

            var allStateProvinceIds = _stateProvinceService.GetAllStateProvinces(true)
                                      .Select(x => x.Id)
                                      .ToList();

            var allCustomerNumbers = _genericAttributeService.GetAttributes(SystemCustomerAttributeNames.CustomerNumber, _attributeKeyGroup)
                                     .Select(x => x.Value)
                                     .ToList();

            using (var scope = new DbContextScope(ctx: _services.DbContext, autoDetectChanges: false, proxyCreation: false, validateOnSave: false, autoCommit: false))
            {
                var segmenter = context.GetSegmenter <Customer>();

                Init(context, _dataExchangeSettings);

                context.Result.TotalRecords = segmenter.TotalRows;

                while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                {
                    var batch = segmenter.CurrentBatch;

                    _customerRepository.Context.DetachAll(false);

                    context.SetProgress(segmenter.CurrentSegmentFirstRowIndex - 1, segmenter.TotalRows);

                    try
                    {
                        ProcessCustomers(context, batch, allAffiliateIds, allCustomerRoles);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessCustomers");
                    }

                    // reduce batch to saved (valid) records.
                    // No need to perform import operations on errored records.
                    batch = batch.Where(x => x.Entity != null && !x.IsTransient).ToArray();

                    // update result object
                    context.Result.NewRecords      += batch.Count(x => x.IsNew && !x.IsTransient);
                    context.Result.ModifiedRecords += batch.Count(x => !x.IsNew && !x.IsTransient);

                    try
                    {
                        _services.DbContext.AutoDetectChangesEnabled = true;

                        ProcessGenericAttributes(context, batch, allCountryIds, allStateProvinceIds, allCustomerNumbers);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessGenericAttributes");
                    }
                    finally
                    {
                        _services.DbContext.AutoDetectChangesEnabled = false;
                    }
                }
            }
        }
Beispiel #4
0
        protected override void Import(IImportExecuteContext context)
        {
            var srcToDestId = new Dictionary <int, ImportProductMapping>();

            var templateViewPaths = _productTemplateService.GetAllProductTemplates()
                                    .GroupBy(x => x.ViewPath, StringComparer.OrdinalIgnoreCase)
                                    .ToDictionary(x => x.Key, x => x.First().Id);

            using (var scope = new DbContextScope(ctx: _productRepository.Context, autoDetectChanges: false, proxyCreation: false, validateOnSave: false))
            {
                var segmenter = context.GetSegmenter <Product>();

                Init(context, _dataExchangeSettings);

                context.Result.TotalRecords = segmenter.TotalRows;

                while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                {
                    var batch = segmenter.CurrentBatch;

                    // Perf: detach all entities
                    _productRepository.Context.DetachAll(false);

                    context.SetProgress(segmenter.CurrentSegmentFirstRowIndex - 1, segmenter.TotalRows);

                    // ===========================================================================
                    // 1.) Import products
                    // ===========================================================================
                    try
                    {
                        ProcessProducts(context, batch, templateViewPaths, srcToDestId);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessProducts");
                    }

                    // reduce batch to saved (valid) products.
                    // No need to perform import operations on errored products.
                    batch = batch.Where(x => x.Entity != null && !x.IsTransient).ToArray();

                    // update result object
                    context.Result.NewRecords      += batch.Count(x => x.IsNew && !x.IsTransient);
                    context.Result.ModifiedRecords += batch.Count(x => !x.IsNew && !x.IsTransient);

                    // ===========================================================================
                    // 2.) Import SEO Slugs
                    // IMPORTANT: Unlike with Products AutoCommitEnabled must be TRUE,
                    //            as Slugs are going to be validated against existing ones in DB.
                    // ===========================================================================
                    if (segmenter.HasColumn("SeName") || batch.Any(x => x.IsNew || x.NameChanged))
                    {
                        try
                        {
                            _productRepository.Context.AutoDetectChangesEnabled = true;
                            ProcessSlugs(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessSlugs");
                        }
                        finally
                        {
                            _productRepository.Context.AutoDetectChangesEnabled = false;
                        }
                    }

                    if (segmenter.HasColumn("LimitedToStores") && segmenter.HasColumn("StoreIds"))
                    {
                        try
                        {
                            _productRepository.Context.AutoDetectChangesEnabled = true;
                            ProcessStoreMappings(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessStoreMappings");
                        }
                        finally
                        {
                            _productRepository.Context.AutoDetectChangesEnabled = false;
                        }
                    }

                    // ===========================================================================
                    // 3.) Import Localizations
                    // ===========================================================================
                    try
                    {
                        ProcessLocalizations(context, batch);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessLocalizations");
                    }

                    // ===========================================================================
                    // 4.) Import product category mappings
                    // ===========================================================================
                    if (segmenter.HasColumn("CategoryIds"))
                    {
                        try
                        {
                            ProcessProductCategories(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessProductCategories");
                        }
                    }

                    // ===========================================================================
                    // 5.) Import product manufacturer mappings
                    // ===========================================================================
                    if (segmenter.HasColumn("ManufacturerIds"))
                    {
                        try
                        {
                            ProcessProductManufacturers(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessProductManufacturers");
                        }
                    }

                    // ===========================================================================
                    // 6.) Import product picture mappings
                    // ===========================================================================
                    if (segmenter.HasColumn("ImageUrls"))
                    {
                        try
                        {
                            ProcessProductPictures(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessProductPictures");
                        }
                    }
                }

                // ===========================================================================
                // 7.) Map parent id of inserted products
                // ===========================================================================
                if (srcToDestId.Any() && segmenter.HasColumn("Id") && segmenter.HasColumn("ParentGroupedProductId"))
                {
                    segmenter.Reset();

                    while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                    {
                        var batch = segmenter.CurrentBatch;

                        _productRepository.Context.DetachAll(false);

                        try
                        {
                            ProcessProductMappings(context, batch, srcToDestId);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessParentMappings");
                        }
                    }
                }
            }
        }