private IEnumerable <StateProvinceViewModel> GetAllStateProvinces()
        {
            var stateProvinces   = _stateProvinceService.GetAllStateProvinces();
            var stateProvincesVm = Mapper.Map <IEnumerable <StateProvince>, IEnumerable <StateProvinceViewModel> >(stateProvinces);

            return(stateProvincesVm);
        }
        private void PrepareModel(ByRegionTaxRateListModel model)
        {
            var taxCategories  = _taxCategoryService.GetAllTaxCategories().ToDictionary(x => x.Id);
            var taxRates       = _taxRateService.GetAllTaxRates();
            var countries      = _countryService.GetAllCountries(true).ToDictionary(x => x.Id);
            var stateProvinces = _stateProvinceService.GetAllStateProvinces(true).ToDictionary(x => x.Id);
            var stateProvincesOfFirstCountry = stateProvinces.Values.Where(x => x.CountryId == countries.Values.FirstOrDefault().Id).ToList();
            var unavailable = T("Common.Unavailable").Text;

            model.AvailableTaxCategories = taxCategories.Values.Select(x => new SelectListItem
            {
                Text  = x.Name,
                Value = x.Id.ToString()
            })
                                           .ToList();

            model.AvailableCountries = countries.Values.Select(x => new SelectListItem
            {
                Text  = x.Name,
                Value = x.Id.ToString()
            })
                                       .ToList();

            model.AvailableStates = stateProvincesOfFirstCountry.Select(x => new SelectListItem
            {
                Text  = x.Name,
                Value = x.Id.ToString()
            })
                                    .ToList();
            model.AvailableStates.Insert(0, new SelectListItem {
                Text = "*", Value = "0"
            });

            model.TaxRates = taxRates.Select(x =>
            {
                var m = new ByRegionTaxRateModel
                {
                    Id              = x.Id,
                    TaxCategoryId   = x.TaxCategoryId,
                    CountryId       = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip             = x.Zip.HasValue() ? x.Zip : "*",
                    Percentage      = x.Percentage
                };

                taxCategories.TryGetValue(x.TaxCategoryId, out TaxCategory tc);
                m.TaxCategoryName = tc?.Name.EmptyNull();

                countries.TryGetValue(x.CountryId, out Country c);
                m.CountryName = c?.Name ?? unavailable;

                stateProvinces.TryGetValue(x.StateProvinceId, out StateProvince s);
                m.StateProvinceName = s?.Name ?? "*";

                return(m);
            })
                             .ToList();
        }
