GithubHelp home page GithubHelp logo

valdisiljuconoks / localization-provider-core Goto Github PK

View Code? Open in Web Editor NEW
114.0 9.0 23.0 10.27 MB

Database driven localization provider for .NET applications (with administrative management UI)

License: Apache License 2.0

PowerShell 0.63% C# 72.23% CSS 0.44% JavaScript 1.35% HTML 25.35%
adminui localization localization-tool dotnetcore database localizationprovider

localization-provider-core's Introduction

Quality Gate Status

Supporting LocalizationProvider

If you find this library useful, cup of coffee would be awesome! You can support further development of the library via Paypal.

Localization Provider v8.0 IS OUT!

Read more about v8.0 release here.

What is the LocalizationProvider project?

LocalizationProvider project is ASP.NET Core web application localization provider on steroids.

Giving you the main following features:

  • Database-driven localization provider for .Net applications
  • Easy resource registrations via code
  • Supports hierarchical resources (with the help of child classes)

Source Code Repos

The whole package of libraries is split into multiple git repos (with submodule linkage in between). Below is list of all related repositories:

Project Structure

Database localization provider is split into main abstraction projects and .NET Core support project (this).

Getting Started

Bare Minimum to Start With

Below are code fragments that are essential to get started with a localization provider.

Install required packages:

> dotnet add package LocalizationProvider.AspNetCore
> dotnet add package LocalizationProvider.AdminUI.AspNetCore
> dotnet add package LocalizationProvider.Storage.SqlServer

Following service configuration (usually in Startup.cs) is required to get the localization provider working:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // add your authorization provider (asp.net identity, identity server, whichever..)
    
        services
            .AddControllersWithViews()
            .AddMvcLocalization();
    
        services.AddRazorPages();
        services.AddRouting();
    
        services.AddDbLocalizationProvider(_ =>
        {
            _.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            ...
        });
    
        services.AddDbLocalizationProviderAdminUI(_ =>
        {
            ...
        });
    }

    ...
}

And following setup of the application is required as a minimum (also usually located in Startup.cs):

public class Startup
{
    ...

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
    
        app.UseDbLocalizationProvider();
        app.UseDbLocalizationProviderAdminUI();
        app.UseDbLocalizationClientsideProvider(); //assuming that you like also Javascript
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapDbLocalizationAdminUI();
            endpoints.MapDbLocalizationClientsideProvider();
        });
    }
}

You can grab some snippets from this sample Startup.cs file:

using System.Collections.Generic;
using System.Globalization;
using DbLocalizationProvider.AdminUI.AspNetCore;
using DbLocalizationProvider.AdminUI.AspNetCore.Routing;
using DbLocalizationProvider.AspNetCore;
using DbLocalizationProvider.AspNetCore.ClientsideProvider.Routing;
using DbLocalizationProvider.Core.AspNetSample.Data;
using DbLocalizationProvider.Core.AspNetSample.Resources;
using DbLocalizationProvider.Storage.SqlServer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace SampleApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(
                options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services
                .AddDefaultIdentity<IdentityUser>()
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services
                .AddControllersWithViews()
                .AddMvcLocalization();

            services.AddRazorPages();
            services.AddRouting();

            var supportedCultures = new List<CultureInfo> { new CultureInfo("sv"), new CultureInfo("no"), new CultureInfo("en") };

            services.Configure<RequestLocalizationOptions>(opts =>
            {
                opts.DefaultRequestCulture = new RequestCulture("en");
                opts.SupportedCultures = supportedCultures;
                opts.SupportedUICultures = supportedCultures;
            });

            services.AddDbLocalizationProvider(_ =>
            {
                _.EnableInvariantCultureFallback = true;
                _.ScanAllAssemblies = true;
                _.FallbackCultures.Try(supportedCultures);
                _.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            services.AddDbLocalizationProviderAdminUI(_ =>
            {
                _.RootUrl = "/localization-admin";
                _.ShowInvariantCulture = true;
                _.ShowHiddenResources = false;
                _.DefaultView = ResourceListView.Tree;
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
            app.UseRequestLocalization(options.Value);

            app.UseRouting();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseDbLocalizationProvider();
            app.UseDbLocalizationProviderAdminUI();
            app.UseDbLocalizationClientsideProvider();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();

                endpoints.MapDbLocalizationAdminUI();
                endpoints.MapDbLocalizationClientsideProvider();
            });
        }
    }
}

