Пример #1
0
        public void RegisterLocalizations(IServiceCollection services, IMvcBuilder mvcBuilder)
        {
            mvcBuilder.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            mvcBuilder.AddDataAnnotationsLocalization();
            mvcBuilder.AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(ValidationMessages));
            });

            services.Configure <LocalizationOptions>(options =>
            {
                options.ResourcesPath = "Resources";
            });

            services.Configure <MvcOptions>(options =>
            {
                options.ModelMetadataDetailsProviders.Add(
                    new CustomValidationMetadataProvider());
            });

            services.Configure <RequestLocalizationOptions>(options =>
            {
                options.SupportedUICultures = new List <CultureInfo>
                {
                    new CultureInfo("fr"),
                    new CultureInfo("en"),
                    new CultureInfo("es"),
                    new CultureInfo("pt"),
                };
                options.DefaultRequestCulture = new RequestCulture("en");
            }
                                                            );
        }
        public static IMvcBuilder AddAppLocalization(this IMvcBuilder builder)
        {
            builder.Services.AddRouting(o =>
            {
                o.ConstraintMap["culture"] = typeof(CultureRouteConstraint);
            });

            //builder.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            builder.AddDataAnnotationsLocalization(options =>
            {
                // TODO: (core) Set DataAnnotationLocalizerProvider
                //options.DataAnnotationLocalizerProvider = (type, factory) =>
                //{
                //	var scope = EfStringLocalizerFactory.ResolveTranslationScope(type, "SmartStore.DataAnnotations.Validation");
                //	return factory.Create(scope, type.FullName);
                //};
            });

            //builder.Services.AddScoped<IStringLocalizerScope, StringLocalizerScope>();
            //builder.Services.AddScoped<ITranslationService, TranslationService>();
            //builder.Services.AddTransient<IViewLocalizer, SmartViewLocalizer>();
            //builder.Services.AddSingleton<IStringLocalizerFactory, EfStringLocalizerFactory>();
            //builder.Services.AddSingleton<IUrlHelper, SmartUrlHelper>();

            builder.Services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, AppLocalizationMvcOptionsSetup>());

            return(builder);
        }
Пример #3
0
        /// <summary>
        /// Adds services required for application localization.
        /// Calls the IServiceCollection.AddLocalization() method.
        /// Registers an IMetadataDetailsProvider that handles validation attributes to Microsoft.AspNetCore.Mvc.MvcOptions.
        /// </summary>
        /// <param name="mvcBuilder">The Microsoft.Extensions.DependencyInjection.IMvcBuilder.</param>
        /// <param name="enableDataAnnotationsLocalization"><c>true</c> to call <see cref="MvcLocalizationMvcBuilderExtensions.AddViewLocalization"/> on <paramref name="mvcBuilder"/>, otherwise false.</param>
        /// <param name="enableViewLocalization"><c>true</c> to call <see cref="MvcDataAnnotationsMvcBuilderExtensions.AddDataAnnotationsLocalization"/> on <paramref name="mvcBuilder"/>, otherwise false.</param>
        /// <returns>The <see cref="IMvcBuilder"/> so that additional calls can be chained.</returns>
        public static IMvcBuilder AddForEvolveLocalization(this IMvcBuilder mvcBuilder, bool enableViewLocalization, bool enableDataAnnotationsLocalization)
        {
            // New registration
            var services = mvcBuilder.Services;

            services
            // Configure ForEvolve.AspNetCore.Localization
            .AddSingleton <ISupportedCulturesCollection, SupportedCulturesCollection>()
            .AddSingleton <ILocalizationValidationMetadataProvider, ForEvolveLocalizationValidationMetadataProvider <DataAnnotationSharedResource> >()
            .AddSingleton <ILocalizationValidationAttributeAdapter, StringLengthLocalizationValidationAttributeAdapter>()
            .AddSingleton <ILocalizationValidationAttributeAdapter, DefaultLocalizationValidationAttributeAdapter>()

            // Add custom options initializers to configures Asp.Net Core
            .AddSingleton <IConfigureOptions <RequestLocalizationOptions>, RequestLocalizationOptionsInitializer>()
            .AddSingleton <IConfigureOptions <LocalizationOptions>, LocalizationOptionsInitializer>()
            .AddSingleton <IConfigureOptions <MvcOptions>, MvcOptionsInitializer>()

            // Adds services required for application localization.
            .AddLocalization()
            ;

            if (enableViewLocalization)
            {
                mvcBuilder.AddViewLocalization();
            }
            if (enableDataAnnotationsLocalization)
            {
                mvcBuilder.AddDataAnnotationsLocalization();
            }

            return(mvcBuilder);
        }
