Ejemplo n.º 1
0
        public JsonStringLocalizerFactory(
            IHostingEnvironment applicationEnvironment,
            IOptions <JsonLocalizationOptions> localizationOptions,
            ILogger logger,
            Container container)
        {
            if (localizationOptions == null)
            {
                throw new ArgumentNullException(nameof(localizationOptions));
            }

            _applicationEnvironment = applicationEnvironment ?? throw new ArgumentNullException(nameof(applicationEnvironment));
            _logger   = logger ?? throw new ArgumentNullException(nameof(logger));
            Container = container ?? throw new ArgumentNullException(nameof(container));

            ResourceRelativePath = localizationOptions.Value.ResourcesPath ?? string.Empty;
            if (!string.IsNullOrWhiteSpace(ResourceRelativePath))
            {
                ResourceRelativePath = ResourceRelativePath
                                       .Replace(Path.AltDirectorySeparatorChar, '.')
                                       .Replace(Path.DirectorySeparatorChar, '.');
            }

            logger.Trace($"Created {nameof(JsonStringLocalizerFactory)} with:{Environment.NewLine}" +
                         $"  (application name: {applicationEnvironment.ApplicationName}){Environment.NewLine}" +
                         $"  (resources relateive path: {ResourceRelativePath})");
        }
Ejemplo n.º 2
0
        public override string ToString()
        {
            var startIndex = ResourceRelativePath.LastIndexOf("/") + 1;
            var endIndex   = ResourceRelativePath.LastIndexOf(".");

            return(ResourceRelativePath.Substring(startIndex, endIndex - startIndex).ToTitleCase());
        }
        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());
        }
        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, '.');
            }
        }
        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());
        }
        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);
        }