Git Product home page Git Product logo

askmethat-aspnet-jsonlocalizer's Introduction

Obsolete

This repository was moved to : AlexTeixeira/Askmethat-Aspnet-JsonLocalize

Askmethat-Aspnet-JsonLocalizer

Json Localizer library for .NetStandard and .NetCore Asp.net projects

Nuget

NuGet

Build

Build Status

Project

This library allows users to use JSON files instead of RESX in an ASP.NET application. The code tries to be most compliant with Microsoft guidelines. The library is compatible with NetStandard & NetCore.

Configuration

An extension method is available for IServiceCollection. You can have a look at the method here

Options

A set of options is available. You can define them like this :

services.AddJsonLocalization(options => {
        options.CacheDuration = TimeSpan.FromMinutes(15);
        options.ResourcesPath = "mypath";
        options.FileEncoding = Encoding.GetEncoding("ISO-8859-1");
        options.SupportedCultureInfos = new HashSet<CultureInfo>()
        {
          new CultureInfo("en-US"),
          new CultureInfo("fr-FR")
        };
    });

Current Options

  • SupportedCultureInfos : _Default value : List containing only default culture and CurrentUICulture. Optionnal array of cultures that you should provide to plugin. _(Like RequestLocalizationOptions)
  • ResourcesPath : Default value : $"{_env.WebRootPath}/Resources/". Base path of your resources. The plugin will browse the folder and sub-folders and load all present JSON files.
  • AdditionalResourcePaths : Default value : null. Optionnal array of additional paths to search for resources.
  • CacheDuration : Default value : 30 minutes. We cache all values to memory to avoid loading files for each request, this parameter defines the time after which the cache is refreshed.
  • FileEncoding : default value : UTF8. Specify the file encoding.
  • IsAbsolutePath : _default value : false. Look for an absolute path instead of project path.
  • UseBaseName : _default value : false. Use base name location for Views and constructors like default Resx localization in ResourcePathFolder. Please have a look at the documentation below to see the different possiblities for structuring your translation files.
  • Caching : _default value: MemoryCache. Internal caching can be overwritted by using custom class that extends IMemoryCache.
  • PluralSeparator : _default value: |. Seperator used to get singular or pluralized version of localization. More information in Pluralization
  • MissingTranslationLogBehavior : _default value: LogConsoleError. Define the logging mode
  • LocalizationMode : _default value: Basic. Define the localization mode for the Json file. Currently Basic and I18n. More information in LocalizationMode
  • MissingTranslationsOutputFile : This enables to specify in which file the missing translations will be written when MissingTranslationLogBehavior = MissingTranslationLogBehavior.CollectToJSON, defaults to MissingTranslations.json
  • IgnoreJsonErrors: This properly will ignore the JSON errors if set to true. Recommended in production but not in development.

Search patterns when UseBaseName = true

If UseBaseName is set to true, it will be searched for lingualization files by the following order - skipping the options below if any option before matches.

  • If you use a non-typed IStringLocalizer all files in the Resources-directory, including all subdirectories, will be used to find a localization. This can cause unpredictable behavior if the same key is used in multiple files.

  • If you use a typed localizer, the following applies - Namespace is the "short namespace" without the root namespace:

    • Nested classes will use the translation file of their parent class.
    • If there is a folder named "Your/Namespace/And/Classname", all contents of this folder will be used.
    • If there is a folder named "Your/Namespace" the folder will be searched for all json-files beginning with your classname.
    • Otherwise there will be searched for a json-file starting with "Your.Namespace.And.Classname" in your Resources-folder.
    • If there any .shared.json file at base path, all the keys that do not exist in other files will be added.
  • If you need a base shared files, just add a file named localization.shared.json in your ResourcesPath

Pluralization

In version 2.0.0, Pluralization was introduced. You are now able to manage a singular (left) and plural (right) version for the same Key. PluralSeparator is used as separator between the two strings.

For example : User|Users for key Users

To use plural string, use parameters from IStringLocalizer, if last parameters is a boolean, pluralization will be activated.