Пример #4
0
 /// <summary>
 /// Adds MVC data annotations localization to the application.
 /// </summary>
 /// <typeparam name="TResource">Type of resource source.</typeparam>
 /// <param name="mvc">The Microsoft.Extensions.DependencyInjection.IMvcBuilder.</param>
 /// <returns>The Microsoft.Extensions.DependencyInjection.IMvcBuilder.</returns>
 public static IMvcBuilder AddDataAnnotationsLocalization <TResource>(this IMvcBuilder mvc) where TResource : class
 {
     return(mvc.AddDataAnnotationsLocalization(options =>
                                               options.DataAnnotationLocalizerProvider = (type, factory) =>
     {
         return new MultiResourceLocalizer(factory, typeof(TResource), type);
     }));
 }
 /// <summary>
 /// Adds MVC data annotations localization with inheritance to the application.
 /// </summary>
 /// <params>
 /// <param name="builder">The <see cref="IMvcBuilder" />.</param>
 /// </params>
 /// <returns>The <see cref="IMvcBuilder" />.</returns>
 public static IMvcBuilder AddDataAnnotationsLocalizationWithInheritance(this IMvcBuilder builder)
 {
     return(builder.AddDataAnnotationsLocalization(setup =>
     {
         setup.DataAnnotationLocalizerProvider = (type, factory) =>
                                                 new InheritingLocalizerProvider(type, factory);
     }));
 }
Пример #6
0
 /// <summary>
 /// Adds MVC data annotations localization to the application.
 /// </summary>
 /// <param name="mvc">The Microsoft.Extensions.DependencyInjection.IMvcBuilder.</param>
 /// <param name="resourceType">Type of resource source.</param>
 /// <returns>The Microsoft.Extensions.DependencyInjection.IMvcBuilder.</returns>
 public static IMvcBuilder AddDataAnnotationsLocalization(this IMvcBuilder mvc, Type resourceType)
 {
     return(mvc.AddDataAnnotationsLocalization(options =>
                                               options.DataAnnotationLocalizerProvider = (type, factory) =>
     {
         return new MultiResourceLocalizer(factory, resourceType, type);
     }));
 }
Пример #7
0
 public static IMvcBuilder AddCustomDataAnnotationLocalization(this IMvcBuilder builder, IServiceCollection services, Type typeOfSharedResource)
 {
     builder.AddDataAnnotationsLocalization(option =>
     {
         var localizer = new FactoryLocalizer().Set(services, typeOfSharedResource);
         option.DataAnnotationLocalizerProvider = (type, factory) => localizer;
     });
     return(builder);
 }
Пример #8
0
        public static IMvcBuilder AddCustomDataAnnotationLocalization(this IMvcBuilder builder, IServiceCollection services, Type SharedResource)
        {
            builder.AddDataAnnotationsLocalization(Options =>
            {
                var Localizer = new FactoryLocalizer().Set(services, SharedResource);

                Options.DataAnnotationLocalizerProvider = (t, f) => Localizer;
            });

            return(builder);
        }
Пример #9
0
 public static IMvcBuilder UseToolkitAttributeTranslator(this IMvcBuilder builder, AttributeTranslationOptions options)
 {
     return(builder.AddDataAnnotationsLocalization(opt =>
     {
         opt.DataAnnotationLocalizerProvider = (type, factory) =>
         {
             var retVal = new FallbackLocalizer(factory.Create(type), factory, options);
             return retVal;
         };
     }));
 }
