Git Product home page Git Product logo

aspnetcorelocalization's Introduction

Build Localization.SqlLocalizer
.net core Build status NuGet Status

========================

Documentation: http://localizationsqllocalizer.readthedocs.io/en/latest/

NuGet | Issues | Code

Basic Usage ASP.NET Core

Add the NuGet package to the project.csproj file

"dependencies": {
        "Localization.SqlLocalizer": "3.1.0",

Add the DbContext and use the AddSqlLocalization extension method to add the SQL Localization package.

public void ConfigureServices(IServiceCollection services)
{
    // init database for localization
    var sqlConnectionString = Configuration["DbStringLocalizer:ConnectionString"];

    services.AddDbContext<LocalizationModelContext>(options =>
        options.UseSqlite(
            sqlConnectionString,
            b => b.MigrationsAssembly("ImportExportLocalization")
        ),
        ServiceLifetime.Singleton,
        ServiceLifetime.Singleton
    );

    // Requires that LocalizationModelContext is defined
    services.AddSqlLocalization(options => options.UseTypeFullNames = true);

Create your database

dotnet ef migrations add Localization --context localizationModelContext

dotnet ef database update Localization --context localizationModelContext

========================

ASP.NET Core MVC Localization Example

aspnetcorelocalization's People

Contributors

coredx9 avatar damienbod avatar dependabot[bot] avatar jakakonda avatar jeremyeinfeld avatar kurnakovv avatar nehio avatar remibou avatar vitalragaz 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

aspnetcorelocalization's Issues

Issues with RC1

Hello,

I was trying to get localization to work with RC1 but have run into issues with mine as well as your project. It seems to not able to return the resource. When it tries to get the resource "Name" it just returns Name because it is erroring out with the ResourceManagerStringLocalizer. I've tried your project running in VS and Console and still does not return the appropriate resource. I'm not sure what I am missing here.

When I to evaluate in in debug I get this:
?_htmlLocalizer["Name"];
{Name}
Name: "Name"
ResourceNotFound: true
Value: "Name"

Thanks for your help.

Realtime update?

I notice the localize text wasn't shown on the UI every time when I updated the localize text in database. Is this intentional or am I missing something? Is there anyway I can make it to updated in real time?

I am using SQL Server so I have the below instead

services
	.AddDbContext<ApplicationDbContext>(options =>
		options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
	)
	.AddDbContext<LocalizationModelContext>(options => 
		options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
	);

I also created the LocalizationRecords table in my model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApp.Models
{
    public class LocalizationRecords
    {
        public long ID { get; set; }

        public string Key { get; set; }

        public string ResourceKey { get; set; }

        public string Text { get; set; }

        public string LocalizationCulture { get; set; }

        public DateTime UpdatedTimestamp { get; set; }
    }
}

Working with LocalizationModelContext

Hi again @damienbod
I'm curious, how would I work with the underlying DbContext in my app?
Suppose I want to seed localization data at Startup (populating the LocalizationRecords table).
Or maybe I want to create a web console in my app, where I can query the records, do CRUD operations etc.

Thanks in advance ๐ŸŒž

How-to(s): Return per culture JSON / Form Validation / Identity Culture in REST API

Hi Damien,

Is it possible to get all localized strings for a specific culture as a serialized JSON dictionary (like your CSV Export sample in JSON format)?

I want to fetch the JSON localized strings in one go to build my client side UI, and don't get them as a kind of ViewBag/ViewData for each Razor View request.

I would like to set the culture in the REST API Controller through a Culture property I specified the culture as a member of my Identity user (Asp.net Core Identity via HttpContext.User).

I can only find solutions via query string, culture route, or http header. Is that possible?

So what I would like to do is something like that:

[HttpGet]
public async Task Get() {

var user = await userManager.GetUserAsync(user);
var myString = localizer[user.Culture, textKey];

return myString;
}

One question regarding DataAnnotations:

Could you provide one sample with a Razor View that contains a form and a ViewModel with validation texts that shows the multilingual feature ? I could only find the BoxController sample, maybe I think to complicated but I didn't understand how it would work on a form.

Thanks,
Eric

How to force Update resources without restart application ?

Hi,

If we modify the data directly in the database, how to reset the location cache without restarting the application?
Using method " _stringExtendedLocalizerFactory.ResetCache() ", we find that the data has not been updated?

public IActionResult Contact()
        {
            _stringExtendedLocalizerFactory.ResetCache();
            ViewData["Message"] = _homeLocalizerizer["ContactTitle"];

            return View();
        }

Any idea ? Thanks ^_^

WithCulture and GetAllStrings

Hi,
can you fix/add WithCulture and GetAllStrings

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.Localization;

namespace Localization.SqlLocalizer.DbStringLocalizer
{
public class SqlStringLocalizer : IStringLocalizer
{

    private readonly Dictionary<string, string> _localizations;

    private readonly DevelopmentSetup _developmentSetup;
    private readonly string _resourceKey;
    private bool _returnKeyOnlyIfNotFound;
    private bool _createNewRecordWhenLocalisedStringDoesNotExist;

    private CultureInfo _currentCulture;


    public SqlStringLocalizer(Dictionary<string, string> localizations, 
        DevelopmentSetup developmentSetup, 
        string resourceKey, bool returnKeyOnlyIfNotFound, 
        bool createNewRecordWhenLocalisedStringDoesNotExist,
        CultureInfo culture = null)
    {
        _localizations = localizations;
        _developmentSetup = developmentSetup;
        _resourceKey = resourceKey;
        _returnKeyOnlyIfNotFound = returnKeyOnlyIfNotFound;
        _createNewRecordWhenLocalisedStringDoesNotExist = createNewRecordWhenLocalisedStringDoesNotExist;
        _currentCulture = culture;
    }
    public LocalizedString this[string name]
    {
        get
        {
            bool notSucceed;
            var text = GetText(name, out notSucceed);
            
            return new LocalizedString(name, text,notSucceed);
        }
    }

    public LocalizedString this[string name, params object[] arguments]
    {
        get
        {
            return this[name];
        }
    }

    public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
    {
        return _localizations.Select(x => new LocalizedString(x.Key, x.Value));

    }

    public IStringLocalizer WithCulture(CultureInfo culture)
    {
        return new SqlStringLocalizer(_localizations,
         _developmentSetup,
         _resourceKey,  _returnKeyOnlyIfNotFound,
         _createNewRecordWhenLocalisedStringDoesNotExist,
         culture);
    }

    private string GetText(string key,out bool notSucceed)
    {

#if NET451
var _culture = _currentCulture ?? System.Threading.Thread.CurrentThread.CurrentCulture; //var culture = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
#elif NET46
var _culture = _currentCulture ?? System.Threading.Thread.CurrentThread.CurrentCulture; //var culture = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
#else
var _culture = _currentCulture ?? CultureInfo.CurrentCulture; //CultureInfo.CurrentCulture.ToString();
#endif

        string culture = _culture.ToString();

        string computedKey = $"{key}.{culture}";

        string result;
        if (_localizations.TryGetValue(computedKey, out result))
        {
            notSucceed = false;
            return result;
        }
        else
        {
            notSucceed = true;
            if (_createNewRecordWhenLocalisedStringDoesNotExist)
            {
                _developmentSetup.AddNewLocalizedItem(key, culture, _resourceKey);
                _localizations.Add(computedKey, computedKey);
                return computedKey;
            }
            if (_returnKeyOnlyIfNotFound)
            {
                return key;
            }

            return _resourceKey + "." + computedKey;
        }
    }

    

}

}

Problem "The instance of entity type 'LocalizationRecord' cannot be tracked"

Hello,

Thank you very much for your project. it's very interesting :). However, when I run the project the first time I get the error in the screenshot (screen-1.png).

I checked at the database and the row is inserted properly. When I inspect the code, it is if it passes 2 times by the function "_context.LocalizationRecords.Add (localizationRecord);" In the "DevelopmentSetup.cs"

Note that after a second use, the page is displayed correctly.

This problem unfolds each time a new resource is added to the project.

Any help ? Thank you :)

screen-1

Localization of data annotation

Hello,
Thanks for the great project.

However, can you please tell how can we do localization of data annotations using SQL. I have written custom attribute for each of the validation(Like required,compare etc) and I want to implement localization logic in it.

Thanks for the help !

Support for Multi-tenancy ?

Hello there !
Is there any plans to support database-per-tenant for LocalizationModelContext ?

Thanks in advance !

Package Localization.SqlLocalizer 1.0.9 is not compatible with net461 (.NETFramework,Version=v4.6.1). Package Localization.SqlLocalizer 1.0.9 supports: netcoreapp1.1 (.NETCoreApp,Version=v1.1)

Hi Damien,

My Asp.Net Core WebApp must be targeted to full .NET 4.6.1 because several Azure packages , like the Microsoft.Azure.NotificationHubs v.1.0.8 package are currently not available on .NET Core runtime.

Now I wanted to add your Localization.SqlLocalizer v.1.0.9 nuget package but get that error:

Package Localization.SqlLocalizer 1.0.9 is not compatible with net461 (.NETFramework,Version=v4.6.1). Package Localization.SqlLocalizer 1.0.9 supports: netcoreapp1.1 (.NETCoreApp,Version=v1.1)

Is there any way or workaround to get it installed?

thanks
Eric

Exception on GetAllFromDatabaseForResource()

Sometimes, when I start asp core 2.1 app, it throws an exception in method GetAllFromDatabaseForResource() in SqlStringLocalizerFactory class.

A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

Do you have an idea where is problem?
Thank you ;)

