public void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            //Load custom data settings
            var dataSettingsManager = new DataSettingsManager();
            DataSettings dataSettings = dataSettingsManager.LoadSettings();

            string nameOrConnectionString = null;

            if (dataSettings != null && dataSettings.IsValid())
            {
                //determine if the connection string exists
                nameOrConnectionString = dataSettings.DataConnectionString;
            }

            //Register custom object context
            builder.Register<IDbContext>(c => RegisterIDbContext(c, dataSettings)).Named<IDbContext>(CONTEXT_NAME).InstancePerHttpRequest();
            builder.Register(c => RegisterIDbContext(c, dataSettings)).InstancePerHttpRequest();

            //Register services
            builder.RegisterType<ViewTrackingService>().As<IViewTrackingService>();

            builder.RegisterType<NopCommerceC5ConnectorInstallationService>().AsSelf().InstancePerHttpRequest();

            //Override the repository injection
            builder.RegisterType<EfRepository<TrackingRecord>>().As<IRepository<TrackingRecord>>().WithParameter(ResolvedParameter.ForNamed<IDbContext>(CONTEXT_NAME)).InstancePerHttpRequest();
        }
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            builder.RegisterType<ShippingByWeightService>().As<IShippingByWeightService>().InstancePerHttpRequest();

            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new ShippingByWeightObjectContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>("nop_object_context_shipping_weight_zip")
                    .InstancePerHttpRequest();

                builder.Register<ShippingByWeightObjectContext>(c => new ShippingByWeightObjectContext(dataProviderSettings.DataConnectionString))
                    .InstancePerHttpRequest();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new ShippingByWeightObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>("nop_object_context_shipping_weight_zip")
                    .InstancePerHttpRequest();

                builder.Register<ShippingByWeightObjectContext>(c => new ShippingByWeightObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerHttpRequest();
            }

            //override required repository with our custom context
            builder.RegisterType<EfRepository<ShippingByWeightRecord>>()
                .As<IRepository<ShippingByWeightRecord>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_shipping_weight_zip"))
                .InstancePerHttpRequest();
        }
Ejemplo n.º 3
0
 public static void InitConnectionString()
 {
     var manager = new DataSettingsManager();
     var settings = manager.LoadSettings();
     if (!String.IsNullOrEmpty(settings.DataConnectionString))
         _connectionString = settings.DataConnectionString;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Returns a value indicating whether database is already installed
 /// </summary>
 /// <returns></returns>
 public static bool DatabaseIsInstalled()
 {
     if (!_databaseIsInstalled.HasValue)
     {
         var manager = new DataSettingsManager();
         var settings = manager.LoadSettings();
         _databaseIsInstalled = settings != null && !String.IsNullOrEmpty(settings.DataConnectionString);
     }
     return _databaseIsInstalled.Value;
 }
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            builder.RegisterType<ExtendedVendorService>().As<IExtendedVendorService>().InstancePerRequest();

            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new ExtendedVendorObjectContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>(CONTEXT_NAME)
                    .InstancePerRequest();

                builder.Register<ExtendedVendorObjectContext>(c => new ExtendedVendorObjectContext(dataProviderSettings.DataConnectionString))
                    .InstancePerRequest();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new ExtendedVendorObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>(CONTEXT_NAME)
                    .InstancePerRequest();

                builder.Register<ExtendedVendorObjectContext>(c => new ExtendedVendorObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerRequest();
            }

            //override required repository with our custom context
            builder.RegisterType<EfRepository<Domain.ExtendedVendor>>()
                .As<IRepository<Domain.ExtendedVendor>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(CONTEXT_NAME))
                .InstancePerRequest();

            //override required repository with our custom context
            builder.RegisterType<EfRepository<VendorReview>>()
                .As<IRepository<Domain.VendorReview>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(CONTEXT_NAME))
                .InstancePerRequest();

            //override required repository with our custom context
            builder.RegisterType<EfRepository<Domain.VendorPayout>>()
                .As<IRepository<Domain.VendorPayout>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(CONTEXT_NAME))
                .InstancePerRequest();

        }
        public void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            //Load custom data settings
            var dataSettingsManager = new DataSettingsManager();
            DataSettings dataSettings = dataSettingsManager.LoadSettings();

            //Register custom object context
            builder.Register<IDbContext>(c => RegisterIDbContext(c, dataSettings)).Named<IDbContext>(CONTEXT_NAME).InstancePerHttpRequest();
            builder.Register(c => RegisterIDbContext(c, dataSettings)).InstancePerHttpRequest();

            //Register services
            builder.RegisterType<SagePayServerTransactionService>().As<ISagePayServerTransactionService>();

            //Override the repository injection
            builder.RegisterType<EfRepository<SagePayServerTransaction>>().As<IRepository<SagePayServerTransaction>>().WithParameter(ResolvedParameter.ForNamed<IDbContext>(CONTEXT_NAME)).InstancePerHttpRequest();
        }
        public void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            var dataSettingsManager = new DataSettingsManager();
            DataSettings dataSettings = dataSettingsManager.LoadSettings();

            builder.Register<IDbContext>(c => RegisterIDbContext(c, dataSettings))
                .Named<IDbContext>(CONTEXT_NAME).InstancePerHttpRequest();
            builder.Register(c => RegisterIDbContext(c, dataSettings))
                .InstancePerHttpRequest();

            builder.RegisterType<EfRepository<FloorPackRecord>>().As<IRepository<FloorPackRecord>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(CONTEXT_NAME))
                .InstancePerHttpRequest();

            builder.RegisterType<FloorPackService>().As<IFloorPackService>()
                .InstancePerHttpRequest();
            builder.RegisterType<FloorPackFilterAttribute>().InstancePerHttpRequest();
            builder.RegisterType<FloorPackFilterProvider>().As<IFilterProvider>()
                .InstancePerHttpRequest();
        }
        /// <summary>
        /// Registers the object context.
        /// </summary>
        /// <param name="builder">The builder.</param>
        private void RegisterObjectContext(ContainerBuilder builder)
        {
            //Open the data settings manager
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            string nameOrConnectionString = null;

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //determine if the connection string exists
                nameOrConnectionString = dataProviderSettings.DataConnectionString;
            }

            //Register the named instance
            builder.Register<IDbContext>(c => new MailChimpObjectContext(nameOrConnectionString ?? c.Resolve<DataSettings>().DataConnectionString))
                .Named<IDbContext>(CONTEXT_DEPENDENCY_REGISTRY_KEY).InstancePerHttpRequest();

            //Register the type
            builder.Register(c => new MailChimpObjectContext(nameOrConnectionString ?? c.Resolve<DataSettings>().DataConnectionString)).InstancePerHttpRequest();
        }
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, global::Nop.Core.Configuration.NopConfig config)
        {
            builder.RegisterType<ShoppingCartController>().WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"));
            builder.RegisterType<CheckoutController>().WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"));
            builder.RegisterType<CatalogController>().WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"));
            builder.RegisterType<PromoCheckoutController>().WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"));

            builder.RegisterType<CheckoutAttributeFormatter>().As<global::Nop.Services.Orders.ICheckoutAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType<promoService>().As<IPromoService>().InstancePerLifetimeScope();
            builder.RegisterType<PromoUtilities>().As<IPromoUtilities>().InstancePerLifetimeScope();
            builder.RegisterType<CouponService>().As<ICouponService>().InstancePerLifetimeScope();
            builder.RegisterType<PromoOrderService>().As<IPromoOrderService>().InstancePerLifetimeScope();

            builder.RegisterType<CheckoutActionFilter>().As<IFilterProvider>().InstancePerLifetimeScope();
            builder.RegisterType<ShoppingCartActionFilter>().As<IFilterProvider>().InstancePerLifetimeScope();

            builder.RegisterType<TaxServiceExtensions>().As<ITaxServiceExtensions>().InstancePerLifetimeScope();
            builder.RegisterType<OrderTotalCalculationService>().As<global::Nop.Services.Orders.IOrderTotalCalculationService>().InstancePerLifetimeScope();
            builder.RegisterType<OrderProcessingService>().As<global::Nop.Services.Orders.IOrderProcessingService>().InstancePerLifetimeScope();
            builder.RegisterType<PriceCalculationService>().As<global::Nop.Services.Catalog.IPriceCalculationService>().InstancePerLifetimeScope();
            builder.RegisterType<PromosPriceCalculationService>().As<IPromosPriceCalculationService>().InstancePerLifetimeScope();
            builder.RegisterType<DiscountService>().As<global::Nop.Services.Discounts.IDiscountService>().InstancePerLifetimeScope();
            builder.RegisterType<ShoppingCartService>().As<global::Nop.Services.Orders.IShoppingCartService>().InstancePerLifetimeScope();
            builder.RegisterType<TaxService>().As<global::Nop.Services.Tax.ITaxService>().InstancePerLifetimeScope();
            builder.RegisterType<MessageTokenProvider>().As<global::Nop.Services.Messages.IMessageTokenProvider>().InstancePerLifetimeScope();
            builder.RegisterType<PdfService>().As<global::Nop.Services.Common.IPdfService>().InstancePerLifetimeScope();

            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new NopPromoContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>("nop_object_context_promo").InstancePerLifetimeScope();

                builder.Register<NopPromoContext>(c => new NopPromoContext(dataProviderSettings.DataConnectionString))
                    .InstancePerLifetimeScope();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new NopPromoContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>("nop_object_context_promo").InstancePerLifetimeScope();

                builder.Register<NopPromoContext>(c => new NopPromoContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerLifetimeScope();
            }

            builder.RegisterType<ExportQueueService>().As<IExportQueueService>().InstancePerLifetimeScope();
            builder.RegisterType<AttributeValueService>().As<IAttributeValueService>().InstancePerLifetimeScope();
            builder.RegisterType<ProductAttributeConfigService>().As<IProductAttributeConfigService>().InstancePerLifetimeScope();
            builder.RegisterType<ProductMappingService>().As<IProductMappingService>().InstancePerLifetimeScope();
            builder.RegisterType<PromoDetailService>().As<IPromoDetailService>().InstancePerLifetimeScope();
            builder.RegisterType<ProductPromoMappingService>().As<IProductPromoMappingService>().InstancePerLifetimeScope();
            builder.RegisterType<PromoPictureService>().As<IPromoPictureService>().InstancePerLifetimeScope();

            //override required repository with our custom context
            builder.RegisterType<EfRepository<ExportQueueItem>>()
                .As<IRepository<ExportQueueItem>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<ProductMappingItem>>()
                .As<IRepository<ProductMappingItem>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<AttributeValueMappingItem>>()
                .As<IRepository<AttributeValueMappingItem>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<ProductAttributeConfigItem>>()
                .As<IRepository<ProductAttributeConfigItem>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<PromoDetail>>()
                .As<IRepository<PromoDetail>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<ProductPromotionMapping>>()
                .As<IRepository<ProductPromotionMapping>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<PromoPicture>>()
                .As<IRepository<PromoPicture>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<PromoOrder>>()
                .As<IRepository<PromoOrder>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<PromoOrderItem>>()
                .As<IRepository<PromoOrderItem>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<PromoOrderItemPromotion>>()
                .As<IRepository<PromoOrderItemPromotion>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_promo"))
                .InstancePerLifetimeScope();
        }