Пример #10
0
        /// <summary>
        /// Add XLocalizer with DB support using customized entity models,
        /// and use defined translation service type
        /// </summary>
        /// <typeparam name="TContext">DbContext</typeparam>
        /// <typeparam name="TTranslator">Translation service</typeparam>
        /// <typeparam name="TResource">Type of localization DbEntity</typeparam>
        /// <param name="options">XLDbOptions</param>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IMvcBuilder AddXDbLocalizer <TContext, TTranslator, TResource>(this IMvcBuilder builder, Action <XLocalizerOptions> options)
            where TContext : DbContext
            where TTranslator : ITranslator
            where TResource : class, IXDbResource, new()
        {
            builder.Services.Configure <XLocalizerOptions>(options);

            // ExpressMemoryCache for caching localized values
            builder.Services.AddSingleton <ExpressMemoryCache>();

            // Try add a default data exporter service, unless another service is defined in startup
            builder.Services.TryAddSingleton <IDbResourceExporter, EFDbResourceExporter <TContext> >();

            // Try add a default resx service.
            // if another service has been registered this will be bypassed, and the other service will be in use.
            builder.Services.TryAddSingleton <IDbResourceProvider, EFDbResourceProvider <TContext> >();

            // Register IStringLocalizer for the default shared resource and translation type
            // This is the default (shared) resource entity and translation
            builder.Services.AddSingleton <IStringLocalizer, DbStringLocalizer <TResource> >();
            builder.Services.AddSingleton <IStringLocalizerFactory, DbStringLocalizerFactory <TResource> >();

            // Register IHtmlLocalizer for the default shared resource and translation type
            // This is the default (shared) resource entity and translation
            builder.Services.AddSingleton <IHtmlLocalizer, DbHtmlLocalizer <TResource> >();
            builder.Services.AddSingleton <IHtmlLocalizerFactory, DbHtmlLocalizerFactory <TResource> >();

            // Register generic IDbStringLocalizer for user defined resource and translation entities
            // e.g. IDbStringLocalizer<ProductArea, ProductAreaTranslation>
            // e.g. IDbStringLocalizer<UserArea, UserAreaTranslation>
            builder.Services.AddTransient(typeof(IStringLocalizer <>), typeof(DbStringLocalizer <>));
            builder.Services.AddTransient(typeof(IHtmlLocalizer <>), typeof(DbHtmlLocalizer <>));

            // Express localizer factories for creating localizers with the default shared resource type
            // Use .Create() method for creating localizers.
            builder.Services.AddSingleton <IXStringLocalizerFactory, DbStringLocalizerFactory <TResource> >();
            builder.Services.AddSingleton <IXHtmlLocalizerFactory, DbHtmlLocalizerFactory <TResource> >();

            // Add custom providers for overriding default modelbinding and data annotations errors
            builder.Services.AddSingleton <IConfigureOptions <MvcOptions>, ConfigureMvcOptions>();

            // Add data annotations locailzation
            builder.AddDataAnnotationsLocalization(ops =>
            {
                // This will look for localization resource of default type T (shared resource)
                ops.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(TResource));
            });

            // Configure route culture provide
            return(builder.AddDbDataManagers <TContext>()
                   .AddIdentityErrorsLocalization()
                   .WithTranslationService <TTranslator>());
        }
Пример #11
0
        /// <summary>
        /// Register LHQ types into ASP.NET Core model metadata and data annotations (NET Core &gt;= 2.x).
        /// </summary>
        /// <param name="mvcBuilder">Services container where to register LHQ strings localizer.</param>
        public static IMvcBuilder AddMvcTypedStringsLocalizer(this IMvcBuilder mvcBuilder)
        {
#if !ASP_NET_CORE1
            mvcBuilder.Services.Configure <MvcOptions>(options => { options.ModelMetadataDetailsProviders.Add(new DisplayNameDetailsProvider()); });

            mvcBuilder.AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, localizerFactory) => localizerFactory.Create(type);
            });
#endif
            return(mvcBuilder);
        }
        /// <summary>
        /// Add DataAnnotatons localization to the project.
        /// <para>Related resource files can be downloaded from: https://github.com/LazZiya/ExpressLocalization.Resources </para>
        /// </summary>
        /// <typeparam name="TDataAnnotationsLocalizationResource">Type of DataAnnotations localization resource</typeparam>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IMvcBuilder ExAddDataAnnotationsLocalization <TDataAnnotationsLocalizationResource>(this IMvcBuilder builder) where TDataAnnotationsLocalizationResource : class
        {
            builder.AddDataAnnotationsLocalization(x =>
            {
                var type         = typeof(TDataAnnotationsLocalizationResource);
                var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
                var factory      = builder.Services.BuildServiceProvider().GetService <IStringLocalizerFactory>();
                var localizer    = factory.Create(type.Name, assemblyName.Name);

                x.DataAnnotationLocalizerProvider = (t, f) => localizer;
            });

            return(builder);
        }
