/// <summary>
 /// Kiểm tra xem database đã được khởi tạo chưa bằng cách đọc vào file setting.txt. Quá trình đọc này chỉ được thực hiện duy nhất 1 lần
 /// bởi kết quả sẽ được cache vào 1 biến static
 /// </summary>
 /// <returns></returns>
 public static bool DatabaseIsInstalled()
 {
     if (!_databaseIsInstalled.HasValue) //// khác chỗ này ( thiết lập lock để ngăn truy cập đồng thời ? )
     {
         lock(_lockObj)
         {
             if (_databaseIsInstalled == null)
             {
                 var manager = new DataSettingsManager();
                 var setting = manager.LoadSettings();
                 _databaseIsInstalled = setting != null && setting.IsValid(); //// khác ở đây
             }
         }
     }
     return _databaseIsInstalled.Value;
 }
Beispiel #2
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, GrandConfig config)
        {
            //web helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();

            //powered by
            builder.RegisterType <PoweredByMiddlewareOptions>().As <IPoweredByMiddlewareOptions>().SingleInstance();

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

            builder.Register(c => dataSettingsManager.LoadSettings()).As <DataSettings>();
            builder.Register(x => new MongoDBDataProviderManager(x.Resolve <DataSettings>())).As <BaseDataProviderManager>().InstancePerDependency();
            builder.Register(x => x.Resolve <BaseDataProviderManager>().LoadDataProvider()).As <IDataProvider>().InstancePerDependency();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                var connectionString = dataProviderSettings.DataConnectionString;
                var databaseName     = new MongoUrl(connectionString).DatabaseName;
                builder.Register(c => new MongoClient(connectionString).GetDatabase(databaseName)).SingleInstance();
                builder.Register <IMongoDBContext>(c => new MongoDBContext(connectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <MongoDBContext>().As <IMongoDBContext>().InstancePerLifetimeScope();
            }

            //MongoDbRepository
            builder.RegisterGeneric(typeof(MongoDBRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();

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

            //cache manager
            builder.RegisterType <PerRequestCacheManager>().InstancePerLifetimeScope();
            builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().SingleInstance();

            if (config.RedisCachingEnabled)
            {
                builder.Register(r => new DistributedRedisCache(config.RedisCachingConnectionString)).As <ICacheManager>().SingleInstance();
            }

            if (config.RunOnAzureWebApps)
            {
                builder.RegisterType <AzureWebAppsMachineNameProvider>().As <IMachineNameProvider>().SingleInstance();
            }
            else
            {
                builder.RegisterType <DefaultMachineNameProvider>().As <IMachineNameProvider>().SingleInstance();
            }
            //work context
            builder.RegisterType <WebWorkContext>().As <IWorkContext>().InstancePerLifetimeScope();
            //store context
            builder.RegisterType <WebStoreContext>().As <IStoreContext>().InstancePerLifetimeScope();

            builder.RegisterType <SettingService>().As <ISettingService>().InstancePerLifetimeScope();
            builder.RegisterType <LocalizationService>().As <ILocalizationService>().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 <ProductReservationService>().As <IProductReservationService>().InstancePerLifetimeScope();
            builder.RegisterType <AuctionService>().As <IAuctionService>().InstancePerLifetimeScope();
            builder.RegisterType <ProductCourseService>().As <IProductCourseService>().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();
            builder.RegisterType <TopicTemplateService>().As <ITopicTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <ProductTagService>().As <IProductTagService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeFormatter>().As <IAddressAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeParser>().As <IAddressAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeService>().As <IAddressAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressService>().As <IAddressService>().InstancePerLifetimeScope();
            builder.RegisterType <AffiliateService>().As <IAffiliateService>().InstancePerLifetimeScope();
            builder.RegisterType <VendorService>().As <IVendorService>().InstancePerLifetimeScope();
            builder.RegisterType <SearchTermService>().As <ISearchTermService>().InstancePerLifetimeScope();
            builder.RegisterType <GenericAttributeService>().As <IGenericAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerAttributeFormatter>().As <ICustomerAttributeFormatter>().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();
            builder.RegisterType <CustomerTagService>().As <ICustomerTagService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActionService>().As <ICustomerActionService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActionEventService>().As <ICustomerActionEventService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderService>().As <ICustomerReminderService>().InstancePerLifetimeScope();
            builder.RegisterType <UserApiService>().As <IUserApiService>().InstancePerLifetimeScope();

            builder.RegisterType <RewardPointsService>().As <IRewardPointsService>().InstancePerLifetimeScope();

            builder.RegisterType <PermissionService>().As <IPermissionService>().InstancePerLifetimeScope();
            builder.RegisterType <AclService>().As <IAclService>().InstancePerLifetimeScope();
            builder.RegisterType <PriceCalculationService>().As <IPriceCalculationService>().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();
            builder.RegisterType <StoreMappingService>().As <IStoreMappingService>().InstancePerLifetimeScope();
            builder.RegisterType <DiscountService>().As <IDiscountService>().InstancePerLifetimeScope();


            builder.RegisterType <LanguageService>().As <ILanguageService>().InstancePerLifetimeScope();
            builder.RegisterType <DownloadService>().As <IDownloadService>().InstancePerLifetimeScope();

            var provider = new FileExtensionContentTypeProvider();

            builder.RegisterType <MimeMappingService>().As <IMimeMappingService>()
            .WithParameter(new TypedParameter(typeof(FileExtensionContentTypeProvider), provider))
            .InstancePerLifetimeScope();

            //picture service
            var useAzureBlobStorage  = !String.IsNullOrEmpty(config.AzureBlobStorageConnectionString);
            var useAmazonBlobStorage = (!String.IsNullOrEmpty(config.AmazonAwsAccessKeyId) && !String.IsNullOrEmpty(config.AmazonAwsSecretAccessKey) && !String.IsNullOrEmpty(config.AmazonBucketName) && !String.IsNullOrEmpty(config.AmazonRegion));

            if (useAzureBlobStorage)
            {
                //Windows Azure BLOB
                builder.RegisterType <AzurePictureService>().As <IPictureService>().InstancePerLifetimeScope();
            }
            else if (useAmazonBlobStorage)
            {
                //Amazon S3 Simple Storage Service
                builder.RegisterType <AmazonPictureService>().As <IPictureService>().InstancePerLifetimeScope();
            }
            else
            {
                //standard file system
                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 <NewsletterCategoryService>().As <INewsletterCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <CampaignService>().As <ICampaignService>().InstancePerLifetimeScope();
            builder.RegisterType <BannerService>().As <IBannerService>().InstancePerLifetimeScope();
            builder.RegisterType <PopupService>().As <IPopupService>().InstancePerLifetimeScope();
            builder.RegisterType <InteractiveFormService>().As <IInteractiveFormService>().InstancePerLifetimeScope();
            builder.RegisterType <EmailAccountService>().As <IEmailAccountService>().InstancePerLifetimeScope();
            builder.RegisterType <WorkflowMessageService>().As <IWorkflowMessageService>().InstancePerLifetimeScope();
            builder.RegisterType <ContactAttributeFormatter>().As <IContactAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <ContactAttributeParser>().As <IContactAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <ContactAttributeService>().As <IContactAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <MessageTokenProvider>().As <IMessageTokenProvider>().InstancePerLifetimeScope();
            builder.RegisterType <Tokenizer>().As <ITokenizer>().InstancePerLifetimeScope();
            builder.RegisterType <EmailSender>().As <IEmailSender>().InstancePerLifetimeScope();
            builder.RegisterType <HistoryService>().As <IHistoryService>().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 <ReturnRequestService>().As <IReturnRequestService>().InstancePerLifetimeScope();
            builder.RegisterType <RewardPointsService>().As <IRewardPointsService>().InstancePerLifetimeScope();
            builder.RegisterType <ShoppingCartService>().As <IShoppingCartService>().InstancePerLifetimeScope();
            builder.RegisterType <PaymentService>().As <IPaymentService>().InstancePerLifetimeScope();
            builder.RegisterType <EncryptionService>().As <IEncryptionService>().InstancePerLifetimeScope();
            builder.RegisterType <CookieAuthenticationService>().As <IGrandAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <ApiAuthenticationService>().As <IApiAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <UrlRecordService>().As <IUrlRecordService>().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();
            builder.RegisterType <DefaultLogger>().As <ILogger>().InstancePerLifetimeScope();
            builder.RegisterType <ContactUsService>().As <IContactUsService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActivityService>().As <ICustomerActivityService>().InstancePerLifetimeScope();
            builder.RegisterType <ActivityKeywordsProvider>().As <IActivityKeywordsProvider>().InstancePerLifetimeScope();

            bool databaseInstalled = DataSettingsHelper.DatabaseIsInstalled();

            if (!databaseInstalled)
            {
                //installation service
                builder.RegisterType <CodeFirstInstallationService>().As <IInstallationService>().InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <UpgradeService>().As <IUpgradeService>().InstancePerLifetimeScope();
            }

            builder.RegisterType <ForumService>().As <IForumService>().InstancePerLifetimeScope();
            builder.RegisterType <KnowledgebaseService>().As <IKnowledgebaseService>().InstancePerLifetimeScope();
            builder.RegisterType <PushNotificationsService>().As <IPushNotificationsService>().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 <ExternalAuthenticationService>().As <IExternalAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <GoogleAnalyticsService>().As <IGoogleAnalyticsService>().InstancePerLifetimeScope();
            builder.RegisterType <DocumentTypeService>().As <IDocumentTypeService>().InstancePerLifetimeScope();
            builder.RegisterType <DocumentService>().As <IDocumentService>().InstancePerLifetimeScope();

            builder.RegisterType <CourseActionService>().As <ICourseActionService>().InstancePerLifetimeScope();
            builder.RegisterType <CourseLessonService>().As <ICourseLessonService>().InstancePerLifetimeScope();
            builder.RegisterType <CourseLevelService>().As <ICourseLevelService>().InstancePerLifetimeScope();
            builder.RegisterType <CourseService>().As <ICourseService>().InstancePerLifetimeScope();
            builder.RegisterType <CourseSubjectService>().As <ICourseSubjectService>().InstancePerLifetimeScope();

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

            var validators = typeFinder.FindClassesOfType(typeof(IValidator)).ToList();

            foreach (var validator in validators)
            {
                builder.RegisterType(validator);
            }

            //validator consumers
            var validatorconsumers = typeFinder.FindClassesOfType(typeof(IValidatorConsumer <>)).ToList();

            foreach (var consumer in validatorconsumers)
            {
                builder.RegisterType(consumer)
                .As(consumer.GetTypeInfo().FindInterfaces((type, criteria) =>
                {
                    var isMatch = type.GetTypeInfo().IsGenericType&& ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                    return(isMatch);
                }, typeof(IValidatorConsumer <>)))
                .InstancePerLifetimeScope();
            }

            builder.RegisterType <ResourceManager>().As <IResourceManager>().InstancePerLifetimeScope();

            //Register task
            builder.RegisterType <QueuedMessagesSendScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <ClearCacheScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <ClearLogScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderAbandonedCartScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderBirthdayScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderCompletedOrderScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderLastActivityScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderLastPurchaseScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderRegisteredCustomerScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderUnpaidOrderScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <DeleteGuestsScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <UpdateExchangeRateScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <EndAuctionsTask>().As <IScheduleTask>().InstancePerLifetimeScope();
        }
Beispiel #3
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>()
            .InstancePerRequest();
            builder.Register(c => c.Resolve <HttpContextBase>().Request)
            .As <HttpRequestBase>()
            .InstancePerRequest();
            builder.Register(c => c.Resolve <HttpContextBase>().Response)
            .As <HttpResponseBase>()
            .InstancePerRequest();
            builder.Register(c => c.Resolve <HttpContextBase>().Server)
            .As <HttpServerUtilityBase>()
            .InstancePerRequest();
            builder.Register(c => c.Resolve <HttpContextBase>().Session)
            .As <HttpSessionStateBase>()
            .InstancePerRequest();

            //web helper
            //builder.RegisterType<WebHelper>().As<IWebHelper>().InstancePerRequest();

            var assemblies = typeFinder.GetAssemblies().ToArray();

            //controllers
            builder.RegisterControllers(assemblies);
            //ApiControllers
            builder.RegisterApiControllers(assemblies);

            //View
            //builder.RegisterSource(new ViewRegistrationSource());

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

            builder.Register(c => dataSettingsManager.LoadSettings()).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());
                var dataProvider          = efDataProviderManager.LoadDataProvider();
                //dataProvider.InitConnectionFactory();
                ((SqlServerDataProvider)dataProvider).InitDatabase();

                builder.Register <IDbContext>(c => new EfDbContext(dataProviderSettings.DataConnectionString)).InstancePerRequest();
            }
            else
            {
                builder.Register <IDbContext>(c => new EfDbContext(dataSettingsManager.LoadSettings().DataConnectionString)).InstancePerRequest();
            }


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

            builder.RegisterAssemblyTypes(assemblies)
            .Where(t => typeof(IDependency).IsAssignableFrom(t) && t != typeof(IDependency))
            .AsImplementedInterfaces()
            .InstancePerRequest();
            builder.RegisterAssemblyTypes(assemblies)
            .Where(t => typeof(ISingletonDependency).IsAssignableFrom(t) && t != typeof(ISingletonDependency))
            .AsImplementedInterfaces()
            .SingleInstance();

            //IWorkContext
            builder.RegisterType <WorkContext>().As <IWorkContext>().InstancePerRequest();

            //filter
            builder.RegisterFilterProvider();
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

            //注册YpHnadleError
            //全局注册
            builder.RegisterType <YpHandleErrorAttribute>().AsExceptionFilterFor <Controller>().SingleInstance();
            builder.RegisterType <YpAPIHandleErrorAttribute>().AsWebApiExceptionFilterFor <ApiController>().SingleInstance();
            //单个注册
            //builder.RegisterType<YpHandleErrorAttribute>().SingleInstance();
            //builder.RegisterType<YpAPIHandleErrorAttribute>().SingleInstance();

            //注册YpAuthorizeAttribute
            //全局注册
            builder.RegisterType <YpAPIAuthorizeAttribute>()
            .AsWebApiAuthorizationFilterFor <ApiController>()
            .PropertiesAutowired()
            .InstancePerRequest();
            builder.RegisterType <YpAuthorizeAttribute>()
            .AsAuthorizationFilterFor <Controller>()
            .PropertiesAutowired()
            .InstancePerRequest();
            //单个注册
            //builder.RegisterType<YpAPIAuthorizeAttribute>().PropertiesAutowired().InstancePerRequest();
            //builder.RegisterType<YpAuthorizeAttribute>().PropertiesAutowired().InstancePerRequest();
        }
            /// <summary>
            /// Called asynchronously before the action, after model binding is complete.
            /// </summary>
            /// <param name="context">A context for action filters</param>
            /// <returns>A task that represents the asynchronous operation</returns>
            private async Task SaveLastVisitedPageAsync(ActionExecutingContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

                if (context.HttpContext.Request == null)
                {
                    return;
                }

                //only in GET requests
                if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                if (!await DataSettingsManager.IsDatabaseInstalledAsync())
                {
                    return;
                }

                //check whether we store last visited page URL
                if (!_customerSettings.StoreLastVisitedPage)
                {
                    return;
                }

                //get current page
                var pageUrl = _webHelper.GetThisPageUrl(true);

                if (string.IsNullOrEmpty(pageUrl))
                {
                    return;
                }

                //get previous last page
                var customer = await _workContext.GetCurrentCustomerAsync();

                var previousPageAttribute = (await _genericAttributeService
                                             .GetAttributesForEntityAsync(customer.Id, nameof(Customer)))
                                            .FirstOrDefault(attribute => attribute.Key
                                                            .Equals(NopCustomerDefaults.LastVisitedPageAttribute, StringComparison.InvariantCultureIgnoreCase));

                //save new one if don't match
                if (previousPageAttribute == null)
                {
                    //insert without event notification
                    await _genericAttributeRepository.InsertAsync(new GenericAttribute
                    {
                        EntityId = customer.Id,
                        Key      = NopCustomerDefaults.LastVisitedPageAttribute,
                        KeyGroup = nameof(Customer),
                        Value    = pageUrl,
                        CreatedOrUpdatedDateUTC = DateTime.UtcNow
                    }, false);
                }
                else if (!pageUrl.Equals(previousPageAttribute.Value, StringComparison.InvariantCultureIgnoreCase))
                {
                    //update without event notification
                    previousPageAttribute.Value = pageUrl;
                    previousPageAttribute.CreatedOrUpdatedDateUTC = DateTime.UtcNow;

                    await _genericAttributeRepository.UpdateAsync(previousPageAttribute, false);
                }
            }
Beispiel #5
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="appSettings">App settings</param>
        public virtual void Register(IServiceCollection services, ITypeFinder typeFinder, AppSettings appSettings)
        {
            //file provider
            services.AddScoped <INopFileProvider, NopFileProvider>();

            //web helper
            services.AddScoped <IWebHelper, WebHelper>();

            //user agent helper
            services.AddScoped <IUserAgentHelper, UserAgentHelper>();

            //data layer
            services.AddTransient <IDataProviderManager, DataProviderManager>();
            services.AddTransient(serviceProvider =>
                                  serviceProvider.GetRequiredService <IDataProviderManager>().DataProvider);

            //repositories
            services.AddScoped(typeof(IRepository <>), typeof(EntityRepository <>));

            //plugins
            services.AddScoped <IPluginService, PluginService>();
            services.AddScoped <OfficialFeedManager>();

            //static cache manager
            if (appSettings.DistributedCacheConfig.Enabled)
            {
                services.AddScoped <ILocker, DistributedCacheManager>();
                services.AddScoped <IStaticCacheManager, DistributedCacheManager>();
            }
            else
            {
                services.AddSingleton <ILocker, MemoryCacheManager>();
                services.AddSingleton <IStaticCacheManager, MemoryCacheManager>();
            }

            //work context
            services.AddScoped <IWorkContext, WebWorkContext>();

            //store context
            services.AddScoped <IStoreContext, WebStoreContext>();

            //services
            services.AddScoped <IBackInStockSubscriptionService, BackInStockSubscriptionService>();
            services.AddScoped <ICategoryService, CategoryService>();
            services.AddScoped <ICompanyService, CompanyService>();
            services.AddScoped <ICompareProductsService, CompareProductsService>();
            services.AddScoped <IRecentlyViewedProductsService, RecentlyViewedProductsService>();
            services.AddScoped <IManufacturerService, ManufacturerService>();
            services.AddScoped <IPriceFormatter, PriceFormatter>();
            services.AddScoped <IProductAttributeFormatter, ProductAttributeFormatter>();
            services.AddScoped <IProductAttributeParser, ProductAttributeParser>();
            services.AddScoped <IProductAttributeService, ProductAttributeService>();
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <ICopyProductService, CopyProductService>();
            services.AddScoped <ISpecificationAttributeService, SpecificationAttributeService>();
            services.AddScoped <IProductTemplateService, ProductTemplateService>();
            services.AddScoped <ICategoryTemplateService, CategoryTemplateService>();
            services.AddScoped <IManufacturerTemplateService, ManufacturerTemplateService>();
            services.AddScoped <ITopicTemplateService, TopicTemplateService>();
            services.AddScoped <IProductTagService, ProductTagService>();
            services.AddScoped <IAddressAttributeFormatter, AddressAttributeFormatter>();
            services.AddScoped <IAddressAttributeParser, AddressAttributeParser>();
            services.AddScoped <IAddressAttributeService, AddressAttributeService>();
            services.AddScoped <IAddressService, AddressService>();
            services.AddScoped <IAffiliateService, AffiliateService>();
            services.AddScoped <IVendorService, VendorService>();
            services.AddScoped <IVendorAttributeFormatter, VendorAttributeFormatter>();
            services.AddScoped <IVendorAttributeParser, VendorAttributeParser>();
            services.AddScoped <IVendorAttributeService, VendorAttributeService>();
            services.AddScoped <ISearchTermService, SearchTermService>();
            services.AddScoped <IGenericAttributeService, GenericAttributeService>();
            services.AddScoped <IMaintenanceService, MaintenanceService>();
            services.AddScoped <ICustomerAttributeFormatter, CustomerAttributeFormatter>();
            services.AddScoped <ICustomerAttributeParser, CustomerAttributeParser>();
            services.AddScoped <ICustomerAttributeService, CustomerAttributeService>();
            services.AddScoped <ICustomerService, CustomerService>();
            services.AddScoped <ICustomerRegistrationService, CustomerRegistrationService>();
            services.AddScoped <ICustomerReportService, CustomerReportService>();
            services.AddScoped <IPermissionService, PermissionService>();
            services.AddScoped <IAclService, AclService>();
            services.AddScoped <IPriceCalculationService, PriceCalculationService>();
            services.AddScoped <IGeoLookupService, GeoLookupService>();
            services.AddScoped <ICountryService, CountryService>();
            services.AddScoped <ICurrencyService, CurrencyService>();
            services.AddScoped <IMeasureService, MeasureService>();
            services.AddScoped <IStateProvinceService, StateProvinceService>();
            services.AddScoped <IStoreService, StoreService>();
            services.AddScoped <IStoreMappingService, StoreMappingService>();
            services.AddScoped <IDiscountService, DiscountService>();
            services.AddScoped <ILocalizationService, LocalizationService>();
            services.AddScoped <ILocalizedEntityService, LocalizedEntityService>();
            services.AddScoped <ILanguageService, LanguageService>();
            services.AddScoped <IDownloadService, DownloadService>();
            services.AddScoped <IMessageTemplateService, MessageTemplateService>();
            services.AddScoped <IQueuedEmailService, QueuedEmailService>();
            services.AddScoped <INewsLetterSubscriptionService, NewsLetterSubscriptionService>();
            services.AddScoped <INotificationService, NotificationService>();
            services.AddScoped <ICampaignService, CampaignService>();
            services.AddScoped <IEmailAccountService, EmailAccountService>();
            services.AddScoped <IWorkflowMessageService, WorkflowMessageService>();
            services.AddScoped <IMessageTokenProvider, MessageTokenProvider>();
            services.AddScoped <ITokenizer, Tokenizer>();
            services.AddScoped <ISmtpBuilder, SmtpBuilder>();
            services.AddScoped <IEmailSender, EmailSender>();
            services.AddScoped <ICheckoutAttributeFormatter, CheckoutAttributeFormatter>();
            services.AddScoped <ICheckoutAttributeParser, CheckoutAttributeParser>();
            services.AddScoped <ICheckoutAttributeService, CheckoutAttributeService>();
            services.AddScoped <IGiftCardService, GiftCardService>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <IOrderReportService, OrderReportService>();
            services.AddScoped <IOrderProcessingService, OrderProcessingService>();
            services.AddScoped <IOrderTotalCalculationService, OrderTotalCalculationService>();
            services.AddScoped <IReturnRequestService, ReturnRequestService>();
            services.AddScoped <IRewardPointService, RewardPointService>();
            services.AddScoped <IShoppingCartService, ShoppingCartService>();
            services.AddScoped <ICustomNumberFormatter, CustomNumberFormatter>();
            services.AddScoped <IPaymentService, PaymentService>();
            services.AddScoped <IEncryptionService, EncryptionService>();
            services.AddScoped <IAuthenticationService, CookieAuthenticationService>();
            services.AddScoped <IUrlRecordService, UrlRecordService>();
            services.AddScoped <IShipmentService, ShipmentService>();
            services.AddScoped <IShippingService, ShippingService>();
            services.AddScoped <IDateRangeService, DateRangeService>();
            services.AddScoped <ITaxCategoryService, TaxCategoryService>();
            services.AddScoped <ITaxService, TaxService>();
            services.AddScoped <ILogger, DefaultLogger>();
            services.AddScoped <ICustomerActivityService, CustomerActivityService>();
            services.AddScoped <IForumService, ForumService>();
            services.AddScoped <IGdprService, GdprService>();
            services.AddScoped <IPollService, PollService>();
            services.AddScoped <IBlogService, BlogService>();
            services.AddScoped <ITopicService, TopicService>();
            services.AddScoped <INewsService, NewsService>();
            services.AddScoped <IDateTimeHelper, DateTimeHelper>();
            services.AddScoped <ISitemapGenerator, SitemapGenerator>();
            services.AddScoped <IPageHeadBuilder, PageHeadBuilder>();
            services.AddScoped <IScheduleTaskService, ScheduleTaskService>();
            services.AddScoped <IExportManager, ExportManager>();
            services.AddScoped <IImportManager, ImportManager>();
            services.AddScoped <IPdfService, PdfService>();
            services.AddScoped <IUploadService, UploadService>();
            services.AddScoped <IThemeProvider, ThemeProvider>();
            services.AddScoped <IThemeContext, ThemeContext>();
            services.AddScoped <IExternalAuthenticationService, ExternalAuthenticationService>();
            services.AddSingleton <IRoutePublisher, RoutePublisher>();
            services.AddScoped <IReviewTypeService, ReviewTypeService>();
            services.AddSingleton <IEventPublisher, EventPublisher>();
            services.AddScoped <ISettingService, SettingService>();

            //plugin managers
            services.AddScoped(typeof(IPluginManager <>), typeof(PluginManager <>));
            services.AddScoped <IAuthenticationPluginManager, AuthenticationPluginManager>();
            services.AddScoped <IMultiFactorAuthenticationPluginManager, MultiFactorAuthenticationPluginManager>();
            services.AddScoped <IWidgetPluginManager, WidgetPluginManager>();
            services.AddScoped <IExchangeRatePluginManager, ExchangeRatePluginManager>();
            services.AddScoped <IDiscountPluginManager, DiscountPluginManager>();
            services.AddScoped <IPaymentPluginManager, PaymentPluginManager>();
            services.AddScoped <IPickupPluginManager, PickupPluginManager>();
            services.AddScoped <IShippingPluginManager, ShippingPluginManager>();
            services.AddScoped <ITaxPluginManager, TaxPluginManager>();

            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

            //register all settings
            var settings = typeFinder.FindClassesOfType(typeof(ISettings), false).ToList();

            foreach (var setting in settings)
            {
                services.AddScoped(setting, serviceProvider =>
                {
                    var storeId = DataSettingsManager.IsDatabaseInstalled()
                        ? serviceProvider.GetRequiredService <IStoreContext>().GetCurrentStore()?.Id ?? 0
                        : 0;

                    return(serviceProvider.GetRequiredService <ISettingService>().LoadSettingAsync(setting, storeId).Result);
                });
            }

            //picture service
            if (appSettings.AzureBlobConfig.Enabled)
            {
                services.AddScoped <IPictureService, AzurePictureService>();
            }
            else
            {
                services.AddScoped <IPictureService, PictureService>();
            }

            //roxy file manager service
            services.AddTransient <DatabaseRoxyFilemanService>();
            services.AddTransient <FileRoxyFilemanService>();

            services.AddScoped <IRoxyFilemanService>(serviceProvider =>
            {
                return(serviceProvider.GetRequiredService <IPictureService>().IsStoreInDbAsync().Result
                    ? serviceProvider.GetRequiredService <DatabaseRoxyFilemanService>()
                    : serviceProvider.GetRequiredService <FileRoxyFilemanService>());
            });

            //installation service
            if (!DataSettingsManager.IsDatabaseInstalled())
            {
                services.AddScoped <IInstallationService, InstallationService>();
            }

            //slug route transformer
            if (DataSettingsManager.IsDatabaseInstalled())
            {
                services.AddScoped <SlugRouteTransformer>();
            }

            //event consumers
            var consumers = typeFinder.FindClassesOfType(typeof(IConsumer <>)).ToList();

            foreach (var consumer in consumers)
            {
                foreach (var findInterface in consumer.FindInterfaces((type, criteria) =>
                {
                    var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                    return(isMatch);
                }, typeof(IConsumer <>)))
                {
                    services.AddScoped(findInterface, consumer);
                }
            }
        }
Beispiel #6
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();

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


            //controllers
            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());

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

            builder.Register(c => dataSettingsManager.LoadSettings()).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());
                var dataProvider          = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();

                builder.Register <IDbContext>(c => new NopObjectContext(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.Register <IDbContext>(c => new NopObjectContext(dataSettingsManager.LoadSettings().DataConnectionString)).InstancePerLifetimeScope();
            }


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

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

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


            //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 <AddressAttributeFormatter>().As <IAddressAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeParser>().As <IAddressAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeService>().As <IAddressAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressService>().As <IAddressService>().InstancePerLifetimeScope();
            builder.RegisterType <AffiliateService>().As <IAffiliateService>().InstancePerLifetimeScope();
            builder.RegisterType <VendorService>().As <IVendorService>().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();

            builder.RegisterType <DefaultLogger>().As <ILogger>().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();
        }