Ejemplo n.º 10
0
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            //HTTP context and other related stuff
            builder.Register(c =>
                //register FakeHttpContext when HttpContext is not available
                HttpContext.Current != null ?
                (new HttpContextWrapper(HttpContext.Current) as HttpContextBase) :
                (new FakeHttpContext("~/") as HttpContextBase))
                .As<HttpContextBase>()
                .InstancePerLifetimeScope();
            builder.Register(c => c.Resolve<HttpContextBase>().Request)
                .As<HttpRequestBase>()
                .InstancePerLifetimeScope();
            builder.Register(c => c.Resolve<HttpContextBase>().Response)
                .As<HttpResponseBase>()
                .InstancePerLifetimeScope();
            builder.Register(c => c.Resolve<HttpContextBase>().Server)
                .As<HttpServerUtilityBase>()
                .InstancePerLifetimeScope();
            builder.Register(c => c.Resolve<HttpContextBase>().Session)
                .As<HttpSessionStateBase>()
                .InstancePerLifetimeScope();

            builder.RegisterType<NopConfig>().As<NopConfig>().InstancePerLifetimeScope();
            //web helper
            builder.RegisterType<WebHelper>().As<IWebHelper>().InstancePerLifetimeScope();
            //user agent helper
            builder.RegisterType<UserAgentHelper>().As<IUserAgentHelper>().InstancePerLifetimeScope();

            ////TODO fix compilation warning (below)
            //#pragma warning disable 0618
            //Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
            //var context = new NopObjectContext( "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + @"\\Nop.Data.Tests.Db.sdf;Persist Security Info=False");
            //context.Database.Delete();
            //context.Database.Create();
            //builder.Register<IDbContext>(c => context).InstancePerLifetimeScope();
            //builder.Register(x => x.Resolve<BaseDataProviderManager>().LoadDataProvider()).As<IDataProvider>().InstancePerDependency();

            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings(@"C:\Development\Git\AtrendUsa\Tests\Anko.Plugins.IntegrationTests\settings.txt");//todo ,make relative
            builder.Register(c => dataSettingsManager.LoadSettings(@"C:\Development\Git\AtrendUsa\Tests\Anko.Plugins.IntegrationTests\settings.txt")).As<DataSettings>();
            builder.Register(x => new EfDataProviderManager(x.Resolve<DataSettings>())).As<BaseDataProviderManager>().InstancePerDependency();

            builder.Register(x => x.Resolve<BaseDataProviderManager>().LoadDataProvider()).As<IDataProvider>().InstancePerDependency();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                var efDataProviderManager = new EfDataProviderManager(dataSettingsManager.LoadSettings(@"C:\Development\Git\AtrendUsa\Tests\Anko.Plugins.IntegrationTests\settings.txt"));
                var dataProvider = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();

                builder.Register<IDbContext>(c => new NopObjectContext(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.Register<IDbContext>(c => new NopObjectContext(dataSettingsManager.LoadSettings(@"C:\Development\Git\AtrendUsa\Tests\Anko.Plugins.IntegrationTests\settings.txt").DataConnectionString)).InstancePerLifetimeScope();
            }

            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

            //plugins
            builder.RegisterType<PluginFinder>().As<IPluginFinder>().InstancePerLifetimeScope();

            //cache manager
            builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();

            //work context
            builder.RegisterType<WebWorkContext>().As<IWorkContext>().InstancePerLifetimeScope();
            //store context
            builder.RegisterType<WebStoreContext>().As<IStoreContext>().InstancePerLifetimeScope();

            //services
            builder.RegisterType<BackInStockSubscriptionService>().As<IBackInStockSubscriptionService>().InstancePerLifetimeScope();
            builder.RegisterType<CategoryService>().As<ICategoryService>().InstancePerLifetimeScope();
            builder.RegisterType<CompareProductsService>().As<ICompareProductsService>().InstancePerLifetimeScope();
            builder.RegisterType<RecentlyViewedProductsService>().As<IRecentlyViewedProductsService>().InstancePerLifetimeScope();
            builder.RegisterType<ManufacturerService>().As<IManufacturerService>().InstancePerLifetimeScope();
            builder.RegisterType<PriceFormatter>().As<IPriceFormatter>().InstancePerLifetimeScope();
            builder.RegisterType<ProductAttributeFormatter>().As<IProductAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType<ProductAttributeParser>().As<IProductAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType<ProductAttributeService>().As<IProductAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType<ProductService>().As<IProductService>().InstancePerLifetimeScope();
            builder.RegisterType<CopyProductService>().As<ICopyProductService>().InstancePerLifetimeScope();
            builder.RegisterType<SpecificationAttributeService>().As<ISpecificationAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType<ProductTemplateService>().As<IProductTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType<CategoryTemplateService>().As<ICategoryTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType<ManufacturerTemplateService>().As<IManufacturerTemplateService>().InstancePerLifetimeScope();
            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            builder.RegisterType<ProductTagService>().As<IProductTagService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();

            builder.RegisterType<AffiliateService>().As<IAffiliateService>().InstancePerLifetimeScope();
            builder.RegisterType<VendorService>().As<IVendorService>().InstancePerLifetimeScope();
            builder.RegisterType<AddressService>().As<IAddressService>().InstancePerLifetimeScope();
            builder.RegisterType<SearchTermService>().As<ISearchTermService>().InstancePerLifetimeScope();
            builder.RegisterType<GenericAttributeService>().As<IGenericAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType<FulltextService>().As<IFulltextService>().InstancePerLifetimeScope();
            builder.RegisterType<MaintenanceService>().As<IMaintenanceService>().InstancePerLifetimeScope();

            builder.RegisterType<CustomerAttributeParser>().As<ICustomerAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType<CustomerAttributeService>().As<ICustomerAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType<CustomerService>().As<ICustomerService>().InstancePerLifetimeScope();
            builder.RegisterType<CustomerRegistrationService>().As<ICustomerRegistrationService>().InstancePerLifetimeScope();
            builder.RegisterType<CustomerReportService>().As<ICustomerReportService>().InstancePerLifetimeScope();

            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            builder.RegisterType<PermissionService>().As<IPermissionService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();
            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            builder.RegisterType<AclService>().As<IAclService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();
            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            builder.RegisterType<PriceCalculationService>().As<IPriceCalculationService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();

            builder.RegisterType<GeoLookupService>().As<IGeoLookupService>().InstancePerLifetimeScope();
            builder.RegisterType<CountryService>().As<ICountryService>().InstancePerLifetimeScope();
            builder.RegisterType<CurrencyService>().As<ICurrencyService>().InstancePerLifetimeScope();
            builder.RegisterType<MeasureService>().As<IMeasureService>().InstancePerLifetimeScope();
            builder.RegisterType<StateProvinceService>().As<IStateProvinceService>().InstancePerLifetimeScope();

            builder.RegisterType<StoreService>().As<IStoreService>().InstancePerLifetimeScope();
            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            builder.RegisterType<StoreMappingService>().As<IStoreMappingService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();

            builder.RegisterType<DiscountService>().As<IDiscountService>().InstancePerLifetimeScope();

            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            builder.RegisterType<SettingService>().As<ISettingService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();
            builder.RegisterSource(new SettingsSource());

            //pass MemoryCacheManager as cacheManager (cache locales between requests)
            builder.RegisterType<LocalizationService>().As<ILocalizationService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();

            //pass MemoryCacheManager as cacheManager (cache locales between requests)
            builder.RegisterType<LocalizedEntityService>().As<ILocalizedEntityService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();
            builder.RegisterType<LanguageService>().As<ILanguageService>().InstancePerLifetimeScope();

            builder.RegisterType<DownloadService>().As<IDownloadService>().InstancePerLifetimeScope();
            builder.RegisterType<PictureService>().As<IPictureService>().InstancePerLifetimeScope();

            builder.RegisterType<MessageTemplateService>().As<IMessageTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType<QueuedEmailService>().As<IQueuedEmailService>().InstancePerLifetimeScope();
            builder.RegisterType<NewsLetterSubscriptionService>().As<INewsLetterSubscriptionService>().InstancePerLifetimeScope();
            builder.RegisterType<CampaignService>().As<ICampaignService>().InstancePerLifetimeScope();
            builder.RegisterType<EmailAccountService>().As<IEmailAccountService>().InstancePerLifetimeScope();
            builder.RegisterType<WorkflowMessageService>().As<IWorkflowMessageService>().InstancePerLifetimeScope();
            builder.RegisterType<MessageTokenProvider>().As<IMessageTokenProvider>().InstancePerLifetimeScope();
            builder.RegisterType<Tokenizer>().As<ITokenizer>().InstancePerLifetimeScope();
            builder.RegisterType<EmailSender>().As<IEmailSender>().InstancePerLifetimeScope();

            builder.RegisterType<CheckoutAttributeFormatter>().As<ICheckoutAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType<CheckoutAttributeParser>().As<ICheckoutAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType<CheckoutAttributeService>().As<ICheckoutAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType<GiftCardService>().As<IGiftCardService>().InstancePerLifetimeScope();
            builder.RegisterType<OrderService>().As<IOrderService>().InstancePerLifetimeScope();
            builder.RegisterType<OrderReportService>().As<IOrderReportService>().InstancePerLifetimeScope();
            builder.RegisterType<OrderProcessingService>().As<IOrderProcessingService>().InstancePerLifetimeScope();
            builder.RegisterType<OrderTotalCalculationService>().As<IOrderTotalCalculationService>().InstancePerLifetimeScope();
            builder.RegisterType<ShoppingCartService>().As<IShoppingCartService>().InstancePerLifetimeScope();

            builder.RegisterType<PaymentService>().As<IPaymentService>().InstancePerLifetimeScope();

            builder.RegisterType<EncryptionService>().As<IEncryptionService>().InstancePerLifetimeScope();
            builder.RegisterType<FormsAuthenticationService>().As<IAuthenticationService>().InstancePerLifetimeScope();

            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            builder.RegisterType<UrlRecordService>().As<IUrlRecordService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();

            builder.RegisterType<ShipmentService>().As<IShipmentService>().InstancePerLifetimeScope();
            builder.RegisterType<ShippingService>().As<IShippingService>().InstancePerLifetimeScope();

            builder.RegisterType<TaxCategoryService>().As<ITaxCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType<TaxService>().As<ITaxService>().InstancePerLifetimeScope();
            builder.RegisterType<TaxCategoryService>().As<ITaxCategoryService>().InstancePerLifetimeScope();

            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            builder.RegisterType<CustomerActivityService>().As<ICustomerActivityService>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();

            if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["UseFastInstallationService"]) &&
                Convert.ToBoolean(ConfigurationManager.AppSettings["UseFastInstallationService"]))
            {
                builder.RegisterType<SqlFileInstallationService>().As<IInstallationService>().InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType<CodeFirstInstallationService>().As<IInstallationService>().InstancePerLifetimeScope();
            }

            builder.RegisterType<ForumService>().As<IForumService>().InstancePerLifetimeScope();

            builder.RegisterType<PollService>().As<IPollService>().InstancePerLifetimeScope();
            builder.RegisterType<BlogService>().As<IBlogService>().InstancePerLifetimeScope();
            builder.RegisterType<WidgetService>().As<IWidgetService>().InstancePerLifetimeScope();
            builder.RegisterType<TopicService>().As<ITopicService>().InstancePerLifetimeScope();
            builder.RegisterType<NewsService>().As<INewsService>().InstancePerLifetimeScope();

            builder.RegisterType<DateTimeHelper>().As<IDateTimeHelper>().InstancePerLifetimeScope();
            builder.RegisterType<SitemapGenerator>().As<ISitemapGenerator>().InstancePerLifetimeScope();
            builder.RegisterType<PageHeadBuilder>().As<IPageHeadBuilder>().InstancePerLifetimeScope();

            builder.RegisterType<ScheduleTaskService>().As<IScheduleTaskService>().InstancePerLifetimeScope();

            builder.RegisterType<ExportManager>().As<IExportManager>().InstancePerLifetimeScope();
            builder.RegisterType<ImportManager>().As<IImportManager>().InstancePerLifetimeScope();
            builder.RegisterType<PdfService>().As<IPdfService>().InstancePerLifetimeScope();
            builder.RegisterType<ThemeProvider>().As<IThemeProvider>().InstancePerLifetimeScope();
            builder.RegisterType<ThemeContext>().As<IThemeContext>().InstancePerLifetimeScope();

            builder.RegisterType<ExternalAuthorizer>().As<IExternalAuthorizer>().InstancePerLifetimeScope();
            builder.RegisterType<OpenAuthenticationService>().As<IOpenAuthenticationService>().InstancePerLifetimeScope();

            builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().SingleInstance();

            //Register event consumers
            var consumers = typeFinder.FindClassesOfType(typeof(IConsumer<>)).ToList();
            foreach (var consumer in consumers)
            {
                builder.RegisterType(consumer)
                    .As(consumer.FindInterfaces((type, criteria) =>
                    {
                        var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                        return isMatch;
                    }, typeof(IConsumer<>)))
                    .InstancePerLifetimeScope();
            }
            builder.RegisterType<EventPublisher>().As<IEventPublisher>().SingleInstance();
            builder.RegisterType<SubscriptionService>().As<ISubscriptionService>().SingleInstance();

            //Anko.Plugins.Admin.Uploader
            builder.RegisterType<ProductUploader>().As<IProductUploader>();
            builder.RegisterType<ProductValidator>().As<IProductValidator>();
            builder.RegisterType<ConsoleLogger>().As<ILogger>().InstancePerLifetimeScope();
            builder.RegisterType<ProductResolver>().As<IProductResolver>().InstancePerLifetimeScope();
        }