Пример #13
0
 public static IMvcBuilder AddDataAnnotationsJsonLocalization(this IMvcBuilder builder)
 {
     if (builder == null)
     {
         throw new ArgumentNullException(nameof(builder));
     }
     builder.AddDataAnnotationsLocalization(o =>
     {
         var provider  = builder.Services.BuildServiceProvider();
         var localizer = provider.GetService <IStringLocalizer>();
         o.DataAnnotationLocalizerProvider = (t, f) => localizer;
     });
     return(builder);
 }
        /// <summary>
        /// Add DataAnnotations localization with specified resource type.
        /// </summary>
        /// <typeparam name="TResource">Type of DataAnnotations localization resource</typeparam>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IMvcBuilder AddDataAnnotationsLocalization <TResource>(this IMvcBuilder builder)
            where TResource : class
        {
            // Add data annotations locailzation
            builder.AddDataAnnotationsLocalization(ops =>
            {
                // This will look for localization resource with type of T (shared resource)
                ops.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(TResource));

                // This will look for localization resources depending on specific type, e.g. LoginModel.en.xml
                //ops.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(t);
            });

            return(builder);
        }
Пример #15
0
        /// <summary>
        /// Add DataAnnotatons localization to the project.
        /// <para>Related resource files can be downloaded from: https://github.com/LazZiya/ExpressLocalization.Resources </para>
        /// </summary>
        /// <typeparam name="TDataAnnotationsLocalizationResource">Type of DataAnnotations localization resource</typeparam>
        /// <param name="builder"></param>
        /// <param name="useExpressValidationAttributes">Express validiation attributes provides already localized eror messages</param>
        /// <returns></returns>
        public static IMvcBuilder ExAddDataAnnotationsLocalization <TDataAnnotationsLocalizationResource>(this IMvcBuilder builder, bool useExpressValidationAttributes) where TDataAnnotationsLocalizationResource : class
        {
            builder.AddDataAnnotationsLocalization(ops => {
                var t = typeof(TDataAnnotationsLocalizationResource);
                ops.DataAnnotationLocalizerProvider = (type, factory) =>
                                                      factory.Create(t.Name, t.Assembly.GetName().Name);
            });

            if (useExpressValidationAttributes)
            {
                builder.Services.AddSingleton <IValidationAttributeAdapterProvider, ExpressValidationAttributeAdapterProvider <TDataAnnotationsLocalizationResource> >();
            }

            return(builder);
        }
        public static IMvcBuilder AddSimpleLocalizationForDataAnnotations <TSharedResourceClass>(
            this IMvcBuilder mvcBuilder)
            where TSharedResourceClass : class
        {
            if (mvcBuilder == null)
            {
                throw new ArgumentNullException(nameof(mvcBuilder));
            }

            return(mvcBuilder.AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    return factory.Create(typeof(TSharedResourceClass));
                };
            }));
        }
 public static IMvcBuilder AddVirgoDataAnnotationsLocalization(this IMvcBuilder builder, Type programType)
 {
     builder.AddDataAnnotationsLocalization(options =>
     {
         options.DataAnnotationLocalizerProvider = (type, factory) =>
         {
             //if (Core.CoreProgram.Buildindll.Any(x => type.FullName.StartsWith(x)))
             //{
             //    return factory.Create(typeof(KnifeZ.Virgo.Core.CoreProgram));
             //}
             //else
             //{
             return(factory.Create(programType));
             //}
         };
     });
     return(builder);
 }
Пример #18
0
        public void ConfigureDataAnnotationServices(IMvcBuilder builder)
        {
            builder.Services.ReplaceLast(ServiceDescriptor.Singleton <IValidationAttributeAdapterProvider, CustomValidationAttributeAdapterProvider>());

            builder.Services.AddOptions <MvcOptions>()
            .Configure <IValidationAttributeAdapterProvider, IOptions <MvcDataAnnotationsLocalizationOptions>, IStringLocalizerFactory>(
                (options, validationAttributeAdapterProvider, localizationOptions, stringLocalizerFactory) =>
                options.ModelValidatorProviders.Add(new DataAnnotationsLocalizationAdjuster(validationAttributeAdapterProvider, localizationOptions, stringLocalizerFactory)));

            builder.AddDataAnnotationsLocalization();

            builder.Services.AddOptions <MvcDataAnnotationsLocalizationOptions>()
            .Configure <ILoggerFactory>((options, loggerFactory) => options.DataAnnotationLocalizerProvider = (type, stringLocalizerFactory) =>
                                                                                                              new CompositeStringLocalizer(
                                            stringLocalizerFactory,
                                            types: new[] { type, typeof(ValidationErrorMessages) },
                                            logger: loggerFactory.CreateLogger <CompositeStringLocalizer>()));
        }
