Coder Social home page Coder Social logo

forevolve.aspnetcore.localization's Introduction

ForEvolve.AspNetCore.Localization

Build, Test, and Deploy feedz.io NuGet.org

The ForEvolve.AspNetCore.Localization package allows you to enable localization of Asp.Net Core 2.1+ applications in one line of code. Moreover, it translates System.ComponentModel.DataAnnotations.ValidationAttributes automagically, without the need to specify any string or error message (like the [Required] attribute).

Twitter Follow GitHub Sponsor PayPal Me

Supported languages:

Supported attributes

  • CompareAttribute
  • EmailAddressAttribute
  • RequiredAttribute
  • CreditCardAttribute
  • FileExtensionsAttribute
  • MaxLengthAttribute
  • MinLengthAttribute
  • PhoneAttribute
  • RangeAttribute
  • RegularExpressionAttribute
  • UrlAttribute
  • StringLengthAttribute (see StringLengthLocalizationValidationAttributeAdapter.cs)

You can also create and register your own adapters and attributes like normal.

Versioning

The packages follows semantic versioning and uses Nerdbank.GitVersioning to automatically version packages based on git commits/hashes.

NuGet (Release)

You can:

Install-Package ForEvolve.AspNetCore.Localization

or

dotnet add package ForEvolve.AspNetCore.Localization

or take a look at https://www.nuget.org/packages/ForEvolve.AspNetCore.Localization/.

CI builds

PR builds are pushed to feedz.io before getting released to NuGet, thanks to their Open Source subscription.

The NuGet v3 URL is: https://f.feedz.io/forevolve/localization/nuget/index.json

How to use

To enable localization for everything, including data annotation, you need to:

  1. Add the ForEvolve.AspNetCore.Localization NuGet package to your project.
  2. In Startup.cs, AddForEvolveLocalization() and optionally UseRequestLocalization() (see below).
  3. Run your application
public void ConfigureServices(IServiceCollection services)
{
    // MVC (2.1)
    services
        .AddMvc()
        .AddForEvolveLocalization()
    ;

    // MVC (3+)
    services
        .AddRazorPages() // or other part of MVC that returns an IMvcBuilder
        .AddForEvolveLocalization()
    ;
}

public void Configure(IApplicationBuilder app)
{
    // (optional)
    // Adds the Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware to automatically
    // set culture information for requests based on information provided by the client.
    app.UseRequestLocalization();

    //...
}

As you can see, it took only one line of code to enable localization, and another line to automatically set the culture information for requests using RequestLocalizationMiddleware.

IMvcBuilder.AddForEvolveLocalization(); adds all necessary services to the DI container. It calls IServiceCollection.AddLocalization(...), set the default ResourcesPath to "Resources", registers the ILocalizationValidationMetadataProvider (which does the validation attributes localization magic), and calls both IMvcBuilder.AddViewLocalization() and IMvcBuilder.AddDataAnnotationsLocalization().

If you don't want IMvcBuilder.AddViewLocalization() or IMvcBuilder.AddDataAnnotationsLocalization() to be called, you can opt-out by using an overload of IMvcBuilderAddForEvolveLocalization(), like that:

services
    .AddRazorPages() // or other part of MVC that returns an IMvcBuilder
    .AddForEvolveLocalization(
        enableViewLocalization: false,
        enableDataAnnotationsLocalization: false
    )
;

Migrating to 3.0

If you want to change any Asp.Net-related options, you can Configure them or implements IConfigureOptions<TOptions> classes as you would normally do. In 3.0 all options has been removed, so no need to learn how the library work, you must use Asp.Net options directly. See the Change log for more info.

If you built custom ILocalizationValidationAttributeAdapter, just register them with the DI container, like:

services.AddSingleton<ILocalizationValidationAttributeAdapter, MyAdapter>()

For any other use-case that I may have forgotten, please open an issue.

How to contribute a translation

Since I only know French and English, I can't translate messages into more languages, so contributions are very welcome.

