Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 41 additions & 13 deletions src/My.Extensions.Localization.Json/Internal/JsonResourceManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,29 @@ namespace My.Extensions.Localization.Json.Internal;

public class JsonResourceManager
{
private readonly List<JsonFileWatcher> _jsonFileWatchers = new();
private readonly List<JsonFileWatcher> _jsonFileWatchers = [];
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, string>> _resourcesCache = new();
private readonly ConcurrentDictionary<string, HashSet<string>> _loadedFilesCache = new();

public JsonResourceManager(string resourcesPath, string resourceName = null)
: this([resourcesPath], fallBackToParentUICultures: true, resourceName)
{
}

public JsonResourceManager(string[] resourcesPaths, string resourceName = null)
public JsonResourceManager(string[] resourcesPaths, bool fallBackToParentUICultures, string resourceName = null)
{
ResourcesPaths = resourcesPaths ?? Array.Empty<string>();
ResourceName = resourceName;
FallBackToParentUICultures = fallBackToParentUICultures;

foreach (var path in ResourcesPaths)
{
SetupFileWatcher(path);
}
}

public JsonResourceManager(string[] resourcesPaths)
: this(resourcesPaths, null)
public JsonResourceManager(string[] resourcesPaths, string resourceName = null)
: this(resourcesPaths, fallBackToParentUICultures: true, resourceName)
{
}

Expand All @@ -36,6 +41,12 @@ public JsonResourceManager(string[] resourcesPaths)

public string ResourcesFilePath { get; private set; }

/// <summary>
/// Gets a value indicating whether to fall back to parent UI cultures
/// when a localized string is not found for the current culture.
/// </summary>
public bool FallBackToParentUICultures { get; }

public virtual ConcurrentDictionary<string, string> GetResourceSet(CultureInfo culture, bool tryParents)
{
TryLoadResourceSet(culture);
Expand Down Expand Up @@ -75,7 +86,7 @@ public virtual ConcurrentDictionary<string, string> GetResourceSet(CultureInfo c
public virtual string GetString(string name)
{
var culture = CultureInfo.CurrentUICulture;
GetResourceSet(culture, tryParents: true);
GetResourceSet(culture, tryParents: FallBackToParentUICultures);

if (_resourcesCache.IsEmpty)
{
Expand All @@ -93,6 +104,11 @@ public virtual string GetString(string name)
}
}

if (!FallBackToParentUICultures)
{
break;
}

culture = culture.Parent;
} while (culture != culture.Parent);

Expand All @@ -101,22 +117,34 @@ public virtual string GetString(string name)

public virtual string GetString(string name, CultureInfo culture)
{
GetResourceSet(culture, tryParents: true);
GetResourceSet(culture, tryParents: FallBackToParentUICultures);

if (_resourcesCache.IsEmpty)
{
return null;
}

var key = $"{ResourceName}.{culture.Name}";
if (!_resourcesCache.TryGetValue(key, out var resources))
var currentCulture = culture;
do
{
return null;
}
var key = $"{ResourceName}.{currentCulture.Name}";
if (_resourcesCache.TryGetValue(key, out var resources))
{
if (resources.TryGetValue(name, out var value))
{
return value.ToString();
}
}

if (!FallBackToParentUICultures)
{
break;
}

currentCulture = currentCulture.Parent;
} while (currentCulture != currentCulture.Parent);

return resources.TryGetValue(name, out var value)
? value.ToString()
: null;
return null;
}

private void TryLoadResourceSet(CultureInfo culture)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
using System;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;

namespace My.Extensions.Localization.Json;

public class JsonLocalizationOptions : LocalizationOptions
{
public ResourcesType ResourcesType { get; set; } = ResourcesType.TypeBased;

public new string[] ResourcesPath { get; set; } = Array.Empty<string>();
public new string[] ResourcesPath { get; set; } = [];
}
23 changes: 16 additions & 7 deletions src/My.Extensions.Localization.Json/JsonStringLocalizerFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
Expand All @@ -19,16 +20,26 @@ public class JsonStringLocalizerFactory : IStringLocalizerFactory
private readonly ConcurrentDictionary<string, JsonStringLocalizer> _localizerCache = new();
private readonly string[] _resourcesPaths;
private readonly ResourcesType _resourcesType = ResourcesType.TypeBased;
private readonly bool _fallBackToParentUICultures = true;
private readonly ILoggerFactory _loggerFactory;

public JsonStringLocalizerFactory(
IOptions<JsonLocalizationOptions> localizationOptions,
ILoggerFactory loggerFactory)
: this(localizationOptions, loggerFactory, null)
{
}

public JsonStringLocalizerFactory(
IOptions<JsonLocalizationOptions> localizationOptions,
ILoggerFactory loggerFactory,
IOptions<RequestLocalizationOptions> requestLocalizationOptions)
{
ArgumentNullException.ThrowIfNull(localizationOptions);

_resourcesPaths = localizationOptions.Value.ResourcesPath ?? Array.Empty<string>();
_resourcesPaths = localizationOptions.Value.ResourcesPath ?? [];
_resourcesType = localizationOptions.Value.ResourcesType;
_fallBackToParentUICultures = requestLocalizationOptions?.Value?.FallBackToParentUICultures ?? true;
_loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
}

Expand Down Expand Up @@ -91,8 +102,8 @@ protected virtual JsonStringLocalizer CreateJsonStringLocalizer(
string resourceName)
{
var resourceManager = _resourcesType == ResourcesType.TypeBased
? new JsonResourceManager(resourcesPaths, resourceName)
: new JsonResourceManager(resourcesPaths);
? new JsonResourceManager(resourcesPaths, _fallBackToParentUICultures, resourceName)
: new JsonResourceManager(resourcesPaths, _fallBackToParentUICultures, null);
var logger = _loggerFactory.CreateLogger<JsonStringLocalizer>();

return new JsonStringLocalizer(resourceManager, _resourceNamesCache, logger);
Expand All @@ -104,12 +115,10 @@ private string[] GetResourcePaths(Assembly assembly)

if (resourceLocationAttribute != null)
{
return new[] { Path.Combine(PathHelpers.GetApplicationRoot(), resourceLocationAttribute.ResourceLocation) };
return [Path.Combine(PathHelpers.GetApplicationRoot(), resourceLocationAttribute.ResourceLocation)];
}

return _resourcesPaths
.Select(p => Path.Combine(PathHelpers.GetApplicationRoot(), p))
.ToArray();
return [.. _resourcesPaths.Select(p => Path.Combine(PathHelpers.GetApplicationRoot(), p))];
}

private static string GetRootNamespace(Assembly assembly)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Localization" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Localization" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -10,6 +7,8 @@
using Microsoft.Extensions.Options;
using Moq;
using My.Extensions.Localization.Json.Tests.Common;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace My.Extensions.Localization.Json.Tests;
Expand All @@ -22,7 +21,7 @@
{
var _localizationOptions = new Mock<IOptions<JsonLocalizationOptions>>();
_localizationOptions.Setup(o => o.Value)
.Returns(() => new JsonLocalizationOptions { ResourcesPath = new[] { "Resources" } });
.Returns(() => new JsonLocalizationOptions { ResourcesPath = ["Resources"] });
var localizerFactory = new JsonStringLocalizerFactory(_localizationOptions.Object, NullLoggerFactory.Instance);
var location = "My.Extensions.Localization.Json.Tests";
var basename = $"{location}.Common.{nameof(Test)}";
Expand Down Expand Up @@ -128,14 +127,14 @@
}

[Fact]
public async void CultureBasedResourcesUsesIStringLocalizer()

Check warning on line 130 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

Support for 'async void' unit tests is being removed from xUnit.net v3. To simplify upgrading, convert the test to 'async Task' instead. (https://xunit.net/xunit.analyzers/rules/xUnit1048)

Check warning on line 130 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

Support for 'async void' unit tests is being removed from xUnit.net v3. To simplify upgrading, convert the test to 'async Task' instead. (https://xunit.net/xunit.analyzers/rules/xUnit1048)
{
var webHostBuilder = new WebHostBuilder()

Check warning on line 132 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

'WebHostBuilder' is obsolete: 'WebHostBuilder is deprecated in favor of HostBuilder and WebApplicationBuilder. For more information, visit https://aka.ms/aspnet/deprecate/004.' (https://aka.ms/aspnet/deprecate/004)

Check warning on line 132 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

'WebHostBuilder' is obsolete: 'WebHostBuilder is deprecated in favor of HostBuilder and WebApplicationBuilder. For more information, visit https://aka.ms/aspnet/deprecate/004.' (https://aka.ms/aspnet/deprecate/004)
.ConfigureServices(services =>
{
services.AddJsonLocalization(options =>
{
options.ResourcesPath = new[] { "Resources" };
options.ResourcesPath = ["Resources"];
options.ResourcesType = ResourcesType.CultureBased;
});
})
Expand All @@ -155,7 +154,7 @@
});
});

using var server = new TestServer(webHostBuilder);

Check warning on line 157 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

'TestServer.TestServer(IWebHostBuilder)' is obsolete: 'IWebHost, which this method uses, is obsolete. Use one of the ctors that takes an IServiceProvider instead. For more information, visit https://aka.ms/aspnet/deprecate/008.' (https://aka.ms/aspnet/deprecate/008)

Check warning on line 157 in test/My.Extensions.Localization.Json.Tests/JsonStringLocalizerTests.cs

View workflow job for this annotation

GitHub Actions / build

'TestServer.TestServer(IWebHostBuilder)' is obsolete: 'IWebHost, which this method uses, is obsolete. Use one of the ctors that takes an IServiceProvider instead. For more information, visit https://aka.ms/aspnet/deprecate/008.' (https://aka.ms/aspnet/deprecate/008)
var client = server.CreateClient();
var response = await client.GetAsync("/");
}
Expand All @@ -177,6 +176,83 @@
Assert.Equal(expected, translation);
}

[Fact]
public void GetTranslation_WithFallBackToParentUICulturesDisabled_DoesNotFallbackToParentCulture()
{
// Arrange
var localizationOptions = new Mock<IOptions<JsonLocalizationOptions>>();
localizationOptions.Setup(o => o.Value)
.Returns(() => new JsonLocalizationOptions
{
ResourcesPath = ["Resources"]
});

var requestLocalizationOptions = new Mock<IOptions<RequestLocalizationOptions>>();
requestLocalizationOptions.Setup(o => o.Value)
.Returns(() => new RequestLocalizationOptions
{
FallBackToParentUICultures = false
});

var localizerFactory = new JsonStringLocalizerFactory(
localizationOptions.Object,
NullLoggerFactory.Instance,
requestLocalizationOptions.Object);
var location = "My.Extensions.Localization.Json.Tests";
var basename = $"{location}.Common.{nameof(Test)}";
var localizer = localizerFactory.Create(basename, location);

LocalizationHelper.SetCurrentCulture("fr-FR");

// Act
// "Yes" exists only in Test.fr.json (parent culture), not in Test.fr-FR.json
var translation = localizer["Yes"];

// Assert
// When FallBackToParentUICultures is disabled, it should not find "Yes" in fr-FR
// and return the key itself as the translation was not found
Assert.Equal("Yes", translation.Value);
Assert.True(translation.ResourceNotFound);
}

[Fact]
public void GetTranslation_WithFallBackToParentUICulturesEnabled_FallsBackToParentCulture()
{
// Arrange
var localizationOptions = new Mock<IOptions<JsonLocalizationOptions>>();
localizationOptions.Setup(o => o.Value)
.Returns(() => new JsonLocalizationOptions
{
ResourcesPath = ["Resources"]
});

var requestLocalizationOptions = new Mock<IOptions<RequestLocalizationOptions>>();
requestLocalizationOptions.Setup(o => o.Value)
.Returns(() => new RequestLocalizationOptions
{
FallBackToParentUICultures = true
});

var localizerFactory = new JsonStringLocalizerFactory(
localizationOptions.Object,
NullLoggerFactory.Instance,
requestLocalizationOptions.Object);
var location = "My.Extensions.Localization.Json.Tests";
var basename = $"{location}.Common.{nameof(Test)}";
var localizer = localizerFactory.Create(basename, location);

LocalizationHelper.SetCurrentCulture("fr-FR");

// Act
// "Yes" exists only in Test.fr.json (parent culture), not in Test.fr-FR.json
var translation = localizer["Yes"];

// Assert
// When FallBackToParentUICultures is enabled (default), it should find "Yes" in fr (parent)
Assert.Equal("Oui", translation.Value);
Assert.False(translation.ResourceNotFound);
}

private class SharedResource
{
public string Hello { get; set; }
Expand Down
Loading