Ejemplo n.º 11
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
                return RedirectToRoute("HomePage");

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code,
                });
            }

            model.DisableSqlCompact = _config.UseFastInstallationService;
            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            //SQL Server
            if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringWrongFormat"));
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                        ModelState.AddModelError("", _locService.GetResource("SqlServerNameRequired"));
                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                        ModelState.AddModelError("", _locService.GetResource("DatabaseNameRequired"));

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                            ModelState.AddModelError("", _locService.GetResource("SqlServerUsernameRequired"));
                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                            ModelState.AddModelError("", _locService.GetResource("SqlServerPasswordRequired"));
                    }
                }
            }


            //Consider granting access rights to the resource to the ASP.NET request identity. 
            //ASP.NET has a base process identity 
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, 
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>, 
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve<IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();
            foreach (string dir in dirsToCheck)
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));

            var filesToCheck = FilePermissionHelper.GetFilesWrite();
            foreach (string file in filesToCheck)
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    string connectionString;
                    if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string

                            //we know that MARS option is required when using Entity Framework
                            //let's ensure that it's specified
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            if (this.UseMars)
                            {
                                sqlCsb.MultipleActiveResultSets = true;
                            }
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                model.SqlServerName, model.SqlDatabaseName,
                                model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var collation = model.UseCustomCollation ? model.Collation : "";
                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (!String.IsNullOrEmpty(errorCreatingDatabase))
                                    throw new Exception(errorCreatingDatabase);
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                                throw new Exception(_locService.GetResource("DatabaseNotExists"));
                        }
                    }
                    else
                    {
                        //SQL CE
                        string databaseFileName = "Nop.Db.sdf";
                        string databasePath = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        string databaseFullPath = CommonHelper.MapPath("~/App_Data/") + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }
                    }

                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings = new DataSettings
                    {
                        DataProvider = dataProvider,
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //init data provider
                    var dataProviderInstance = EngineContext.Current.Resolve<BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();


                    //now resolve installation service
                    var installationService = EngineContext.Current.Resolve<IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.Resolve<IPluginFinder>();
                    var plugins = pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.All)
                        .ToList()
                        .OrderBy(x => x.PluginDescriptor.Group)
                        .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                        .ToList();
                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation) ?
                        new List<string>() :
                        _config.PluginsIgnoredDuringInstallation
                        .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim())
                        .ToList();
                    foreach (var plugin in plugins)
                    {
                        if (pluginsIgnoredDuringInstallation.Contains(plugin.PluginDescriptor.SystemName))
                            continue;
                        plugin.Install();
                    }

                    //register default permissions
                    //var permissionProviders = EngineContext.Current.Resolve<ITypeFinder>().FindClassesOfType<IPermissionProvider>();
                    var permissionProviders = new List<Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve<IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    webHelper.RestartAppDomain();

                    //Redirect to home page
                    return RedirectToRoute("HomePage");
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();

                    var cacheManager = EngineContext.Current.ContainerManager.Resolve<ICacheManager>("nop_cache_static");
                    cacheManager.Clear();

                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return View(model);
        }
