public string[] GetGlobalFileLocations(CultureInfo culture)
        {
            var cultureSuffix = "." + culture.Name;

            cultureSuffix = cultureSuffix == "." ? string.Empty : cultureSuffix;

            if (LocalizerUtil.IsChildCulture(DefaultCulture.UICulture, culture) || LocalizerUtil.IsChildCulture(culture, DefaultCulture.UICulture))
            {
                cultureSuffix = string.Empty;
            }

            var cacheName = "global";

            cacheName += string.IsNullOrEmpty(cultureSuffix) ? ".default" : cultureSuffix;

            string root = _app.ContentRootPath;

            if (!string.IsNullOrEmpty(ResourceRelativePath))
            {
                root = Path.Combine(root, ResourceRelativePath.Trim('/', '\\'));
            }

            var resourceBaseName      = GlobalName;
            var resourceFileLocations = LocalizerUtil.ExpandPaths(resourceBaseName, _app.ApplicationName).ToList();

            return(resourceFileLocations.Select(resourceFileLocation => resourceFileLocation + cultureSuffix + ".json")
                   .Select(resourcePath => Path.Combine(root, resourcePath))
                   .ToArray());
        }
Esempio n. 2
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 string[] GetAreaFileLocations(CultureInfo culture, string areaName)
        {
            if (string.IsNullOrEmpty(areaName?.Trim()))
            {
                throw new ArgumentNullException(nameof(areaName));
            }

            var cultureSuffix = "." + culture.Name;

            cultureSuffix = cultureSuffix == "." ? string.Empty : cultureSuffix;

            if (LocalizerUtil.IsChildCulture(DefaultCulture.UICulture, culture) || LocalizerUtil.IsChildCulture(culture, DefaultCulture.UICulture))
            {
                cultureSuffix = string.Empty;
            }

            var areaSuffix = $".{areaName}";

            var cacheName = $"{AreaName}{areaSuffix}";

            cacheName += string.IsNullOrEmpty(cultureSuffix) ? ".default" : cultureSuffix;

            string root = _app.ContentRootPath;

            if (!string.IsNullOrEmpty(ResourceRelativePath))
            {
                root = Path.Combine(root, ResourceRelativePath.Trim('/', '\\'));
            }

            var resourceBaseName      = AreaName;
            var resourceFileLocations = LocalizerUtil.ExpandPaths(resourceBaseName, _app.ApplicationName).ToList();

            return(resourceFileLocations.Select(resourceFileLocation => resourceFileLocation + areaSuffix + cultureSuffix + ".json")
                   .Select(resourcePath => Path.Combine(root, resourcePath))
                   .ToArray());
        }