Beispiel #7
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config)
        {
            //web helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();

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

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

            builder.Register(c => dataSettingsManager.LoadSettings()).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());
                var dataProvider          = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();

                builder.Register <IDbContext>(c => new NopObjectContext(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.Register <IDbContext>(c => new NopObjectContext(dataSettingsManager.LoadSettings().DataConnectionString)).InstancePerLifetimeScope();
            }

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

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

            //cache manager
            builder.RegisterType <PerRequestCacheManager>().As <ICacheManager>().InstancePerLifetimeScope();

            //static cache manager
            if (config.RedisCachingEnabled)
            {
                builder.RegisterType <RedisConnectionWrapper>().As <IRedisConnectionWrapper>().SingleInstance();
                builder.RegisterType <RedisCacheManager>().As <IStaticCacheManager>().InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <MemoryCacheManager>().As <IStaticCacheManager>().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();
            builder.RegisterType <TopicTemplateService>().As <ITopicTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <ProductTagService>().As <IProductTagService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeFormatter>().As <IAddressAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeParser>().As <IAddressAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeService>().As <IAddressAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressService>().As <IAddressService>().InstancePerLifetimeScope();
            builder.RegisterType <AffiliateService>().As <IAffiliateService>().InstancePerLifetimeScope();
            builder.RegisterType <VendorService>().As <IVendorService>().InstancePerLifetimeScope();
            builder.RegisterType <VendorAttributeFormatter>().As <IVendorAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <VendorAttributeParser>().As <IVendorAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <VendorAttributeService>().As <IVendorAttributeService>().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 <CustomerAttributeFormatter>().As <ICustomerAttributeFormatter>().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();
            builder.RegisterType <PermissionService>().As <IPermissionService>().InstancePerLifetimeScope();
            builder.RegisterType <AclService>().As <IAclService>().InstancePerLifetimeScope();
            builder.RegisterType <PriceCalculationService>().As <IPriceCalculationService>().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();
            builder.RegisterType <StoreMappingService>().As <IStoreMappingService>().InstancePerLifetimeScope();
            builder.RegisterType <DiscountService>().As <IDiscountService>().InstancePerLifetimeScope();
            builder.RegisterType <LocalizationService>().As <ILocalizationService>().InstancePerLifetimeScope();
            builder.RegisterType <LocalizedEntityService>().As <ILocalizedEntityService>().InstancePerLifetimeScope();
            builder.RegisterType <LanguageService>().As <ILanguageService>().InstancePerLifetimeScope();
            builder.RegisterType <DownloadService>().As <IDownloadService>().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 <ReturnRequestService>().As <IReturnRequestService>().InstancePerLifetimeScope();
            builder.RegisterType <RewardPointService>().As <IRewardPointService>().InstancePerLifetimeScope();
            builder.RegisterType <ShoppingCartService>().As <IShoppingCartService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomNumberFormatter>().As <ICustomNumberFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <PaymentService>().As <IPaymentService>().InstancePerLifetimeScope();
            builder.RegisterType <EncryptionService>().As <IEncryptionService>().InstancePerLifetimeScope();
            builder.RegisterType <CookieAuthenticationService>().As <IAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <UrlRecordService>().As <IUrlRecordService>().InstancePerLifetimeScope();
            builder.RegisterType <ShipmentService>().As <IShipmentService>().InstancePerLifetimeScope();
            builder.RegisterType <ShippingService>().As <IShippingService>().InstancePerLifetimeScope();
            builder.RegisterType <DateRangeService>().As <IDateRangeService>().InstancePerLifetimeScope();
            builder.RegisterType <TaxCategoryService>().As <ITaxCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <TaxService>().As <ITaxService>().InstancePerLifetimeScope();
            builder.RegisterType <DefaultLogger>().As <ILogger>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActivityService>().As <ICustomerActivityService>().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 <UploadService>().As <IUploadService>().InstancePerLifetimeScope();
            builder.RegisterType <ThemeProvider>().As <IThemeProvider>().InstancePerLifetimeScope();
            builder.RegisterType <ThemeContext>().As <IThemeContext>().InstancePerLifetimeScope();
            builder.RegisterType <ExternalAuthenticationService>().As <IExternalAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <RoutePublisher>().As <IRoutePublisher>().SingleInstance();
            builder.RegisterType <EventPublisher>().As <IEventPublisher>().SingleInstance();
            builder.RegisterType <SubscriptionService>().As <ISubscriptionService>().SingleInstance();
            builder.RegisterType <SettingService>().As <ISettingService>().InstancePerLifetimeScope();


            builder.RegisterType <ActionContextAccessor>().As <IActionContextAccessor>().InstancePerLifetimeScope();

            //register all settings
            builder.RegisterSource(new SettingsSource());

            //picture service
            if (!string.IsNullOrEmpty(config.AzureBlobStorageConnectionString))
            {
                builder.RegisterType <AzurePictureService>().As <IPictureService>().InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <PictureService>().As <IPictureService>().InstancePerLifetimeScope();
            }

            //installation service
            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                if (config.UseFastInstallationService)
                {
                    builder.RegisterType <SqlFileInstallationService>().As <IInstallationService>().InstancePerLifetimeScope();
                }
                else
                {
                    builder.RegisterType <CodeFirstInstallationService>().As <IInstallationService>().InstancePerLifetimeScope();
                }
            }

            //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();
            }
        }
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled)
            {
                return(RedirectToRoute("Homepage"));
            }

            //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.AvailableDataProviders.AddRange(
                _locService.GetAvailableProviderTypes()
                .OrderBy(v => v.Value)
                .Select(pt => new SelectListItem
            {
                Value = pt.Key.ToString(),
                Text  = pt.Value
            }));

            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            //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 (var dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), CurrentOSUser.FullName, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!_fileProvider.FileExists(file))
                {
                    continue;
                }

                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureFilePermissions"), CurrentOSUser.FullName, file));
                }
            }

            //if (!ModelState.IsValid)
            //    return View(model);

            try
            {
                var dataProvider = DataProviderManager.GetDataProvider(model.DataProvider);

                var connectionString = model.ConnectionStringRaw ? model.ConnectionString : dataProvider.BuildConnectionString(model);

                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new Exception(_locService.GetResource("ConnectionStringWrongFormat"));
                }

                DataSettingsManager.SaveSettings(new DataSettings
                {
                    DataProvider     = model.DataProvider,
                    ConnectionString = connectionString
                }, _fileProvider);

                DataSettingsManager.LoadSettings(reloadSettings: true);

                if (model.CreateDatabaseIfNotExists)
                {
                    try
                    {
                        dataProvider.CreateDatabase(model.Collation);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format(_locService.GetResource("DatabaseCreationError"), ex.Message));
                    }
                }
                else
                {
                    //check whether database exists
                    if (!dataProvider.IsDatabaseExists())
                    {
                        throw new Exception(_locService.GetResource("DatabaseNotExists"));
                    }
                }

                dataProvider.InitializeDatabase();

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

                if (model.InstallSampleData)
                {
                    installationService.InstallSampleData(model.AdminEmail);
                }

                //prepare plugins to install
                var pluginService = EngineContext.Current.Resolve <IPluginService>();
                pluginService.ClearInstalledPluginsList();

                var pluginsIgnoredDuringInstallation = new List <string>();
                if (!string.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation))
                {
                    pluginsIgnoredDuringInstallation = _config.PluginsIgnoredDuringInstallation
                                                       .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(pluginName => pluginName.Trim()).ToList();
                }

                var plugins = pluginService.GetPluginDescriptors <IPlugin>(LoadPluginsMode.All)
                              .Where(pluginDescriptor => !pluginsIgnoredDuringInstallation.Contains(pluginDescriptor.SystemName))
                              .OrderBy(pluginDescriptor => pluginDescriptor.Group).ThenBy(pluginDescriptor => pluginDescriptor.DisplayOrder)
                              .ToList();

                foreach (var plugin in plugins)
                {
                    pluginService.PreparePluginToInstall(plugin.SystemName, checkDependencies: false);
                }

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

                //installation completed notification
                try
                {
                    var languageCode = _locService.GetCurrentLanguage().Code?.Substring(0, 2);
                    var client       = EngineContext.Current.Resolve <NopHttpClient>();
                    await client.InstallationCompletedAsync(model.AdminEmail, languageCode);
                }
                catch { }

                return(View(new InstallModel {
                    RestartUrl = Url.RouteUrl("Homepage")
                }));
            }
            catch (Exception exception)
            {
                //reset cache
                DataSettingsManager.ResetCache();

                var staticCacheManager = EngineContext.Current.Resolve <IStaticCacheManager>();
                staticCacheManager.Clear();

                //clear provider settings if something got wrong
                DataSettingsManager.SaveSettings(new DataSettings(), _fileProvider);

                ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("SetupFailed"), exception.Message));
            }

            return(View(model));
        }
        /// <summary>
        /// Register services and interfaces
        /// DepeRegister服务和接口
        /// </summary>
        /// <param name="builder">Container builder容器建造者</param>
        /// <param name="typeFinder">Type finder 类型查找器</param>
        /// <param name="config">Config配置</param>
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config)
        {
            //HTTP context and other related stuff
            //HTTP上下文和其他相关的东西
            builder.Register(c =>
                             //register FakeHttpContext when HttpContext is not available
                             //当HttpContext不可用时注册FakeHttpContext
                             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();

            //web helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();

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

            //controllers
            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());


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

            builder.Register(c => dataSettingsManager.LoadSettings()).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());
                var dataProvider          = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();
                builder.Register <IDbContext>(c => new NopObjectContext(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.Register <IDbContext>(c => new NopObjectContext(dataSettingsManager.LoadSettings().DataConnectionString)).InstancePerLifetimeScope();
            }

            // 注入ef到仓储
            builder.RegisterGeneric(typeof(EfRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();


            //log
            builder.RegisterType <DefaultLogger>().As <ILogger>().InstancePerLifetimeScope();

            //cache managers
            if (config != null && config.RedisCachingEnabled)
            {
                builder.RegisterType <RedisConnectionWrapper>().As <IRedisConnectionWrapper>().SingleInstance();
                builder.RegisterType <RedisCacheManager>().As <ICacheManager>().Named <ICacheManager>("nop_cache_static").InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().Named <ICacheManager>("nop_cache_static").SingleInstance();
            }
            builder.RegisterType <PerRequestCacheManager>().As <ICacheManager>().Named <ICacheManager>("nop_cache_per_request").InstancePerLifetimeScope();

            // 注入Service及接口
            //builder.RegisterAssemblyTypes(typeof(TestService).Assembly)
            //        .AsImplementedInterfaces()
            //        .InstancePerLifetimeScope();

            builder.RegisterType <UserActivityService>().As <IUserActivityService>().InstancePerLifetimeScope();


            //use static cache (between HTTP requests)
            builder.RegisterType <SettingService>().As <ISettingService>()
            .WithParameter(ResolvedParameter.ForNamed <ICacheManager>("nop_cache_static"))
            .InstancePerLifetimeScope();
            builder.RegisterSource(new SettingsSource());
        }
Beispiel #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>()
            .InstancePerHttpRequest();
            builder.Register(c => c.Resolve <HttpContextBase>().Request)
            .As <HttpRequestBase>()
            .InstancePerHttpRequest();
            builder.Register(c => c.Resolve <HttpContextBase>().Response)
            .As <HttpResponseBase>()
            .InstancePerHttpRequest();
            builder.Register(c => c.Resolve <HttpContextBase>().Server)
            .As <HttpServerUtilityBase>()
            .InstancePerHttpRequest();
            builder.Register(c => c.Resolve <HttpContextBase>().Session)
            .As <HttpSessionStateBase>()
            .InstancePerHttpRequest();

            //web helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerHttpRequest();

            //cache manager
            builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().Named <ICacheManager>("ocean_cache_static").SingleInstance();
            builder.RegisterType <PerRequestCacheManager>().As <ICacheManager>().Named <ICacheManager>("ocean_cache_per_request").InstancePerHttpRequest();

            //controllers
            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());

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

            builder.Register(c => dataSettingsManager.LoadSettings()).As <DataSettings>().InstancePerDependency();
            builder.Register(x => new EfDataProviderManager(x.Resolve <DataSettings>())).As <BaseDataProviderManager>().InstancePerDependency();
            builder.Register(x => (IEfDataProvider)x.Resolve <BaseDataProviderManager>().LoadDataProvider()).As <IDataProvider>().InstancePerDependency();
            builder.Register(x => (IEfDataProvider)x.Resolve <BaseDataProviderManager>().LoadDataProvider()).As <IEfDataProvider>().InstancePerDependency();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                var efDataProviderManager = new EfDataProviderManager(dataSettingsManager.LoadSettings());
                var dataProvider          = (IEfDataProvider)efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();
                builder.Register <IDbContext>(c => new OceanObjectContext(dataProviderSettings.DataConnectionString)).InstancePerHttpRequest();
            }
            else
            {
                builder.Register <IDbContext>(c => new OceanObjectContext(dataSettingsManager.LoadSettings().DataConnectionString)).InstancePerHttpRequest();
            }

            //builder.Register<IDbContext>(c => new OceanObjectContext("EFDbContext")).InstancePerHttpRequest();
            builder.RegisterGeneric(typeof(EfRepository <>)).As(typeof(IRepository <>)).InstancePerHttpRequest();

            //service
            builder.RegisterType <EnumTypeService>().As <IEnumTypeService>().InstancePerHttpRequest();
            builder.RegisterType <EnumDataService>().As <IEnumDataService>().InstancePerHttpRequest();
            builder.RegisterType <AdminService>().As <IAdminService>().InstancePerHttpRequest();
            builder.RegisterType <AdminLoggerService>().As <IAdminLoggerService>().InstancePerHttpRequest();
            builder.RegisterType <PermissionOrganizationService>().As <IPermissionOrganizationService>().InstancePerHttpRequest();
            builder.RegisterType <PermissionModuleService>().As <IPermissionModuleService>().InstancePerHttpRequest();
            builder.RegisterType <PermissionModuleCodeService>().As <IPermissionModuleCodeService>().InstancePerHttpRequest();
            builder.RegisterType <PermissionRoleService>().As <IPermissionRoleService>().InstancePerHttpRequest();
            builder.RegisterType <CategoryService>().As <ICategoryService>().InstancePerHttpRequest();
            builder.RegisterType <ProductService>().As <IProductService>().InstancePerHttpRequest();
            builder.RegisterType <LoanService>().As <ILoanService>()
            .WithParameter(ResolvedParameter.ForNamed <ICacheManager>("ocean_cache_static"))
            .InstancePerHttpRequest();
            builder.RegisterType <LoanAssignLoggerService>().As <ILoanAssignLoggerService>().InstancePerHttpRequest();
            builder.RegisterType <MpCenterService>().As <IMpCenterService>().InstancePerHttpRequest();
            builder.RegisterType <MpMaterialService>().As <IMpMaterialService>().InstancePerHttpRequest();
            builder.RegisterType <MpMaterialItemService>().As <IMpMaterialItemService>().InstancePerHttpRequest();
            builder.RegisterType <MpUserGroupService>().As <IMpUserGroupService>().InstancePerHttpRequest();
            builder.RegisterType <MpReplyService>().As <IMpReplyService>().InstancePerHttpRequest();
            builder.RegisterType <MpUserService>().As <IMpUserService>().InstancePerHttpRequest();
            builder.RegisterType <FunongbaoService>().As <IFunongbaoService>().InstancePerHttpRequest();
            builder.RegisterType <FunongbaoApplyService>().As <IFunongbaoApplyService>().InstancePerHttpRequest();
            builder.RegisterType <BranchService>().As <IBranchService>().InstancePerHttpRequest();
            builder.RegisterType <MobileCodeService>().As <IMobileCodeService>().InstancePerHttpRequest();
            builder.RegisterType <ConfigurationService>().As <IConfigurationService>().InstancePerHttpRequest();
            builder.RegisterType <ScheduleTaskService>().As <IScheduleTaskService>().InstancePerHttpRequest();
            builder.RegisterType <MpQrSceneService>().As <IMpQrSceneService>().InstancePerHttpRequest();

            //KF
            builder.RegisterType <KfNumberService>().As <IKfNumberService>().InstancePerHttpRequest();
            builder.RegisterType <KfMeetingService>().As <IKfMeetingService>().InstancePerHttpRequest();
            builder.RegisterType <KfMeetingMessageService>().As <IKfMeetingMessageService>().InstancePerHttpRequest();

            //configuration and setting
            builder.RegisterGeneric(typeof(ConfigurationProvider <>)).As(typeof(IConfigurationProvider <>));
            builder.RegisterSource(new SettingsSource());
            builder.RegisterType <SettingService>().As <ISettingService>().InstancePerHttpRequest();

            //theme helper
            builder.RegisterType <MobileDeviceHelper>().As <IMobileDeviceHelper>().InstancePerHttpRequest();
            builder.RegisterType <ThemeProvider>().As <IThemeProvider>().InstancePerHttpRequest();
            builder.RegisterType <ThemeContext>().As <IThemeContext>().InstancePerHttpRequest();

            //Visual Plugins
            builder.RegisterType <PluginBaseService>().As <IPluginBaseService>().InstancePerHttpRequest();
            builder.RegisterType <PluginBaseStyleService>().As <IPluginBaseStyleService>().InstancePerHttpRequest();
            builder.RegisterType <PluginService>().As <IPluginService>().InstancePerHttpRequest();
            builder.RegisterType <PluginResultService>().As <IPluginResultService>().InstancePerHttpRequest();
            builder.RegisterType <PluginUsedService>().As <IPluginUsedService>().InstancePerHttpRequest();
            builder.RegisterType <PluginAllowUserService>().As <IPluginAllowUserService>().InstancePerHttpRequest();
            builder.RegisterType <PluginSceneApllyCodeAllowerService>().As <IPluginSceneApllyCodeAllowerService>().InstancePerHttpRequest();
            builder.RegisterType <PluginSceneResultService>().As <IPluginSceneResultService>().InstancePerHttpRequest();
            builder.RegisterType <PluginSceneVerifyCodeDetailService>().As <IPluginSceneVerifyCodeDetailService>().InstancePerHttpRequest();

            //plugins
            builder.RegisterType <PluginFinder>().As <IPluginFinder>().InstancePerHttpRequest();
            builder.RegisterType <EmbeddedViewResolver>().As <IEmbeddedViewResolver>().SingleInstance();
            builder.RegisterType <RoutePublisher>().As <IRoutePublisher>().SingleInstance();
            builder.RegisterType <WidgetService>().As <IWidgetService>().InstancePerHttpRequest();
            Log4NetImpl.SetConfig(FileHelper.GetMapPath("~/config/log4net.config"));

            //pos
            builder.RegisterType <PosApplyService>().As <IPosApplyService>().InstancePerHttpRequest();
            builder.RegisterType <PosAuthService>().As <IPosAuthService>().InstancePerHttpRequest();
            builder.RegisterType <PosService>().As <IPosService>().InstancePerHttpRequest();

            //vote
            builder.RegisterType <VoteItemService>().As <IVoteItemService>().InstancePerHttpRequest();
            builder.RegisterType <VoteInfoService>().As <IVoteInfoService>().InstancePerHttpRequest();
            builder.RegisterType <VoteBaseService>().As <IVoteBaseService>().InstancePerHttpRequest();

            //scoresys
            builder.RegisterType <ScoreUserService>().As <IScoreUserService>().InstancePerHttpRequest();
            builder.RegisterType <ScoreTradeInfoService>().As <IScoreTradeInfoService>().InstancePerHttpRequest();
            builder.RegisterType <ScoreStoreItemService>().As <IScoreStoreItemService>().InstancePerHttpRequest();
            builder.RegisterType <ScorePluginResultService>().As <IScorePluginResultService>().InstancePerHttpRequest();
            builder.RegisterType <ScoreConsumeInfoService>().As <IScoreConsumeInfoService>().InstancePerHttpRequest();

            //xypluginuser
            builder.RegisterType <XYPluginUserService>().As <IXYPluginUserService>().InstancePerHttpRequest();


            //baoxian
            builder.RegisterType <ComplainService>().As <IComplainService>().InstancePerHttpRequest();
            builder.RegisterType <DrivingLicenseService>().As <IDrivingLicenseService>().InstancePerHttpRequest();
            builder.RegisterType <VehicleLicenseService>().As <IVehicleLicenseService>().InstancePerHttpRequest();
        }