Ejemplo n.º 12
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
                return RedirectToAction("Index", "Home");

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();

            //SQL Server
            if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                        ModelState.AddModelError("", "A SQL connection string is required");

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("", "Wrong SQL connection string format");
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                        ModelState.AddModelError("", "SQL Server name is required");
                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                        ModelState.AddModelError("", "Database name is required");

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                            ModelState.AddModelError("", "SQL Username is required");
                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                            ModelState.AddModelError("", "SQL Password is required");
                    }
                }
            }

            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

            //validate permissions
            string rootDir = Server.MapPath("~/");
            var dirsToCheck = new List<string>();
            //dirsToCheck.Add(rootDir);
            dirsToCheck.Add(rootDir + "App_Data");
            dirsToCheck.Add(rootDir + "bin");
            dirsToCheck.Add(rootDir + "content");
            dirsToCheck.Add(rootDir + "content\\images");
            dirsToCheck.Add(rootDir + "content\\images\\thumbs");
            dirsToCheck.Add(rootDir + "content\\images\\uploaded");
            dirsToCheck.Add(rootDir + "content\\files\\exportimport");
            dirsToCheck.Add(rootDir + "plugins");
            dirsToCheck.Add(rootDir + "plugins\\bin");
            foreach (string dir in dirsToCheck)
                if (!checkPermissions(dir, false, true, true, true))
                    ModelState.AddModelError("", string.Format("The '{0}' account is not granted with Modify permission on folder '{1}'. Please configure these permissions.", WindowsIdentity.GetCurrent().Name, dir));

            var filesToCheck = new List<string>();
            filesToCheck.Add(rootDir + "Global.asax");
            filesToCheck.Add(rootDir + "web.config");
            filesToCheck.Add(rootDir + "App_Data\\InstalledPlugins.txt");
            filesToCheck.Add(rootDir + "App_Data\\Settings.txt");
            foreach (string file in filesToCheck)
                if (!checkPermissions(file, false, true, true, true))
                    ModelState.AddModelError("", string.Format("The '{0}' account is not granted with Modify permission on file '{1}'. Please configure these permissions.", WindowsIdentity.GetCurrent().Name, file));

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    string connectionString = null;
                    if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string
                            connectionString = model.DatabaseConnectionString;
                        }
                        else
                        {
                            //values
                            connectionString = createConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                model.SqlServerName, model.SqlDatabaseName,
                                model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!sqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var errorCreatingDatabase = createDatabase(connectionString);
                                if (!String.IsNullOrEmpty(errorCreatingDatabase))
                                    throw new Exception(errorCreatingDatabase);
                                else
                                {
                                    //Database cannot be created sometimes. Weird! Seems to be Entity Framework issue
                                    //that's just wait 3 seconds
                                    Thread.Sleep(3000);
                                }
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!sqlServerDatabaseExists(connectionString))
                                throw new Exception("Database does not exist or you don't have permissions to connect to it");
                        }
                    }
                    else
                    {
                        //SQL CE
                        string databaseFileName = "Nop.Db.sdf";
                        string databasePath = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        string databaseFullPath = HostingEnvironment.MapPath("~/App_Data/") + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }
                    }

                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings = new DataSettings()
                    {
                        DataProvider = dataProvider,
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //init data provider
                    var dataProviderInstance = EngineContext.Current.Resolve<BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    //now resolve installation service
                    var installationService = EngineContext.Current.Resolve<IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.Resolve<IPluginFinder>();
                    var plugins = pluginFinder.GetPlugins<IPlugin>(false)
                        .ToList()
                        .OrderBy(x => x.PluginDescriptor.Group)
                        .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                        .ToList();
                    foreach (var plugin in plugins)
                    {
                        plugin.Install();
                    }

                    //register default permissions
                    //var permissionProviders = EngineContext.Current.Resolve<ITypeFinder>().FindClassesOfType<IPermissionProvider>();
                    var permissionProviders = new List<Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve<IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    var webHelper = EngineContext.Current.Resolve<IWebHelper>();
                    webHelper.RestartAppDomain();

                    //Redirect to home page
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", "Setup failed: " + exception);
                }
            }
            return View(model);
        }