Pluralization is available with IStringLocalizer, IViewLocalizer and HtmlStringLocalizer :

In version 3.1.1 and above you can have multiple pluralization, to use it, you should use IJsonStringLocalizer interface and this method LocalizedString GetPlural(string key, double count, params object[] arguments)

localizer.GetString("Users", true);

Clean Memory Cache

Version 2.2.0+ allows you to clean cache. It's usefull when you want's tu update in live some translations.

Example

public class HomeController{
  private readonly IJsonStringLocalizer _localizer;
  
  public HomeController(IJsonStringLocalizer<HomeController> localizer)
  {
      _localizer = localizer;
      _localizer.ClearMemCache(new List<CultureInfo>()
      {
          new CultureInfo("en-US")
      });
  }
}

Blazor Server HTML parsing

As you know, Blazor Server does not provide IHtmlLocalizer. To avoid this, you can now use from IJsonStringLocalizer this method MarkupString GetHtmlBlazorString(string name, bool shouldTryDefaultCulture = true)

Information

Platform Support

Version 3.2 and bellow

Platform Version
NetCore 3.0.0+
NetStandard 2.1.0+
Blazor Server 3.0.0+

Version 4 and above

Platform Version
NetCore 5.0.0+
NetStandard 2.1.0+
Blazor Server 5.0.0+
Blazor Wasm 5.0.0+

WithCulture method

WhithCulture method is not implemented and will not be implemented. ASP.NET Team, start to set this method Obsolete for version 3 and will be removed in version 4 of asp.net core.

For more information : #46

Localization mode

As asked on the request #64, Some user want to have the possiblities to manage file with i18n way. To answer this demand, a localization mode was introduced with default value Basic. Basic version means the the one describe in the previous parts

I18n

To use the i18n file management, use the the option Localization mode like this : cs LocalizationMode = LocalizationMode.I18n. After that, you should be able to use this json :

{
   "Name": "Name",
   "Color": "Color"
}

File name

File name are important for some purpose (Culture looking, parent culture, fallback).

Please use this pattern : [fileName].[culture].json If you need a fallback culture that target all culture, you can create a file named localisation.json. Of course, if this file does not exist, the chosen default culture is the fallback.

Important: In this mode, the UseBaseName options should be False.

For more information : #64

Performances

After talking with others Devs about my package, they asked my about performance.

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000
Intel Core i7-10870H CPU 2.20GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK=6.0.101
  [Host]     : .NET 6.0.1 (6.0.121.56705), X64 RyuJIT
  DefaultJob : .NET 6.0.1 (6.0.121.56705), X64 RyuJIT

Method Mean Error StdDev Min Max Ratio RatioSD Gen 0 Gen 1 Gen 2 Allocated
Localizer 57.34 ns 0.590 ns 0.523 ns 56.65 ns 58.46 ns 1.00 0.00 - - - -
JsonLocalizer 41.50 ns 0.552 ns 0.516 ns 40.60 ns 42.46 ns 0.72 0.01 0.0057 - - 48 B
JsonLocalizerWithCreation 169,174.60 ns 1,070.840 ns 1,001.664 ns 167,445.80 ns 170,873.85 ns 2,950.03 33.21 4.6387 2.1973 0.2441 40,706 B
I18nJsonLocalizerWithCreation 228,438.65 ns 4,188.350 ns 6,643.166 ns 218,070.12 ns 245,103.20 ns 4,026.62 130.32 12.2070 6.1035 0.4883 104,172 B
JsonLocalizerWithCreationAndExternalMemoryCache 2,813.26 ns 51.894 ns 48.541 ns 2,731.36 ns 2,920.27 ns 49.04 0.92 0.5264 0.2632 - 4,424 B
JsonLocalizerDefaultCultureValue 145.34 ns 1.284 ns 1.201 ns 142.61 ns 146.81 ns 2.53 0.04 0.0315 - - 264 B
LocalizerDefaultCultureValue 159.06 ns 0.919 ns 0.859 ns 157.63 ns 160.51 ns 2.77 0.03 0.0257 - - 216 B