Also, you can refer to sample app in GitHub for some more hints if needed.

More Detailed Help

GitHub Source Code Structure

.NET Core support project has its own repo while main abstraction projects are included as submodules here.

How to Contribute

It's super cool if you read this section and are interesed how to help the library. Forking and playing around sample application is the fastest way to understand how localization provider is working and how to get started.

Forking and cloning repo is first step you do. Keep in mind that provider is split into couple repositories to keep thigns separated. Additional repos are pulled in as submodules. If you Git client does not support automatic checkout of the submodules, just execute this command at the root of the checkout directory:

git clone --recurse-submodules git://github.com/...

Building AdminUI.AspNetCore Project

You will need to run npm install at root of the project to get some of the dependencies downloaded to get started. Some files from these packages are embedded as part of the AdminUI - therefore compilation will fail without those files.

Other Versions

v7.0 is OUT

Please read more in this blog post!

What's new in v6?

Please refer to this post to read more about new features in v6.

More Info

localization-provider-core's People

Contributors

dependabot[bot] avatar mend-bolt-for-github[bot] avatar ruwen avatar snyk-bot avatar surjitbharath-hiddenfoundry avatar valdisiljuconoks 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

localization-provider-core's Issues

Some Errors

Hello,
DbLocalizationProvider.Core.AspNetSample I get an error when I run the project. Is there a live example or a sample project that works with Net.core 3.1 using only SQL
Error_1
Error_2
Error_3

Add web translation function

HI

Is it possible, to add and extra custom step?.
i.e. if it does not find the translation in the db, it runs online through one of the online translations, ie. google. or mymemory
to the get the translation puts it in db for next time.

Admin UI .Net Core 2.2

Hi there,

Does this work with .Net Core 2.2?
I've followed the steps for the admin package and keep getting a 404 error.
How does the database table get created?

Thanks,
David

Check access roles for AdminUI

Null connection string exception when using with AspNet Core 2.2

It appears LanguageEntities class is broken, because it is using _connectionString property in OnConfiguring method, but it is not getting initialized in default constructor which is used pretty much everywhere in DbLocalizationProvider.AspNetCore library.

When I'm using NuGet version I keep getting following error:

ArgumentNullException: Value cannot be null.
Parameter name: connectionString
Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(string value, string parameterName)
Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, string connectionString, Action sqlServerOptionsAction)
DbLocalizationProvider.AspNetCore.LanguageEntities.OnConfiguring(DbContextOptionsBuilder options)
...

CVE-2020-11022 (Medium) detected in jquery-3.4.1.tgz

CVE-2020-11022 - Medium Severity Vulnerability

Vulnerable Library - jquery-3.4.1.tgz

JavaScript library for DOM operations

Library home page: https://registry.npmjs.org/jquery/-/jquery-3.4.1.tgz

Path to dependency file: localization-provider-core/src/DbLocalizationProvider.AdminUI.AspNetCore/package.json

Path to vulnerable library: localization-provider-core/src/DbLocalizationProvider.AdminUI.AspNetCore/node_modules/jquery/package.json

Dependency Hierarchy:

  • โŒ jquery-3.4.1.tgz (Vulnerable Library)

Found in HEAD commit: e89a2797c0c70f1b24cea320b9c44d4a011ddcf9

Found in base branch: master

Vulnerability Details

In jQuery versions greater than or equal to 1.2 and before 3.5.0, passing HTML from untrusted sources - even after sanitizing it - to one of jQuery's DOM manipulation methods (i.e. .html(), .append(), and others) may execute untrusted code. This problem is patched in jQuery 3.5.0.

Publish Date: 2020-04-29

URL: CVE-2020-11022

CVSS 3 Score Details (6.1)

Base Score Metrics:

  • Exploitability Metrics:
    • Attack Vector: Network
    • Attack Complexity: Low
    • Privileges Required: None
    • User Interaction: Required
    • Scope: Changed
  • Impact Metrics:
    • Confidentiality Impact: Low
    • Integrity Impact: Low
    • Availability Impact: None

For more information on CVSS3 Scores, click here.

Suggested Fix

Type: Upgrade version

Origin: https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/

Release Date: 2020-04-29

