• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IContentAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IRealType
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystem
          • IFileSystemBrowse
          • IFileSystemCreateDirectory
          • IFileSystemDelete
          • IFileSystemFileAttribute
          • IFileSystemMount
          • IFileSystemMove
          • IFileSystemObserve
          • IFileSystemOpen
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Events
      • Utilities
        • Dispose
        • File Scanner
        • Visit Tree
        • File Operation
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
      • Asp.Net
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Logging
        • Validation
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • ItfMessages
        • Win32Messages
        • ClrMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • Tuples
        • StructList
        • ArrayList
        • BijectionMap
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • EnumerableExtensions
        • TupleUtilities
        • ArrayUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • String
        • IEscaper
        • UnicodeString
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Text Localization

    This article explains the different ways to acquire localized texts.

    .LocalizedTextCached[(culture, key)] gets a text that is localized to specific 'culture' and 'key'.

    // Get text localized to a language
    ILocalizedText text = Localization.Default.LocalizedTextCached[(culture: "en", key: "Namespace.Today")];
    // Print with 'fi' format provider
    string print = text.Print(formatProvider: CultureInfo.GetCultureInfo("fi"), new object[] { DateTime.Now });
    // Write to console
    WriteLine(print); // "Today is 24.3.2022 13.34.07."
    

    .FormatLocalizedTextCached[((culture, formatProvider) key)] gets a text that is localized to specific 'culture', 'format' and 'key'.

    // Get text localized to a language and format provider
    ILocalizedText text = Localization.Default.FormatLocalizedTextCached[((culture: "en", format: CultureInfo.GetCultureInfo("fi")), key: "Namespace.Today")];
    // Print with the pre-assigned format provider ("fi")
    string print = text.Print(formatProvider: null, new object[] { DateTime.Now });
    // Write to console
    WriteLine(print); // "Today is 24.3.2022 13.34.07."
    

    .LocalizableTextCached[key] gets a text that localizes to the language in provided in the 'formatProvider' parameter.

    // Get text
    ILocalizableText localizable = Localization.Default.LocalizableTextCached[key: "Namespace.Today"];
    
    // Get format
    IFormatProvider format = CultureInfo.GetCultureInfo("fi");
    // Print to language indicated by format
    string print = localizable.Print(formatProvider: format, new object[] { DateTime.Now });
    // Write to console
    WriteLine(print); // "Tänään on 24.3.2022 13.34.07."
    
    // Localize to "fi"
    ILocalizedText localized_fi = localizable.Localize("fi")!.Value;
    // Print
    WriteLine(localized_fi.Print(new object[] { DateTime.Now })); // "Tänään on 24.3.2022 13.34.07."
    

    .LocalizingTextCached[key] gets a text that localizes to the language in the assigned 'cultureProvider'.

    // Create cultrue provider
    ICultureProvider cultureProvider = new CultureProvider("en");
    // Get automatically localizing text
    ILocalizingText localizing = Localization.Default.LocalizingTextCached[(cultureProvider, key: "Namespace.Today")];
    // Assign language
    cultureProvider.Culture = "en";
    // Assign format
    cultureProvider.Format = CultureInfo.GetCultureInfo("fi");
    
    // Print to active culture
    string print = localizing.Print(new object[] { DateTime.Now });
    // Write to console
    WriteLine(print); // "Today is 24.3.2022 13.34.07."
    
    // Localize to active culture (culture="en", format="fi")
    ILocalizedText localized = localizing.Value!.Value;
    // Print
    WriteLine(localized.Print(new object[] { DateTime.Now })); // "Today is 24.3.2022 13.34.07."
    

    TextLocalizer(localization, cultureProvider, namespace?) localizes texts with the assigned 'cultureProvider'.

    // Create culture provider
    ICultureProvider cultureProvider = new CultureProvider("en");
    // Create text localizer
    ITextLocalizer textLocalizer = new TextLocalizer(Localization.Default, cultureProvider);
    // Assign language
    cultureProvider.Culture = "en";
    // Assign format
    cultureProvider.Format = CultureInfo.GetCultureInfo("fi");
    // Create localized text
    ILocalizedText text = textLocalizer["Namespace.Today"]!;
    // Print to active culture (culture="en", format="fi")
    string print = text.Print(new object[] { DateTime.Now }); 
    // Write
    WriteLine(print); // "Today is 24.3.2022 13.34.07."
    

    'namespace' can be supplied in constructor to create keys as "namespace.name".

    // Create cultrue provider
    ICultureProvider cultureProvider = new CultureProvider("en");
    // Create text localizer
    ITextLocalizer textLocalizer = new TextLocalizer(Localization.Default, cultureProvider, "Namespace");
    // Assign language
    cultureProvider.Culture = "en";
    // Assign format
    cultureProvider.Format = CultureInfo.GetCultureInfo("fi");
    // Create localized text (culture="en", format="fi")
    ILocalizedText text = textLocalizer["Today"]!;
    // Print to active culture
    string print = text.Print(new object[] { DateTime.Now });
    // Write
    WriteLine(print); // "Today is 24.3.2022 13.34.07."
    
    ILocalizer<T>
    /// <summary>Base interface for localizer.</summary>
    public interface ILocalizer
    {
        /// <summary>Namespace prefix</summary>
        string? Namespace { get; set; }
    
        /// <summary>Resource Type</summary>
        Type ResourceType { get; }
    
        /// <summary>Applicable actice culture provider</summary>
        ICultureProvider CultureProvider { get; set; }
    
        /// <summary>
        /// Get localized resource for <paramref name="name"/>.
        /// 
        /// If <see cref="ILocalizer.Namespace"/> or <paramref name="name"/> is null, then counter part is used as key without separator '.'.
        /// </summary>
        ILocalized? this[string? name] { get; }
    }
    
    /// <summary><typeparamref name="T"/> localizer.</summary>
    /// <typeparam name="T">Resource type</typeparam>
    public interface ILocalizer<out T> : ILocalizer
    {
        /// <summary>
        /// Get localized resource for <paramref name="name"/>. 
        /// 
        /// If <see cref="ILocalizer.Namespace"/> or <paramref name="name"/> is null, then counter part is used as key without separator '.'.
        /// </summary>
        new ILocalized<T>? this[string? name] { get; }
    }
    
    /// <summary><typeparamref name="T"/> for <typeparamref name="Namespace"/>.</summary>
    /// <typeparam name="T">Resource type</typeparam>
    /// <typeparam name="Namespace">Key namespace</typeparam>
    public interface ILocalizer<T, Namespace> : ILocalizer<T> { }
    
    /// <summary><typeparamref name="T"/> localizer for <typeparamref name="Namespace"/> using <typeparamref name="CultureProvider"/>.</summary>
    /// <remarks>This interfaces is typically used with dependency injection.</remarks>
    /// <typeparam name="T">Resource type</typeparam>
    /// <typeparam name="Namespace">Key namespace</typeparam>
    /// <typeparam name="CultureProvider">Culture provider type. Type must have a parameterless constructor.</typeparam>
    public interface ILocalizer<T, Namespace, CultureProvider> : ILocalizer<T, Namespace> where CultureProvider : ICultureProvider { }
    
    ILocalizedText
    /// <summary>Localizable text that can have an assignment into specific culture.</summary>
    public interface ILocalizedText : ILocalizationKeyProvider, ICultureProvider, ITemplatePrintable, ITemplateText, ILocalized
    {
        /// <summary>Choose pluralized version. Each returned variation has same parameter signature.</summary>
        ITemplatePrintable Pluralize(object?[]? arguments);
        /// <summary>Choose pluralized version. Each returned variation has same parameter signature.</summary>
        ITemplateText Pluralize(IFormatProvider? formatProvider, object?[]? arguments);
    }
    
    ILocalizableText
    /// <summary>Localizable text that can be printed in different cultures.</summary>
    public interface ILocalizableText : ILocalizedText, ILocalizable<ILocalizedText> { }
    
    ILocalizingText
    /// <summary>
    /// Localizing text that uses a <see cref="ICultureProvider"/> as a source of assigned culture. 
    /// Localizes to the currently assigned culture when printing without explicitly assigned one.
    /// </summary>
    public interface ILocalizingText : ILocalizedText, ILocalizing<ILocalizedText> { }
    
    ITextLocalizer
    /// <summary>Text localizer</summary>
    public interface ITextLocalizer : ILocalizer<ITemplatePrintable> 
    {
        /// <summary>
        /// Get localized text for key "Namespace.Name".
        /// 
        /// If <see cref="ILocalizer.Namespace"/> or <paramref name="name"/> is null, then counter part is used as key without separator '.'.
        /// </summary>
        new ILocalizedText? this[string? name] { get; }
    }
    /// <summary>Text localizer</summary>
    public interface ITextLocalizer<Namespace> : ITextLocalizer, ILocalizer<ITemplatePrintable, Namespace> { }
    /// <summary>Text localizer</summary>
    public interface ITextLocalizer<Namespace, CultureProvider> : ITextLocalizer<Namespace>, ILocalizer<ITemplatePrintable, Namespace, CultureProvider> where CultureProvider : ICultureProvider { }
    

    Full Example

    Full example
    using System.Globalization;
    using Avalanche.Localization;
    using static System.Console;
    
    class textlocalization
    {
        public static void Run()
        {
            {
                // <01>
                // Get text localized to a language
                ILocalizedText text = Localization.Default.LocalizedTextCached[(culture: "en", key: "Namespace.Today")];
                // Print with 'fi' format provider
                string print = text.Print(formatProvider: CultureInfo.GetCultureInfo("fi"), new object[] { DateTime.Now });
                // Write to console
                WriteLine(print); // "Today is 24.3.2022 13.34.07."
                // </01>
            }
            {
                // <02>
                // Get text localized to a language and format provider
                ILocalizedText text = Localization.Default.FormatLocalizedTextCached[((culture: "en", format: CultureInfo.GetCultureInfo("fi")), key: "Namespace.Today")];
                // Print with the pre-assigned format provider ("fi")
                string print = text.Print(formatProvider: null, new object[] { DateTime.Now });
                // Write to console
                WriteLine(print); // "Today is 24.3.2022 13.34.07."
                // </02>
            }
            {
                // <03> 
                // Get text
                ILocalizableText localizable = Localization.Default.LocalizableTextCached[key: "Namespace.Today"];
    
                // Get format
                IFormatProvider format = CultureInfo.GetCultureInfo("fi");
                // Print to language indicated by format
                string print = localizable.Print(formatProvider: format, new object[] { DateTime.Now });
                // Write to console
                WriteLine(print); // "Tänään on 24.3.2022 13.34.07."
    
                // Localize to "fi"
                ILocalizedText localized_fi = localizable.Localize("fi")!.Value;
                // Print
                WriteLine(localized_fi.Print(new object[] { DateTime.Now })); // "Tänään on 24.3.2022 13.34.07."
                // </03>
            }
            {
                // <04>
                // Create cultrue provider
                ICultureProvider cultureProvider = new CultureProvider("en");
                // Get automatically localizing text
                ILocalizingText localizing = Localization.Default.LocalizingTextCached[(cultureProvider, key: "Namespace.Today")];
                // Assign language
                cultureProvider.Culture = "en";
                // Assign format
                cultureProvider.Format = CultureInfo.GetCultureInfo("fi");
    
                // Print to active culture
                string print = localizing.Print(new object[] { DateTime.Now });
                // Write to console
                WriteLine(print); // "Today is 24.3.2022 13.34.07."
    
                // Localize to active culture (culture="en", format="fi")
                ILocalizedText localized = localizing.Value!.Value;
                // Print
                WriteLine(localized.Print(new object[] { DateTime.Now })); // "Today is 24.3.2022 13.34.07."
                // </04>
            }
            {
                // <05>
                // Create culture provider
                ICultureProvider cultureProvider = new CultureProvider("en");
                // Create text localizer
                ITextLocalizer textLocalizer = new TextLocalizer(Localization.Default, cultureProvider);
                // Assign language
                cultureProvider.Culture = "en";
                // Assign format
                cultureProvider.Format = CultureInfo.GetCultureInfo("fi");
                // Create localized text
                ILocalizedText text = textLocalizer["Namespace.Today"]!;
                // Print to active culture (culture="en", format="fi")
                string print = text.Print(new object[] { DateTime.Now }); 
                // Write
                WriteLine(print); // "Today is 24.3.2022 13.34.07."
                // </05>
            }
            {
                // <06>
                // Create cultrue provider
                ICultureProvider cultureProvider = new CultureProvider("en");
                // Create text localizer
                ITextLocalizer textLocalizer = new TextLocalizer(Localization.Default, cultureProvider, "Namespace");
                // Assign language
                cultureProvider.Culture = "en";
                // Assign format
                cultureProvider.Format = CultureInfo.GetCultureInfo("fi");
                // Create localized text (culture="en", format="fi")
                ILocalizedText text = textLocalizer["Today"]!;
                // Print to active culture
                string print = text.Print(new object[] { DateTime.Now });
                // Write
                WriteLine(print); // "Today is 24.3.2022 13.34.07."
                // </06>
            }
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen