Giter Site home page Giter Site logo

gu.localization's Introduction

Gu.Localization.

Join the chat at https://gitter.im/JohanLarsson/Gu.Localization License Build status NuGet NuGet

Contents.

1. Usage in XAML.

The library has a StaticExtension markupextension that is used when translating. The reason for naming it StaticExtension and not TranslateExtension is that Resharper provides intellisense when named StaticExtension Binding the text like below updates the text when Translator.EffectiveCulturechanges enabling runtime selection of language.

The markupextension has ErrorHandling = ErrorHandling.ReturnErrorInfo as default, it encodes errors in the result, see ErrorFormats)

1.1. Bind a localized string.

<Window ...
        xmlns:p="clr-namespace:Gu.Wpf.Localization.Demo.WithResources.Properties"
        xmlns:l="http://gu.se/Localization">
    ...
    <TextBlock Text="{l:Static p:Resources.SomeResource}" />
    <TextBlock Text="{l:Enum ResourceManager={x:Static p:Resources.ResourceManager}, 
                             Member={x:Static local:SomeEnum.SomeMember}}" />    
    ...

The above will show SomeResource in the Translator.EffectiveCulture and update when culture changes.

1.2. Errorhandling.

<Grid l:ErrorHandling.Mode="ReturnErrorInfo"
     ...   >
    ...
    <TextBlock Text="{l:Static p:Resources.SomeResource}" />
    <TextBlock Text="{l:Enum ResourceManager={x:Static p:Resources.ResourceManager}, 
                             Member={x:Static local:SomeEnum.SomeMember}}" />    
    ...

By setting the attached property ErrorHandling.Mode we override how translation errors are handled by the StaticExtension for the child elements.

1.3. EffectiveCulture.

A markupextension for accessing Translator.EffectiveCulture from xaml. Retruns a binding that updates when EffectiveCulture changes.

<Grid numeric:NumericBox.Culture="{l:EffectiveCulture}"
     ...   >
    ...
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Effective culture: " />
            <TextBlock Text="{l:EffectiveCulture}" />
        </StackPanel>    
    ...

2. Usage in code.

2.1. Translator.

2.1.1. Culture.

Get or set the current culture. The default is null Changing culture updates all translations. Setting culture to a culture for which there is no translation throws. Check ContainsCulture() first.

2.1.2. Culture.

Get or set the current culture. The default is null Changing culture updates all translations. Setting culture to a culture for which there is no translation throws. Check ContainsCulture() first.

2.1.3. EffectiveCulture.

Get the culture used in translations. By the following mechanism:

  1. CurrentCulture if not null.
  2. Any Culture in matching by name.
  3. Any Culture in matching by name.
  4. CultureInfo.InvariantCulture When this value changes EffectiveCultureChanged is raised and all translatins updates and notifies.

2.1.4. Cultures.

Get a list with the available cultures. Cultures are found by looking in current directory and scanning for satellite assemblies.

2.1.5. ErrorHandling.

Get or set how errors are handled. The default value is ReturnErrorInfoPreserveNeutral.

2.1.6. Translate.

Translate a key in a ResourceManager.

Use global culture & error handling:

Translator.CurrentCulture = CultureInfo.GetCultureInfo("en"); // no need to set this every time, just for illustration purposes here.
string inEnglish = Translator.Translate(Properties.Resources.ResourceManager,
                                        nameof(Properties.Resources.SomeResource));

2.1.6.1. Translate to neutral culture:

string neutral = Translator.Translate(Properties.Resources.ResourceManager, 
                                      nameof(Properties.Resources.SomeResource), 
                                      CultureInfo.InvariantCulture);

2.1.6.2. Translate to explicit culture:

string inSwedish = Translator.Translate(Properties.Resources.ResourceManager, 
                                        nameof(Properties.Resources.SomeResource), 
                                        CultureInfo.GetCultureInfo("sv"));

2.1.6.3. Override global error handling (throw on error):

Translator.ErrorHandling = ErrorHandling.ReturnErrorInfo; // no need to set this every time, just for illustration purposes here.
string inSwedish = Translator.Translate(Properties.Resources.ResourceManager, 
                                        nameof(Properties.Resources.SomeResource), 
                                        ErrorHandling.Throw);

2.1.6.4. Override global error handling (return info about error):