Fix Resolution: jQuery - 3.5.0


Step up your Open Source Security Game with WhiteSource here

CVE-2020-11023 (Medium) detected in jquery-3.4.1.tgz

CVE-2020-11023 - Medium Severity Vulnerability

Vulnerable Library - jquery-3.4.1.tgz

JavaScript library for DOM operations

Library home page: https://registry.npmjs.org/jquery/-/jquery-3.4.1.tgz

Path to dependency file: localization-provider-core/src/DbLocalizationProvider.AdminUI.AspNetCore/package.json

Path to vulnerable library: localization-provider-core/src/DbLocalizationProvider.AdminUI.AspNetCore/node_modules/jquery/package.json

Dependency Hierarchy:

  • โŒ jquery-3.4.1.tgz (Vulnerable Library)

Found in HEAD commit: e89a2797c0c70f1b24cea320b9c44d4a011ddcf9

Found in base branch: master

Vulnerability Details

In jQuery versions greater than or equal to 1.0.3 and before 3.5.0, passing HTML containing elements from untrusted sources - even after sanitizing it - to one of jQuery's DOM manipulation methods (i.e. .html(), .append(), and others) may execute untrusted code. This problem is patched in jQuery 3.5.0.

Publish Date: 2020-04-29

URL: CVE-2020-11023

CVSS 3 Score Details (6.1)

Base Score Metrics:

  • Exploitability Metrics:
    • Attack Vector: Network
    • Attack Complexity: Low
    • Privileges Required: None
    • User Interaction: Required
    • Scope: Changed
  • Impact Metrics:
    • Confidentiality Impact: Low
    • Integrity Impact: Low
    • Availability Impact: None

For more information on CVSS3 Scores, click here.

Suggested Fix

Type: Upgrade version

Origin: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-11023

Release Date: 2020-04-29

Fix Resolution: jquery - 3.5.0


Step up your Open Source Security Game with WhiteSource here

Exception of type 'System.StackOverflowException' was thrown

Hi,

I'm using your library in my new Asp.Net Core project and I like it so far. However, I have an issue. I have a model class named Projects which uses attribute [LocalizedModel]. Whenever I start debugging I get "The application is in break mode" with the exception "Exception of type 'System.StackOverflowException' was thrown." If I comment out the attribute everything works fine.
I'm using this attribute on other model classes, but without exception. Do you have any suggestions on how to solve this issue, or what could cause this problem?

Thanks in advance.

CVE-2019-10742 (High) detected in axios-0.18.0.tgz

CVE-2019-10742 - High Severity Vulnerability

Vulnerable Library - axios-0.18.0.tgz

Promise based HTTP client for the browser and node.js

Library home page: https://registry.npmjs.org/axios/-/axios-0.18.0.tgz

Path to dependency file: /localization-provider-core/src/DbLocalizationProvider.AdminUI.AspNetCore/package.json

Path to vulnerable library: /localization-provider-core/src/DbLocalizationProvider.AdminUI.AspNetCore/node_modules/axios/package.json

Dependency Hierarchy:

  • โŒ axios-0.18.0.tgz (Vulnerable Library)

Found in HEAD commit: 00a2f13097df92d8ac65b9354cc05b8993ac9659

Vulnerability Details

Axios up to and including 0.18.0 allows attackers to cause a denial of service (application crash) by continuing to accepting content after maxContentLength is exceeded.

Publish Date: 2019-05-07

URL: CVE-2019-10742

CVSS 3 Score Details (7.5)

Base Score Metrics:

  • Exploitability Metrics:
    • Attack Vector: Network
    • Attack Complexity: Low
    • Privileges Required: None
    • User Interaction: None
    • Scope: Unchanged
  • Impact Metrics:
    • Confidentiality Impact: None
    • Integrity Impact: None
    • Availability Impact: High

For more information on CVSS3 Scores, click here.

Suggested Fix

Type: Upgrade version

Origin: axios/axios#1098

Release Date: 2019-05-31

Fix Resolution: 0.19.0


Step up your Open Source Security Game with WhiteSource here

Questions about AdminUI

Hello,

I got a bunch of questions about AdminUI, thanks in advance for answering them.

Tree view

I saw somewhere that there is a nice tree view for translation keys:
image
Is it part of this library? I can't find any configuration switch.

Import/Export