Beispiel #11
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();
            //WEB Helpers
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();
            //controllers
            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());
            builder.RegisterApiControllers(typeFinder.GetAssemblies().ToArray());//注册api容器的实现
            //data layer
            var dataSettingsManager  = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            builder.Register(c => dataSettingsManager.LoadSettings()).As <DataSettings>();
            builder.Register(x => new EfDataProviderManager(x.Resolve <DataSettings>())).As <BaseDataProviderManager>().InstancePerDependency();
            builder.Register(x => (IEfDataProvider)x.Resolve <BaseDataProviderManager>().LoadDataProvider()).As <IDataProvider>().InstancePerDependency();
            builder.Register(x => (IEfDataProvider)x.Resolve <BaseDataProviderManager>().LoadDataProvider()).As <IEfDataProvider>().InstancePerDependency();
            builder.Register(x => x.Resolve <BaseDataProviderManager>().LoadDataProvider()).As <IDataProvider>().InstancePerDependency();
            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                var efDataProviderManager = new EfDataProviderManager(dataSettingsManager.LoadSettings());
                var dataProvider          = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();
                builder.Register <IDbContext>(c => new ObjectContextExt(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.Register <IDbContext>(c => new ObjectContextExt(dataSettingsManager.LoadSettings().DataConnectionString)).InstancePerLifetimeScope();
            }
            builder.RegisterGeneric(typeof(EfRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();
            //cache manager
            builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().Named <ICacheManager>("JNKJ_cache_static").SingleInstance();
            builder.RegisterType <PerRequestCacheManager>().As <ICacheManager>().Named <ICacheManager>("JNKJ_cache_per_request").InstancePerLifetimeScope();
            builder.RegisterSource(new SettingsSource());
            #region 将自定义接口注入容器
            builder.RegisterType <QiniuService>().As <IQiniuService>().InstancePerLifetimeScope();                   //七牛服务
            builder.RegisterType <SubContractorService>().As <ISubContractor>().InstancePerLifetimeScope();          //企业信息--企业信息
            builder.RegisterType <UserInfoService>().As <IUserInfo>().InstancePerLifetimeScope();                    //用户接口
            builder.RegisterType <EnterpriseInfoService>().As <IEnterpriseInfoService>().InstancePerLifetimeScope(); //企业接口
            builder.RegisterType <TokenService>().As <ITokenService>().InstancePerLifetimeScope();                   //Token验证
            builder.RegisterType <TencentImService>().As <ITencentImService>().InstancePerLifetimeScope();           //腾讯IM云通信
            builder.RegisterType <UserLoginService>().As <IUserLogin>().InstancePerLifetimeScope();                  //登陆
            builder.RegisterType <DeptInfoService>().As <IDeptInfoService>().InstancePerLifetimeScope();             //组织架构
            builder.RegisterType <MenuOrButtonService>().As <IMenuOrButtonService>().InstancePerLifetimeScope();     //菜单和按钮
            builder.RegisterType <RolesService>().As <IRolesService>().InstancePerLifetimeScope();                   //角色权限
            builder.RegisterType <RelationshipService>().As <IRelationshipService>().InstancePerLifetimeScope();
            builder.RegisterType <SmsService>().As <ISmsService>().InstancePerLifetimeScope();                       //角色权限
            builder.RegisterType <RelationshipService>().As <IRelationshipService>().InstancePerLifetimeScope();

            #endregion
            //Register event consumers
            #region service register
            #endregion
        }
        /// <summary>
        /// Configure static file serving
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public static void UseNopStaticFiles(this IApplicationBuilder application)
        {
            var fileProvider = EngineContext.Current.Resolve <INopFileProvider>();
            var appSettings  = EngineContext.Current.Resolve <AppSettings>();

            void staticFileResponse(StaticFileResponseContext context)
            {
                if (!string.IsNullOrEmpty(appSettings.CommonConfig.StaticFilesCacheControl))
                {
                    context.Context.Response.Headers.Append(HeaderNames.CacheControl, appSettings.CommonConfig.StaticFilesCacheControl);
                }
            }

            //common static files
            application.UseStaticFiles(new StaticFileOptions {
                OnPrepareResponse = staticFileResponse
            });

            //themes static files
            application.UseStaticFiles(new StaticFileOptions
            {
                FileProvider      = new PhysicalFileProvider(fileProvider.MapPath(@"Themes")),
                RequestPath       = new PathString("/Themes"),
                OnPrepareResponse = staticFileResponse
            });

            //plugins static files
            var staticFileOptions = new StaticFileOptions
            {
                FileProvider      = new PhysicalFileProvider(fileProvider.MapPath(@"Plugins")),
                RequestPath       = new PathString("/Plugins"),
                OnPrepareResponse = staticFileResponse
            };

            //exclude files in blacklist
            if (!string.IsNullOrEmpty(appSettings.CommonConfig.PluginStaticFileExtensionsBlacklist))
            {
                var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();

                foreach (var ext in appSettings.CommonConfig.PluginStaticFileExtensionsBlacklist
                         .Split(';', ',')
                         .Select(e => e.Trim().ToLower())
                         .Select(e => $"{(e.StartsWith(".") ? string.Empty : ".")}{e}")
                         .Where(fileExtensionContentTypeProvider.Mappings.ContainsKey))
                {
                    fileExtensionContentTypeProvider.Mappings.Remove(ext);
                }

                staticFileOptions.ContentTypeProvider = fileExtensionContentTypeProvider;
            }

            application.UseStaticFiles(staticFileOptions);

            //add support for backups
            var provider = new FileExtensionContentTypeProvider
            {
                Mappings = { [".bak"] = MimeTypes.ApplicationOctetStream }
            };

            application.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new PhysicalFileProvider(fileProvider.GetAbsolutePath(NopCommonDefaults.DbBackupsPath)),
                RequestPath         = new PathString("/db_backups"),
                ContentTypeProvider = provider
            });

            //add support for webmanifest files
            provider.Mappings[".webmanifest"] = MimeTypes.ApplicationManifestJson;

            application.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new PhysicalFileProvider(fileProvider.GetAbsolutePath("icons")),
                RequestPath         = "/icons",
                ContentTypeProvider = provider
            });

            if (DataSettingsManager.IsDatabaseInstalled())
            {
                application.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider      = new RoxyFilemanProvider(fileProvider.GetAbsolutePath(NopRoxyFilemanDefaults.DefaultRootDirectory.TrimStart('/').Split('/'))),
                    RequestPath       = new PathString(NopRoxyFilemanDefaults.DefaultRootDirectory),
                    OnPrepareResponse = staticFileResponse
                });
            }
        }
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

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

            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("MongoDBServerNameRequired"));
                }
                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 databaseName = new MongoUrl(connectionString).DatabaseName;
                    var database     = client.GetDatabase(databaseName);
                    await database.RunCommandAsync((Command <BsonDocument>) "{ping:1}");

                    var filter = new BsonDocument("name", "GrandNodeVersion");
                    var found  = database.ListCollectionsAsync(new ListCollectionsOptions {
                        Filter = filter
                    }).Result;

                    if (found.Any())
                    {
                        ModelState.AddModelError("", _locService.GetResource("AlreadyInstalled"));
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
            }

            var webHelper = _serviceProvider.GetRequiredService <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
                {
                    //save settings
                    var settings = new DataSettings
                    {
                        DataProvider         = "mongodb",
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    var dataProviderInstance = _serviceProvider.GetRequiredService <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    var dataSettingsManager  = new DataSettingsManager();
                    var dataProviderSettings = dataSettingsManager.LoadSettings(reloadSettings: true);

                    var installationService = _serviceProvider.GetRequiredService <IInstallationService>();
                    await installationService.InstallData(model.AdminEmail, model.AdminPassword, model.Collation, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = _serviceProvider.GetRequiredService <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;
                        }

                        try
                        {
                            await plugin.Install();
                        }
                        catch (Exception ex)
                        {
                            var _logger = _serviceProvider.GetRequiredService <ILogger>();
                            await _logger.InsertLog(Core.Domain.Logging.LogLevel.Error, "Error during installing plugin " + plugin.PluginDescriptor.SystemName,
                                                    ex.Message + " " + ex.InnerException?.Message);
                        }
                    }

                    //register default permissions
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        var provider = (IPermissionProvider)Activator.CreateInstance(providerType);
                        await _serviceProvider.GetRequiredService <IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    await _cacheManager.SetAsync("Installed", true, 120);

                    return(View(new InstallModel()
                    {
                        Installed = true
                    }));
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();
                    await _cacheManager.Clear();

                    System.IO.File.Delete(CommonHelper.MapPath("~/App_Data/Settings.txt"));

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message + " " + exception.InnerException?.Message));
                }
            }

            //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,
                });
            }

            //prepare collation list
            foreach (var col in _locService.GetAvailableCollations())
            {
                model.AvailableCollation.Add(new SelectListItem
                {
                    Value    = col.Value,
                    Text     = col.Name,
                    Selected = _locService.GetCurrentLanguage().Code == col.Value,
                });
            }

            return(View(model));
        }
