### Usage example for GetString Source: https://github.com/hishamco/my.extensions.localization.json Shows how to use GetString with a resource class and handle ResourceNotFound for fallback. ```csharp public class Resources { public string Hello { get; set; } public string WelcomeMessage { get; set; } } IStringLocalizer localizer = ...; // non-generic localizer LocalizedString hello = localizer.GetString(r => r.Hello); LocalizedString welcome = localizer.GetString(r => r.WelcomeMessage); Console.WriteLine(hello.Value); if (welcome.ResourceNotFound) { // fall back to default text } ``` -------------------------------- ### GetAllStrings usage example Source: https://github.com/hishamco/my.extensions.localization.json Example of iterating over all strings for the current culture with includeParentCultures set to false, printing each name and value. ```csharp foreach (var item in localizer.GetAllStrings(includeParentCultures: false)) { Console.WriteLine($"{item.Name} = {item.Value}"); } ``` -------------------------------- ### Install My.Extensions.Localization.Json NuGet package Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/README.md Adds the My.Extensions.Localization.Json package to the project. Run this command in the project directory. ```bash dotnet add package My.Extensions.Localization.Json ``` -------------------------------- ### Usage example with using declaration Source: https://github.com/hishamco/my.extensions.localization.json Shows typical usage: create a watcher with a path, subscribe to Changed, and check for .json files. ```csharp using var watcher = new JsonFileWatcher(Path.Combine(appRoot, "Resources")); watcher.Changed += (s, e) => { if (e.Name?.EndsWith(".json", StringComparison.Ordinal) == true) { Console.WriteLine($"Resource file changed: {e.FullPath}"); } }; // ... application lifetime ... ``` -------------------------------- ### Usage example with JsonResourceManager Source: https://github.com/hishamco/my.extensions.localization.json Demonstrates obtaining the application root, combining with a relative path, and creating a JsonResourceManager. Shows typical usage for resource file placement. ```csharp using My.Extensions.Localization.Json.Internal; string root = PathHelpers.GetApplicationRoot(); string resourcesDirectory = Path.Combine(root, "Resources"); var manager = new JsonResourceManager(resourcesDirectory); Console.WriteLine($"Resource paths: {string.Join(", ", manager.ResourcesPaths)}"); ``` -------------------------------- ### Usage example: creating provider and calling GetAllResourceStrings Source: https://github.com/hishamco/my.extensions.localization.json Shows how to instantiate JsonStringProvider with a JsonResourceManager and ResourceNamesCache, then call GetAllResourceStrings for a specific culture with throwOnMissing set to false. ```csharp var manager = new JsonResourceManager("Resources"); var provider = new JsonStringProvider(new ResourceNamesCache(), manager); var names = provider.GetAllResourceStrings(CultureInfo.GetCultureInfo("fr-FR"), throwOnMissing: false); ``` -------------------------------- ### RootNamespaceAttribute example Source: https://github.com/hishamco/my.extensions.localization.json Sets the root namespace used to trim type-based resource names. If absent, the assembly name is used instead. ```csharp [assembly: RootNamespace("MyCustomNamespace")] ``` -------------------------------- ### Usage example: custom provider plugged into localizer Source: https://github.com/hishamco/my.extensions.localization.json Shows how to create a custom IResourceStringProvider and pass it to JsonStringLocalizer along with the manager and logger. ```csharp // Custom provider plugged into the localizer IResourceStringProvider custom = new MyProvider(); var localizer = new JsonStringLocalizer(manager, custom, logger); ``` -------------------------------- ### Example JSON resource file Source: https://github.com/hishamco/my.extensions.localization.json Shows a sample JSON file with scalar, nested object, and array values. Flattening yields keys Hello, Greeting.Morning, Items[0], and Items[1]. ```json { "Hello": "Bonjour", "Greeting": { "Morning": "Bonjour" }, "Items": ["a", "b"] } ``` -------------------------------- ### Subscribing to Changed event Source: https://github.com/hishamco/my.extensions.localization.json Example of creating a JsonFileWatcher and subscribing to the Changed event to handle file changes, e.g., to reload resources. ```csharp var watcher = new JsonFileWatcher("Resources"); watcher.Changed += (sender, e) => { Console.WriteLine($"Changed: {e.FullPath}"); // e.g. reload resources for the affected culture }; ``` -------------------------------- ### Configure JsonLocalizationOptions with AddJsonLocalization Source: https://github.com/hishamco/my.extensions.localization.json Shows typical DI setup using AddJsonLocalization's setupAction to set ResourcesPath, ResourcesType, and MissingLocalizationBehavior. The defaults are TypeBased, Ignore, and empty paths. ```csharp builder.Services.AddJsonLocalization(options => { options.ResourcesPath = new[] { "Resources", "SharedResources" }; options.ResourcesType = ResourcesType.TypeBased; options.MissingLocalizationBehavior = MissingLocalizationBehavior.LogWarning; }); ``` -------------------------------- ### Use icon with Foundation span Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Use the fi-icon-name class to display an icon in Foundation. ```html ``` -------------------------------- ### Custom NoOpCache implementation Source: https://github.com/hishamco/my.extensions.localization.json Example of a custom implementation of IResourceNamesCache that does not cache and simply invokes the valueFactory each time. Useful for scenarios where caching is not desired. ```csharp // Custom implementation behind the interface public sealed class NoOpCache : IResourceNamesCache { public IList GetOrAdd(string name, Func> valueFactory) => valueFactory(name); } ``` -------------------------------- ### Usage example with ResourceNamesCache Source: https://github.com/hishamco/my.extensions.localization.json Shows how to use ResourceNamesCache to cache resource names for a specific culture. The factory loads the JSON resource file and extracts its keys. The result is printed to the console. ```csharp var cache = new ResourceNamesCache(); var names = cache.GetOrAdd("Culture=fr-FR;resourceName=", _ => JsonResourceLoader.Load("Resources/fr-FR.json").Keys.ToList()); Console.WriteLine(string.Join(", ", names)); ``` -------------------------------- ### Include default stylesheet Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Link to the default Open Iconic stylesheet. Available in font/css/open-iconic.{css, less, scss, styl}. ```html ``` -------------------------------- ### Include Foundation stylesheet Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Link to the Foundation stylesheet for Open Iconic. Available in font/css/open-iconic-foundation.{css, less, scss, styl}. ```html ``` -------------------------------- ### JsonFileWatcher Constructor Source: https://github.com/hishamco/my.extensions.localization.json Initializes a new instance of the JsonFileWatcher class, which monitors a directory for changes to JSON files. The watcher starts immediately on construction. ```APIDOC ## Constructor ### Description Initializes a new instance of the JsonFileWatcher class, which monitors a directory for changes to JSON files. The watcher starts immediately on construction. ### Method Constructor ### Signature public JsonFileWatcher(string rootDirectory) ### Parameters - **rootDirectory** (string) - Required - Directory to monitor for changes to JSON files ### Exceptions Throws the same exceptions as the FileSystemWatcher(string) constructor when rootDirectory is invalid (e.g. ArgumentException, PlatformNotSupportedException on unsupported platforms) — not guarded by this class. ``` -------------------------------- ### Use icon with Bootstrap span Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Use the oi class with an icon name to display an icon in Bootstrap. ```html ``` -------------------------------- ### Include Bootstrap stylesheet Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Link to the Bootstrap stylesheet for Open Iconic. Available in font/css/open-iconic-bootstrap.{css, less, scss, styl}. ```html ``` -------------------------------- ### Use icon with default span Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Use the oi class with data-glyph attribute to display an icon on its own. ```html ``` -------------------------------- ### AddJsonLocalization(this IServiceCollection services, Action setupAction) Source: https://github.com/hishamco/my.extensions.localization.json Registers JSON localization services with custom options. This extension method allows configuration of `JsonLocalizationOptions` via a setup action and returns the same service collection for chaining. ```APIDOC ## AddJsonLocalization(this IServiceCollection services, Action setupAction) ### Description Registers JSON localization services with custom options. This extension method allows configuration of `JsonLocalizationOptions` via a setup action and returns the same service collection for chaining. ### Method Extension method on `IServiceCollection` ### Parameters - **services** (`IServiceCollection`) - Required (this) - Service collection to which JSON localization services will be added - **setupAction** (`Action`) - Required - Action to configure the JSON localization options ### Return - The same `IServiceCollection` instance for chaining. ### Throws - `ArgumentNullException` if `services` or `setupAction` is null. ### Remarks Registers options through `services.Configure(setupAction)` and applies the core registrations. ``` -------------------------------- ### this[string name, params object[] arguments] Source: https://github.com/hishamco/my.extensions.localization.json Gets the localized string for the specified name and formats it with the provided arguments. Returns the name itself if not found, with ResourceNotFound set to true. ```APIDOC ## this[string name, params object[] arguments] ### Description Gets the localized string for the specified name and formats it with the provided arguments. Returns the name itself if not found, with ResourceNotFound set to true. ### Method Indexer Get ### Parameters - **name** (string) - Required - The name of the resource to retrieve. - **arguments** (object[]) - Required - The arguments to format the resource string with. ### Return Value - **LocalizedString** - The raw value (or name if missing) is formatted with string.Format(format ?? name, arguments) before being placed in Value. ResourceNotFound is true when the format string itself was not found. ### Throws - **ArgumentNullException** - if name is null. - **FormatException** - (from string.Format) if the resource string contains malformed placeholders for the supplied arguments. ### Request Example ```csharp LocalizedString message = localizer["Hello, {0}", user.Name]; string text = message.Value; // e.g. "Bonjour, Hisham" ``` ``` -------------------------------- ### Color SVG icons with fill rule Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Set the fill rule on the use tag to color an icon. ```css .icon-account-login { fill: #f00; } ``` -------------------------------- ### this[string name] Source: https://github.com/hishamco/my.extensions.localization.json Gets the localized string for the specified name in the current culture. Returns the name itself if not found, with ResourceNotFound set to true. ```APIDOC ## this[string name] ### Description Gets the localized string for the specified name in the current culture. Returns the name itself if not found, with ResourceNotFound set to true. ### Method Indexer Get ### Parameters - **name** (string) - Required - The name of the resource to retrieve. ### Return Value - **LocalizedString** - The localized string for name in CultureInfo.CurrentUICulture, or name itself when not found, with ResourceNotFound set to true when the value was not found. SearchedLocation carries the current ResourcesFilePath of the underlying resource manager. ### Throws - **ArgumentNullException** - if name is null. ### Request Example ```csharp var localizer = services.GetRequiredService>(); LocalizedString greeting = localizer["WelcomeMessage"]; if (greeting.ResourceNotFound) { Console.WriteLine($"'{greeting.Name}' was not found in {greeting.SearchedLocation}"); } Console.WriteLine(greeting.Value); ``` ``` -------------------------------- ### Create JsonResourceManager with culture-based naming Source: https://github.com/hishamco/my.extensions.localization.json Constructs a JsonResourceManager using a single base path for culture-based resource files (e.g., 'Resources/ar.json'). The example sets CurrentUICulture to 'ar' and retrieves a string, walking the culture hierarchy. ```csharp // Culture-based naming — one file per culture, e.g. "Resources/ar.json" var cultureManager = new JsonResourceManager("Resources"); CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("ar"); string greeting = cultureManager.GetString("Hello"); // walks culture hierarchy ``` -------------------------------- ### Size SVG icons with CSS Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Set equal width and height on the svg tag to size icons, as all icons are square. ```css .icon { width: 16px; height: 16px; } ``` -------------------------------- ### Display SVG icon with img tag Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Use this to display an Open Iconic SVG icon as a regular image. Remember to include the alt attribute for accessibility. ```html icon name ``` -------------------------------- ### Use SVG sprite with use tag Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/samples/LocalizationSample.Blazor.Client/wwwroot/css/open-iconic/README.md Display an icon from the SVG sprite. Add a general class to the svg tag and a unique class for each icon in the use tag for easy styling. ```html ``` -------------------------------- ### Guarding for null return from GetApplicationRoot Source: https://github.com/hishamco/my.extensions.localization.json Shows how to handle the null-returning edge case (single-file publish) by throwing an exception when root is null. ```csharp // Guarding for the null-returning edge case (single-file publish) string? root = PathHelpers.GetApplicationRoot(); if (root is null) { throw new InvalidOperationException("Cannot resolve application root; use absolute resource paths."); } ``` -------------------------------- ### GetApplicationRoot method implementation Source: https://github.com/hishamco/my.extensions.localization.json Returns the directory of the executing assembly using Path.GetDirectoryName and Assembly.Location. Returns null when location is empty (e.g., single-file publish). ```csharp public static string GetApplicationRoot() => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); ``` -------------------------------- ### Load and retrieve a resource value Source: https://github.com/hishamco/my.extensions.localization.json Loads a resource file and retrieves the value for key 'Hello'. If found, prints it to the console. ```csharp IDictionary resources = JsonResourceLoader.Load("Resources/Views.Home.Index.fr-FR.json"); if (resources.TryGetValue("Hello", out var value)) { Console.WriteLine(value); } ``` -------------------------------- ### GetApplicationRoot method signature Source: https://github.com/hishamco/my.extensions.localization.json Method signature for GetApplicationRoot. No parameters, returns string or null when location is unknown. ```csharp public static string GetApplicationRoot() ``` -------------------------------- ### AddJsonLocalization extension method with setupAction Source: https://github.com/hishamco/my.extensions.localization.json Registers JSON localization services with a configuration action. Throws ArgumentNullException if services or setupAction is null. Returns the same IServiceCollection for chaining. ```csharp public static IServiceCollection AddJsonLocalization(this IServiceCollection services, Action setupAction) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(setupAction); AddJsonLocalizationServices(services, setupAction); return services; } ``` -------------------------------- ### IResourceStringProvider interface Source: https://github.com/hishamco/my.extensions.localization.json Retrieves all resource strings for a culture. Implemented by JsonStringProvider. Accepted by JsonStringLocalizer constructors and queried by GetAllStrings. ```csharp public interface IResourceStringProvider { IList GetAllResourceStrings(CultureInfo culture, bool throwOnMissing); } ``` -------------------------------- ### GetApplicationRoot() Source: https://github.com/hishamco/my.extensions.localization.json Resolves the application root directory by returning the directory of the executing assembly. This is used to anchor relative resource paths and is the sole path-resolution primitive in the package. ```APIDOC ## GetApplicationRoot() ### Description Resolves the application root directory by returning the directory of the executing assembly. This is used to anchor relative resource paths and is the sole path-resolution primitive in the package. ### Method GetApplicationRoot ### Endpoint PathHelpers.GetApplicationRoot() ### Parameters #### Path Parameters - *(none)* - Not applicable - This method takes no parameters. ### Response #### Success Response - **Return** (string) - The directory containing the currently executing assembly, or `null` when the location is unknown. ### Usage Example ```csharp using My.Extensions.Localization.Json.Internal; string root = PathHelpers.GetApplicationRoot(); string resourcesDirectory = Path.Combine(root, "Resources"); var manager = new JsonResourceManager(resourcesDirectory); Console.WriteLine($"Resource paths: {string.Join(", ", manager.ResourcesPaths)}"); ``` ```csharp // Guarding for the null-returning edge case (single-file publish) string? root = PathHelpers.GetApplicationRoot(); if (root is null) { throw new InvalidOperationException("Cannot resolve application root; use absolute resource paths."); } ``` ``` -------------------------------- ### Minimalist registration and usage Source: https://github.com/hishamco/my.extensions.localization.json Shows the simplest registration with defaults only, and then using the standard localizer abstraction in a controller. ```csharp // Minimalist registration — defaults only services.AddJsonLocalization(); // Then use the standard localizer abstractions public class HomeController(IStringLocalizer localizer) : Controller { public IActionResult Index() => Content(localizer["WelcomeMessage"]); } ``` -------------------------------- ### JsonFileWatcher constructor Source: https://github.com/hishamco/my.extensions.localization.json Constructor that takes a root directory to monitor. Throws the same exceptions as FileSystemWatcher(string) if the directory is invalid. ```csharp public JsonFileWatcher(string rootDirectory) ``` -------------------------------- ### Use IStringLocalizer in a controller Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/README.md Shows injecting IStringLocalizer and retrieving a localized string by key. The resource file must be named based on the type (TypeBased) or culture. ```csharp public class HomeController : Controller { private readonly IStringLocalizer _localizer; public HomeController(IStringLocalizer localizer) { _localizer = localizer; } public IActionResult Index() { ViewData["Message"] = _localizer["WelcomeMessage"]; return View(); } } ``` -------------------------------- ### AddJsonLocalization DI registration Source: https://github.com/hishamco/my.extensions.localization.json Registers JsonLocalization services via AddJsonLocalization. Sets ResourcesPath to a single 'Resources' folder, uses TypeBased resource naming, and logs a warning for missing localization entries. ```csharp builder.Services.AddJsonLocalization(options => { options.ResourcesPath = new[] { "Resources" }; options.ResourcesType = ResourcesType.TypeBased; options.MissingLocalizationBehavior = MissingLocalizationBehavior.LogWarning; }); ``` -------------------------------- ### JSON resource file content Source: https://github.com/hishamco/my.extensions.localization.json Plain key/value JSON resource file. Comments and trailing commas are tolerated. Nested objects produce dot-separated keys, arrays produce index keys, and {0} placeholders are consumed by IStringLocalizer's arguments indexer. ```json { "Hello": "Bonjour", "WelcomeMessage": "Bienvenue sur notre application !" } ``` -------------------------------- ### Create(string baseName, string location) method signature Source: https://github.com/hishamco/my.extensions.localization.json Implements IStringLocalizerFactory.Create(string, string). Returns a cached JsonStringLocalizer with cache key baseName={baseName},location={location}. Throws ArgumentNullException if baseName or location is null. ```csharp public IStringLocalizer Create(string baseName, string location) ``` -------------------------------- ### Load missing file returns empty dictionary Source: https://github.com/hishamco/my.extensions.localization.json Demonstrates that missing files are tolerated: an empty dictionary is returned, and Count is 0. ```csharp // Missing files are tolerated — an empty dictionary is returned IDictionary empty = JsonResourceLoader.Load("does/not/exist.json"); Console.WriteLine(empty.Count); // 0 ``` -------------------------------- ### Register JSON localization services with AddJsonLocalization Source: https://github.com/hishamco/my.extensions.localization.json/blob/main/README.md Adds JSON localization services to the DI container in Program.cs or Startup.cs. Configures ResourcesPath to the 'Resources' folder and sets ResourcesType to TypeBased. ```csharp builder.Services.AddJsonLocalization(options => { options.ResourcesPath = new[] { "Resources" }; options.ResourcesType = ResourcesType.TypeBased; }); ``` -------------------------------- ### GetAllResourceStrings method signature Source: https://github.com/hishamco/my.extensions.localization.json Method signature for retrieving all resource keys for a culture. Results are cached under key 'Culture={culture.Name};resourceName={jsonResourceManager.ResourceName}' via resourceNamesCache.GetOrAdd. Throws MissingManifestResourceException when culture has no resource set and throwOnMissing is true; returns null when throwOnMissing is false and no resources exist. ```csharp public IList GetAllResourceStrings(CultureInfo culture, bool throwOnMissing) ``` -------------------------------- ### Programmatic options for factory tests / non-DI usage Source: https://github.com/hishamco/my.extensions.localization.json Creates JsonLocalizationOptions manually for tests or non-DI scenarios, then instantiates JsonStringLocalizerFactory with the options and a logger factory. Uses CultureBased and ThrowException to override defaults. ```csharp // Programmatic options for factory tests / non-DI usage var options = Options.Create(new JsonLocalizationOptions { ResourcesPath = ["Resources"], ResourcesType = ResourcesType.CultureBased, MissingLocalizationBehavior = MissingLocalizationBehavior.ThrowException }); var factory = new JsonStringLocalizerFactory(options, loggerFactory); ``` -------------------------------- ### JsonStringLocalizerFactory primary constructor (3 parameters) Source: https://github.com/hishamco/my.extensions.localization.json Primary constructor. Copies FallBackToParentUICultures from requestLocalizationOptions?.Value?.FallBackToParentUICultures ?? true. Throws ArgumentNullException if localizationOptions or loggerFactory is null. ```csharp public JsonStringLocalizerFactory( IOptions localizationOptions, ILoggerFactory loggerFactory, IOptions requestLocalizationOptions) ``` -------------------------------- ### Load method signature Source: https://github.com/hishamco/my.extensions.localization.json Loads a JSON resource file and returns a dictionary of key/value strings. Returns an empty dictionary if the file does not exist or contains no resources. Throws JsonException for invalid JSON, and surfaces IO exceptions from StreamReader. ```csharp public static IDictionary Load(string filePath) ``` -------------------------------- ### Create JsonStringLocalizerFactory with Options Source: https://github.com/hishamco/my.extensions.localization.json Constructs a JsonStringLocalizerFactory using JsonLocalizationOptions with ResourcesPath set to "Resources" and ResourcesType set to TypeBased. Then creates localizers via Create(Type) and Create(string, AssemblyName). ```csharp var options = Options.Create(new JsonLocalizationOptions { ResourcesPath = new[] { "Resources" }, ResourcesType = ResourcesType.TypeBased }); var factory = new JsonStringLocalizerFactory(options, NullLoggerFactory.Instance); IStringLocalizer localizer = factory.Create(typeof(HomeController)); IStringLocalizer other = factory.Create($"{typeof(HomeController).FullName}", typeof(HomeController).Assembly.FullName); ``` -------------------------------- ### Register JsonLocalization via DI and Create Localizer Source: https://github.com/hishamco/my.extensions.localization.json Registers JsonLocalization services with ResourcesPath set to "Resources" using AddJsonLocalization, then resolves IStringLocalizerFactory from the service provider and creates a localizer for "Views.Home.Index" with the given assembly name. ```csharp var services = new ServiceCollection(); services.AddJsonLocalization(o => o.ResourcesPath = new[] { "Resources" }); var provider = services.BuildServiceProvider(); var factory = provider.GetRequiredService(); IStringLocalizer localizer = factory.Create("Views.Home.Index", assemblyName); ``` -------------------------------- ### JsonStringLocalizer usage with missing key handling Source: https://github.com/hishamco/my.extensions.localization.json Shows constructing a JsonStringLocalizer with LogWarning behavior, then performing a lookup that is not cached and catching MissingLocalizationException for another missing key. ```csharp var localizer = new JsonStringLocalizer( resourceManager, provider, MissingLocalizationBehavior.LogWarning, logger); // A lookup that is not cached yet string value = localizer["MissingKey"]; try { string value2 = localizer["AnotherMissingKey"]; } catch (MissingLocalizationException ex) { Console.WriteLine(ex.Key); Console.WriteLine(ex.Culture); Console.WriteLine(ex.SearchedLocation); } ``` -------------------------------- ### Indexer this[string name] Source: https://github.com/hishamco/my.extensions.localization.json Returns a LocalizedString with the value for name in CurrentUICulture, or name itself with ResourceNotFound true when missing. SearchedLocation carries the current ResourcesFilePath. Throws ArgumentNullException if name is null. ```csharp public LocalizedString this[string name] { get { ... } } ``` ```csharp var localizer = services.GetRequiredService>(); LocalizedString greeting = localizer["WelcomeMessage"]; if (greeting.ResourceNotFound) { Console.WriteLine($"'{greeting.Name}' was not found in {greeting.SearchedLocation}"); } Console.WriteLine(greeting.Value); ``` -------------------------------- ### GetAllStrings(bool includeParentCultures, CultureInfo culture) - Protected overload Source: https://github.com/hishamco/my.extensions.localization.json Protected overload that collects resource names by walking the culture hierarchy when includeParentCultures is true, otherwise uses IResourceStringProvider.GetAllResourceStrings. Throws ArgumentNullException if culture is null. Each yielded item has ResourceNotFound set when no value is found. ```csharp protected virtual IEnumerable GetAllStrings(bool includeParentCultures, CultureInfo culture) ``` -------------------------------- ### Indexer this[string name, params object[] arguments] Source: https://github.com/hishamco/my.extensions.localization.json Formats the raw value (or name if missing) with string.Format(format ?? name, arguments) before placing it in Value. ResourceNotFound is true when the format string was not found. Throws ArgumentNullException if name is null and FormatException for malformed placeholders. ```csharp public LocalizedString this[string name, params object[] arguments] { get { ... } } ``` ```csharp LocalizedString message = localizer["Hello, {0}", user.Name]; string text = message.Value; // e.g. "Bonjour, Hisham" ``` -------------------------------- ### GetAllStrings(bool includeParentCultures) Source: https://github.com/hishamco/my.extensions.localization.json Returns one LocalizedString per resource name available for the current UI culture. Optionally walks parent cultures to collect resource names. ```APIDOC ## GetAllStrings(bool includeParentCultures) ### Description Returns one `LocalizedString` per resource name available for `CultureInfo.CurrentUICulture`, optionally walking parent cultures. ### Method GetAllStrings ### Parameters #### Method Parameters - **includeParentCultures** (bool) - Required - Whether to walk parent cultures when collecting resource names. ### Response #### Success Response - **IEnumerable** - One `LocalizedString` per resource name available for the current UI culture. ### Request Example ```csharp foreach (var item in localizer.GetAllStrings(includeParentCultures: false)) { Console.WriteLine($"{item.Name} = {item.Value}"); } ``` ``` -------------------------------- ### JsonResourceManager primary constructor with multiple paths Source: https://github.com/hishamco/my.extensions.localization.json Primary constructor accepting an array of resource paths, a fallback flag, and an optional resource name. If resourcesPaths is null, it is normalized to an empty array. ```csharp public JsonResourceManager(string[] resourcesPaths, bool fallBackToParentUICultures, string resourceName = null) ``` -------------------------------- ### Error handling for non-member expression Source: https://github.com/hishamco/my.extensions.localization.json Demonstrates that passing a method call expression throws NullReferenceException, and how to catch it. ```csharp // Error handling — expression must be a member access try { // This throws NullReferenceException: the body is a method call, not a member LocalizedString bad = localizer.GetString(r => r.Hello.Trim()); } catch (NullReferenceException) { Console.WriteLine("Expressions must reference a property directly."); } ``` -------------------------------- ### JsonResourceManager constructor with multiple paths and default fallback Source: https://github.com/hishamco/my.extensions.localization.json Constructor that accepts multiple resource paths and an optional resource name, defaulting fallBackToParentUICultures to true. ```csharp public JsonResourceManager(string[] resourcesPaths, string resourceName = null) : this(resourcesPaths, fallBackToParentUICultures: true, resourceName) { } ``` -------------------------------- ### Create(Type resourceSource) method signature Source: https://github.com/hishamco/my.extensions.localization.json Implements IStringLocalizerFactory.Create(Type). Returns a cached JsonStringLocalizer for the type. Throws ArgumentNullException if resourceSource is null. Cache key is culture={CultureInfo.CurrentUICulture.Name}, typeName={typeName}. ```csharp public IStringLocalizer Create(Type resourceSource) ``` -------------------------------- ### Load(string filePath) Source: https://github.com/hishamco/my.extensions.localization.json Loads a JSON resource file and returns a flat dictionary of key/value strings. Returns an empty dictionary if the file does not exist or contains no resources. ```APIDOC ## Load(string filePath) ### Description Loads a JSON resource file and returns a flat dictionary of key/value strings. Returns an empty dictionary if the file does not exist or contains no resources. ### Method Load ### Endpoint JsonResourceLoader.Load(string filePath) ### Parameters #### Path Parameters - **filePath** (string) - Required - Path to the JSON resource file ### Response #### Success Response - **IDictionary** - Resource keys mapped to their string values. Returns an empty dictionary if the file does not exist or contains no resources. ### Request Example ```csharp IDictionary resources = JsonResourceLoader.Load("Resources/Views.Home.Index.fr-FR.json"); ``` ### Response Example ```csharp if (resources.TryGetValue("Hello", out var value)) { Console.WriteLine(value); } ``` ``` -------------------------------- ### JsonResourceManager constructor with single path Source: https://github.com/hishamco/my.extensions.localization.json Constructor that initializes the manager with a single resource path, defaulting fallBackToParentUICultures to true and resourceName to null. ```csharp public JsonResourceManager(string resourcesPath, string resourceName = null) : this([resourcesPath], fallBackToParentUICultures: true, resourceName) { } ``` -------------------------------- ### GetAllStrings(bool includeParentCultures) - Public overload Source: https://github.com/hishamco/my.extensions.localization.json Returns all resource strings for the current UI culture, optionally including parent cultures. This public overload delegates to the protected overload with CultureInfo.CurrentUICulture. ```csharp public virtual IEnumerable GetAllStrings(bool includeParentCultures) => GetAllStrings(includeParentCultures, CultureInfo.CurrentUICulture); ``` -------------------------------- ### MissingLocalizationException(string key, string culture, string searchedLocation) constructor Source: https://github.com/hishamco/my.extensions.localization.json Constructor used by the localizer. Builds the message 'Localization for key '{key}' was not found for culture '{culture}' in '{searchedLocation}'.' and populates the Key, Culture, and SearchedLocation properties. Source: MissingLocalizationException.cs:44-51. ```csharp public MissingLocalizationException(string key, string culture, string searchedLocation) : base($"Localization for key '{key}' was not found for culture '{culture}' in '{searchedLocation}'.") { Key = key; Culture = culture; SearchedLocation = searchedLocation; } ``` -------------------------------- ### GetAllStrings(bool includeParentCultures, CultureInfo culture) Source: https://github.com/hishamco/my.extensions.localization.json Returns one LocalizedString per resource name available for the specified culture. Optionally walks parent cultures to collect resource names. ```APIDOC ## GetAllStrings(bool includeParentCultures, CultureInfo culture) ### Description Returns one `LocalizedString` per resource name available for the specified culture, optionally walking parent cultures. ### Method GetAllStrings ### Parameters #### Method Parameters - **includeParentCultures** (bool) - Required - Whether to walk parent cultures when collecting resource names. - **culture** (CultureInfo) - Required - The culture to retrieve resource strings for. ### Response #### Success Response - **IEnumerable** - One `LocalizedString` per resource name available for the specified culture. ### Error Handling - **ArgumentNullException** - Thrown if `culture` is null. ``` -------------------------------- ### GetResourceSet(CultureInfo culture, bool tryParents) Source: https://github.com/hishamco/my.extensions.localization.json Loads resources for the specified culture and returns a dictionary of key-value pairs. When tryParents is true, it aggregates entries from the culture and its ancestors, with the most specific culture taking precedence. ```APIDOC ## GetResourceSet(CultureInfo culture, bool tryParents) ### Description Triggers a load for `culture` across all configured paths, then returns the resource set. With `tryParents == false`, returns the cache entry for the exact culture or `null` if absent. With `tryParents == true`, aggregates entries from the culture and its ancestors (up to but not including `InvariantCulture`), merging with `TryAdd` so the most specific culture wins. ### Method GetResourceSet ### Parameters - `culture` (CultureInfo) - Required - The culture for which to load resources. - `tryParents` (bool) - Required - Whether to include parent cultures in the result. ### Response #### Success Response - Returns a `ConcurrentDictionary` of resource key/value pairs, or `null` when nothing is available for `tryParents == false`. ``` -------------------------------- ### Catch MissingLocalizationException Source: https://github.com/hishamco/my.extensions.localization.json Use this try/catch to handle the library-defined MissingLocalizationException when JsonLocalizationOptions.MissingLocalizationBehavior is set to ThrowException and a string lookup misses. The exception carries Key, Culture, and SearchedLocation properties. Because it inherits Exception, place this specific catch before a general catch (Exception) handler. ```csharp try { LocalizedString s = localizer["MissingKey"]; } catch (MissingLocalizationException ex) { Console.WriteLine($"Key={ex.Key}, Culture={ex.Culture}, Location={ex.SearchedLocation}"); } ``` -------------------------------- ### ResourceNamesCache default implementation Source: https://github.com/hishamco/my.extensions.localization.json Thread-safe default implementation backed by ConcurrentDictionary>. GetOrAdd delegates to the dictionary's GetOrAdd, so the factory is executed at most once per key. Throws ArgumentNullException if name or valueFactory is null; factory exceptions propagate on first computation. ```csharp public class ResourceNamesCache : IResourceNamesCache { private readonly ConcurrentDictionary> _cache = new(); public IList GetOrAdd(string name, Func> valueFactory) => _cache.GetOrAdd(name, valueFactory); } ``` -------------------------------- ### IResourceNamesCache interface Source: https://github.com/hishamco/my.extensions.localization.json Provides a cache for resource names. Implemented by ResourceNamesCache. Accepted by JsonStringProvider constructor and JsonStringLocalizer constructors that wrap a cache. ```csharp public interface IResourceNamesCache { IList GetOrAdd(string name, Func> valueFactory); } ``` -------------------------------- ### C# robust lookup pattern for IStringLocalizer with fallback and error logging Source: https://github.com/hishamco/my.extensions.localization.json Use this pattern in application-level IStringLocalizer consumers to handle both fallback behavior (Ignore/LogWarning) and exceptions (ThrowException) from the localizer. It catches MissingLocalizationException to return a caller-provided fallback key, and catches JsonException when logging is enabled to log a malformed JSON resource file error and return the key. ```csharp string Lookup(IStringLocalizer localizer, string key) { try { return localizer[key].Value; } catch (MissingLocalizationException) { return key; // caller-provided fallback } catch (JsonException ex) when (Log.IsEnabled(LogLevel.Error)) { Log.Error(ex, "Malformed JSON resource file"); return key; } } ``` -------------------------------- ### Usage with WebApplication and options Source: https://github.com/hishamco/my.extensions.localization.json Configures JSON localization with ResourcesPath and ResourcesType.TypeBased, then enables request localization for 'en-US' and 'fr-FR'. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddJsonLocalization(options => { options.ResourcesPath = new[] { "Resources" }; options.ResourcesType = ResourcesType.TypeBased; }); var app = builder.Build(); app.UseRequestLocalization("en-US", "fr-FR"); app.Run(); ``` -------------------------------- ### MissingLocalizationException Source: https://github.com/hishamco/my.extensions.localization.json Custom exception thrown by My.Extensions.Localization.Json when a string lookup misses and MissingLocalizationBehavior.ThrowException is configured. It carries Key, Culture, and SearchedLocation properties and can be caught specifically or as a general Exception. ```APIDOC ## MissingLocalizationException ### Description Custom exception thrown by My.Extensions.Localization.Json when a string lookup misses and MissingLocalizationBehavior.ThrowException is configured. It carries Key, Culture, and SearchedLocation properties and can be caught specifically or as a general Exception. ### Exception Type `My.Extensions.Localization.Json.MissingLocalizationException` ### Inheritance Derives from `Exception` ### Properties - **Key** (string) - The missing localization key - **Culture** (string) - The culture being looked up - **SearchedLocation** (string) - The location where the search was performed ### Trigger Conditions - `JsonLocalizationOptions.MissingLocalizationBehavior == MissingLocalizationBehavior.ThrowException` and a string lookup misses - The same behavior configured and the lookup hits the localizer's in-memory missing-key cache (previous miss) - The same behavior configured and `JsonResourceManager` threw `MissingManifestResourceException`, which is caught and re-dispatched to `HandleMissingLocalization` ### How to Catch ```csharp try { LocalizedString s = localizer["MissingKey"]; } catch (MissingLocalizationException ex) { Console.WriteLine($"Key={ex.Key}, Culture={ex.Culture}, Location={ex.SearchedLocation}"); } ``` ### Notes - The throw occurs on the **first** access of a missing key; after that the key is cached, so every subsequent access throws again without touching the resource manager. - Both indexer variants (`this[string]` and `this[string, object[]]`) and `GetAllStrings` pass through `GetStringSafely`, so all three can throw. ``` -------------------------------- ### MissingLocalizationException(string key, string culture, string searchedLocation) Source: https://github.com/hishamco/my.extensions.localization.json Initializes a new instance of the MissingLocalizationException class with the localization key, culture, and searched location. This constructor is used by the localizer and builds a descriptive message and populates the Key, Culture, and SearchedLocation properties. ```APIDOC ## MissingLocalizationException(string key, string culture, string searchedLocation) ### Description Initializes a new instance of the MissingLocalizationException class with the localization key, culture, and searched location. This constructor is used by the localizer and builds a descriptive message and populates the Key, Culture, and SearchedLocation properties. ### Constructor ```csharp public MissingLocalizationException(string key, string culture, string searchedLocation) : base($"Localization for key '{key}' was not found for culture '{culture}' in '{searchedLocation}'.") { Key = key; Culture = culture; SearchedLocation = searchedLocation; } ``` ### Parameters - **key** (string) - Required - The localization key that was not found - **culture** (string) - Required - The culture for which the localization was not found (culture name, e.g. `fr-FR`) - **searchedLocation** (string) - Required - The location where the localization was searched ### Response No return value. ``` -------------------------------- ### Registered services in AddJsonLocalizationServices Source: https://github.com/hishamco/my.extensions.localization.json Internal registrations for the JSON localization services. Uses TryAdd* so previously registered localizer services are left untouched. Registers IStringLocalizerFactory as singleton, and IStringLocalizer<> and IStringLocalizer as transient. ```csharp services.TryAddSingleton(); services.TryAddTransient(typeof(IStringLocalizer<>), typeof(StringLocalizer<>)); services.TryAddTransient(typeof(IStringLocalizer), typeof(StringLocalizer)); ``` -------------------------------- ### JsonStringLocalizer primary constructor (JsonResourceManager, IResourceStringProvider, MissingLocalizationBehavior, ILogger) Source: https://github.com/hishamco/my.extensions.localization.json Primary constructor; all others funnel into it. Throws ArgumentNullException if jsonResourceManager, resourceStringProvider, or logger is null. ```csharp public JsonStringLocalizer( JsonResourceManager jsonResourceManager, IResourceStringProvider resourceStringProvider, MissingLocalizationBehavior missingLocalizationBehavior, ILogger logger) ``` -------------------------------- ### AddJsonLocalization extension method (no options) Source: https://github.com/hishamco/my.extensions.localization.json Registers JSON localization services with default options (ResourcesPath empty, TypeBased, Ignore behavior). Calls services.AddOptions() to ensure options infrastructure is present. Returns the same IServiceCollection for chaining. ```csharp public static IServiceCollection AddJsonLocalization(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); services.AddOptions(); AddJsonLocalizationServices(services); return services; } ``` -------------------------------- ### IResourceStringProvider.GetAllResourceStrings Source: https://github.com/hishamco/my.extensions.localization.json Interface method that returns all resource keys for a given culture. Implement this interface to customize the resource-name source for the localizer. ```APIDOC ## IResourceStringProvider.GetAllResourceStrings ### Description Returns all resource keys for the specified culture. If the culture is missing and `throwOnMissing` is `false`, returns an empty list. ### Method GetAllResourceStrings ### Signature `IList GetAllResourceStrings(CultureInfo culture, bool throwOnMissing)` ### Parameters - `culture` (CultureInfo) - Required - The culture for which to retrieve resource strings. - `throwOnMissing` (bool) - Required - If `true`, throws an exception when the culture has no resource set; if `false`, returns an empty list. ### Return Value `IList` - The list of resource keys for the culture, or an empty list if missing and `throwOnMissing` is `false`. ``` -------------------------------- ### JsonStringLocalizerFactory constructor (2 parameters) Source: https://github.com/hishamco/my.extensions.localization.json Delegates to the 3-parameter constructor with requestLocalizationOptions: null, enabling parent-UICulture fallback (true). ```csharp public JsonStringLocalizerFactory( IOptions localizationOptions, ILoggerFactory loggerFactory) ``` -------------------------------- ### JsonStringProvider.GetAllResourceStrings Source: https://github.com/hishamco/my.extensions.localization.json Implementation of IResourceStringProvider that enumerates resource names from a JsonResourceManager with per-culture caching. Results are cached to avoid re-enumeration. ```APIDOC ## JsonStringProvider.GetAllResourceStrings ### Description Returns the resource keys for the specified culture. Results are cached under key `Culture={culture.Name};resourceName={jsonResourceManager.ResourceName}` via `resourceNamesCache.GetOrAdd`. ### Method GetAllResourceStrings ### Signature `public IList GetAllResourceStrings(CultureInfo culture, bool throwOnMissing)` ### Parameters - `culture` (CultureInfo) - Required - The culture for which to retrieve resource strings. - `throwOnMissing` (bool) - Required - If `true`, throws `MissingManifestResourceException` when the culture has no resource set; if `false`, returns `null` when no resources exist. ### Return Value `IList` - The resource keys for the culture, or `null` if missing and `throwOnMissing` is `false`. ### Exceptions - `MissingManifestResourceException` - Thrown when `culture` has no resource set and `throwOnMissing` is `true`. Message: `The manifest resource for the culture '{culture.Name}' is missing.` - `ArgumentNullException` - From `GetResourceSet` internals if `culture` is null. ### Usage Example ```csharp var manager = new JsonResourceManager("Resources"); var provider = new JsonStringProvider(new ResourceNamesCache(), manager); var names = provider.GetAllResourceStrings(CultureInfo.GetCultureInfo("fr-FR"), throwOnMissing: false); ``` ``` -------------------------------- ### JsonFileWatcher watcher configuration Source: https://github.com/hishamco/my.extensions.localization.json Configures the underlying FileSystemWatcher with a filter for JSON files, notify filters for LastWrite and Size, and enables raising events immediately. ```csharp _filesWatcher = new(rootDirectory) { Filter = JsonExtension, // "*.json" NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size, EnableRaisingEvents = true }; ``` -------------------------------- ### JsonStringLocalizerFactory.GetResourcePaths using PathHelpers Source: https://github.com/hishamco/my.extensions.localization.json Shows how the factory uses PathHelpers to resolve resource paths from ResourceLocationAttribute or configured ResourcesPath values, both relative to the application root. ```csharp var resourceLocationAttribute = assembly.GetCustomAttribute(); if (resourceLocationAttribute != null) { return [Path.Combine(PathHelpers.GetApplicationRoot(), resourceLocationAttribute.ResourceLocation)]; } return [.. _resourcesPaths.Select(p => Path.Combine(PathHelpers.GetApplicationRoot(), p))]; ``` -------------------------------- ### MissingLocalizationException() empty constructor Source: https://github.com/hishamco/my.extensions.localization.json Empty constructor; message is null. Key, Culture, and SearchedLocation remain null. Source: MissingLocalizationException.cs:14. ```csharp public MissingLocalizationException() { } ``` -------------------------------- ### JsonDocumentOptions with relaxed settings Source: https://github.com/hishamco/my.extensions.localization.json Configures JSON parsing to skip comments and allow trailing commas. All other options remain at defaults, such as MaxDepth 64. ```csharp private static readonly JsonDocumentOptions _jsonDocumentOptions = new() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; ``` -------------------------------- ### JsonStringLocalizerFactory(IOptions, ILoggerFactory, IOptions?) Source: https://github.com/hishamco/my.extensions.localization.json Initializes a new instance of the JsonStringLocalizerFactory class with the specified options and logger factory. This is the primary constructor that allows controlling parent-UICulture fallback behavior. ```APIDOC ## Constructor ### Description Initializes a new instance of the JsonStringLocalizerFactory class with the specified options and logger factory. This is the primary constructor that allows controlling parent-UICulture fallback behavior. ### Signature ```csharp public JsonStringLocalizerFactory( IOptions localizationOptions, ILoggerFactory loggerFactory, IOptions requestLocalizationOptions) ``` ### Parameters - **localizationOptions** (`IOptions`) - Required - Options configuring resource paths and resource type - **loggerFactory** (`ILoggerFactory`) - Required - Factory used to create loggers for localization operations - **requestLocalizationOptions** (`IOptions`) - Optional - Request localization options used to read `FallBackToParentUICultures`; when `null`, fallback is `true` ### Exceptions - **ArgumentNullException** - Thrown if `localizationOptions` or `loggerFactory` is null. ### Remarks The `FallBackToParentUICultures` flag is copied from `requestLocalizationOptions?.Value?.FallBackToParentUICultures ?? true`. ``` -------------------------------- ### JsonStringLocalizerFactory(IOptions, ILoggerFactory) Source: https://github.com/hishamco/my.extensions.localization.json Initializes a new instance of the JsonStringLocalizerFactory class. This constructor delegates to the primary constructor with requestLocalizationOptions set to null, enabling parent-UICulture fallback. ```APIDOC ## Constructor ### Description Initializes a new instance of the JsonStringLocalizerFactory class. This constructor delegates to the primary constructor with requestLocalizationOptions set to null, enabling parent-UICulture fallback. ### Signature ```csharp public JsonStringLocalizerFactory( IOptions localizationOptions, ILoggerFactory loggerFactory) ``` ### Parameters - **localizationOptions** (`IOptions`) - Required - Options configuring resource paths and resource type - **loggerFactory** (`ILoggerFactory`) - Required - Factory used to create loggers for localization operations ### Remarks This constructor sets `FallBackToParentUICultures` to `true`. ```