I built a small tool to help find the culture-neutral and culture-specifics CultureInfo about a language; please make sure that your translation covers the culture-neutral CultureInfo before creating a culture-specific one.

How to submit a new translation:

  1. Fork the repo
  2. Create a resource file for the language you want to translate error messages into.
  3. Translate it (obviously)
  4. Add the new language to the _supportedCultures array in SupportedCulturesCollection.cs.
  5. Add the new language to the Supported languages section of the README.md file with a "thanks to you" attribution and a link.
  6. Open a pull request

Since I don't speak all languages, I cannot validate those that I don't know (except maybe by using Google Translate), so it's up to you to makes things right! (or PR corrections)

I will do my best to integrates PR as fast as possible.

Where are the error messages located?

If you look under src/ForEvolve.AspNetCore.Localization/Resources/, you will find DataAnnotationSharedResource.resx and DataAnnotationSharedResource.{lang}.resx files. You can copy any one of those and translate the values.

If you want to create a culture-specific translation, example: fr-CA, please make sure that there is an fr translation (neutral culture) first which will be the default for that language.

Example:

  • First we need a DataAnnotationSharedResource.fr.resx file (already there).
  • Then we could add DataAnnotationSharedResource.fr-CA.resx, DataAnnotationSharedResource.fr-FR.resx, etc.

Error messages

I modified default error messages a little to make them more linear. Sometimes it was written The field {0} ... and sometimes it was The {0} field .... I decided to normalize messages to The {0} field ....

I am open to suggestion if you think this makes no sense. English is only my secondary language.

Error messages source (if you want the original error messages): corefx/src/System.ComponentModel.Annotations/src/Resources/Strings.resx

The history of the project

I created this project because I did not want to code something similar to this every single time I start a new Asp.Net Core application. I did not want to write an error message on every ValidationAttribute either (which seems to be the official solution).

To be honest, I was a little disappointed to see how hard it is to localize Asp.Net Core validation attributes. This should be trivial.

Don't get me wrong here; I don't want to criticize the design made by the team that built that system. I can only assume that there are some good reasons behind these design choices (technical or not).

That said, the other parts of the localization pipeline of Asp.Net Core are pretty neat with IStringLocalizer, IHtmlLocalizer and IViewLocalizer.

How to contribute?

If you have ideas, requests or find bugs, please open an issue. If you want to contributes some code, other than translating error messages, please open an issue first so you don't waste your time.

For more information, please read Contributing to ForEvolve open source projects.

Contributor Covenant Code of Conduct

Also, please read the Contributor Covenant Code of Conduct that applies to all ForEvolve repositories.

Change log