Beispiel #14
0
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
                {
                    await next();

                    return;
                }
                //check whether this filter has been overridden for the Action
                var actionFilter = context.ActionDescriptor.FilterDescriptors
                                   .Where(f => f.Scope == FilterScope.Action)
                                   .Select(f => f.Filter).OfType <ClosedStoreAttribute>().FirstOrDefault();

                if (actionFilter?.IgnoreFilter ?? _ignoreFilter)
                {
                    await next();

                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    await next();

                    return;
                }

                //store isn't closed
                if (!_storeInformationSettings.StoreClosed)
                {
                    await next();

                    return;
                }

                //get action and controller names
                var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
                var actionName       = actionDescriptor?.ActionName;
                var controllerName   = actionDescriptor?.ControllerName;

                if ((string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName)) ||
                    (controllerName.Equals("Common", StringComparison.OrdinalIgnoreCase) &&
                     actionName.Equals("StoreClosed", StringComparison.OrdinalIgnoreCase)))
                {
                    await next();

                    return;
                }

                //pages accessible when a store is closed
                if (controllerName.Equals("Page", StringComparison.OrdinalIgnoreCase) &&
                    actionName.Equals("PageDetails", StringComparison.OrdinalIgnoreCase))
                {
                    //get identifiers of pages are accessible when a store is closed
                    var now            = DateTime.UtcNow;
                    var allowedPageIds = (await _pageService.GetAllPages(_workContext.CurrentStore.Id))
                                         .Where(t => t.AccessibleWhenStoreClosed &&
                                                (!t.StartDateUtc.HasValue || t.StartDateUtc < now) && (!t.EndDateUtc.HasValue || t.EndDateUtc > now))
                                         .Select(page => page.Id);

                    //check whether requested page is allowed
                    var requestedPageId = context.RouteData.Values["pageId"] as string;
                    if (!string.IsNullOrEmpty(requestedPageId) && allowedPageIds.Contains(requestedPageId))
                    {
                        await next();

                        return;
                    }
                }

                //check whether current customer has access to a closed store
                if (await _permissionService.Authorize(StandardPermission.AccessClosedStore))
                {
                    await next();

                    return;
                }

                //store is closed and no access, so redirect to 'StoreClosed' page
                context.Result = new RedirectToRouteResult("StoreClosed", new RouteValueDictionary());
            }
