// This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages()
            .AddDataAnnotationsLocalization()
            .AddViewLocalization();
            services.AddServerSideBlazor();
            services.AddScoped <WeatherForecastService>();

            var jsonLocalizationOptions = Configuration.GetSection(nameof(JsonLocalizationOptions));

            _jsonLocalizationOptions = jsonLocalizationOptions.Get <JsonLocalizationOptions>();
            _defaultRequestCulture   = new RequestCulture(_jsonLocalizationOptions.DefaultCulture,
                                                          _jsonLocalizationOptions.DefaultUICulture);
            _supportedCultures = _jsonLocalizationOptions.SupportedCultureInfos.ToList();

            services.AddJsonLocalization(options =>
            {
                options.ResourcesPath         = _jsonLocalizationOptions.ResourcesPath;
                options.UseBaseName           = _jsonLocalizationOptions.UseBaseName;
                options.CacheDuration         = _jsonLocalizationOptions.CacheDuration;
                options.SupportedCultureInfos = _jsonLocalizationOptions.SupportedCultureInfos;
                options.FileEncoding          = _jsonLocalizationOptions.FileEncoding;
                options.IsAbsolutePath        = _jsonLocalizationOptions.IsAbsolutePath;
                options.LocalizationMode      = LocalizationMode.I18n;
            });

            services.Configure <RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = _defaultRequestCulture;
                // Formatting numbers, dates, etc.
                options.SupportedCultures = _supportedCultures;
                // UI strings that we have localized.
                options.SupportedUICultures = _supportedCultures;
            });
        }
        public ConcurrentDictionary <string, LocalizatedFormat> ConstructLocalization(
            IEnumerable <string> myFiles, CultureInfo currentCulture, JsonLocalizationOptions options)
        {
            _options = options;

            foreach (string file in myFiles)
            {
                ConcurrentDictionary <string, JsonLocalizationFormat> tempLocalization =
                    LocalisationModeHelpers.ReadAndDeserializeFile <string, JsonLocalizationFormat>(file,
                                                                                                    options.FileEncoding);

                if (tempLocalization == null)
                {
                    continue;
                }

                foreach (KeyValuePair <string, JsonLocalizationFormat> temp in tempLocalization)
                {
                    LocalizatedFormat localizedValue = GetLocalizedValue(currentCulture, temp);
                    AddOrUpdateLocalizedValue <JsonLocalizationFormat>(localizedValue, temp);
                }
            }

            return(localization);
        }
        public ConcurrentDictionary <string, LocalizatedFormat> ConstructLocalization(IEnumerable <string> myFiles,
                                                                                      CultureInfo currentCulture,
                                                                                      JsonLocalizationOptions options)
        {
            _options = options;

            var enumerable  = myFiles as string[] ?? myFiles.ToArray();
            var neutralFile = enumerable.FirstOrDefault(file => Path.GetFileName(file)
                                                        .Count(s => s.CompareTo('.') == 0) == 1);
            var isInvariantCulture =
                currentCulture.DisplayName == CultureInfo.InvariantCulture.ThreeLetterISOLanguageName;

            var files = isInvariantCulture
                ? new string[] { }
                : enumerable.Where(file => Path.GetFileName(file).Split('.').Any(
                                       s => (s.IndexOf(currentCulture.Name, StringComparison.OrdinalIgnoreCase) >= 0 ||
                                             s.IndexOf(currentCulture.Parent.Name, StringComparison.OrdinalIgnoreCase) >= 0)
                                       )).ToArray();


            if (files.Any() && !isInvariantCulture)
            {
                foreach (var file in files)
                {
                    var fileName    = Path.GetFileName(file);
                    var fileCulture = new CultureInfo(fileName.Split('.')[^ 2] ?? String.Empty);
예제 #4
0
    public void GetJsonStringConfig_Culture()
    {
        // 获得 it-it 文化信息
        // 回落默认语音为 en 测试用例为 zh 找不到资源文件
        var option  = new JsonLocalizationOptions();
        var configs = option.GetJsonStringFromAssembly(this.GetType().Assembly, "en-US");

        Assert.NotEmpty(configs);
    }
예제 #5
0
 public JsonStringLocalizer(string resourceBaseName,
                            IHostingEnvironment env,
                            JsonGlobalResources globalResources,
                            RequestCulture defaultCulture,
                            IActionContextAccessor actionContextAccessor,
                            JsonLocalizationOptions options,
                            ILoggerFactory loggerFactory) : base(resourceBaseName, env, globalResources, defaultCulture, actionContextAccessor, options, loggerFactory)
 {
 }
예제 #6
0
        /// <summary>
        /// Adds localization (similar to .AddLocalization()) based on .json files.
        /// Use configuration to define a folder for the .json files if needed.
        /// The localizer will look for files specified by 'baseName' and 'location' parameters of the
        /// IStringLocalizerFactory.Create method.
        /// </summary>
        /// <param name="services">The service collection to extend.</param>
        /// <param name="configure">Localization configuration.</param>
        /// <returns></returns>
        public static IServiceCollection AddJsonLocalization(this IServiceCollection services, Action <JsonLocalizationOptions> configure = null)
        {
            JsonLocalizationOptions options = new JsonLocalizationOptions();

            services.TryAddSingleton <IFileSystem, FileSystem>();
            services.AddSingleton <IStringLocalizerFactory>(s => new JsonStringLocalizerFactory(s.GetRequiredService <IFileSystem>(), options));

            return(services);
        }
예제 #7
0
    public void GetJsonStringConfig_Ok()
    {
        var option = new JsonLocalizationOptions
        {
            AdditionalJsonFiles = new string[]
            {
                "zh-CN.json"
            }
        };
        var configs = option.GetJsonStringFromAssembly(this.GetType().Assembly);
        var section = configs.FirstOrDefault(i => i.Key == "BootstrapBlazor.Shared.Foo");
        var v       = section.GetValue("Name", "");

        Assert.NotEmpty(v);
    }
예제 #8
0
        public void Translate(string expected, string json, string key, string fallback, string[] args)
        {
            var options = new JsonLocalizationOptions
            {
                ResourceFolders = new[] { "test" },
                DefaultLocale   = "en-CA"
            };

            DefaultDictionaryBuilder.ReadAllText       = path => json;
            DefaultDictionaryBuilder.DirectoryGetFiles = (path, searchPattern, searchOption) => new[] { "en-ca.json" };

            I18N.BuildDictionary(new DefaultDictionaryBuilder(), options);

            var sut = new I18N(new OptionsWrapper <JsonLocalizationOptions>(options), new DefaultKeyProvider());

            Assert.Equal(expected, sut.Translate(key, fallback, args));
        }
예제 #9
0
        private void AddValueToLocalization(JsonLocalizationOptions options, string file, bool isParent)
        {
            ConcurrentDictionary <string, string> tempLocalization =
                LocalisationModeHelpers.ReadAndDeserializeFile <string, string>(file, options.FileEncoding);

            if (tempLocalization == null)
            {
                return;
            }

            foreach (var temp in tempLocalization)
            {
                LocalizatedFormat localizedValue = GetLocalizedValue(temp, isParent);

                AddOrUpdateLocalizedValue(localizedValue, temp);
            }
        }
    /// <summary>
    /// 构造方法
    /// </summary>
    /// <param name="client"></param>
    /// <param name="cacheManager"></param>
    /// <param name="options"></param>
    /// <param name="localizerOptions"></param>
    public CodeSnippetService(
        HttpClient client,
        ICacheManager cacheManager,
        IOptionsMonitor <WebsiteOptions> options,
        IOptionsMonitor <JsonLocalizationOptions> localizerOptions)
    {
        LocalizerOptions = localizerOptions.CurrentValue;

        CacheManager       = cacheManager;
        Client             = client;
        Client.Timeout     = TimeSpan.FromSeconds(5);
        Client.BaseAddress = new Uri(options.CurrentValue.RepositoryUrl);

        IsDevelopment   = options.CurrentValue.IsDevelopment;
        ContentRootPath = options.CurrentValue.ContentRootPath;
        ServerUrl       = options.CurrentValue.ServerUrl;
    }
        /// <summary>
        /// Setup the factory.
        /// </summary>
        /// <param name="options">The JsonLocalization options.</param>
        /// <param name="cultureInfoService">Service providing the current culture.</param>
        /// <param name="extensionResolverService">The service resolver to get the JsonLocalization
        /// extension service.</param>
        /// <param name="cacheService">The service to cache the loaded data.</param>
        /// <param name="logger">Logger where to log processing messages.</param>
        public JsonStringLocalizerFactory(
            IOptions <JsonLocalizationOptions> options,
            ICultureInfoService cultureInfoService,
            IExtensionResolverService extensionResolverService,
            ICacheService cacheService,
            ILogger <JsonStringLocalizerFactory> logger)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            this.logger  = logger;
            this.options = options.Value;
            this.extensionResolverService = extensionResolverService;
            this.cultureInfoService       = cultureInfoService;
            this.cacheService             = cacheService;
        }
예제 #12
0
        public ConcurrentDictionary <string, LocalizatedFormat> ConstructLocalization(IEnumerable <string> myFiles,
                                                                                      CultureInfo currentCulture,
                                                                                      JsonLocalizationOptions options)
        {
            _options = options;

            var neutralFile = myFiles.FirstOrDefault(file => file.Split(Path.AltDirectorySeparatorChar)
                                                     .Last().Count(s => s.CompareTo('.') == 0) == 1);

            var isInvariantCulture =
                currentCulture.DisplayName == CultureInfo.InvariantCulture.ThreeLetterISOLanguageName;

            var files = isInvariantCulture ? new string[] {} : myFiles.Where(file => file.Split(Path.AltDirectorySeparatorChar).Any(
                                                                                 s => (s.IndexOf(currentCulture.Name, StringComparison.OrdinalIgnoreCase) >= 0 ||
                                                                                       s.IndexOf(currentCulture.Parent.Name, StringComparison.OrdinalIgnoreCase) >= 0)
                                                                                 )).ToArray();


            if (files.Any() && !isInvariantCulture)
            {
                foreach (var file in files)
                {
                    var splittedFiles = file.Split(Path.AltDirectorySeparatorChar);
                    var stringCulture = splittedFiles.Last().Split('.')[1];
                    var fileCulture   = new CultureInfo(stringCulture);

                    var isParent =
                        fileCulture.Name.Equals(currentCulture.Parent.Name, StringComparison.OrdinalIgnoreCase);

                    if (fileCulture.Name.Equals(currentCulture.Name, StringComparison.OrdinalIgnoreCase) ||
                        isParent && fileCulture.Name != "json")
                    {
                        AddValueToLocalization(options, file, isParent);
                    }
                }
            }
            else
            {
                AddValueToLocalization(options, neutralFile, true);
            }

            return(localization);
        }
    /// <summary>
    /// 通过系统 JsonLocalizationOptions 获取当前 Json 格式资源配置集合
    /// </summary>
    /// <param name="option"></param>
    /// <param name="assembly"></param>
    /// <param name="cultureName"></param>
    /// <returns></returns>
    public static IEnumerable <IConfigurationSection> GetJsonStringFromAssembly(this JsonLocalizationOptions option, Assembly assembly, string?cultureName = null)
    {
        cultureName ??= CultureInfo.CurrentUICulture.Name;
        var langHandler = GetLangHandlers(cultureName);

        var builder = new ConfigurationBuilder();

        foreach (var h in langHandler)
        {
            builder.AddJsonStream(h);
        }

        // 获得配置外置资源文件
        if (option.AdditionalJsonFiles != null)
        {
            var file = option.AdditionalJsonFiles.FirstOrDefault(f =>
            {
                var fileName = Path.GetFileNameWithoutExtension(f);
                return(fileName.Equals(cultureName, StringComparison.OrdinalIgnoreCase));
            });
            if (!string.IsNullOrEmpty(file))
            {
                builder.AddJsonFile(file, true, true);
            }
        }

        var config = builder.Build();

        // dispose json stream
        foreach (var h in langHandler)
        {
            h.Dispose();
        }
        return(config.GetChildren());

        List <Stream> GetLangHandlers(string cultureName)
        {
            // 获取程序集中的资源文件
            var langHandler = GetResourceStream(assembly, cultureName);

            AddResourceStream();
            return(langHandler);
예제 #14
0
        public JsonStringLocalizerFactory(
            IHostingEnvironment hostingEnvironment,
            IOptions <JsonLocalizationOptions> options,
            IOptions <RequestLocalizationOptions> requestLocalizationOptions,
            IActionContextAccessor actionContextAccessor,
            ILoggerFactory loggerFactory)
        {
            _options               = options.Value;
            _env                   = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
            _defaultCulture        = requestLocalizationOptions.Value.DefaultRequestCulture;
            _actionContextAccessor = actionContextAccessor ?? throw new ArgumentNullException(nameof(actionContextAccessor));
            _loggerFactory         = loggerFactory;

            _resourcesRelativePath = _options.ResourcesPath ?? string.Empty;
            if (!string.IsNullOrEmpty(_resourcesRelativePath))
            {
                _resourcesRelativePath = _resourcesRelativePath.Replace(Path.AltDirectorySeparatorChar, '.').Replace(Path.DirectorySeparatorChar, '.');
            }

            _globalResources = new JsonGlobalResources(hostingEnvironment, options, _defaultCulture, _loggerFactory);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            _ = services.AddControllersWithViews()
                .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0)
                .AddDataAnnotationsLocalization()
                .AddViewLocalization();
            _ = services.AddRazorPages()
                .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0)
                .AddDataAnnotationsLocalization()
                .AddViewLocalization();

            // Get json localization options from appsettings
            var jsonLocalizationOptions = Configuration.GetSection(nameof(JsonLocalizationOptions));

            _jsonLocalizationOptions = jsonLocalizationOptions.Get <JsonLocalizationOptions>();
            _defaultRequestCulture   = new RequestCulture(_jsonLocalizationOptions.DefaultCulture,
                                                          _jsonLocalizationOptions.DefaultUICulture);
            _supportedCultures = _jsonLocalizationOptions.SupportedCultureInfos.ToList();

            _ = services.AddJsonLocalization(options =>
            {
                options.ResourcesPath         = _jsonLocalizationOptions.ResourcesPath;
                options.UseBaseName           = _jsonLocalizationOptions.UseBaseName;
                options.CacheDuration         = _jsonLocalizationOptions.CacheDuration;
                options.SupportedCultureInfos = _jsonLocalizationOptions.SupportedCultureInfos;
                options.FileEncoding          = _jsonLocalizationOptions.FileEncoding;
                options.IsAbsolutePath        = _jsonLocalizationOptions.IsAbsolutePath;
                options.DefaultCulture        = _defaultRequestCulture.Culture;
                options.DefaultUICulture      = _defaultRequestCulture.UICulture;
            });

            _ = services.Configure <RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = _defaultRequestCulture;
                // Formatting numbers, dates, etc.
                options.SupportedCultures = _supportedCultures;
                // UI strings that we have localized.
                options.SupportedUICultures = _supportedCultures;
            });
        }
        public JsonGlobalResources(IHostingEnvironment hostingEnvironment,
                                   IOptions <JsonLocalizationOptions> options,
                                   RequestCulture defaultCulture,
                                   ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _options       = options.Value;
            _app           = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
            GlobalName     = _options.GlobalResourceFileName ?? "global";
            AreaName       = _options.AreasResourcePrefix ?? "areas";
            DefaultCulture = defaultCulture ?? throw new ArgumentNullException(nameof(defaultCulture));
            _logger        = loggerFactory.CreateLogger <JsonGlobalResources>();

            ResourceRelativePath = _options.ResourcesPath ?? string.Empty;
            if (!string.IsNullOrEmpty(ResourceRelativePath))
            {
                ResourceRelativePath = ResourceRelativePath.Replace(Path.AltDirectorySeparatorChar, '.').Replace(Path.DirectorySeparatorChar, '.');
            }
        }