Пример #19
0
        public static IMvcBuilder AddCustomLocalization(this IMvcBuilder mvcBuilder, IServiceCollection services)
        {
            mvcBuilder.AddDataAnnotationsLocalization(options =>
            {
                const string resourcesPath = "Resources";
                string baseName            = $"{resourcesPath}.{nameof(SharedResource)}";
                var location = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName).Name;

                options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(baseName, location);
            });

            services.AddLocalization();
            services.AddScoped <IStringLocalizer>(provider =>
                                                  provider.GetRequiredService <IStringLocalizer <SharedResource> >());

            services.AddTranslation();
            return(mvcBuilder);
        }
        /// <summary>
        /// Register all XLocalization services...
        /// </summary>
        /// <typeparam name="TResource">Resource file type</typeparam>
        /// <typeparam name="TTranslator">Translation service type</typeparam>
        /// <param name="builder"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IMvcBuilder AddXLocalizer <TResource, TTranslator>(this IMvcBuilder builder, Action <XLocalizerOptions> options)
            where TResource : class
            where TTranslator : ITranslator
        {
            // Configure XLocalizer options
            builder.Services.Configure <XLocalizerOptions>(options);

            // ExpressMemoryCache for caching localized values
            builder.Services.AddSingleton <ExpressMemoryCache>();

            // Try add a default resx service.
            // if another service has been registered this will be bypassed, and the other service will be in use.
            builder.Services.TryAddSingleton <IXResourceProvider, ResxResourceProvider>();
            builder.Services.TryAddTransient <IXResourceExporter, XmlResourceExporter>();

            builder.Services.AddSingleton <IStringLocalizer, XStringLocalizer <TResource> >();
            builder.Services.AddSingleton <IHtmlLocalizer, XHtmlLocalizer <TResource> >();

            builder.Services.AddTransient(typeof(IStringLocalizer <>), typeof(XStringLocalizer <>));
            builder.Services.AddTransient(typeof(IHtmlLocalizer <>), typeof(XHtmlLocalizer <>));

            builder.Services.AddSingleton <IStringLocalizerFactory, XStringLocalizerFactory <TResource> >();
            builder.Services.AddSingleton <IHtmlLocalizerFactory, XHtmlLocalizerFactory <TResource> >();

            builder.Services.AddSingleton <IXStringLocalizerFactory, XStringLocalizerFactory <TResource> >();
            builder.Services.AddSingleton <IXHtmlLocalizerFactory, XHtmlLocalizerFactory <TResource> >();

            // Add custom providers for overriding default modelbinding and data annotations errors
            builder.Services.AddSingleton <IConfigureOptions <MvcOptions>, ConfigureMvcOptions>();

            // Add data annotations locailzation
            builder.AddDataAnnotationsLocalization(ops =>
            {
                // This will look for localization resource with type of T (shared resource)
                ops.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(TResource));
            });

            return(builder.AddIdentityErrorsLocalization()
                   .WithTranslationService <TTranslator>());
        }
Пример #21
0
        /// <summary>
        /// Registers an IMetadataDetailsProvider that handles validation attributes to Microsoft.AspNetCore.Mvc.MvcOptions.
        /// This also (on an opt-out basis) calls AddViewLocalization() and AddDataAnnotationsLocalization() on the IMvcBuilder.
        /// </summary>
        /// <param name="mvcBuilder">The Microsoft.Extensions.DependencyInjection.IMvcBuilder.</param>
        /// <returns>The Microsoft.Extensions.DependencyInjection.IMvcBuilder so that additional calls can be chained.</returns>
        public static IMvcBuilder AddForEvolveMvcLocalization(this IMvcBuilder mvcBuilder)
        {
            // Add the ValidationMetadataProvider to MVC
            mvcBuilder
            .AddMvcOptions(options =>
            {
                options.ModelMetadataDetailsProviders.Add(ValidationMetadataProvider);
            });

            // Add the default ViewLocalization (opt-out basis)
            if (Options.MvcOptions.EnableViewLocalization)
            {
                mvcBuilder.AddViewLocalization();
            }

            // Add the default DataAnnotationsLocalization (opt-out basis)
            if (Options.MvcOptions.EnableDataAnnotationsLocalization)
            {
                mvcBuilder.AddDataAnnotationsLocalization();
            }

            return(mvcBuilder);
        }