Contributors

Michael Monsour
Michael Monsour
Luka Gospodnetic
Luka Gospodnetic
Christoph Sonntag
Christoph Sonntag
Nacho
Nacho
Ashley Medway
Ashley Medway
Serhii Voitovych
Serhii Voitovych
James Hill
James Hill
Ferenc Czirok
Ferenc Czirok
rohanreddyg
rohanreddyg
rickszyr
rickszyr
ErikApption
ErikApption

A special thanks to @Compufreak345 for is hard work. He did a lot for this repo.

A special thanks to @EricApption for is work to improve the repo and making a very good stuff on migrating to net6 and System.Text.Json & making it working for blazor wasm

License

MIT Licence

askmethat-aspnet-jsonlocalizer's People

Contributors

alexteixeira avatar czirok avatar erikapption avatar iorlandoni avatar jameshill3 avatar lethek avatar rohan-pesa avatar rohanreddyg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

askmethat-aspnet-jsonlocalizer's Issues

Localization in Fluent Validation

How I will Implement multilingual for fluent validation

this.RuleFor(u => u.Username).NotEmpty().WithMessage("Please enter username");
this.RuleFor(u => u.Password).NotEmpty().WithMessage("Please enter password");

Culture not processed correctly

Hi,
I started using your nice library to overcome old resx structures ;). It is a .NET Core WebApplication where the translations should be returned for the current culture of the user. (Done with stringLocalizer.WithCulture(user.Culture)....

But unfortunately I always receive the translation for the default culture (German in my case). If I read your code correctly, WithCulture has no effect and for the initialization of the Localizer the CurrentUICulture is used, which I can't use. So it is currently not possible for me to get things right...

Are there any plans to change the culture behavior (and only fallback to CurrentUICulture if nothing is set)? Even if not, it would be great to add a note to the docs to avoid needless research in future ;)

Thanks!

Blazor sample I18nTestSample doesn't work

IViewLocalizer ends up throwing an exception which according to https://docs.microsoft.com/en-us/aspnet/core/blazor/globalization-localization?view=aspnetcore-3.1 is expected:

A limited set of ASP.NET Core's localization scenarios are currently supported:

IStringLocalizer and IStringLocalizer<T> are supported in Blazor apps.
IHtmlLocalizer, IViewLocalizer, and Data Annotations localization are ASP.NET Core MVC scenarios and not supported in Blazor apps. 

The demo app works by replacing IViewLocalizer with IStringLocalizer

Factory should implement caching

Hi,

In the default implementation of IStringLocalizerFactory, they do IStringLocalizer caching (using ConcurentDictornary). According to feedback from the .NET CORE development team, if one decides to implement a custom IStringLocalizerFactory they should implement caching them self.

Implementation should cache localizers to prevent them from being created needlessly.

Unfortunately your test case is small controller so you can't reproduce this issues. In my case, where there is massive use of ISTringLocalizer, it is called many times.

Why was there a need to implement the JsonStringLocalizerFactory? As far as I can tell, you could have solved it all just by using the IStringLocalizer implementation and just keep using the Microsoft default IStringLocalizerFactory (that uses caching)

I will try to make it work without it in my scenario because I currently don't see the benefit of Factory customization. But please let me know if I am missing something...

tnx!
Luka

Pluralization

Be able from Localizer and IHtmlLocalizer to have pluralization.

Example :

Key : User
Values : User | Users

Be able to get User or Users

Relative Json file path

Greate package. I'm trying to use your package in order to localize two Json files in two different paths. I couldn't do this because in the startup.cs the resource path should be fixed.
But this is not the problem, even if i try to put the two json files under the same resource folder what i get in the result is always the content of the two Json resource files.
I thnik that is because the basename is never user when instanciating a JsonStringLocalizer class iin the JsonStringLocalizerFactory. Create method :

  public IStringLocalizer Create(string baseName, string location)
        {
            return (IStringLocalizer)new JsonStringLocalizer(_env, _memCache, _resourcesRelativePath, _localizationOptions);
        }