Beispiel #15
0
        public override void Up()
        {
            if (!DataSettingsManager.IsDatabaseInstalled())
            {
                return;
            }

            var resources = new Dictionary <string, string>
            {
                // Menu
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Menu.Root", "Swiper Slider" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Menu.Root.Configuration", "Configuration" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Menu.Root.List", "Slider List" },

                // Activity Logs
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.ActivityLog.AddNewSwiperSlider", "Added a new swiper slider ({0})" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.ActivityLog.EditSwiperSlider", "Added a new swiper slider ({0})" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.ActivityLog.DeleteSwiperSlider", "Added a new swiper slider ({0})" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.ActivityLog.DeleteSwiperSliders", "Multiple swiper slider were deleted. (IDs : {0})" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.ActivityLog.AddNewSwiperSliderItem", "Added a new swiper slider item ({0})" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.ActivityLog.EditSwiperSliderItem", "Added a new swiper slider item ({0})" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.ActivityLog.DeleteSwiperSliderItem", "Added a new swiper slider item ({0})" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.ActivityLog.DeleteSwiperSliderItems", "Multiple swiper slider items were deleted. (IDs : {0})" },

                // Notification Messages
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.Sliders.Added", "{0} has beed added." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.Sliders.NotAdded", "Swiper slider could not be added." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.Sliders.Updated", "{0} has beed updated." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.Sliders.Deleted", "{0} has beed deleted." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.Sliders.AllDeleted", "The selected sliders are deleted." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.Slider.NotFound", "No swiper slider found with the specified id" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.SliderItems.Added", "{0} has beed added." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.SliderItems.NotAdded", "Swiper slider item could not be added." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.SliderItems.Updated", "{0} has beed updated." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.SliderItems.Deleted", "{0} has beed deleted." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Notifications.SliderItems.AllDeleted", "The selected slider items are deleted." },

                // General
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.NoCustomerRolesAvailable", "No customer roles available" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.NoStoresAvailable", "No stores available" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.BackToList", "back to list" },

                // Configuration
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Cards.General.Title", "General" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.ContainerCssSelector", "Container Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.ContainerCssSelector.Hint", "Swiper Slider kapsayan html elementine ait css selector girin. id için #selector, class için .selector!" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.PaginationCssSelector", "Pagination Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.PaginationCssSelector.Hint", "Pagination Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.NavigationNextCssSelector", "Navigation Next Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.NavigationNextCssSelector.Hint", "Navigation Next Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.NavigationPrevCssSelector", "Navigation Prev Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.NavigationPrevCssSelector.Hint", "Navigation Prev Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.ScrollBarCssSelector", "Scroll Bar Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.ScrollBarCssSelector.Hint", "Scroll Bar Css Selector" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.Direction", "Direction" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.Direction.Hint", "Direction" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.InitialSlide", "Initial Slide" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.InitialSlide.Hint", "Initial Slide" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.Speed", "Speed" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.Speed.Hint", "Speed" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.Loop", "Loop" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.Loop.Hint", "Loop" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.LoopFillGroupWithBlankEnabled", "Loop Fill Group With Blank Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.LoopFillGroupWithBlankEnabled.Hint", "Loop Fill Group With Blank Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.PaginationEnabled", "Pagination Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.PaginationEnabled.Hint", "Pagination Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.PaginationClickableEnabled", "Pagination Clickable Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.PaginationClickableEnabled.Hint", "Pagination Clickable Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.NavigationEnabled", "Navigation Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.NavigationEnabled.Hint", "Navigation Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.ScrollBarEnabled", "Scroll Bar Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.ScrollBarEnabled.Hint", "Scroll Bar Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.AutoPlayEnabled", "Auto Play Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.AutoPlayEnabled.Hint", "Auto Play Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.AutoPlayDelay", "Auto Play Delay" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.AutoPlayDelay.Hint", "Auto Play Delay" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.AutoPlayDisableOnInteraction", "Auto Play Disable On Interaction" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.AutoPlayDisableOnInteraction.Hint", "Auto Play Disable On Interaction" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.SlidesPerGroup", "Slides Per Group" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.SlidesPerGroup.Hint", "Slides Per Group" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.SpaceBetween", "Space Between" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.SpaceBetween.Hint", "Space Between" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.SlidesPerView", "Slides Per View" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.SlidesPerView.Hint", "Slides Per View" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.SlidesPerColumn", "Slides Per Column" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.SlidesPerColumn.Hint", "Slides Per Column" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.FreeModeEnabled", "Free Mode Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.FreeModeEnabled.Hint", "Free Mode Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.DynamicBulletsEnabled", "Dynamic Bullets Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.DynamicBulletsEnabled.Hint", "Dynamic Bullets Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.CenteredSlidesEnabled", "Centered Slides Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.CenteredSlidesEnabled.Hint", "Centered Slides Enabled" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.CustomCss", "Custom Css" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Fields.CustomCss.Hint", "Custom Css" },

                // Pages
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.PageTitle", "Configure Swiper Slider Plugin" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Configuration.Title", "Configure Swiper Slider Plugin" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.List.PageTitle", "Swiper Sliders" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.List.Title", "Swiper Slider List" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Create.PageTitle", "Create Swiper Slider" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Create.Title", "Add a New Swiper Slider" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Edit.PageTitle", "Update {0} - Swiper Slider" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Edit.Title", "Update Swiper Slider - {0}" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Create.PageTitle", "Create Swiper Slider Item" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Create.Title", "Add a New Swiper Slider  Item" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Edit.PageTitle", "Update {0} - Swiper Slider  Item" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Edit.Title", "Update Swiper Slider  Item- {0}" },

                // Cards
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Cards.Info.Title", "Info" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Cards.Mappings.Title", "Mappings" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Cards.Items.Title", "Slider Items" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Cards.Info.Title", "Info" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Cards.Mappings.Title", "Mappings" },

                // Slider Field Names
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.Name", "Slider Name" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.Name.Hint", "Slider Name" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.DisplayOrder", "Display Order" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.DisplayOrder.Hint", "Display Order" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.Published", "Published" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.Published.Hint", "Published" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.AclCustomerRoles", "Customer Roles" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.AclCustomerRoles.Hint", "Customer Roles" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.LimitedToStores", "Limited To Stores" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.Sliders.Fields.LimitedToStores.Hint", "Limited To Stores" },

                // Slider Item Field Names
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Slider", "Slider Name" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Slider.Hint", "Slider Name" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Name", "Slider Item Name" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Name.Hint", "Slider Item Name" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Picture", "Picture" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Picture.Hint", "Picture" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Url", "Url" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Url.Hint", "Url" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.AlternateText", "Alternate Text" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.AlternateText.Hint", "Alternate Text" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.DisplayOrder", "Display Order" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.DisplayOrder.Hint", "Display Order" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Published", "Published" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.Published.Hint", "Published" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.AclCustomerRoles", "Customer Roles" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.AclCustomerRoles.Hint", "Customer Roles" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.LimitedToStores", "Limited To Stores" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.Fields.LimitedToStores.Hint", "Limited To Stores" },

                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.BackToSlider", "back to edit slider" },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.SaveBeforeEdit", "You need to save the slider before you can add slider items for this slider page." },
                { "Nop.Plugin.Widgets.SwiperSlider.Admin.SliderItems.CreateButton", "Add New Slider Item" },
            };

            var localizationService = EngineContext.Current.Resolve <ILocalizationService>();

            localizationService.AddOrUpdateLocaleResourceAsync(resources).Wait();
        }