Ejemplo n.º 13
0
        public void Register(IBinder x, IScanner scanner) 
        {
            x.Bind<HttpContext>(_ => HttpContext.Current);
            x.Bind<HttpContextBase>(_ => new HttpContextWrapper(HttpContext.Current));

            x.Bind(c => c.Resolve<HttpContext>().Request);
            x.Bind(c => c.Resolve<HttpContext>().Response);
            x.Bind(c => c.Resolve<HttpContext>().Server);
            x.Bind(c => c.Resolve<HttpContext>().Session);

            x.BindSingleton<ICache>(_ => new BrigitaCache(MemoryCache.Default));
            x.Bind<ICacheManager, MemoryCacheManager>();

            //x.Register<IRoutePublisher, RoutePublisher>();

            x.Bind<IEventPublisher, EventPublisher>();
            x.Bind<ISubscriptionService, SubscriptionService>();

            x.Bind<IGenericAttributeService, GenericAttributeService>();

            x.Bind<IPluginFinder, BrigitaPluginFinder>();

            x.Bind<ILogger, NullLogger>();


            x.BindGeneric(typeof(IRepo<>), typeof(Repo<>));
                        
            x.Bind<ILinkProvider, LinkProvider>();

            x.Bind<IMediator, Mediator>();

            x.Bind<IPicSource, PicSource>();
            x.Bind<IPictureService, PictureService>();

            x.Bind<ILocaleContext, LocaleContext>();
            x.Bind<ILocaleCodeProvider, LocaleCodeProvider>();
            
            x.BindGeneric(typeof(ILocalizer<>), typeof(Localizer<>));
            x.BindGeneric(typeof(IStringLocalizer<>), typeof(StringLocalizer<>));
            x.BindGeneric(typeof(ICurrencyLocalizer<>), typeof(CurrencyLocalizer<>));


            x.Bind<IWorkContext, BrigitaWorkContext>();




            x.Bind<IPageHelper, PageHelper>();
            x.Bind<ILinkHelper, LinkHelper>();

            //!!!!!!!! JUST FOR TESTING... !!!!!!!!!
            x.Bind(new StoreInformationSettings());
            x.Bind(new TaxSettings());
            x.Bind(new CurrencySettings());
            x.Bind(new LocalizationSettings());
            x.Bind(new CustomerSettings());
            x.Bind(new CommonSettings());
            x.Bind(new CatalogSettings());
            x.Bind(new SeoSettings());
            x.Bind(new MediaSettings());
            x.Bind<ISettingService, SettingService>();

            x.Bind<IUserAgentHelper, UserAgentHelper>();
            x.Bind<IWebHelper, WebHelper>();

            /*x.Bind<IWorkContext, WebWorkContext>();*/
            x.Bind<IStoreContext, WebStoreContext>();

            x.Bind<ICategories, BrigitaCategories>();
            x.Bind<IScopedCategories, ScopedCategories>();

            x.Bind<IProducts, BrigitaProducts>();


            x.Bind<ICustomerService, CustomerService>();
            x.Bind<IVendorService, VendorService>();
            x.Bind<IStoreService, BrigitaStores>();
            x.Bind<IAuthenticationService, FormsAuthenticationService>();
            x.Bind<ILanguageService, LanguageService>();
            x.Bind<ICurrencyService, CurrencyService>();
            x.Bind<IStoreMappingService, StoreMappingService>();

            x.Bind<IPageHeadBuilder, PageHeadBuilder>();


            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();
            x.Bind<DataSettings>(c => dataSettingsManager.LoadSettings());

            x.BindTransient<BaseDataProviderManager, EfDataProviderManager>();
            x.BindTransient<IDataProvider>(c => c.Resolve<BaseDataProviderManager>().LoadDataProvider());

            if(dataProviderSettings != null && dataProviderSettings.IsValid()) {
                var efDataProviderManager = new EfDataProviderManager(dataSettingsManager.LoadSettings());
                var dataProvider = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();

                x.Bind<IDbContext>(c => new NopObjectContext(dataProviderSettings.DataConnectionString, false, false));
            }
            else {
                x.Bind<IDbContext>(c => new NopObjectContext(dataSettingsManager.LoadSettings().DataConnectionString, false, false));
            }

            x.BindGeneric(typeof(IRepository<>), typeof(EfRepository<>));



            //all entities taken from the db should be auto cached, 


            var controllerTypes = scanner.ScanTypes(typeof(Registrar).Assembly)
                                            .Where(t => !t.IsAbstract
                                                        && typeof(IController).IsAssignableFrom(t));

            foreach(var type in controllerTypes) {
                x.Bind(type, type);
            }

        }
Ejemplo n.º 14
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
                return RedirectToRoute("HomePage");

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code,
                });
            }

            string connectionString = "";

            if (model.MongoDBConnectionInfo)
            {
                if(String.IsNullOrEmpty(model.DatabaseConnectionString))
                {
                    ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                }
                else
                {
                    connectionString = model.DatabaseConnectionString;
                }
            }
            else
            {
                if (String.IsNullOrEmpty(model.MongoDBDatabaseName))
                {
                    ModelState.AddModelError("", _locService.GetResource("DatabaseNameRequired"));
                }
                if (String.IsNullOrEmpty(model.MongoDBServerName))
                {
                    ModelState.AddModelError("", _locService.GetResource("MongoDBNameRequired"));
                }
                string userNameandPassword = "";
                if (!(String.IsNullOrEmpty(model.MongoDBUsername)))
                {
                    userNameandPassword = model.MongoDBUsername + ":" + model.MongoDBPassword + "@";
                }
                connectionString = "mongodb://" + userNameandPassword + model.MongoDBServerName + "/" + model.MongoDBDatabaseName;

            }

            if (!String.IsNullOrEmpty(connectionString))
            {
                /*
                try
                {
                    var client = new MongoClient(connectionString);
                    var databases = client.ListDatabasesAsync().Result;
                }
                catch (Exception ex)
                {

                    if (ex.InnerException == null)
                        ModelState.AddModelError("", ex.Message);
                    else
                    {
                        ModelState.AddModelError("", ex.InnerException.Message);
                    }
                }
                */
            }
            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve<IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper);
            foreach (string dir in dirsToCheck)
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);
            foreach (string file in filesToCheck)
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings = new DataSettings
                    {
                        DataProvider = "mongodb",
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //DataSettingsHelper.InitConnectionString();

                    var dataProviderInstance = EngineContext.Current.Resolve<BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    //now resolve installation service
                    var installationService = EngineContext.Current.Resolve<IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.Resolve<IPluginFinder>();
                    var plugins = pluginFinder.GetPlugins<IPlugin>(LoadPluginsMode.All)
                        .ToList()
                        .OrderBy(x => x.PluginDescriptor.Group)
                        .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                        .ToList();
                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation) ?
                        new List<string>() :
                        _config.PluginsIgnoredDuringInstallation
                        .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim())
                        .ToList();
                    foreach (var plugin in plugins)
                    {
                        if (pluginsIgnoredDuringInstallation.Contains(plugin.PluginDescriptor.SystemName))
                            continue;
                        plugin.Install();
                    }

                    //register default permissions
                    var permissionProviders = new List<Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve<IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    webHelper.RestartAppDomain();

                    //Redirect to home page
                    return RedirectToRoute("HomePage");

                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return View(model);
        }