Пример #22
0
        public static IServiceCollection AddConfiguredMvc(this IServiceCollection services)
        {
            var parameterTransformer = new SlugifyParameterTransformer();

            IMvcBuilder mvc = services.AddMvc(options =>
            {
                var convention = new RouteTokenTransformerConvention(parameterTransformer);
                options.Conventions.Add(convention);
            });

            mvc.AddRazorPagesOptions(options =>
            {
                var convention = new PageRouteTransformerConvention(parameterTransformer);
                options.Conventions.Add(convention);
            });

            mvc.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            mvc.AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResources));
            });

            return(services);
        }
Пример #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                _services = services;

                _services.AddScoped <IEmailSender, AuthMessageSender>();
                _services.AddScoped <ISmsSender, AuthMessageSender>();
                _services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
                _services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

                _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

                _services.AddLogging(loggingBuilder =>
                                     loggingBuilder.AddSerilog(dispose: true));

                _services.AddOptions();
                _services.AddSingleton(typeof(IStringLocalizer), typeof(NccStringLocalizer <SharedResource>));
                _services.AddLocalization();

                _mvcBuilder = _services.AddMvc(config =>
                {
                    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                    config.CacheProfiles.Add(NccCacheProfile.Default,
                                             new CacheProfile()
                    {
                        VaryByHeader    = "User-Agent",
                        Duration        = 300,
                        VaryByQueryKeys = new string[] { "id", "name", "pageNumber", "page", "pageSize", "model", "lang", "status", "sessionId", "requestId", "start", "slug", }
                    });
                });

                _mvcBuilder.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
                _mvcBuilder.AddDataAnnotationsLocalization(options =>
                {
                    options.DataAnnotationLocalizerProvider = (type, factory) => new NccStringLocalizer <SharedResource>(factory, new HttpContextAccessor());
                });

                _services.AddMaintenance(() => _setupConfig.IsMaintenanceMode, Encoding.UTF8.GetBytes("<div style='width:100%;text-align:center; padding-top:10px;'><h1>" + _setupConfig.MaintenanceMessage + "</h1></div>"), "text/html", _setupConfig.MaintenanceDownTime * 60);

                _services.AddSession(options =>
                {
                    options.Cookie.Name     = ".DamaCoreCMS.Cookie.Session";
                    options.IdleTimeout     = TimeSpan.FromMinutes(20);
                    options.Cookie.HttpOnly = true;
                });

                _services.AddResponseCacheingAndCompression(_serviceProvider);

                _services.AddSingleton(Configuration);

                _services.AddNccCoreModuleServices();
                _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

                _services.SetGlobalCache(_serviceProvider);

                var themeFolder             = Path.Combine(_hostingEnvironment.ContentRootPath, NccInfo.ThemeFolder);
                var moduleFolder            = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.ModuleFolder);
                var coreModuleFolder        = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.CoreModuleFolder);
                var themesDirectoryContents = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.ThemeFolder);

                _themeManager.ScanThemeDirectory(themeFolder);
                _themeManager.RegisterThemes(_mvcBuilder, _services, _serviceProvider, themesDirectoryContents);

                var loggerFactory = _serviceProvider.GetService <ILoggerFactory>();
                var logger        = loggerFactory.CreateLogger <Startup>();

                _moduleManager.LoadModules(coreModuleFolder, logger);
                _moduleManager.LoadModules(moduleFolder, logger);

                _services.AddModuleDependencies(_mvcBuilder);

                if (SetupHelper.IsDbCreateComplete)
                {
                    _startup.SelectDatabase(_services);
                    _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);
                    _moduleManager.AddModulesAsApplicationPart(_mvcBuilder, _services, _serviceProvider, logger);

                    _moduleManager.AddModuleServices(_services, logger);
                    _moduleManager.AddModuleFilters(_services, logger);
                    _moduleManager.AddShortcodes(_services, logger);
                    _moduleManager.AddModuleWidgets(_services, logger);
                    _moduleManager.AddModuleAuthorizationHandlers(_services, logger);

                    _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

                    _services.AddCustomizedIdentity(_serviceProvider.GetService <INccSettingsService>());
                    _moduleManager.LoadModuleMenus(logger);
                }

                var defaultCulture = new RequestCulture("en");

                if (SetupHelper.IsAdminCreateComplete)
                {
                    GlobalContext.SetupConfig = SetupHelper.LoadSetup();
                    defaultCulture            = new RequestCulture(GlobalContext.SetupConfig.Language);
                }

                _services.Configure <RouteOptions>(options =>
                {
                    options.ConstraintMap.Add("lang", typeof(LanguageRouteConstraint));
                });

                _services.Configure <RequestLocalizationOptions>(
                    opts =>
                {
                    var supportedCultures      = SupportedCultures.Cultures;
                    opts.DefaultRequestCulture = defaultCulture;
                    opts.SupportedCultures     = supportedCultures;
                    opts.SupportedUICultures   = supportedCultures;

                    var provider = new RouteDataRequestCultureProvider();
                    provider.RouteDataStringKey   = "lang";
                    provider.UIRouteDataStringKey = "lang";
                    provider.Options             = opts;
                    opts.RequestCultureProviders = new[] { provider };
                }
                    );

                _services.Configure <ClassLibraryLocalizationOptions>(
                    options => options.ResourcePaths = new Dictionary <string, string>
                {
                    { "DamaCoreCMS.Framework", "i18n/Resources" },
                    { "DamaCoreCMS.Web", "Resources" }
                }
                    );

                _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);
                _serviceProvider = _services.BuildModules(ConfigurationRoot, _hostingEnvironment);

                if (SetupHelper.IsDbCreateComplete)
                {
                    _themeManager.RegisterThemeWidgets(_mvcBuilder, _services, _serviceProvider, themesDirectoryContents);
                    _moduleManager.RegisterModuleWidgets(_mvcBuilder, _services, _serviceProvider, logger);
                    _moduleManager.RegisterModuleFilters(_mvcBuilder, _serviceProvider, logger);
                    _moduleManager.RegisterModuleShortCodes(_mvcBuilder, _serviceProvider);
                }

                GlobalContext.ServiceProvider   = _serviceProvider;
                GlobalContext.Services          = _services;
                DamaCoreCMSHost.Mediator        = _serviceProvider.GetService <IMediator>();
                DamaCoreCMSHost.Services        = _services;
                DamaCoreCMSHost.ServiceProvider = _serviceProvider;
                GlobalMessageRegistry.LoadMessagesFromStorage();
            }
            catch (Exception ex)
            {
                _exceptions[ExceptionsOnConfigureServices].Add(ex);
            }
        }