Beispiel #16
0
        public virtual IActionResult Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled)
            {
                return(RedirectToRoute("HomePage"));
            }

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

            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            if (model.DataProvider == DataProviderType.SqlServer)
            {
                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
                    {
                        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");
                        }
                    }
                }
            }

            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();

            foreach (var dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError("", $"The '{WindowsIdentity.GetCurrent().Name}' account is not granted with Modify permission on folder '{dir}'. Please configure these permissions.");
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError("", $"The '{WindowsIdentity.GetCurrent().Name}' account is not granted with Modify permission on file '{file}'. Please configure these permissions.");
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var connectionString = string.Empty;
                    if (model.DataProvider == DataProviderType.SqlServer)
                    {
                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string
                            var sqlStringBuilder = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            if (UseMars)
                            {
                                sqlStringBuilder.MultipleActiveResultSets = true;
                            }
                            connectionString = sqlStringBuilder.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(
                                model.SqlAuthenticationType == "windowsauthentication",
                                model.SqlServerName, model.SqlDatabaseName,
                                model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                var collation = model.UseCustomCollation ? model.Collation : "";

                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (!string.IsNullOrEmpty(errorCreatingDatabase))
                                {
                                    throw new Exception(errorCreatingDatabase);
                                }
                            }
                        }
                        else
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                throw new Exception("Database does not exist or you don't have permissions to connect to it");
                            }
                        }
                    }

                    DataSettingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = model.DataProvider,
                        DataConnectionString = connectionString
                    }, _fileProvider);

                    //initialize database
                    EngineContext.Current.Resolve <IDataProvider>().InitializeDatabase();

                    var installationService = EngineContext.Current.Resolve <IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminUsername, model.AdminPassword, model.InstallSampleData);

                    DataSettingsManager.ResetCache();

                    //prepare plugins to install
                    var pluginService = EngineContext.Current.Resolve <IPluginService>();
                    pluginService.ClearInstalledPluginsList();

                    var pluginsIgnoredDuringInstallation = new List <string>();
                    if (!string.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation))
                    {
                        pluginsIgnoredDuringInstallation = _config.PluginsIgnoredDuringInstallation
                                                           .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(pluginName => pluginName.Trim())
                                                           .ToList();
                    }

                    var plugins = pluginService.GetPluginDescriptors <IPlugin>(LoadPluginsMode.All)
                                  .Where(pluginDescriptor =>
                                         !pluginsIgnoredDuringInstallation.Contains(pluginDescriptor.SystemName))
                                  .OrderBy(pluginDescriptor => pluginDescriptor.Group).ToList();

                    foreach (var plugin in plugins)
                    {
                        pluginService.PreparePluginToInstall(plugin.SystemName);
                    }

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

                    webHelper.RestartAppDomain();

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

                    var cacheManager = EngineContext.Current.Resolve <IStaticCacheManager>();
                    cacheManager.Clear();

                    //clear provider settings if something got wrong
                    DataSettingsManager.SaveSettings(new DataSettings(), _fileProvider);

                    ModelState.AddModelError("", $"Setup failed: {exception.Message}");
                }
            }

            return(View(model));
        }