예제 #17
0
        public ConcurrentDictionary <string, LocalizatedFormat> ConstructLocalization(IEnumerable <string> myFiles,
                                                                                      CultureInfo currentCulture,
                                                                                      JsonLocalizationOptions options)
        {
            _options = options;

            var neutralFile = myFiles.FirstOrDefault(file => file.Split(Path.AltDirectorySeparatorChar)
                                                     .Last().Count(s => s.CompareTo('.') == 0) == 1);

            var isInvariantCulture =
                currentCulture.DisplayName == CultureInfo.InvariantCulture.ThreeLetterISOLanguageName;

            var files = isInvariantCulture ? new string[] {} : myFiles.Where(file => file.Split(Path.AltDirectorySeparatorChar).Any(
                                                                                 s => (s.Contains(currentCulture.Name, StringComparison.OrdinalIgnoreCase) ||
                                                                                       s.Contains(currentCulture.Parent.Name, StringComparison.OrdinalIgnoreCase))
                                                                                 )).ToArray();

            if (files.Any() && !isInvariantCulture)
            {
                foreach (var file in files)
                {
                    var splittedFiles = file.Split(Path.AltDirectorySeparatorChar);
                    var fileCulture   = new CultureInfo(splittedFiles[^ 1].Split(".")[1]);
        public void AddJsonLocalizationWithOptions()
        {
            // Arrange
            var services            = new ServiceCollection();
            var localizationOptions = new JsonLocalizationOptions();

            // Act
            JsonLocalizationServiceCollectionExtensions.AddJsonLocalization(services,
                                                                            options => options.ResourcesPath = "Resources");

            var localizationConfigureOptions = (ConfigureNamedOptions <JsonLocalizationOptions>)services
                                               .SingleOrDefault(sd => sd.ServiceType == typeof(IConfigureOptions <JsonLocalizationOptions>))
                                               ?.ImplementationInstance;

            // Assert
            Assert.Equal(1, services.Count(typeof(IStringLocalizerFactory), typeof(JsonStringLocalizerFactory)));
            Assert.Equal(1, services.Count(typeof(IStringLocalizer <>), typeof(StringLocalizer <>)));
            Assert.NotNull(localizationConfigureOptions);

            localizationConfigureOptions.Action.Invoke(localizationOptions);

            Assert.Equal("Resources", localizationOptions.ResourcesPath);
        }
예제 #19
0
        public JsonStringLocalizer(
            string resourceBaseName,
            IHostingEnvironment env,
            JsonGlobalResources globalResources,
            RequestCulture defaultCulture,
            IActionContextAccessor actionContextAccessor,
            JsonLocalizationOptions options,
            ILoggerFactory loggerFactory)
        {
            _options               = options ?? throw new ArgumentNullException(nameof(options));
            _env                   = env ?? throw new ArgumentNullException(nameof(env));
            GlobalResources        = globalResources ?? throw new ArgumentNullException(nameof(globalResources));
            DefaultCulture         = defaultCulture ?? throw new ArgumentNullException(nameof(defaultCulture));
            _actionContextAccessor = actionContextAccessor ?? throw new ArgumentNullException(nameof(actionContextAccessor));
            _logger                = loggerFactory.CreateLogger <JsonStringLocalizer <T> >();

            _resourcesRelativePath = _options.ResourcesPath ?? string.Empty;
            if (!string.IsNullOrEmpty(_resourcesRelativePath))
            {
                _resourcesRelativePath = _resourcesRelativePath.Replace(Path.AltDirectorySeparatorChar, '.').Replace(Path.DirectorySeparatorChar, '.');
            }

            ResourceFileLocations = LocalizerUtil.ExpandPaths(resourceBaseName).ToList();
        }
 public static JsonStringLocalizer Create(JsonLocalizationOptions options, string baseName = null)
 {
     return(new JsonStringLocalizer(Options.Create(options), new HostingEnvironmentStub(), baseName));
 }