I guess it should have been something like this :

  public IStringLocalizer Create(string baseName, string location)
        {
            string filePath = _resourcesRelativePath+baseName
            return (IStringLocalizer)new JsonStringLocalizer(_env, _memCache, filePath, _localizationOptions);
        }

System.Runtime, Version=4.2.1.0

Hi!
I have a class library on netstandart 2.1 and add you package last version 3.1.0 but show error:

Error CS1705 Assembly 'Askmethat.Aspnet.JsonLocalizer' with identity 'Askmethat.Aspnet.JsonLocalizer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null' uses 'System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Runtime' with identity 'System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'_

Last version 3.1.0 does support netstandart 2.1? Where info about this?
Thanks.

Encoding issue

Hi,

would it be possible to add an option to the configuration allowing me to set the encoding in which to read the json file?

I have noticed that after users change the translation file in notepad, save it without checking the encoding, end up setting it to ANSI or something.
After that, special characters are shown like an � after being localized.

so if you could add a config option allowing me to set the encoding in code, users can't ruin the localizations anymore by not saving in the proper encoding.

Compare performance with base ILocalizer

Have a look about performance using benchmarkdotnet comparing to base Asp.net Localizer.

Post result to the Readme file.

If results are bad, try to improve them :)

Target nestandard instead of netcoreapp

Hi,

I've been using JsonLocalizer from some time now. For the time being, I had to stick to an older version because I am referencing it from a library that is compiled against nestandard2.0.

I understand that JsonLocalizer is meant to be used in Top Level projects (weapps), however bringing back netstandard as a dependency instead of netcoreapp could be great for cases like mine where the common face lifting is done in libraries instead of every single application.

Thank you in advance.

"How to" Documentation

Is it possible to add different scenarios of how to use this library? for example data annotation, in views and controllers.
Thank you

WithCulture still does not work in 2.2.0

We still have issues with not getting the correct translation, even when using "WithCulture".

We need to be able to use a localization, not based on geo-position, cookie, browser setting, but based on a predefined setting added(in the database) on the specific page..

we cant get this to work without new page load (change language)

Change request culture and language

I am trying to make my website bilingual, I set the culture with cookie like this.

           public IActionResult SetCulture(string id = "en")
	{
		var culture = id;
		Response.Cookies.Append(
		   CookieRequestCultureProvider.DefaultCookieName,
		   CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), 
                                   new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
	   );
		var referer = Request.Headers["Referer"].ToString();
		referer = String.IsNullOrEmpty(referer) ? "/" : referer;
		var address = new Uri(referer);
		var path = address.AbsolutePath;
		return Redirect(path);
	}

but the language does not get changed unless I restart the application;
how can I change the language while the app is running.
Thanks.

Caching problem - Storing cache with wrong key and using AddSingleton instead of AddScoped

Hi,

According to my interpretation of the code, the library would cache only first language that gets requests. Why? Because JsonStringLocalizer constructor only gets called once. I suppose this is because it is registered (see below) as singleton (AddSingleton) instead of Scoped (AddScoped). And if the JsonStringLocalizer constructor is called only once, then its base class constructor gets called only once, and that means that only the first langues gets cached. If the you user in the next request changes its option and chooses a different language, that change would not be reflected in the code.

internal static void AddJsonLocalizationServices(IServiceCollection services) { services.AddMemoryCache(); services.AddSingleton<IStringLocalizerFactory, JsonStringLocalizerFactory>(); services.AddSingleton<IStringLocalizer, JsonStringLocalizer>(); }

Another issue is that you are not storing the cache with the same value as you are reading it:
First is concatenation of key + language, and you are storing it only using key and without language.
I added a fix #43