Beispiel #17
0
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                await next();

                if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
                {
                    return;
                }

                if (!DataSettingsManager.DatabaseIsInstalled())
                {
                    return;
                }

                //only in GET requests
                if (!HttpMethods.IsGet(context.HttpContext.Request.Method))
                {
                    return;
                }

                //update last activity date
                if (_workContext.CurrentCustomer.LastActivityDateUtc.AddMinutes(1.0) < DateTime.UtcNow)
                {
                    await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastActivityDateUtc, DateTime.UtcNow);
                }

                //get current IP address
                var currentIpAddress = context.HttpContext?.Connection?.RemoteIpAddress?.ToString();

                //update customer's IP address
                if (!string.IsNullOrEmpty(currentIpAddress) && !currentIpAddress.Equals(_workContext.CurrentCustomer.LastIpAddress, StringComparison.OrdinalIgnoreCase))
                {
                    _workContext.CurrentCustomer.LastIpAddress = currentIpAddress;
                    await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastIpAddress, currentIpAddress);
                }

                //whether is need to store last visited page URL
                if (!_customerSettings.StoreLastVisitedPage)
                {
                    return;
                }

                //get current page
                var pageUrl = context.HttpContext?.Request?.GetDisplayUrl();

                if (string.IsNullOrEmpty(pageUrl))
                {
                    return;
                }

                //get previous last page
                var previousPageUrl = _workContext.CurrentCustomer.GetUserFieldFromEntity <string>(SystemCustomerFieldNames.LastVisitedPage);

                //save new one if don't match
                if (!pageUrl.Equals(previousPageUrl, StringComparison.OrdinalIgnoreCase))
                {
                    await _userFieldService.SaveField(_workContext.CurrentCustomer, SystemCustomerFieldNames.LastVisitedPage, pageUrl);
                }

                if (!string.IsNullOrEmpty(context.HttpContext.Request.Headers[HeaderNames.Referer]))
                {
                    if (!context.HttpContext.Request.Headers[HeaderNames.Referer].ToString().Contains(context.HttpContext.Request.Host.ToString()))
                    {
                        var previousUrlReferrer = _workContext.CurrentCustomer.GetUserField <string>(_userFieldService, SystemCustomerFieldNames.LastUrlReferrer);
                        var actualUrlReferrer   = context.HttpContext.Request.Headers[HeaderNames.Referer];
                        if (previousUrlReferrer != actualUrlReferrer)
                        {
                            await _userFieldService.SaveField(_workContext.CurrentCustomer, SystemCustomerFieldNames.LastUrlReferrer, actualUrlReferrer);
                        }
                    }
                }

                if (_customerSettings.SaveVisitedPage)
                {
                    if (!_workContext.CurrentCustomer.IsSearchEngineAccount())
                    {
                        //activity
                        await _customerActivityService.InsertActivity("PublicStore.Url", pageUrl, pageUrl, _workContext.CurrentCustomer);

                        //action
                        await _customerActionEventService.Url(_workContext.CurrentCustomer, context.HttpContext?.Request?.Path.ToString(), context.HttpContext?.Request?.Headers["Referer"]);
                    }
                }
            }
Beispiel #18
0
        /// <summary>
        /// 注册服务
        /// </summary>
        public void Register(ContainerBuilder builder, ITypeFinder typeFinder, WebConfig config)
        {
            //注册Http上下文和其它相关服务
            builder.Register(p => HttpContext.Current == null
                ? (new FakeHttpContext("~/") as HttpContextBase)
                : (new HttpContextWrapper(HttpContext.Current) as HttpContextBase))
            .As <HttpContextBase>()
            .InstancePerLifetimeScope();
            builder.Register(p => p.Resolve <HttpContextBase>().Request)
            .As <HttpRequestBase>()
            .InstancePerLifetimeScope();
            builder.Register(p => p.Resolve <HttpContextBase>().Response)
            .As <HttpResponseBase>()
            .InstancePerLifetimeScope();
            builder.Register(p => p.Resolve <HttpContextBase>().Server)
            .As <HttpServerUtilityBase>()
            .InstancePerLifetimeScope();
            builder.Register(p => p.Resolve <HttpContextBase>().Session)
            .As <HttpSessionStateBase>()
            .InstancePerLifetimeScope();

            //注册路由服务
            builder.RegisterType <RoutePublisher>().As <IRoutePublisher>().SingleInstance();

            //注册 Web Helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();

            //注册 Attribute
            builder.RegisterFilterProvider();

            //注册 Controller
            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());

            //注册数据库操作服务
            var dataSettingsManager = new DataSettingsManager();
            var dataSettings        = dataSettingsManager.LoadSettings();

            builder.Register(p => dataSettingsManager.LoadSettings())
            .As <DataSettings>();
            builder.Register(p => new EFDataProviderManager(dataSettings))
            .As <BaseDataProviderManager>();
            builder.Register(p => p.Resolve <BaseDataProviderManager>().LoadDataProvider())
            .As <IDataProvider>();

            if (dataSettings != null && dataSettings.IsValid())
            {
                var efDataProviderManager = new EFDataProviderManager(dataSettings);
                var dataProvider          = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();

                builder.Register(p => new EntityContext(dataSettings.DataConnectionString))
                .As <IDbContext>();
            }

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


            //注册插件服务

            //注册缓存服务
            builder.RegisterType <PerRequestCacheManager>().As <ICacheManager>().Named <ICacheManager>("cache_per_request").InstancePerLifetimeScope();

            if (config.MemcachedEnable)
            {
                builder.RegisterType <MemcachedManager>().As <ICacheManager>().Named <ICacheManager>("chache_other").SingleInstance();
            }

            if (config.RedisCachingEnable)
            {
                builder.RegisterType <RedisConnectionWrapper>().As <IRedisConnectionWrapper>().SingleInstance();
                builder.RegisterType <RedisCacheManager>().As <ICacheManager>().Named <ICacheManager>("cache_static")
                .InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().Named <ICacheManager>("cache_static").SingleInstance();
            }


            //注册设定
            builder.RegisterType <SettingService>().As <ISettingService>()
            .WithParameter(ResolvedParameter.ForNamed <ICacheManager>("cache_static"))
            .InstancePerLifetimeScope();

            //注册工作上下文
            builder.RegisterType <WorkContext>().As <IWorkContext>().InstancePerLifetimeScope();

            //注册业务服务
            builder.RegisterType <InstallationLocalizationService>().As <IInstallationLocalizationService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerService>().As <ICustomerService>().InstancePerLifetimeScope();
            builder.RegisterType <AdminService>().As <IAdminService>().InstancePerLifetimeScope();
            builder.RegisterType <GuestService>().As <IGuestService>().InstancePerLifetimeScope();
            builder.RegisterType <EncryptionService>().As <IEncryptionService>().InstancePerLifetimeScope();
            builder.RegisterType <FormsAuthenticationService>().As <IAuthenticationService>().InstancePerLifetimeScope();

            builder.RegisterType <RoleService>().As <IRoleService>()
            .WithParameter(ResolvedParameter.ForNamed <ICacheManager>("cache_static"))
            .InstancePerLifetimeScope();
            builder.RegisterType <RegionService>().As <IRegionService>()
            .WithParameter(ResolvedParameter.ForNamed <ICacheManager>("cache_static"))
            .InstancePerLifetimeScope();
        }