3.0.0

  • Remove the need to call IServiceCollection.AddForEvolveLocalization() (see #27)
  • Rename IMvcBuilder.AddForEvolveMvcLocalization() to IMvcBuilder.AddForEvolveLocalization()
  • Leverage the options patterns to configure Asp.Net instead of custom options. Due to that, ForEvolveLocalizationOptions and ForEvolveMvcDefaultLocalizationAdapterOptions has been deleted.
  • Internally leveraging DI more to simplify the initialization process (no more newing volatile dependencies).
  • IApplicationBuilder.UseForEvolveRequestLocalization() is now obsolete, use IApplicationBuilder.UseRequestLocalization() instead.
  • Use Nerdbank.GitVersioning to manage versions automagically.
  • Move builds from Azure DevOps to GitHub Actions so PR can be made to the CI/CD pipeline.
  • You can now use ISupportedCulturesCollection to access the list of supported CultureInfo.

2.2.0

  • Add Polish (pl)

2.1.0

  • Add Chinese (zh)
  • Add Chinese (Traditional) (zh-Hant)
  • Add Chinese (Traditional, Taiwan) (zh-TW)

2.0.0

  • Update MetadataProvider so DataTypeAttribute gets the translation; Fix #21
  • Add functional tests that are covering most scenarios, related to error messages; closing #1
  • Add functional tests that are covering French translation; related to #5. This should ensure that further breaking changes in the Asp.Net Core repo would be detected automatically by the CI pipeline.

Possible/Known issues

  • User-specified ErrorMessage on DataTypeAttribute might (will most likely) get overridden by ForEvolve.AspNetCore.Localization.

1.3.0

  • Add Norwegian (bokmål) (nb) and Norwegian (bokmål) (no)

1.2.0

  • Add Spanish (es)

1.1.0

  • Add Portuguese (pt) and Brazilian portuguese (pt-BR)

1.0.0

  • Initial French (fr) and English (en)
  • Contributed Hebrew (he)

forevolve.aspnetcore.localization's People

Contributors

aboyaniv avatar belangervince avatar carl-hugo avatar fairking avatar jayskyworker avatar matheusavi avatar oswaldodg avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

forevolve.aspnetcore.localization's Issues

Write some tests for StartupExtensions

The code from src/ForEvolve.AspNetCore.Localization/StartupExtensions.cs is not tested.
See also tests placeholder in file test/ForEvolve.AspNetCore.Localization.Tests/ForEvolveLocalizationStartupExtensionsTest.cs

Write some tests for translations and resources

The texts of the resources should be tested to make sure that all translations contain all key/value pairs. The message itself does not need to be tested.

  • Create a test case per message
  • The language should be parameterizable
  • The test cases should be run one per language

If it is too complicated to create these use cases as unit tests, the creation of integration tests will do.

Upgrade projects to Core 3.1

Is your feature request related to a problem? Please describe.
Using Core 2.1 project with a 3.1 project triggers the following warning
Warning AD0001 Analyzer 'Microsoft.AspNetCore.Mvc.Analyzers.TopLevelParameterNameAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'.

I tried to install FxCop analyzers and Microsoft Analyzers nugets, but seems it's kind of a normal behavior that Microsoft won't fix. It happens when 2.x and 3.x are used in same project.

Describe the solution you'd like
Upgrade every projects in solution to Core 3.1 and republish a newer Nuget version for Core 3.1

Describe alternatives you've considered
I tried to upgrade the projects myself but could not transform the tests - ModelAttributes is deprecated in 3.1 and could not find a workaround or a rewrite strategy.

Additional context
No more request that this on. Your project is really great! I'm using it in french for validation errors and also for models resources in /Resources. Thank you!

Add ForEvolve.AspNetCore.Localization to the ForEvolve metapackage & configure CI/CD

Add ForEvolve.AspNetCore.Localization to the ForEvolve meta-package

  1. A push to master should trigger an automatic build and deploy the ForEvolve.AspNetCore.Localization package to MyGet
  2. A successful build should trigger the meta-package to build

Other info:

  • The ForEvolve meta-package should target multiple frameworks: netstandard1.6 and netcoreapp2.0
  • ForEvolve.AspNetCore.Localization should only be added for the target netcoreapp2.0

Release 3.0

Move versioning to Nerdbank.GitVersioning:

Move builds from Azure DevOps to GitHub Actions:

  • Create a feedz.io feed
  • Create the GitHub Actions build
    • Deploy PRs to Feedz.io
    • Deploy pushes to master to NuGet
  • Delete Azure DevOps Pipeline

Others:

  • Remove the second AddForEvolveMvcLocalization() call #27
  • Refactor ForEvolveLocalizationOptions to leverage the Asp.Net Core options patterns
  • Update README.md with relevant examples
  • Add support to SourceLink

Most data annotation attributes won't get their correct error messages

Describe the bug
From what I have tested, only the MaxLengthAttribute gets its correct translation.

To Reproduce

  1. Force French localization.
  2. Create a model with PhoneAttribute, EmailAttribute or CreditCardAttribute.
  3. Create a view for that model.
  4. Post a form that will fail.

Expected behavior
Should be getting messages in French.

Screenshots
Annotation 2019-03-29 171143

My app is using .NET Core 2.2 and I am using version 1.3.1 of ForEvolveAspNetCore.Localization

Support for non mvc web apis

I have used this package to get language specific validation messages in dotnet core web apis. The client is usually a SPA on a separate js-framework app running on a separate domain. We expose the messages from ForEvolve on a custom property on an extended ProblemDetails object. This is handled by error handler middleware.

Dotnet core 3 does not use mvc anymore for these kinds of projects, so we are back to basic error messages provided by Microsoft.

I would love a general approach or custom extension for this use case. Something not scoped to mvc.

As a consumer something that looks something like this:
services.AddForEvolveLocalization(): in place of services.AddMvc().AddForEvolveMvcLocalization();

Would love to know if there are any plans for anything like this?

Remove v3.0 obsolete members in 4.0

From StartupExtensions.cs, remove:

  • public static IServiceCollection AddForEvolveLocalization(this IServiceCollection services)
  • public static IServiceCollection AddForEvolveLocalization(this IServiceCollection services, Action<object> setupAction)
  • public static IMvcBuilder AddForEvolveMvcLocalization(this IMvcBuilder mvcBuilder)
  • public static IApplicationBuilder UseForEvolveRequestLocalization(this IApplicationBuilder app)

Add support for automatic registering of RequestLocalizationOptions

Add support for automatic registering of RequestLocalizationOptions.

  • RequestLocalizationOptions should be added to the IServiceCollection automatically.
  • SupportedCultures and SupportedUICultures should be automatically populated by default values (all translations).
  • DefaultRequestCulture should be defaulted to new RequestCulture(culture: "en", uiCulture: "en").
  • SupportedCultures, SupportedUICultures and DefaultRequestCulture should be parametrable.
  • Users should be able to opt-out of this with a simple bool like EnableConfigureRequestLocalizationOptions = false.

Create a sample projet

Create a sample projet that show how to use the library.
Back the sample by an article?

Remove the second `AddForEvolveMvcLocalization()` call

Remove the IServiceCollection.AddForEvolveMvcLocalization() extension method and merge its content in the IMvcBuilder.AddForEvolveLocalization() instead. Use the "configure options" methods to configure the pipeline.

This change should lead to a leaner experience, but is also a breaking change so:

  • Flag IServiceCollection's extensions as [obsolete]
  • Bump the major version to 3 (see #32)
  • Remove the IMvcBuilder's extensions in 4.0 (create issue + milestone: #31)
  • Update README

Implement this at the same time as #26

User-specified `ErrorMessage` on `DataTypeAttribute` will most likely get overridden

Additional context

  1. Is this even a use-case worth fixing since specifying a custom ErrorMessage would defy the idea behind localizing error message?
  2. This should be validated.

Describe the bug
User-specified ErrorMessage on DataTypeAttribute might (will most likely) get overridden by ForEvolve.AspNetCore.Localization.

To Reproduce
Steps to reproduce the behavior:

  1. Create a model with any DataTypeAttribute decorating a property.
  2. Set a custom ErrorMessage
  3. Display it somewhere and load that page.
  4. The default ForEvolve.AspNetCore.Localization message would most likely be displayed.

Expected behavior
The user-specified ErrorMessage should be displayed.

Create `IApplicationBuilder`extensions methods

Create an UseForEvolveRequestLocalization extension method that automatically register RequestLocalizationOptions.

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

Create a strategy that is using MVC routes to set language

It should be easy to create an application with URL looking like: /en-US/whatever/else/here that gets localized automatically.

The strategy should be enabled by default and should be easy to opt-out.


First, take a look at the existing providers: Globalization and localization in ASP.NET Core | Implement a strategy to select the language/culture for each request and their implementations.


See also RouteDataRequestCultureProvider.cs to see if that could do the trick (maybe with this and adding a route).

Write some documentation

  • Update the Toc project to include the ForEvolve.AspNetCore.Localization project
  • Update the README to include some description and examples
  • Write some XML documentation for Startup Extensions so users knows what to expect of each methods

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.