Translator.ErrorHandling = ErrorHandling.Throw; // no need to set this every time, just for illustration purposes here.
string inSwedish = Translator.Translate(Properties.Resources.ResourceManager, 
                                        nameof(Properties.Resources.SomeResource), 
                                        ErrorHandling.ReturnErrorInfo);

2.1.6.5. Translate with parameter:

Translator.CurrentCulture = CultureInfo.GetCultureInfo("en");
string inSwedish = Translator.Translate(Properties.Resources.ResourceManager, 
                                        nameof(Properties.Resources.SomeResource__0__), 
                                        foo);

2.2. Translator<T>.

Same as translator but used like Translator<Properties.Resources>.Translate(...)

2.3. Translation.

An object with a Translated property that is a string with the value in Translator.EffectiveCulture Implements ÌNotifyPropertyChangedand notifies whenTranslator.EffectiveCulture` changes.

Translation translation = Translation.GetOrCreate(Properties.Resources.ResourceManager, nameof(Properties.Resources.SomeResource))

3. ErrorHandling.

When calling the translate methods an ErrorHandling argument can be provided. If ErrorHandling.ReturnErrorInfo is passed in the method does not throw but returns information about the error in the string. There is also a property Translator.ErrorHandling that sets default behaviour. If an explicit errorhandling is passed in to a method it overrides the global setting.

3.1. Global setting

By setting Translator.Errorhandling the global default is changed.

3.2. ErrorFormats

When ReturnErrorInfo or ReturnErrorInfoPreserveNeutral is used the following formats are used to encode errors.

Error Format
missing key !{key}!
missing culture ~{key}~
missing translation _{key}_
missing resources ?{key}?
invalid format {{"{format}" : {args}}}
unknown error #{key}#

4. Validate.

Conveience API for unit testing localization.

4.1. Translations.

Validate a ResourceManager like this:

TranslationErrors errors = Validate.Translations(Properties.Resources.ResourceManager);
Assert.IsTrue(errors.IsEmpty);

Checks:

  • That all keys has a non null value for all cultures in Translator.AllCultures
  • If the resource is a format string like "First: {0}, second{1}" it checks that.
    • The number of format items are the same for all cultures.
    • That all format strings has format items numbered 0..1..n

4.2. EnumTranslations<T>.

Validate an enum like this:

TranslationErrors errors = Validate.EnumTranslations<DummyEnum>(Properties.Resources.ResourceManager);
Assert.IsTrue(errors.IsEmpty);

Checks:

  • That all enum members has keys in the ResourceManager
  • That all keys has non null value for all cultures in Translator.AllCultures

4.3. TranslationErrors

errors.ToString(" ", Environment.NewLine); Prints a formatted report with the errors found, sample:

Key: EnglishOnly
  Missing for: { de, sv }
Key: Value___0_
  Has format errors, the formats are:
    Value: {0}
    null
    Värde: {0} {1}

4.4. Format

Validate a formatstring like this:

Validate.Format("Value: {0}", 1);
Debug.Assert(Validate.IsValidFormat("Value: {0}", 1), "Invalid format...");

5. FormatString.

Conveience API for testing formatstrings.

5.1. IsFormatString

Returns true if the string contains placeholders like "Value: {0}" and is a valid format string.

5.2. IsValidFormatString

Returns true if the string contains placeholders like "Value: {0}" that matches the number of parameters and is a valid format string.

6. LanguageSelector

A simple control for changing current language. A few flags are included in the library, many are probably missing.

6.1. AutogenerateLanguages

Default is false. If true it popolates itself with Translator.Cultures in the running application and picks the default flag or null.

<l:LanguageSelector AutogenerateLanguages="True" />

6.2. Explicit languages.

<l:LanguageSelector>
    <l:Language Culture="de-DE"
                FlagSource="pack://application:,,,/Gu.Wpf.Localization;component/Flags/de.png" />
    <l:Language Culture="en-GB"
                FlagSource="pack://application:,,,/Gu.Wpf.Localization;component/Flags/en.png" />                
    <l:Language Culture="sv-SE"
                FlagSource="pack://application:,,,/Gu.Wpf.Localization;component/Flags/sv.png" />
</l:LanguageSelector>

screenie

gu.localization's People

Contributors

johanlarsson avatar echterago avatar gitter-badger avatar

Watchers

James Cloos avatar 疯风愚雨 avatar

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.