Ejemplo n.º 15
0
        public ActionResult Register(VendorRegisterViewModel vrmodel, string returnUrl, bool captchaValid, FormCollection form)
        {
            if (vrmodel.CountryId == 0)
            {
                ModelState.AddModelError("CountryId", "This is a required field");
                if (vrmodel.StateProvinceId == 0)
                {
                    ModelState.AddModelError("StateProvinceId", "This is a required field");
                }                
                PrepareVendorRegisterModel(vrmodel);
                return View(vrmodel);
            }

            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();
            var context = new VendorMembershipContext(dataProviderSettings.DataConnectionString);
            using (var transaction = context.Database.BeginTransaction())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        if (ValidateVendorModel(vrmodel))
                        {
                            Vendor vendor = new Vendor();
                            vendor.Name = vrmodel.AttentionTo;
                            vendor.Email = vrmodel.Email;
                            vendor.Active = true;
                            var vendorServiceCore = EngineContext.Current.Resolve<IVendorService>();
                            vendorServiceCore.InsertVendor(vendor);

                            var store = new Store
                            {
                                Name = vrmodel.ShopName,
                                Url = "http://" + vrmodel.ShopName + ".tameiontestsite.com/",
                                Hosts = vrmodel.ShopName + ".tameiontestsite.com,www." + vrmodel.ShopName + ".yourstore.com",
                                CompanyName = vrmodel.ShopName
                            };
                            _storeService.InsertStore(store);
                            vendor.setStore(store);

                            Address address = new Address
                            {
                                City = vrmodel.City,
                                CountryId = vrmodel.CountryId,
                                StateProvinceId = vrmodel.StateProvinceId,
                                PhoneNumber = vrmodel.PhoneNumber,
                                CreatedOnUtc = DateTime.UtcNow,
                                Email = vrmodel.Email,
                                ZipPostalCode = vrmodel.ZipPostalCode,
                                Address1 = vrmodel.Address1,
                                Address2 = vrmodel.Address2
                            };
                            _addressService.InsertAddress(address);
                            _vendorAddressService.InsertVendorAddress(new VendorAddress
                            {
                                VendorId = vendor.Id,
                                AddressId = address.Id,
                                AddressType = AddressType.Address
                            });

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.ShopName,
                                vrmodel.ShopName);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.Password,
                                vrmodel.Password);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.EnableGoogleAnalytics,
                                vrmodel.EnableGoogleAnalytics);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.GoogleAnalyticsAccountNumber,
                                vrmodel.GoogleAnalyticsAccountNumber);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.LogoImage,
                                vrmodel.LogoImage);

                            //_genericAttributeService.SaveAttribute(
                            //    vendor,
                            //    Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.PreferredShippingCarrier,
                            //    model.PreferredShippingCarrier);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.PreferredSubdomainName,
                                vrmodel.PreferredSubdomainName);

                            var productServiceCore = EngineContext.Current.Resolve<Nop.Services.Catalog.IProductService>();

                            foreach (var BusinessTypeId in vrmodel.BusinessTypeIds)
                            {
                                var vb = new VendorBusinessType();
                                //var vendorServiceExt = new VendorService(_vendorBusinessTypeRepository);
                                vb.VendorId = vendor.Id;
                                vb.BusinessTypeId = BusinessTypeId;
                                //vendorServiceExt.InsertVendorBusinessType(vb);
                            }

                            // create groupdeals
                            for (int i = 0; i < 10; i++)
                            {
                                int groupDealProductId = _groupDealService.CreateGroupDealProduct(vrmodel.ShopName + " register", 25m);
                                foreach (var categoryId in vrmodel.BusinessTypeIds)
                                {
                                    var productCategory = new ProductCategory
                                    {
                                        ProductId = groupDealProductId,
                                        CategoryId = categoryId,
                                        IsFeaturedProduct = false,
                                        DisplayOrder = 0
                                    };
                                    _categoryService.InsertProductCategory(productCategory);
                                }
                            }
                            vendor.SetHasPaidGroupDeals(true);

                            var model = new RegisterModel();
                            PrepareCustomerRegisterModel(model, false);
                            //enable newsletter by default
                            model.Newsletter = _customerSettings.NewsletterTickedByDefault;
                            model = vrmodel.ToRegisterModel(model);

                            // core code starts
                            //check whether registration is allowed
                            if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
                                return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });

                            if (_workContext.CurrentCustomer.IsRegistered())
                            {
                                //Already registered customer. 
                                _authenticationService.SignOut();

                                //Save a new record
                                _workContext.CurrentCustomer = _customerService.InsertGuestCustomer();
                            }
                            var customer = _workContext.CurrentCustomer;

                            //add to 'Vendors' role
                            var vendorRole = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Vendors);
                            if (vendorRole == null)
                                throw new NopException("'Vendors' role could not be loaded");
                            customer.CustomerRoles.Add(vendorRole);
                            customer.VendorId = vendor.Id;

                            //custom customer attributes
                            var customerAttributesXml = ParseCustomCustomerAttributes(form);
                            var customerAttributeWarnings = _customerAttributeParser.GetAttributeWarnings(customerAttributesXml);
                            foreach (var error in customerAttributeWarnings)
                            {
                                ModelState.AddModelError("", error);
                            }

                            //validate CAPTCHA
                            if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
                            {
                                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha"));
                            }


                            if (_customerSettings.UsernamesEnabled && model.Username != null)
                            {
                                model.Username = model.Username.Trim();
                            }

                            bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                            var registrationRequest = new CustomerRegistrationRequest(customer, 
                                model.Email,
                                _customerSettings.UsernamesEnabled ? model.Username : model.Email, 
                                model.Password, 
                                _customerSettings.DefaultPasswordFormat, 
                                _storeContext.CurrentStore.Id,
                                isApproved);
                            var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                            if (registrationResult.Success)
                            {
                                //properties
                                if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                                {
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
                                }
                                //VAT number
                                if (_taxSettings.EuVatEnabled)
                                {
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumber, model.VatNumber);

                                    string vatName;
                                    string vatAddress;
                                    var vatNumberStatus = _taxService.GetVatNumberStatus(model.VatNumber, out vatName, out vatAddress);
                                    _genericAttributeService.SaveAttribute(customer,
                                        SystemCustomerAttributeNames.VatNumberStatusId,
                                        (int)vatNumberStatus);
                                    //send VAT number admin notification
                                    if (!String.IsNullOrEmpty(model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
                                        _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(customer, model.VatNumber, vatAddress, _localizationSettings.DefaultAdminLanguageId);

                                }

                                //form fields
                                if (_customerSettings.GenderEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
                                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
                                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
                                if (_customerSettings.DateOfBirthEnabled)
                                {
                                    DateTime? dateOfBirth = model.ParseDateOfBirth();
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
                                }
                                if (_customerSettings.CompanyEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company);
                                if (_customerSettings.StreetAddressEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.StreetAddress);
                                if (_customerSettings.StreetAddress2Enabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.StreetAddress2);
                                if (_customerSettings.ZipPostalCodeEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.ZipPostalCode);
                                if (_customerSettings.CityEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.City);
                                if (_customerSettings.CountryEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId);
                                if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, model.StateProvinceId);
                                if (_customerSettings.PhoneEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
                                if (_customerSettings.FaxEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Fax);

                                //newsletter
                                if (_customerSettings.NewsletterEnabled)
                                {
                                    //save newsletter value
                                    var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.Email, _storeContext.CurrentStore.Id);
                                    if (newsletter != null)
                                    {
                                        if (model.Newsletter)
                                        {
                                            newsletter.Active = true;
                                            _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
                                        }
                                        //else
                                        //{
                                        //When registering, not checking the newsletter check box should not take an existing email address off of the subscription list.
                                        //_newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
                                        //}
                                    }
                                    else
                                    {
                                        if (model.Newsletter)
                                        {
                                            _newsLetterSubscriptionService.InsertNewsLetterSubscription(new NewsLetterSubscription
                                            {
                                                NewsLetterSubscriptionGuid = Guid.NewGuid(),
                                                Email = model.Email,
                                                Active = true,
                                                StoreId = _storeContext.CurrentStore.Id,
                                                CreatedOnUtc = DateTime.UtcNow
                                            });
                                        }
                                    }
                                }

                                //save customer attributes
                                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomCustomerAttributes, customerAttributesXml);

                                //login customer now
                                if (isApproved)
                                    _authenticationService.SignIn(customer, true);

                                //associated with external account (if possible)
                                TryAssociateAccountWithExternalAccount(customer);

                                //insert default address (if possible)
                                var defaultAddress = new Address
                                {
                                    FirstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName),
                                    LastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName),
                                    Email = customer.Email,
                                    Company = customer.GetAttribute<string>(SystemCustomerAttributeNames.Company),
                                    CountryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId) > 0 ?
                                        (int?)customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId) : null,
                                    StateProvinceId = customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId) > 0 ?
                                        (int?)customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId) : null,
                                    City = customer.GetAttribute<string>(SystemCustomerAttributeNames.City),
                                    Address1 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress),
                                    Address2 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress2),
                                    ZipPostalCode = customer.GetAttribute<string>(SystemCustomerAttributeNames.ZipPostalCode),
                                    PhoneNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.Phone),
                                    FaxNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.Fax),
                                    CreatedOnUtc = customer.CreatedOnUtc
                                };
                                if (this._addressService.IsAddressValid(defaultAddress))
                                {
                                    //some validation
                                    if (defaultAddress.CountryId == 0)
                                        defaultAddress.CountryId = null;
                                    if (defaultAddress.StateProvinceId == 0)
                                        defaultAddress.StateProvinceId = null;
                                    //set default address
                                    customer.Addresses.Add(defaultAddress);
                                    customer.BillingAddress = defaultAddress;
                                    customer.ShippingAddress = defaultAddress;
                                    _customerService.UpdateCustomer(customer);
                                }

                                //notifications
                                if (_customerSettings.NotifyNewCustomerRegistration)
                                    _workflowMessageService.SendCustomerRegisteredNotificationMessage(customer, _localizationSettings.DefaultAdminLanguageId);

                                switch (_customerSettings.UserRegistrationType)
                                {
                                    case UserRegistrationType.EmailValidation:
                                        {
                                            //email validation message
                                            _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                                            _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                                            //result
                                            //return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation });
                                            return RedirectToAction("Index", "Orders", new { area = "Vendor" });
                                        }
                                    case UserRegistrationType.AdminApproval:
                                        {
                                            //return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval });
                                            return RedirectToAction("Index", "Orders", new { area = "Vendor" });
                                        }
                                    case UserRegistrationType.Standard:
                                        {
                                            //send customer welcome message
                                            _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                                            var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
                                            if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                                                redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
                                            //return Redirect(redirectUrl);
                                            return RedirectToAction("Index", "Orders", new { area = "Vendor" });
                                        }
                                    default:
                                        {
                                            return RedirectToAction("Index", "Orders", new { area = "Vendor" });
                                        }
                                }
                            }

                            //errors
                            foreach (var error in registrationResult.Errors)
                                ModelState.AddModelError("", error);
                        }
                    }
                    transaction.Commit();

                    //If we got this far, something failed, redisplay form
                    PrepareVendorRegisterModel(vrmodel);
                    return View(vrmodel);
                }
                catch(Exception e)
                {
                    transaction.Rollback();
                    ModelState.AddModelError("", e.Message);
                    PrepareVendorRegisterModel(vrmodel);
                    return View(vrmodel);
                }
            }
        }