Beispiel #19
0
        public virtual IActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            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 (var 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 (var 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
                        var databaseFileName = "Nop.Db.sdf";
                        var databasePath     = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        var 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)
                    {
                        var provider = (IPermissionProvider)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.Resolve <IStaticCacheManager>();
                    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));
        }
 /// <summary>
 /// Database connection string
 /// </summary>
 /// <returns>A task that represents the asynchronous operation</returns>
 protected async Task <string> GetCurrentConnectionStringAsync()
 {
     return((await DataSettingsManager.LoadSettingsAsync()).ConnectionString);
 }
Beispiel #21
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 (Exception exc)
                    {
                        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 + "App_Data\\InstalledPlugins.txt");
            dirsToCheck.Add(rootDir + "App_Data\\Settings.txt");
            dirsToCheck.Add(rootDir + "bin");
            dirsToCheck.Add(rootDir + "content");
            dirsToCheck.Add(rootDir + "content\\images");
            dirsToCheck.Add(rootDir + "content\\images\\thumbs");
            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 + "web.config");
            filesToCheck.Add(rootDir + "bin\\" + "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);
                        }

                        //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
                        //little hack here (SQL CE 4 bug - http://www.hanselman.com/blog/PDC10BuildingABlogWithMicrosoftUnnamedPackageOfWebLove.aspx)
                        string databasePath = HostingEnvironment.MapPath("~/App_Data/") + @"Nop.Db.sdf";
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        if (System.IO.File.Exists(databasePath))
                        {
                            System.IO.File.Delete(databasePath);
                        }
                    }

                    //save settings
                    //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();


                    //only 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>();
                    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)
                {
                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", "Setup failed: " + exception);
                }
            }
            return(View(model));
        }
 /// <summary>
 /// Database connection string
 /// </summary>
 protected string GetCurrentConnectionString()
 {
     return(DataSettingsManager.LoadSettings().ConnectionString);
 }
Beispiel #23
0
        public virtual IActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            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>();

            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
                        var databaseFileName = "Game.Db.sdf";
                        var databasePath     = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        var 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);

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

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //register default permissions
                    //待处理:是否需要注册默认的授权记录,还是用SQL语句批量授权

                    //restart application
                    //webHelper.RestartAppDomain();

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

                    var cacheManager = EngineContext.Current.Resolve <IStaticCacheManager>();
                    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));
        }
            /// <summary>
            /// Called asynchronously before the action, after model binding is complete.
            /// </summary>
            /// <param name="context">A context for action filters</param>
            /// <returns>A task that represents the asynchronous operation</returns>
            private async Task CheckAccessClosedStoreAsync(ActionExecutingContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

                if (!await DataSettingsManager.IsDatabaseInstalledAsync())
                {
                    return;
                }

                //check whether this filter has been overridden for the Action
                var actionFilter = context.ActionDescriptor.FilterDescriptors
                                   .Where(filterDescriptor => filterDescriptor.Scope == FilterScope.Action)
                                   .Select(filterDescriptor => filterDescriptor.Filter)
                                   .OfType <CheckAccessClosedStoreAttribute>()
                                   .FirstOrDefault();

                //ignore filter (the action is available even if a store is closed)
                if (actionFilter?.IgnoreFilter ?? _ignoreFilter)
                {
                    return;
                }

                //store isn't closed
                if (!_storeInformationSettings.StoreClosed)
                {
                    return;
                }

                //get action and controller names
                var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
                var actionName       = actionDescriptor?.ActionName;
                var controllerName   = actionDescriptor?.ControllerName;

                if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName))
                {
                    return;
                }

                //two factor verification accessible when a store is closed
                if (controllerName.Equals("Customer", StringComparison.InvariantCultureIgnoreCase) &&
                    actionName.Equals("MultiFactorVerification", StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                //topics accessible when a store is closed
                if (controllerName.Equals("Topic", StringComparison.InvariantCultureIgnoreCase) &&
                    actionName.Equals("TopicDetails", StringComparison.InvariantCultureIgnoreCase))
                {
                    //get identifiers of topics are accessible when a store is closed

                    var store = await _storeContext.GetCurrentStoreAsync();

                    var allowedTopicIds = (await _topicService.GetAllTopicsAsync(store.Id))
                                          .Where(topic => topic.AccessibleWhenStoreClosed)
                                          .Select(topic => topic.Id);

                    //check whether requested topic is allowed
                    var requestedTopicId = context.RouteData.Values["topicId"] as int?;
                    if (requestedTopicId.HasValue && allowedTopicIds.Contains(requestedTopicId.Value))
                    {
                        return;
                    }
                }

                //check whether current customer has access to a closed store
                if (await _permissionService.AuthorizeAsync(StandardPermissionProvider.AccessClosedStore))
                {
                    return;
                }

                //store is closed and no access, so redirect to 'StoreClosed' page
                context.Result = new RedirectToRouteResult("StoreClosed", null);
            }
Beispiel #25
0
        /// <summary>Collect the UP migration expressions</summary>
        public override void Up()
        {
            if (!DataSettingsManager.IsDatabaseInstalled())
            {
                return;
            }

            //do not use DI, because it produces exception on the installation process
            var settingRepository = EngineContext.Current.Resolve <IRepository <Setting> >();
            var settingService    = EngineContext.Current.Resolve <ISettingService>();

            //#4904 External authentication errors logging
            var externalAuthenticationSettings = settingService.LoadSettingAsync <ExternalAuthenticationSettings>().Result;

            if (!settingService.SettingExistsAsync(externalAuthenticationSettings, settings => settings.LogErrors).Result)
            {
                externalAuthenticationSettings.LogErrors = false;
                settingService.SaveSettingAsync(externalAuthenticationSettings).Wait();
            }

            var multiFactorAuthenticationSettings = settingService.LoadSettingAsync <MultiFactorAuthenticationSettings>().Result;

            if (!settingService.SettingExistsAsync(multiFactorAuthenticationSettings, settings => settings.ForceMultifactorAuthentication).Result)
            {
                multiFactorAuthenticationSettings.ForceMultifactorAuthentication = false;

                settingService.SaveSettingAsync(multiFactorAuthenticationSettings).Wait();
            }

            //#5102 Delete Full-text settings
            settingRepository
            .DeleteAsync(setting => setting.Name == "commonsettings.usefulltextsearch" || setting.Name == "commonsettings.fulltextmode")
            .Wait();

            //#4196
            settingRepository
            .DeleteAsync(setting => setting.Name == "commonsettings.scheduletaskruntimeout" ||
                         setting.Name == "commonsettings.staticfilescachecontrol" ||
                         setting.Name == "commonsettings.supportpreviousnopcommerceversions" ||
                         setting.Name == "securitysettings.pluginstaticfileextensionsBlacklist")
            .Wait();

            var seoSettings  = settingService.LoadSettingAsync <SeoSettings>().Result;
            var newUrlRecord = "products";

            if (!seoSettings.ReservedUrlRecordSlugs.Contains(newUrlRecord))
            {
                seoSettings.ReservedUrlRecordSlugs.Add(newUrlRecord);
                settingService.SaveSettingAsync(seoSettings).Wait();
            }

            //#3015
            if (!settingService.SettingExistsAsync(seoSettings, settings => settings.HomepageTitle).Result)
            {
                seoSettings.HomepageTitle = seoSettings.DefaultTitle;
                settingService.SaveSettingAsync(seoSettings).Wait();
            }

            if (!settingService.SettingExistsAsync(seoSettings, settings => settings.HomepageDescription).Result)
            {
                seoSettings.HomepageDescription = "Your home page description";
                settingService.SaveSettingAsync(seoSettings).Wait();
            }
        }
Beispiel #26
0
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (await DataSettingsManager.IsDatabaseInstalledAsync())
            {
                return(RedirectToRoute("Homepage"));
            }

            model.DisableSampleDataOption  = _appSettings.Get <InstallationConfig>().DisableSampleData;
            model.InstallRegionalResources = _appSettings.Get <InstallationConfig>().InstallRegionalResources;

            PrepareAvailableDataProviders(model);
            PrepareLanguageList(model);
            PrepareCountryList(model);

            //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 (var dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), CurrentOSUser.FullName, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!_fileProvider.FileExists(file))
                {
                    continue;
                }

                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureFilePermissions"), CurrentOSUser.FullName, file));
                }
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                var dataProvider = DataProviderManager.GetDataProvider(model.DataProvider);

                var connectionString = model.ConnectionStringRaw ? model.ConnectionString : dataProvider.BuildConnectionString(model);

                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new Exception(_locService.GetResource("ConnectionStringWrongFormat"));
                }

                DataSettingsManager.SaveSettings(new DataConfig
                {
                    DataProvider     = model.DataProvider,
                    ConnectionString = connectionString
                }, _fileProvider);

                if (model.CreateDatabaseIfNotExists)
                {
                    try
                    {
                        dataProvider.CreateDatabase(model.Collation);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format(_locService.GetResource("DatabaseCreationError"), ex.Message));
                    }
                }
                else
                {
                    //check whether database exists
                    if (!await dataProvider.DatabaseExistsAsync())
                    {
                        throw new Exception(_locService.GetResource("DatabaseNotExists"));
                    }
                }

                dataProvider.InitializeDatabase();

                var cultureInfo = new CultureInfo(NopCommonDefaults.DefaultLanguageCulture);
                var regionInfo  = new RegionInfo(NopCommonDefaults.DefaultLanguageCulture);

                var languagePackInfo = (DownloadUrl : string.Empty, Progress : 0);
                if (model.InstallRegionalResources)
                {
                    //try to get CultureInfo and RegionInfo
                    try
                    {
                        cultureInfo = new CultureInfo(model.Country[3..]);
                        regionInfo  = new RegionInfo(model.Country[3..]);