There is a working export to json, but where I can find import?
Is it hidden by some configuration switch?

Fallback to default language

There is configuration cfg.EnableInvariantCultureFallback = true but is there any possiblity to fallback into chosen language?
The workflow is: I as a developer prepare invariant translations, but the client still could rewrite it via default language (en for example). The issue is with other languages if they miss some translation they should fallback to client's rewrite (en) and not to my invariant.

Database

Is database tightly coupled with SQL Server or is there a possibility to use PostgreSQL (etc)?
Is it complicated to expose DbContext and let the developer choose a database provider? (Obviously, only if the library uses EF under the hood)

Empty translation

I found that if the translation is an empty string, it makes it impossible to change (there is no clickable area in the cell). Do you have any idea about a quick fix?

Method not found: 'Npgsql.NpgsqlDataReader Npgsql.NpgsqlCommand.ExecuteReader()'.

Getting error "Method not found: 'Npgsql.NpgsqlDataReader Npgsql.NpgsqlCommand.ExecuteReader()'." on app.UseDbLocalizationProvider(); Looks like it depends on Npgsql client.

image

  • ASP.NET Core 5.0
  • Windows 10

System.MissingMethodException
HResult=0x80131513
Message=Method not found: 'Npgsql.NpgsqlDataReader Npgsql.NpgsqlCommand.ExecuteReader()'.
Source=DbLocalizationProvider.Storage.PostgreSql
StackTrace:
at DbLocalizationProvider.Storage.PostgreSql.SchemaUpdater.EnsureDatabaseSchema()
at DbLocalizationProvider.Storage.PostgreSql.SchemaUpdater.Execute(Command command)
at DbLocalizationProvider.Commands.Internal.CommandHandlerWrapper`1.Execute(ICommand command)
at DbLocalizationProvider.ICommandExtensions.Execute(ICommand command)
at DbLocalizationProvider.Sync.Synchronizer.UpdateStorageSchema()
at DbLocalizationProvider.Sync.Synchronizer.DiscoverReadMerge()
at DbLocalizationProvider.Sync.Synchronizer.SyncResources(Boolean registerResources)
at DbLocalizationProvider.AspNetCore.InitializationExtensions.UseDbLocalizationProvider(IApplicationBuilder builder)
at Ami.Api.Server.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in C:\Users\andriy.somak\Documents\ami\Api.Server\Startup.cs:line 319
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.b__1(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.d__31.MoveNext()

Any way to use this without a db?

I love what you have done in setting up the strongly typed way of working. I was wondering if there is a way to use this, but without EF and a database? So just the basic .NET core localization with resx files but with your approach to strongly typed?

DbLocaliztionProvider is not working in Model ,I am using [LocalizedModel]

Hello Team,

I am using DbLocaliztionProvider and in my Model I am using [LocalizedModel] But it always displays English Value.

It never displays French or German Value for Validation. This problem is Only for Model and Required Field Validation. All other things on website works fine. Any help will be highly appreciated.

Please see my model.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using DbLocalizationProvider;

namespace MyProject.Web.Models
{
[LocalizedModel]
public class FolderVM
{

[Required(ErrorMessage = "Field_Description")]
[StringLength(200)]
public string Description { get; set; }

}
}

ForeignResources and LocalizedDisplayMetadataProvider

Hi,
documentation indicates to use ForeignResources to register types without [LocalizedModel] attribute.
But LocalizedDisplayMetadataProvider not creating Metadata if type hasn't attribute:

if(containerType.GetCustomAttribute<LocalizedModelAttribute>() == null) return;

How to localize ViewModel if class code can't be modified (decorated with attribute)?

No all resources updated

Hello,
I encountered that:
IEnumerable<Assembly> TypeDiscoveryHelper.GetAssemblies(Func<Assembly, bool> assemblyFilter)
does not load all assemblies due to line:
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies();
what cause not all resources are updated.
Loading all assemblies strategy is presented here.
@valdisiljuconoks, do you think @3dave answer on stackoverflow can be applied in library?

AdminUI incorrectly detects error

If server responds with proper JSON but without content-type, error is shown.
Should parse JSON and if it's not valid - show error.

.Net Core 3.0 upgrade, cant find connectionString

I'm in the process of updating to .Net Core 3.0 and I get an error message now that I didn't use to get
System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action1 sqlServerOptionsAction) at DbLocalizationProvider.AspNetCore.LanguageEntities.OnConfiguring(DbContextOptionsBuilder options) at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.get_Model() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityType()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.CheckState() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityQueryable()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.System.Linq.IQueryable.get_Provider() at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Include[TEntity,TProperty](IQueryable1 source, Expression1 navigationPropertyPath) at DbLocalizationProvider.AspNetCore.Queries.GetAllResourcesHandler.Execute(Query query) at DbLocalizationProvider.Queries.Internal.QueryHandlerWrapper2.Execute(IQuery1 message) at DbLocalizationProvider.IQueryExtensions.Execute[TResult](IQuery1 query)
at Tolk.Web.Controllers.api.TextServiceController.SearchText() in

The connectionstring is set like this:
image

and MyDb is found inn appsettings.json, in the connectionString segment. This worked in .netcore2.2

Do you have any tips to what I can try?
Or is this something that is broken by .Net Core 3.0?

Still UseSqlServer in LocalizationProvider.AspNetCore.MySQL

Hi!
I downloaded LocalizationProvider.AspNetCore.MySQL that was jus released.
I provided correct MySQL connection string in AddDbLocalizationProvider

        services.AddDbLocalizationProvider(o=>
        {
            o.Connection = "server=localhost;port=3306;userid=test;Password=test;database=test;sslmode=none;";
            o.EnableInvariantCultureFallback = true;
        });

But I get a System.ArgumentNullException error in app.UseDbLocalizationProvider() and it's clear that EF Core tries to use UseSqlServer instead of UseMySqlServer:

$exception {System.ArgumentNullException: Value cannot be null.
Parameter name: connectionString
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action1 sqlServerOptionsAction) at DbLocalizationProvider.AspNetCore.LanguageEntities.OnConfiguring(DbContextOptionsBuilder options) at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetRelationalService[TService](IInfrastructure1 databaseFacade)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
at DbLocalizationProvider.AspNetCore.IApplicationBuilderExtensions.UseDbLocalizationProvider(IApplicationBuilder builder)
at OMSY.Core.Mvc.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) } System.ArgumentNullException

Annotations doesn't respect language change

Hello,

thanks a lot for the library, it is really nice and helpful.

I've found one issue with translating annotations (validations), it doesn't change after switching language. It is probably cached somewhere.

Code:
image

GUI:
image

Admin GUI (mixed translations together):
image

I've experimented with cfg.ModelMetadataProviders.UseCachedProviders = true/false; but nothing works.
Am I doing something wrong, or is it a bug?

Empty translation

I found that if the translation is an empty string, it makes it impossible to change (there is no clickable area in the cell). Do you have any idea about a quick fix?

Created from #17

CVE-2020-28168 (Medium) detected in axios-0.19.0.tgz

CVE-2020-28168 - Medium Severity Vulnerability

Vulnerable Library - axios-0.19.0.tgz

Promise based HTTP client for the browser and node.js

Library home page: https://registry.npmjs.org/axios/-/axios-0.19.0.tgz

Path to dependency file: localization-provider-core/src/DbLocalizationProvider.AdminUI.AspNetCore/package.json

Path to vulnerable library: localization-provider-core/src/DbLocalizationProvider.AdminUI.AspNetCore/node_modules/axios/package.json

Dependency Hierarchy:

  • โŒ axios-0.19.0.tgz (Vulnerable Library)

Found in base branch: master

Vulnerability Details

Axios NPM package 0.21.0 contains a Server-Side Request Forgery (SSRF) vulnerability where an attacker is able to bypass a proxy by providing a URL that responds with a redirect to a restricted host or IP address.

Publish Date: 2020-11-06

URL: CVE-2020-28168

CVSS 3 Score Details (5.9)

Base Score Metrics:

  • Exploitability Metrics:
    • Attack Vector: Network
    • Attack Complexity: High
    • Privileges Required: None
    • User Interaction: None
    • Scope: Unchanged
  • Impact Metrics:
    • Confidentiality Impact: High
    • Integrity Impact: None
    • Availability Impact: None

For more information on CVSS3 Scores, click here.


Step up your Open Source Security Game with WhiteSource here

Update manualy LocalizationResourceTranslations table

Hi,
I created this resource

    public class Shared
    {
    
        [LocalizedResource]
        public class TestMessageResources
        {
            
            [TranslationForCulture("Messaggio IT", "it")]
            [TranslationForCulture("Message EN", "en")]
            public static string TestMessage => "Default message";
        }
    }

The SQL Server table LocalizationResourceTranslations after apply migration contains values for italian and english language.

Next I created a method in my controller to test this resource and the result it's ok.

[HttpGet("Translate")]
        public IActionResult Translate()
        {
            var msg= _provider.GetString(() => Shared.TestMessageResources.TestMessage);
            return Ok(msg);
        }

After that i manualy changed value about this resource in SQL table but the result it's original value.
Any idea ?

AdminUI not showing

Hi,

I'm new with the project and I like it! I'm trying to implement everything but I don't see the AdminUI. I don't have any strange routes... I tried to set a custom route:

    services.AddDbLocalizationProviderAdminUI(cfg =>
    {
        cfg.RootUrl = "/a/a/a/a";
    });

Is there a way to debug this?

Adding AdminUI to layout

Is there a way to add the AdminUI to say the @RenderBody() call in an existing layout?

Or at the very least, is there a way to add a custom header (moreso than just css styling)?

Thanks!

JQuery err when it was loading

Message=DOMException: Failed to execute 'querySelectorAll' on 'Element': ',:x' is not a valid selector.
Source=
StackTrace:
DOMException: Failed to execute 'querySelectorAll' on 'Element': '
,:x' is not a valid selector.
at c:\tangj15\code\localization\localization-provider-core\tests\dblocalizationprovider.core.aspnetsample\wwwroot\lib\jquery\dist\jquery.js:1242:9
at assert (c:\tangj15\code\localization\localization-provider-core\tests\dblocalizationprovider.core.aspnetsample\wwwroot\lib\jquery\dist\jquery.js:904:13)
at Sizzle.setDocument (c:\tangj15\code\localization\localization-provider-core\tests\dblocalizationprovider.core.aspnetsample\wwwroot\lib\jquery\dist\jquery.js:1222:4)
at c:\tangj15\code\localization\localization-provider-core\tests\dblocalizationprovider.core.aspnetsample\wwwroot\lib\jquery\dist\jquery.js:2619:2
at c:\tangj15\code\localization\localization-provider-core\tests\dblocalizationprovider.core.aspnetsample\wwwroot\lib\jquery\dist\jquery.js:2674:4
at c:\tangj15\code\localization\localization-provider-core\tests\dblocalizationprovider.core.aspnetsample\wwwroot\lib\jquery\dist\jquery.js:34:4
at c:\tangj15\code\localization\localization-provider-core\tests\dblocalizationprovider.core.aspnetsample\wwwroot\lib\jquery\dist\jquery.js:38:3

Issue with Authorisation

I have implemented both DbLocalizationProvider.AspNetCore and DbLocalizationProvider.AdminUI.AspNetCore.

The config all seems fine however no roles are authorised to view the UI.

I'm unable to set the roles using AuthorizedAdminRoles or AuthorizedEditorRoles as the Set is inaccessible, however the documentation says "Sets roles to users.." so I believe it's a bug.

Issue with Localized Model and Display attribute

Hi,

Had situation when LocalizedModel and property with Display attribute e.g.
[LocalizedModel]
public class MyViewModel
{
[Display(Name = "Name")]
public string Name { get; set; }
}

is not translated when
using Html helpers @Html.LabelFor(x => x.Name) or @Html.DisplayFor(x => x.Name)

This worked fine before on .Net Framework.
Could you please verify this.

Thanks.

Access Denied even if user is in role

Hi there, first of all thank you for developing and maintaining this great module. I'm using:

  • ASP.NET Core 3.1
  • Visual Studio 2019
  • LocalizationProvider.AdminUI.AspNetCore 6.2.2
  • LocalizationProvider.AspNetCore 6.2.2
  • LocalizationProvider.Storage.SqlServer 6.2.2
  • Microsoft.Identity.Web 1.1.0
  • Microsoft.Identity.Web.UI 1.1.0

In my Startup.cs, I have the following:

services.AddDbLocalizationProviderAdminUI(x =>
            {
                x.RootUrl = "/core/localization-admin";
                x.ShowInvariantCulture = true;
                x.ShowHiddenResources = true;
                x.DefaultView = ResourceListView.Tree;
                x.HideDeleteButton = false;

                x.AuthorizedAdminRoles.Clear();
                var authorizedAdminRoleName = Configuration.GetSection("LocalizationAdmin").GetValue<string>("LocalizationAdministratorRoleName");
                x.AuthorizedAdminRoles.Add(authorizedAdminRoleName);
            });

The value of authorizedAdminRoleName is "LocalizationAdministrator".

Then, I have the following:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment() || env.IsEnvironment("Localhost"))
            {
                app.UseDeveloperExceptionPage();

                IdentityModelEventSource.ShowPII = true;
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseSerilogRequestLogging(options =>
            {
                options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
                {
                    diagnosticContext.Set("ActivityId", Activity.Current.Id);
                };
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            if (env.IsDevelopment() || env.IsEnvironment("Localhost") || env.IsStaging())
            {
                app.EnsureUserIsInternal();
            }

            if ((env.IsDevelopment() || env.IsStaging() || env.IsProduction()) && !env.IsEnvironment("Localhost"))
            {
                app.UsePathBase("/core");
            }

            app.EnableLocalizationAdminUI();

            var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
            app.UseRequestLocalization(options.Value);

            app.UseDbLocalizationProvider();
            app.UseDbLocalizationProviderAdminUI();
            app.UseDbLocalizationClientsideProvider();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Map}/{action=Index}/{id?}"
                );
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{area=App}/{controller=Map}/{action=Index}"
                );
                endpoints.MapControllerRoute(
                    name: "profile",
                    pattern: "{area=App}/{controller=Profile}/{action=Index}/{id?}"
                );

                endpoints.MapRazorPages();

                endpoints.MapDbLocalizationAdminUI();
                endpoints.MapDbLocalizationClientsideProvider();
            });
        }

The line app.EnableLocalizationAdminUI(); is a middleware that will add the role to a new identity, if the user is internal. We call a user internal if the email address matches our domain name.

I debugged step by step, the user is internal, the role is added in a 2nd identity, but I always get the following logs with Access Denied:

10/09/2020 23:18:39 -07:00 [Information] 			Final outcome - Internal User: True
10/09/2020 23:18:39 -07:00 [Information] Executing endpoint '"/Account/AccessDenied"'
10/09/2020 23:18:39 -07:00 [Information] Route matched with "{page = \"/Account/AccessDenied\", area = \"MicrosoftIdentity\", action = \"\", controller = \"\"}". Executing page "/Account/AccessDenied"
10/09/2020 23:18:39 -07:00 [Information] Executing handler method "Microsoft.Identity.Web.UI.Areas.MicrosoftIdentity.Pages.Account.AccessDeniedModel.OnGet" - ModelState is Valid
10/09/2020 23:18:39 -07:00 [Information] Executed handler method "OnGet", returned result "".
10/09/2020 23:18:39 -07:00 [Information] Executing an implicit handler method - ModelState is Valid
10/09/2020 23:18:39 -07:00 [Information] Executed an implicit handler method, returned result "Microsoft.AspNetCore.Mvc.RazorPages.PageResult".
10/09/2020 23:18:39 -07:00 [Information] Executed page "/Account/AccessDenied" in 16.5592ms
10/09/2020 23:18:39 -07:00 [Information] Executed endpoint '"/Account/AccessDenied"'
10/09/2020 23:18:39 -07:00 [Information] HTTP "GET" "/MicrosoftIdentity/Account/AccessDenied?ReturnUrl=%2Fcore%2Flocalization-admin%2Fapi%2Fservice%2Fgettree" responded 200 in 33.6944 ms|39ab62bf-4d8c88204829c3c9.
10/09/2020 23:18:39 -07:00 [Information] Request finished in 35.3333ms 200 text/html; charset=utf-8

The UI shows a red message: "There was an error while loading resources. Please check logs for more details!"

Until I moved from using Microsoft.AspNetCore.Authentication.AzureADB2C.UI to using Microsoft.Identity.Web.UI everything was working fine.

Any idea what could be wrong?

Problem with resources for ViewModels

Hello,
I found that there's a problem with ViewModels localizations.

It looks that in properties of attriubutes you have to put Resource Keys instead of texts - ASP.NET Core looks these values (from Name or ErrorMessage) as keys to lookup resources.

In your example you are putting actual texts there but this does not work.

WebApi and AddDbLocalizationProviderAdminUI and disable roles

Hi, it's possibile to configure AddDbLocalizationProviderAdminUI to avoid roles definitions ?
In my solution i have one project to manage backend and angular frontend application.
I configured service like

 services.AddDbLocalizationProviderAdminUI(_ =>
            {
                _.RootUrl = "/localization-admin";
                _.AuthorizedAdminRoles.Clear();             
                _.AuthorizedEditorRoles.Clear();                

                _.ShowHiddenResources = false;
                _.DefaultView = ResourceListView.Tree;
                _.HideDeleteButton = false;                
            });

In Configure method I added this code

          app.UseDbLocalizationProvider();
          app.UseDbLocalizationProviderAdminUI();
            using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
            }


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapDbLocalizationAdminUI();
            });

If I try to navigate http://localhost:5001/localization-admin but I receive 404 error.

SQL Server CS collation

Hi,
I'm facing a smal bug when the database is in CS collation, so the field, table names are case sensitive, please take care of it for next release.

Thank you so much,
Max

PS: for ResourceSynchronizer.cs, the below code is good for CS :

                             group =>
                             {
                                 var sb = new StringBuilder();
                                 sb.AppendLine("declare @resourceId int");

                                 var refactoredResources = group.Where(r => !string.IsNullOrEmpty(r.OldResourceKey));
                                 foreach (var refactoredResource in refactoredResources)
                                 {
                                     sb.Append($@"
                                            if exists(select 1 from LocalizationResources with(nolock) where ResourceKey = '{refactoredResource.OldResourceKey}')
                                            begin
                                                update dbo.LocalizationResources set ResourceKey = '{refactoredResource.Key}', FromCode = 1 where ResourceKey = '{refactoredResource.OldResourceKey}'
                                            end
                                            ");
                                 }

                                 foreach (var property in group)
                                 {
                                     var existingResource = allResources.FirstOrDefault(r => r.ResourceKey == property.Key);

                                     if (existingResource == null)
                                     {
                                         sb.Append($@"
                                                        set @resourceId = isnull((select Id from LocalizationResources where [ResourceKey] = '{property.Key}'), -1)
                                                        if (@resourceId = -1)
                                                        begin
                                                            insert into LocalizationResources ([ResourceKey], ModificationDate, Author, FromCode, IsModified, IsHidden)
                                                            values ('{property.Key}', getutcdate(), 'type-scanner', 1, 0, {Convert.ToInt32(property.IsHidden)})
                                                            set @resourceId = SCOPE_IDENTITY()");

                                         // add all translations
                                         foreach (var propertyTranslation in property.Translations)
                                         {
                                             sb.Append($@"
                                                            insert into LocalizationResourceTranslations (ResourceId, [Language], [Value]) values (@resourceId, '{propertyTranslation.Culture}', N'{
                                                                                                               propertyTranslation.Translation.Replace("'", "''")
                                                                                                           }')
                                                        ");
                                         }

                                         sb.Append(@"
                                            end
                                            ");
                                     }

                                     if (existingResource != null)
                                     {
                                         sb.AppendLine($"update LocalizationResources set FromCode = 1, IsHidden = {Convert.ToInt32(property.IsHidden)} where [Id] = {existingResource.Id}");

                                         var invariantTranslation = property.Translations.First(t => t.Culture == string.Empty);
                                         sb.AppendLine($"update LocalizationResourceTranslations set [Value] = N'{invariantTranslation.Translation.Replace("'", "''")}' where ResourceId={existingResource.Id} and [Language]='{invariantTranslation.Culture}'");

                                         if (existingResource.IsModified.HasValue && !existingResource.IsModified.Value)
                                         {
                                             foreach (var propertyTranslation in property.Translations)
                                                 AddTranslationScript(existingResource, sb, propertyTranslation);
                                         }
                                     }
                                 }

                                 using (var conn = new SqlConnection(ConfigurationContext.Current.DbContextConnectionString))
                                 {
                                     var cmd = new SqlCommand(sb.ToString(), conn)
                                     {
                                         CommandTimeout = 60
                                     };

                                     conn.Open();
                                     cmd.ExecuteNonQuery();
                                     conn.Close();
                                 }
                             });`

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.