Пример #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            _services = services;

            _services.AddLogging(loggingBuilder =>
                                 loggingBuilder.AddSerilog(dispose: true));

            _services.AddOptions();
            //services.AddSingleton(typeof(IStringLocalizerFactory), typeof(ClassLibraryStringLocalizerFactory));
            services.AddSingleton(typeof(IStringLocalizer), typeof(NccStringLocalizer <SharedResource>));

            _services.AddLocalization();

            _mvcBuilder = services.AddMvc();
            _mvcBuilder.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            _mvcBuilder.AddDataAnnotationsLocalization(options => {
                options.DataAnnotationLocalizerProvider = (type, factory) => new NccStringLocalizer <SharedResource>(factory, new HttpContextAccessor());
            });

            _services.AddResponseCaching();
            _services.AddSession();
            _services.AddDistributedMemoryCache();
            _services.AddResponseCompression();
            _services.AddSingleton(Configuration);

            _services.AddNccCoreModuleRepositoryAndServices();

            _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

            _themeManager = new ThemeManager();
            var themeFolder = Path.Combine(_hostingEnvironment.ContentRootPath, NccInfo.ThemeFolder);

            GlobalConfig.Themes = _themeManager.ScanThemeDirectory(themeFolder);

            var themesDirectoryContents = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.ThemeFolder);

            _themeManager.RegisterThemes(_mvcBuilder, _services, _serviceProvider, themesDirectoryContents);

            var moduleFolder     = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.ModuleFolder);
            var coreModuleFolder = _hostingEnvironment.ContentRootFileProvider.GetDirectoryContents(NccInfo.CoreModuleFolder);
            var coreModules      = _moduleManager.LoadModules(coreModuleFolder);
            var userModules      = _moduleManager.LoadModules(moduleFolder);

            GlobalConfig.Modules.AddRange(userModules);


            _services.AddMaintenance(() => _setupConfig.IsMaintenanceMode, Encoding.UTF8.GetBytes("<div style='width:100%;text-align:center; padding-top:10px;'><h1>" + _setupConfig.MaintenanceMessage + "</h1></div>"), "text/html", _setupConfig.MaintenanceDownTime * 60);

            if (SetupHelper.IsDbCreateComplete)
            {
                if (SetupHelper.SelectedDatabase == "SqLite")
                {
                    _services.AddDbContext <NccDbContext>(options =>
                                                          options.UseSqlite(SetupHelper.ConnectionString, opt => opt.MigrationsAssembly("NetCoreCMS.Framework"))
                                                          );
                }
                else if (SetupHelper.SelectedDatabase == "MSSQL")
                {
                    _services.AddDbContext <NccDbContext>(options =>
                                                          options.UseSqlServer(SetupHelper.ConnectionString, opt => opt.MigrationsAssembly("NetCoreCMS.Framework"))
                                                          );
                }
                else if (SetupHelper.SelectedDatabase == "MySql")
                {
                    _services.AddDbContext <NccDbContext>(options =>
                                                          options.UseMySql(SetupHelper.ConnectionString, opt => opt.MigrationsAssembly("NetCoreCMS.Framework"))
                                                          );
                }

                _services.AddCustomizedIdentity();
                _startup.RegisterDatabase(_services);

                _services.AddAuthorization(options =>
                {
                    options.AddPolicy("SuperAdmin", policy => policy.Requirements.Add(new AuthRequire("SuperAdmin", "")));
                    options.AddPolicy("Administrator", policy => policy.Requirements.Add(new AuthRequire("Administrator", "")));
                    options.AddPolicy("Editor", policy => policy.Requirements.Add(new AuthRequire("Editor", "")));
                    options.AddPolicy("Author", policy => policy.Requirements.Add(new AuthRequire("Author", "")));
                    options.AddPolicy("Contributor", policy => policy.Requirements.Add(new AuthRequire("Contributor", "")));
                    options.AddPolicy("Subscriber", policy => policy.Requirements.Add(new AuthRequire("Subscriber", "")));
                });

                _services.AddSingleton <IAuthorizationHandler, AuthRequireHandler>();
                _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

                GlobalConfig.Modules = _moduleManager.RegisterModules(_mvcBuilder, _services, _serviceProvider);
                _moduleManager.RegisterModuleRepositoryAndServices(_mvcBuilder, _services, _serviceProvider);

                _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

                GlobalConfig.Widgets = _moduleManager.RegisterModuleWidgets(_mvcBuilder, _services, _serviceProvider);
                var themeWidgets = _themeManager.RegisterThemeWidgets(_mvcBuilder, _services, _serviceProvider, themesDirectoryContents);

                if (themeWidgets != null && themeWidgets.Count > 0)
                {
                    GlobalConfig.Widgets.AddRange(themeWidgets);
                }

                _nccShortCodeProvider   = _serviceProvider.GetService <NccShortCodeProvider>();
                GlobalConfig.ShortCodes = _nccShortCodeProvider.ScanAndRegisterShortCodes(GlobalConfig.Modules);
            }

            var defaultCulture = new RequestCulture("en");

            if (SetupHelper.IsAdminCreateComplete)
            {
                GlobalConfig.SetupConfig = SetupHelper.LoadSetup();
                defaultCulture           = new RequestCulture(GlobalConfig.SetupConfig.Language);
            }

            services.Configure <RouteOptions>(options =>
            {
                options.ConstraintMap.Add("lang", typeof(LanguageRouteConstraint));
            });

            _services.Configure <RequestLocalizationOptions>(
                opts =>
            {
                var supportedCultures      = SupportedCultures.Cultures;
                opts.DefaultRequestCulture = defaultCulture;
                opts.SupportedCultures     = supportedCultures;
                opts.SupportedUICultures   = supportedCultures;

                var provider = new RouteDataRequestCultureProvider();
                provider.RouteDataStringKey   = "lang";
                provider.UIRouteDataStringKey = "lang";
                provider.Options = opts; opts.RequestCultureProviders = new[] { provider };
            }
                );

            services.Configure <ClassLibraryLocalizationOptions>(
                options => options.ResourcePaths = new Dictionary <string, string>
            {
                { "NetCoreCMS.Framework", "i18n/Resources" },
                { "NetCoreCMS.Web", "Resources" }
            }
                );

            _serviceProvider = _services.Build(ConfigurationRoot, _hostingEnvironment);

            GlobalConfig.ServiceProvider = _serviceProvider;
            GlobalConfig.Services        = _services;
        }