if (!_memCache.TryGetValue($"{CACHE_KEY}_{currentCulture.ThreeLetterISOLanguageName}", out localization)) { ConstructLocalizationObject(_resourcesRelativePath, currentCulture); // Set cache options. var cacheEntryOptions = new MemoryCacheEntryOptions() // Keep in cache for this time, reset time if accessed. .SetSlidingExpiration(_memCacheDuration); // Save data in cache. _memCache.Set(CACHE_KEY, localization, cacheEntryOptions); }

Controller inheritance

Hi,

I have HomeController which inherits BaseController

Constructor of HomeController:

 public HomeController(IConfiguration configuration,
            **IJsonStringLocalizer<HomeController> localizer**) :
        base(configuration, localizer){
}

Class BaseController:

private readonly IConfiguration _configuration;
 protected  IJsonStringLocalizer<BaseController> _localizer;

       public BaseController(IConfiguration configuration,
           **IJsonStringLocalizer<BaseController> localizer**)
       {
           this.apiHandler = apiHandler;
           this._configuration = configuration;
           this._localizer = localizer;
       }

If we want to use it this way, we would actually need (I assume):

public interface IJsonStringLocalizer<out T> : IJsonStringLocalizer
instead of

public interface IJsonStringLocalizer<T> : IJsonStringLocalizer

<T> -> <out T>

it does not seems like localizer.withculture() work

If i use

@{
var desiredLanguageLocalizer = Localizer.WithCulture(new CultureInfo("da"));
}
<p>@desiredLanguageLocalizer['myKey']</p>

It does not seem to use the culture i selected from above, but the "default one"..

I need to be able to use a predefined language set in a db, and pretty much have to ignore what the user have it the users accept-language/cookie.. But it seems i cant do anything to make it work, without a pageload or redirect which seems silly?

The above should be the normal way to force the localizer to use a predetermined language, but it seems to ignore it.

(the above is tried directly in the view, but is ignored. I have not tried directly from the controller, but i guess its the same)

I18N - Exception while getting relevant culture file when folders have "." in folder name Ex: "Culture is not supported. (Parameter 'name')\r\n <folderpartname> is an invalid culture identifier."

Hi,

Getting exception while retrieving a localized string using GetString method of IStringLocalizer class. Below is the exception:
Culture is not supported. (Parameter 'name')\r\n <FolderPartName" is an invalid culture identifier.

Root Cause:
This exception occurs when a I18N JSON resource files with format like "localization.en-US.json" is in a folder path which has atleast one folder in the heirarchy with a dot (".") in its name.
This is because filename splitter is assuming that only filenames will have dot in the absolute path. which may not be the case.

Fix:
Fix is to use Path.GetFileName to first get filename from the absolute folder path and then try to retrieve the file culture details from last but one index of filename split array.

Json file missing

Hi. I get this error after using this package with asp.net core 2.2
DirectoryNotFoundException: Could not find a part of the path '\bin\Debug\netcoreapp2.2\json'.
but after I copy manually JSON file to \bin\Debug\netcoreapp2.2\json the error gets fixed.

CultureInfo.CurrentCulture vs CultureInfo.CurrentUICulture

Should the localizer be using CurrentUICulture instead of CurrentCulture by default?

From documentation I've read, it sounds like CurrentUICulture is meant to be used for resource-strings, and CurrentCulture is intended for formatting (numbers, dates, currency, etc.). Microsoft's own implementations of resource-string managers and StringLocalizers also rely on just CurrentUICulture.

However, I've also come across a couple comments that Windows can misrepresent a person's chosen culture with CurrentUICulture (back in 2012 with en-GB at least): see the Question Comments here https://stackoverflow.com/questions/329033/what-is-the-difference-between-currentculture-and-currentuiculture-properties-of#comment-11872860. I'd think that might only be a concern with desktop applications though. Web-apps shouldn't be affected as there'd typically be a culture-provider selecting the relevant culture to use from a request/cookie etc.

Absolute Json Path

Is it possible to set the Resource path as an absolute address instead of one relative to the project folder?

[Discussion] Better BaseName matching

I think to completely support BaseName matching in JsonStringLocalizerFactory the Create-Method with a Type as input parameter should be changed to use the type:

public IStringLocalizer Create(Type resourceSource)
        {
            return this.Create(resourceSource.FullName, string.Empty);
        }

I also tried to get the matching more closely to what is mentioned in the MSDN regarding DataAnnotations localization:

Using the option ResourcesPath = "Resources", the error messages in RegisterViewModel can be stored in either of the following paths:
Resources/ViewModels.Account.RegisterViewModel.fr.resx
Resources/ViewModels/Account/RegisterViewModel.fr.resx

As I need this for my lingualization design but did not want to break the existing functionality, I tried to implement a priorized search for localization files working as you implemented it before when there is a matching folder found. This is the logic:

Search patterns when UseBaseName = true

If UseBaseName is set to true, it will be searched for lingualization files by the following order - skipping the options below if any option before matches.

  • If you use a non-typed IStringLocalizer all files in the Resources-directory, including all subdirectories, will be used to find a localization. This can cause unpredictable behavior if the same key is used in multiple files.

  • If you use a typed localizer, the following applies - Namespace is the "short namespace" without the root namespace:

    • If there is a folder named "Your/Namespace/And/Classname", all contents of this folder will be used.
    • If there is a folder named "Your/Namespace" the folder will be searched for all json-files beginning with your classname.
    • Otherwise there will be searched for a json-file starting with "Your.Namespace.And.Classname" in your Resources-folder.

You can see how I implemented it in my latest commit. I also extended the TestSample-Project to reflect the different ways of adding translation files.

The more strict matching from the beginning of this post might be considered as breaking change.

Pluralization -avoir NullPointerException If separator does not exist

Reproduce Step

JSON

{
"Users":{
"Values":{
"en-US": "Users"
}
}
}

C#

Localizer.GetString("Users", true) or Localizer.GetString("Users", false) will throw exception.

This could be avoided by catching or checking if separator exist.
If translation was not implemented with separator, return value.

Improve return for translation not found

Improve the default behavor of IStringLocalizer for translation not found

Cases of Translation not found

  1. The key was not found in localized files
  2. Current language key was not found for looking translation

Proposition

  • For the case 1 : Throw a exception. The key should exist if user try to use it
  • For the case 2 : Throw a warning to advert user that current language does not exist for current and get default language key

Corresponding .json file search with UseBaseName = true is not working for typed localizer

The typed localizer is not working properly - JsonStringLocalizerOfT receives a nullable baseName parameter.

Proposed fix for JsonStringLocalizerOfT:

namespace Askmethat.Aspnet.JsonLocalizer.Localizer
{
    //resource not use, only here to match microsoft interfaces
    internal class JsonStringLocalizerOfT<T> : JsonStringLocalizer, IJsonStringLocalizer<T>, IStringLocalizer<T>
    {
#if NETCORE
         public JsonStringLocalizerOfT(IOptions<JsonLocalizationOptions> localizationOptions, IWebHostEnvironment env, string baseName
 = null) : base(localizationOptions, env, ModifyBaseName())
        {
        }
#else
        public JsonStringLocalizerOfT(IOptions<JsonLocalizationOptions> localizationOptions, IHostingEnvironment env,
            string baseName = null) : base(localizationOptions, env, ModifyBaseName())
        {
        }
#endif

        static string ModifyBaseName()
        {
            return typeof(T).ToString();
        }

    }
}

Using ClearMemCache

I am changing my json file at run time. Then I execute the ClearMemCache method and refresh the view containing the keys. Should the view display the new key values?

AbsolutPath Error

Hi,

if you have your json files stored in an Assembly which (Copy files to Output Directory = true) is used by your maybe Blazor app, you have to set "AbsolutPath=False".
But in the .net core web app the filepath then will be like this:

...bin\\Debug\\netcoreapp3.1\Locales\\localisation.de-DE.json

Then you will get an error "Culture is not supported" because he has found o localization Name like '1\Locales…."

I have view your source Code and there is a Problem in your i18 Class:

`
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);

                }

            }

        }`

Global shared File not working

Shared files are used to avoid duplicating key/values in JSON Files.

Files are working correctly for .shared.files under a base path but not for the one in base path.

How do we set the Default Culture and UI Culture

Can someone help me with setting up the Default Culture and Default UI Culture?

I did try setting the following options at the Startup. cs:

       services.AddJsonLocalization(options =>
       {

           options.SupportedCultureInfos = new HashSet<CultureInfo>()
                   {
                         new CultureInfo("np"),
                         new CultureInfo("en-US")
                   };
           options.DefaultCulture = new CultureInfo("np");
           options.DefaultUICulture = new CultureInfo("np");
           options.CacheDuration = TimeSpan.FromMinutes(15);
           options.ResourcesPath = "Resources";
           options.LocalizationMode = LocalizationMode.I18n;
       });

However, it is always taking the "en-Us" as the default culture resource. Here is the snapshot of the file located on the project:
image

Any help would be much more appreciable.

Thanks

Can't use JsonOptions

i have installed the plugin in my project but i can't refrernce
using Askmethat.Aspnet.JsonLocalizer.JsonOptions;
askmethat

oprions

Please note that i downloaded the repo and i can see the refrence for this working.

Improve translation managemement for multiple files

Currently, same keys in multiple files are not properly managed.
You can have multple times the same key, with the same translation with any merge or control.

Improvement proposition

  • Merge same keys comming from multiple JSON files
  • Throw an exception if identical key have the same language translation ( Two translation for en-US )

GetCultureToUse-Method unclear

I am currently trying to understand the "GetCultureToUse"-method. I understand that it gets the localization from the MemCache which seems to be fine - what I don't understand are the calls to "SetCurrentCultureToCache" - they don't seem to have any effect as at the end of the method SetCurrentCultureToCache(cultureToUse); overrides the other 2 calls. Am I right to assume that only the last call is relevant and the other 2 can be removed? I also think the elsepart can be removed as it was done at the beginning.

        protected void GetCultureToUse(CultureInfo cultureToUse)
        {
            if (!_memCache.TryGetValue(GetCacheKey(cultureToUse), out localization))
            {
                if (_memCache.TryGetValue(GetCacheKey(cultureToUse.Parent), out localization))
                {
                    SetCurrentCultureToCache(cultureToUse.Parent);
                }
                else
                {
                    _memCache.TryGetValue(GetCacheKey(cultureToUse), out localization);
                    SetCurrentCultureToCache(_localizationOptions.Value.DefaultCulture);
                }
            }
            SetCurrentCultureToCache(cultureToUse);
        }

I think this method should do the same:

protected void GetCultureToUse(CultureInfo cultureToUse)
        {
            if (!_memCache.TryGetValue(GetCacheKey(cultureToUse), out localization))
            {
                _memCache.TryGetValue(GetCacheKey(cultureToUse.Parent), out localization));
            }
            SetCurrentCultureToCache(cultureToUse);
        }

Alternate File Configuration

would you add support for an alternate file layout configuration?

example 1
Resources/localization.en-US.json
Resources/localization.fr-FR.json

example 2
Resources/en-US/localization.json
Resources/fr-FR/localization.json

Does the I18N model support hierarchical relationships?

Does the I18N model support hierarchical relationships?
If it is not supported, Put all keys in the same file?

eg:
localization.en-US.json
{
"Page":{
"Title": "title for page"
}
}

localization.zh-CN.json
{
"Page":{
"Title": "标题"
}
}

Improve Caching to be able to use culture Request

Today, all the key values are cached without taking care of the current culture provided (By browser or something else).

The blob key should be enhanced to take the current culture or parent culture.

This should :

  • Improve performance
  • Reduce memory consumption
  • Improve compliance with the Microsoft localizer

Force Invalidation / Refresh of Memory Cache

I would love to see a way to invalidation/refresh the memory cache.

I'm allowing my users to update the localization.json file from an admin screen, and I need the changes to take effect immediately, not at the end of the expiration period.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.