Doesn't work on RC2

Hi Damien :godmode:

Came across your repo, cool package and thanks for sharing ๐ŸŽ‰.
However I'm having trouble using this in a RC2 project. Everything's alright except when I try to add and apply the migration. The library code is integrated properly, and everything is set up according to your documentation. Here's the migration error:

warning NU1012: Dependency conflict. Microsoft.EntityFrameworkCore 1.0.0-rc3-21343 expected Microsoft.Extensions.Logging >= 1.0.0-rc3-21343 but go t 1.0.0-rc2-final

And a little more down in the stack trace:
Could not load type 'Microsoft.Extensions.DependencyInjection.ServiceCollectionE xtensions' from assembly 'Microsoft.Extensions.DependencyInjection, Version=1.0. 0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

I think if you rebuild the package on RC2, this issue will be resolved.

Add example for display attribute localization

The runtime doesnโ€™t look up localized strings for non-validation attributes. In the code above, โ€œEmailโ€ (from [Display(Name = "Email")]) will not be localized.

it is really annoying to state a problem in official documentation without telling a solution or a workaround.

Thanks a lot

connectionstring error

For some reason this project cannot run the dotnet ef database update Localization --context localizationModelContext
It gives an error Keyword not supported: 'initial catalog'. or Keyword not supported: 'server' according the connectionstring you use.