示例#3
0
        public ActionResult GetAllStates()
        {
            var states = _stateProvinceService.GetAllStateProvinces().ToList();
            var result = (from s in states
                          select new { id = s.Id, name = s.GetLocalized(x => x.Name).Value })
                         .ToList();

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
示例#4
0
        protected override void Import(ImportExecuteContext context)
        {
            var customer = _services.WorkContext.CurrentCustomer;
            var allowManagingCustomerRoles = _services.Permissions.Authorize(StandardPermissionProvider.ManageCustomerRoles, customer);

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

            var allCountries = new Dictionary <string, int>();

            foreach (var country in _countryService.GetAllCountries(true))
            {
                if (!allCountries.ContainsKey(country.TwoLetterIsoCode))
                {
                    allCountries.Add(country.TwoLetterIsoCode, country.Id);
                }

                if (!allCountries.ContainsKey(country.ThreeLetterIsoCode))
                {
                    allCountries.Add(country.ThreeLetterIsoCode, country.Id);
                }
            }

            var allStateProvinces = _stateProvinceService.GetAllStateProvinces(true)
                                    .ToDictionarySafe(x => new Tuple <int, string>(x.CountryId, x.Abbreviation), x => x.Id);

            var allCustomerNumbers = new HashSet <string>(
                _genericAttributeService.GetAttributes(SystemCustomerAttributeNames.CustomerNumber, _attributeKeyGroup).Select(x => x.Value),
                StringComparer.OrdinalIgnoreCase);

            var allCustomerRoles = _customerRoleRepository.Table.ToDictionarySafe(x => x.SystemName, StringComparer.OrdinalIgnoreCase);

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

                Initialize(context);
                AddInfoForDeprecatedFields(context);

                while (context.Abort == DataExchangeAbortion.None && segmenter.ReadNextBatch())
                {
                    var batch = segmenter.GetCurrentBatch <Customer>();

                    _customerRepository.Context.DetachAll(true);

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

                    // ===========================================================================
                    // Process customers
                    // ===========================================================================
                    try
                    {
                        ProcessCustomers(context, batch, allAffiliateIds);
                    }
                    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);

                    // ===========================================================================
                    // Process customer roles
                    // ===========================================================================
                    try
                    {
                        _customerRepository.Context.AutoDetectChangesEnabled = true;
                        ProcessCustomerRoles(context, batch, allCustomerRoles);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessCustomerRoles");
                    }
                    finally
                    {
                        _customerRepository.Context.AutoDetectChangesEnabled = false;
                    }

                    // ===========================================================================
                    // Process generic attributes
                    // ===========================================================================
                    try
                    {
                        ProcessGenericAttributes(context, batch, allCountries, allStateProvinces, allCustomerNumbers);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessGenericAttributes");
                    }

                    // ===========================================================================
                    // Process avatars
                    // ===========================================================================
                    if (_customerSettings.AllowCustomersToUploadAvatars)
                    {
                        try
                        {
                            ProcessAvatars(context, batch);
                        }
                        catch (Exception exception)
                        {
                            context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessAvatars");
                        }
                    }

                    // ===========================================================================
                    // Process addresses
                    // ===========================================================================
                    try
                    {
                        _services.DbContext.AutoDetectChangesEnabled = true;
                        ProcessAddresses(context, batch, allCountries, allStateProvinces);
                    }
                    catch (Exception exception)
                    {
                        context.Result.AddError(exception, segmenter.CurrentSegment, "ProcessAddresses");
                    }
                    finally
                    {
                        _services.DbContext.AutoDetectChangesEnabled = false;
                    }
                }
            }
        }
        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;
                    }
                }
            }
        }
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Model</param>
        /// <param name="address">Address</param>
        /// <param name="excludeProperties">A value indicating whether to exclude properties</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="localizationService">Localization service (used to prepare a select list)</param>
        /// <param name="stateProvinceService">State service (used to prepare a select list). null to don't prepare the list.</param>
        /// <param name="loadCountries">A function to load countries  (used to prepare a select list). null to don't prepare the list.</param>
        public static void PrepareModel(this AddressModel model,
                                        Address address,
                                        bool excludeProperties,
                                        AddressSettings addressSettings,
                                        ILocalizationService localizationService   = null,
                                        IStateProvinceService stateProvinceService = null,
                                        Func <IList <Country> > loadCountries      = null)
        {
            Guard.NotNull(model, nameof(model));
            Guard.NotNull(addressSettings, nameof(addressSettings));

            // Form fields
            MiniMapper.Map(addressSettings, model);

            if (!excludeProperties && address != null)
            {
                MiniMapper.Map(address, model);

                model.EmailMatch  = address.Email;
                model.CountryName = address.Country?.GetLocalized(x => x.Name);
                if (address.StateProvinceId.HasValue && address.StateProvince != null)
                {
                    model.StateProvinceName = address.StateProvince.GetLocalized(x => x.Name);
                }
                model.FormattedAddress = Core.Infrastructure.EngineContext.Current.Resolve <IAddressService>().FormatAddress(address, true);
            }

            // Countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                if (localizationService == null)
                {
                    throw new ArgumentNullException("localizationService");
                }

                model.AvailableCountries.Add(new SelectListItem {
                    Text = localizationService.GetResource("Address.SelectCountry"), Value = "0"
                });
                var listOfCountries = loadCountries();

                foreach (var c in listOfCountries)
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = c.GetLocalized(x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    // States
                    if (stateProvinceService == null)
                    {
                        throw new ArgumentNullException("stateProvinceService");
                    }

                    var states = stateProvinceService
                                 .GetAllStateProvinces()
                                 .ToList();
                    if (states.Count > 0)
                    {
                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = s.GetLocalized(x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = localizationService.GetResource("Address.OtherNonUS"),
                            Value = "0"
                        });
                    }
                }
            }

            if (localizationService != null)
            {
                string salutations = addressSettings.GetLocalized(x => x.Salutations);
                foreach (var sal in salutations.SplitSafe(","))
                {
                    model.AvailableSalutations.Add(new SelectListItem {
                        Value = sal, Text = sal
                    });
                }
            }
        }