Esempio n. 4
0
        private JsonDocument GetResourceObject(CultureInfo currentCulture)
        {
            if (currentCulture == null)
            {
                throw new ArgumentNullException(nameof(currentCulture));
            }

            var cultureSuffix = "." + currentCulture.Name;

            cultureSuffix = cultureSuffix == "." ? string.Empty : cultureSuffix;

            if (LocalizerUtil.IsChildCulture(DefaultCulture.UICulture, currentCulture) || LocalizerUtil.IsChildCulture(currentCulture, DefaultCulture.UICulture))
            {
                cultureSuffix = string.Empty;
            }

            var cacheKey = string.IsNullOrEmpty(cultureSuffix) ? "default" : cultureSuffix;

            var lazyJsonDocumentGetter = new Lazy <JsonDocument>(
                () =>
            {
                _logger.LogDebug_Localizer($"Resource file content not found in cache ({cacheKey}), try to load from file.");

                string root = _env.ContentRootPath;

                if (!string.IsNullOrEmpty(_resourcesRelativePath))
                {
                    root = Path.Combine(root, _resourcesRelativePath.Trim('/', '\\'));
                }

                _logger.LogDebug_Localizer($"Looking for resource files in {root}");

                // First attempt to find a resource file location that exists.
                string resourcePath = null;
                foreach (var resourceFileLocation in ResourceFileLocations)
                {
                    resourcePath = resourceFileLocation + cultureSuffix + ".json";
                    resourcePath = Path.Combine(root, resourcePath);

                    if (File.Exists(resourcePath))
                    {
                        _logger.LogDebug_Localizer($"Resource file found: {resourcePath}");
                        break;
                    }
                    else
                    {
                        _logger.LogDebug_Localizer($"Resource file not found: {resourcePath}");
                        resourcePath = null;
                    }
                }

                if (resourcePath == null)
                {
                    _logger.LogWarning_Localizer($"There is no resource file found for {cacheKey}");
                    return(null);
                }

                // Found a resource file path: attempt to parse it into a JsonDocument.
                try
                {
                    var resourceFileStream = new FileStream(resourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan);
                    using (resourceFileStream)
                    {
                        var content = JsonDocument.Parse(resourceFileStream);

                        _logger.LogInformation_Localizer($"Resource file content loaded: {resourcePath}");

                        return(content);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError_Localizer(ex, $"Error while loading resource file: {ex.Message} ({resourcePath})");
                    return(null);
                }
            }, LazyThreadSafetyMode.ExecutionAndPublication);

            _logger.LogInformation_Localizer($"Trying to load resource file content from cache {cacheKey}.");

            lazyJsonDocumentGetter = _resourceObjectCache.GetOrAdd(cacheKey, lazyJsonDocumentGetter);
            var resourceObject = lazyJsonDocumentGetter.Value;

            return(resourceObject);
        }
        public JsonDocument GetAreaResources(CultureInfo culture, string areaName)
        {
            if (string.IsNullOrEmpty(areaName?.Trim()))
            {
                throw new ArgumentNullException(nameof(areaName));
            }

            var cultureSuffix = "." + culture.Name;

            cultureSuffix = cultureSuffix == "." ? string.Empty : cultureSuffix;

            if (LocalizerUtil.IsChildCulture(DefaultCulture.UICulture, culture) || LocalizerUtil.IsChildCulture(culture, DefaultCulture.UICulture))
            {
                cultureSuffix = string.Empty;
            }

            var areaSuffix = $".{areaName}";

            var cacheName = $"{AreaName}{areaSuffix}";

            cacheName += string.IsNullOrEmpty(cultureSuffix) ? ".default" : cultureSuffix;

            var lazyJObjectGetter = new Lazy <JsonDocument>(
                () =>
            {
                _logger.LogDebug_Localizer($"Resource file content not found in cache ({cacheName}), try to load from file.");

                string root = _app.ContentRootPath;

                if (!string.IsNullOrEmpty(ResourceRelativePath))
                {
                    root = Path.Combine(root, ResourceRelativePath.Trim('/', '\\'));
                }

                _logger.LogDebug_Localizer($"Looking for resource files in {root}");

                var resourceBaseName      = AreaName;
                var resourceFileLocations = LocalizerUtil.ExpandPaths(resourceBaseName, _app.ApplicationName).ToList();

                string resourcePath = null;
                foreach (var resourceFileLocation in resourceFileLocations)
                {
                    resourcePath = resourceFileLocation + areaSuffix + cultureSuffix + ".json";
                    resourcePath = Path.Combine(root, resourcePath);

                    if (File.Exists(resourcePath))
                    {
                        _logger.LogDebug_Localizer($"Resource file found: {resourcePath}");
                        break;
                    }
                    else
                    {
                        _logger.LogDebug_Localizer($"Resource file not found: {resourcePath}");
                        resourcePath = null;
                    }
                }

                if (resourcePath == null)
                {
                    _logger.LogWarning_Localizer($"There is no resource file found for {resourceBaseName}");
                    return(null);
                }

                try
                {
                    var resourceFileStream = new FileStream(resourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan);
                    using (resourceFileStream)
                    {
                        var content = JsonDocument.Parse(resourceFileStream);

                        _logger.LogInformation_Localizer($"Resource file content loaded: {resourcePath}");

                        return(content);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError_Localizer(ex, $"Error while loading resource file: {ex.Message} ({resourcePath})");
                    return(null);
                }
            }, LazyThreadSafetyMode.ExecutionAndPublication);

            _logger.LogInformation_Localizer($"Trying to load resource file content from cache {cacheName}.");

            lazyJObjectGetter = _resources.GetOrAdd(cacheName, lazyJObjectGetter);
            return(lazyJObjectGetter.Value);
        }