"ConnectionString": "Server=(localdb)\mssqllocaldb;Database=LocalizationDb;Trusted_Connection=True;MultipleActiveResultSets=true"

"providerName": "System.Data.SqlClient"

"ConnectionString": "Data Source=(localdb)\mssqllocaldb;Initial Catalog=LocalizationDb;Trusted_Connection=True;MultipleActiveResultSets=true",
"providerName": "System.Data.SqlClient"

Changing table schema

Hi, given the generic names (ExportHistory,ImportHistory) it would be nice to be able to change the schema containing the tables.
I don't know how I should do this, with a short explanation i can send PR.

Localization doesn't work.

Hello!
I have tried your sample, but it seems it is not working.
Localization doesn't work correctly. Only work neutral resource strings.
errorrecourses
Appreciate any help.

Return default value if localization not found

Is there a way we can return the default localization value if the selected one is not available? e.g. if the default culture is en-CA and the client is viewing the site using fr-CA and there is no entry for SharedResource.Phone.fr-CA then return the value for SharedResource.Phone.en-CA. I am creating an app where users can create labels/fields on the site but I don't want to force them to translate to all languages...if they don't provide the other languages then we will just show the default.

Data Annotations - Caching

I'm using ASP.NET Core 2 together with this adaptation of AspNetCoreLocalization. I'm however a bit 'stuck' on resetting the cache for my data annotation translations.

When I reset the cache, everything is updated (global translations (custom) and my resource translations) however, my data annotations refuse to be 'updated', even though they should be used as resource translations (stock behaviour).

const bool useTypeFullNames = false;
const bool useOnlyPropertyNames = false;
const bool returnOnlyKeyIfNotFound = false;
bool createNewRecord = env.IsDevelopment();
            

services.AddDapperLocalization(options => options.UseSettings(
       useTypeFullNames, useOnlyPropertyNames, returnOnlyKeyIfNotFound, createNewRecord
));

services.AddMvc()
       .AddViewLocalization()
       .AddDataAnnotationsLocalization()
       .AddRazorOptions(options => { options.PageViewLocationFormats.Add("/Pages/Partials/{0}.cshtml"); });

Is there any way I can also make the data annotation translations reset cache?

Create ResourceKey, Razor IViewLocalizer example

How shound be format for the ResourceKey field for use inside View (injecting IViewLocalizer) ? I try for example: Views.Home.Index .. not works
Or, in other words โ€“ Can use IViewLocalizer

problems using sql server as database

I'm trying to use sql as a database
Microsoft SQL Server 2017

i created the tables on db

(i used identity instead of
AUTOINCREMENT because it dont work)

i add the connection UseSqlServer

but when i start the application i have the following error
SqlException: The data types text and nvarchar are incompatible in the equal to operator.

Return Key if localization is not found

Hi, Is there anyway to return the key if the localization is not found instead of the searched key?

_localizer["This is a localize text"]

to

This is a localize text

instead of

SharedResource.This is a localize text.en-US

This would be extremely useful in View to have default text which tremendously reduce the database records which has all the default localize text.

Perhaps an options which consist one of the below

services.AddSqlLocalization(options => 
{
	options.ReturnKeyIfNotFound = true,
	options.ReturnSearchKeyIfNotFound = false,
});

When all resx files have culture it does not work

Dear Damien

I read through your post on github asp.net localization and totally agree with you on the stupid empty class etc. I did open my own ticket as it seems it still does not work... With your example I have made a few changes to demonstrate. Please see image for what I did. :)

If you agree with me please add your voice on that post as well. We should stop this localization rookie absurdity.

test

ImproveDataImport

Library should except data imports from mixed items, existing, new and bad items. After the import a details import status should be returned with failed items

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.