• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IFieldAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • Dto
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Configuration
      • Introduction
      • Configuration Binding
      • ConfigurationExtensions
      • MemoryConfiguration
      • PrintTree
      • Saving IOptions
      • Yaml
    • Avalanche.Converter
      • Introduction
      • EnumConverter
      • Func<,>
      • HexConverter
      • PrimitiveConverter
      • StringConverter
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IFloatingPointType
      • Dto
        • DtoTarget
        • Class
        • Enum
        • FieldInfo
        • IList<T>
        • IDictionary<K,V>
        • OneOfAttribute
        • StructLayoutAttribute
        • IntermediateTarget
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
        • CustomAttributeUtilities
        • ToStringRequest
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystemBrowse
        • IFileSystemCreateDirectory
        • IFileSystemDelete
        • IFileSystemFileAttribute
        • IFileSystemMount
        • IFileSystemMove
        • IFileSystemObserve
        • IFileSystemOpenStream
        • IFileSystemOpenMemory
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Utilities
        • Dispose
        • FileDictionary
        • FileScanner
        • FilterEnumerable
        • OperationSession
        • PollingFilterWatchToken
        • VisitTree
      • Article
        • Examples
        • PrintTree
    • 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
        • Unicode.CLDR43
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Memory
      • Introduction
      • IMemory<T>
      • BlockMemory<T>
      • FileMemory
      • ListMemory<L, T>
      • MemoryMemory<T>
      • MMFMemory<T>
      • PointerMemory<T>
      • Slice<M, T>
      • StreamMemory
      • Concurrency
        • RWLockedMemory
        • SynchronizedMemory
      • Serialization
        • Benchmarks
        • FixedSize<T>
        • FixedSizeZigZag<T>
        • VariableSized<T>
        • VariableSizedZigZag<T>
        • StringEncoding
      • Articles
        • Fixed-size and Variable-sized
        • IBlockPool<T>
        • Print Tree
        • Read and Write events
        • Stream View
        • Zero Heap
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageDescriptionsBase
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Localization Templates
        • Logging
        • Validation
    • Avalanche.Module
      • Introduction
      • IServiceCollection
      • IServiceBuilder
      • IHostBuilder
      • Dependencies
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • Avalanche.Protobuf
      • Introduction
    • 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
        • IHostBuilder
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • StorageMessages
        • ItfMessages
        • Win32Messages
        • WindowsMessages
        • SspiMessages
        • CertMessages
        • MediaServerMessages
        • SetupApiMessages
        • ScardMessages
        • ComPlusMessages
        • ClrMessages
        • UserModeFilterManagerMessages
        • GraphicsMessages
        • TpmServicesMessages
        • TpmSoftwareMessages
        • PlaMessages
        • FveMessages
        • FwpMessages
        • NdisMessages
        • DltMessages
      • 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
        • ArrayList
        • ArrayUtilities
        • BijectionMap
        • CachedSelect
        • DictionaryAdapter
        • EnumerableExtensions
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • StructList
        • Tuples
        • TupleUtilities
      • 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
        • SharedResource
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • Reflection
        • EnumDescription
      • String
        • IEscaper
        • UnicodeString
        • Hex
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • ITreeNode
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    IMessageDescription Localization

    Avalanche.Message.Localization.dll contains extension methods that help localizing message descriptions. This library requires Avalanche.Localization and Avalanche.Message.

    .Localize(localization, cultureProvider?) localizes the template text of the 'messageDescription'. 'messageDescription' cannot be in read-only state.

    // Create localization
    ILocalization localization = new Localization().AddLine("fi", "NULL.S_OK", "Detect", "Operaatio onnistui");
    // Create message description.
    IMessageDescription ok = new MessageDescription("NULL.S_OK", 0x00000000, "Operation successful").Localize(localization);
    // "Operation successful"
    WriteLine(ok.New().Print(CultureInfo.InvariantCulture));
    // "Operaatio onnistui"
    WriteLine(ok.New().Print(CultureInfo.GetCultureInfo("fi")));
    

    'cultureProvider' can be used to provide default culture externally.

    // Create localization
    ILocalization localization = new Localization().AddLine("fi", "NULL.S_OK", "Detect", "Operaatio onnistui");
    // Create culture provider
    ICultureProvider cultureProvider = new CultureProvider();
    // Create message description.
    IMessageDescription ok = new MessageDescription("NULL.S_OK", 0x00000000, "Operation successful").Localize(localization, cultureProvider);
    // Set language
    cultureProvider.Culture = "en";
    // "Operation successful"
    WriteLine(ok.New().Print());
    // Set language
    cultureProvider.Culture = "fi";
    // "Operaatio onnistui"
    WriteLine(ok.New().Print());
    

    .Localized(localization, cultureProvider?) creates decorated version of 'messageDescription' where text is localized. Can be used with 'messageDescription' that is in read-only state.

    // Create localization
    ILocalization localization = new Localization().AddLine("fi", HResult.S_OK.Key, "Detect", "Operaatio onnistui");
    // Decorate to localize
    IMessageDescription ok = HResult.S_OK.Localized(localization);
    // "Operation successful"
    WriteLine(ok.New().Print(CultureInfo.InvariantCulture));
    // "Operaatio onnistui"
    WriteLine(ok.New().Print(CultureInfo.GetCultureInfo("fi")));
    

    Localization.Default is the default localization singleton that is preconfigured to search localization files under "Resources/" folder.

    // Decorate to localize
    IMessageDescription ok = HResult.S_OK.Localized(Localization.Default);
    

    .LocalizeMessages(localization) can be used to localize entire message description table.

    /// <summary></summary>
    public class StatusCodes : MessageDescriptions
    {
        /// <summary>Base id for datatype codes.</summary>
        public const int BaseCode = 0x20A10000;
        /// <summary>Singleton</summary>
        static Lazy<StatusCodes> instance = new Lazy<StatusCodes>(() => new StatusCodes().ReadSummaryXmls().LocalizeMessages(Localization.Default).SetAllReadOnly<StatusCodes>().SetReadOnly());
        /// <summary>Singleton</summary>
        public static StatusCodes Instance => instance.Value;
    
        /// <summary>Initialize fields</summary>
        public StatusCodes() : base() { this.AddRange(MessageDescriptionsExtensions.FieldReader(this)); }
    
        /// <summary>Create description</summary>
        static IMessageDescription Create(long id, string key, string text) => new MessageDescription($"Library.{key}", id, text).SetHResult(id);
    
        /// <summary>Captured unexpected <see cref="System.Exception"/>.</summary>
        public readonly IMessageDescription BadUnexpected = Create(0xA0A10001, nameof(BadUnexpected), "'{object}': Unexpected error");
        /// <summary>Captured unexpected <see cref="System.Exception"/>.</summary>
        public readonly IMessageDescription BadArgumentNull = Create(0xA0A10002, nameof(BadArgumentNull), "'{object}': Unexpected error");
        /// <summary>Good result.</summary>
        public readonly IMessageDescription GoodResult = Create(0x20A10003, nameof(GoodResult), "'{object}': Unexpected error");
    
    }
    

    Localization can be applied to a new table instance.

    // Create localized message description table
    BasicMessages basicMessages = new BasicMessages()
        .Initialize()
        .LocalizeMessages(Localization.Default)
        .SetAllReadOnly<BasicMessages>()
        .SetReadOnly();
    // Get message description
    IMessageDescription fail = basicMessages.E_FAIL;
    // "Unspecified error"
    WriteLine(fail.New().Print(CultureInfo.InvariantCulture));
    // "Määrittelemätön virhe"
    WriteLine(fail.New().Print(CultureInfo.GetCultureInfo("fi")));
    

    Resources/NULL.l.yaml:

    TemplateFormat: Brace
    PluralRules: Unicode.CLDR
    
    Invariant:
    - Culture: ""
      Items:
      - Key: NULL.S_OK
        Text: "Operation successful"
      - Key: NULL.E_FAIL
        Text: "Unspecified error"
    
    Finnish:
    - Culture: fi
      Items:
      - Key: NULL.S_OK
        Text: "Operatio onnistui"
      - Key: NULL.E_FAIL
        Text: "Määrittelemätön virhe"
    
    /// <summary></summary>
    public class StatusCodes : MessageDescriptions
    {
        /// <summary>Base id for datatype codes.</summary>
        public const int BaseCode = 0x20A10000;
        /// <summary>Singleton</summary>
        static Lazy<StatusCodes> instance = new Lazy<StatusCodes>(() => new StatusCodes().ReadSummaryXmls().LocalizeMessages(Localization.Default).SetAllReadOnly<StatusCodes>().SetReadOnly());
        /// <summary>Singleton</summary>
        public static StatusCodes Instance => instance.Value;
    
        /// <summary>Initialize fields</summary>
        public StatusCodes() : base() { this.AddRange(MessageDescriptionsExtensions.FieldReader(this)); }
    
        /// <summary>Create description</summary>
        static IMessageDescription Create(long id, string key, string text) => new MessageDescription($"Library.{key}", id, text).SetHResult(id);
    
        /// <summary>Captured unexpected <see cref="System.Exception"/>.</summary>
        public readonly IMessageDescription BadUnexpected = Create(0xA0A10001, nameof(BadUnexpected), "'{object}': Unexpected error");
        /// <summary>Captured unexpected <see cref="System.Exception"/>.</summary>
        public readonly IMessageDescription BadArgumentNull = Create(0xA0A10002, nameof(BadArgumentNull), "'{object}': Unexpected error");
        /// <summary>Good result.</summary>
        public readonly IMessageDescription GoodResult = Create(0x20A10003, nameof(GoodResult), "'{object}': Unexpected error");
    
    }
    

    Full Example

    Full example
    using System.Collections.Generic;
    using System;
    using System.Globalization;
    using System.Text;
    using Avalanche.Localization;
    using Avalanche.Message;
    using Avalanche.StatusCode;
    using Avalanche.Template;
    using Avalanche.Utilities;
    using Microsoft.Extensions.DependencyInjection;
    using YamlDotNet.RepresentationModel;
    using static System.Console;
    using static di;
    using System.Diagnostics;
    
    class localization
    {
        public static void Run()
        {
            {
                // <01>
                // Create localization
                ILocalization localization = new Localization().AddLine("fi", "NULL.S_OK", "Detect", "Operaatio onnistui");
                // Create message description.
                IMessageDescription ok = new MessageDescription("NULL.S_OK", 0x00000000, "Operation successful").Localize(localization);
                // "Operation successful"
                WriteLine(ok.New().Print(CultureInfo.InvariantCulture));
                // "Operaatio onnistui"
                WriteLine(ok.New().Print(CultureInfo.GetCultureInfo("fi")));
                // </01>
            }
            {
                // <02>
                // Create localization
                ILocalization localization = new Localization().AddLine("fi", "NULL.S_OK", "Detect", "Operaatio onnistui");
                // Create culture provider
                ICultureProvider cultureProvider = new CultureProvider();
                // Create message description.
                IMessageDescription ok = new MessageDescription("NULL.S_OK", 0x00000000, "Operation successful").Localize(localization, cultureProvider);
                // Set language
                cultureProvider.Culture = "en";
                // "Operation successful"
                WriteLine(ok.New().Print());
                // Set language
                cultureProvider.Culture = "fi";
                // "Operaatio onnistui"
                WriteLine(ok.New().Print());
                // </02>
            }
            {
                // <03>
                // Create localization
                ILocalization localization = new Localization().AddLine("fi", HResult.S_OK.Key, "Detect", "Operaatio onnistui");
                // Decorate to localize
                IMessageDescription ok = HResult.S_OK.Localized(localization);
                // "Operation successful"
                WriteLine(ok.New().Print(CultureInfo.InvariantCulture));
                // "Operaatio onnistui"
                WriteLine(ok.New().Print(CultureInfo.GetCultureInfo("fi")));
                // </03>
            }
            {
                // <04>
                // Decorate to localize
                IMessageDescription ok = HResult.S_OK.Localized(Localization.Default);
                // </04>
            }
            {
                // <05>
                // Create localized message description table
                BasicMessages basicMessages = new BasicMessages()
                    .Initialize()
                    .LocalizeMessages(Localization.Default)
                    .SetAllReadOnly<BasicMessages>()
                    .SetReadOnly();
                // Get message description
                IMessageDescription fail = basicMessages.E_FAIL;
                // "Unspecified error"
                WriteLine(fail.New().Print(CultureInfo.InvariantCulture));
                // "Määrittelemätön virhe"
                WriteLine(fail.New().Print(CultureInfo.GetCultureInfo("fi")));
                // </05>
            }
            {
                // <06>
                // Create localized table
                IMessage msg = StatusCodes.Instance.BadUnexpected.New("obj");
                // </06>
            }
    
        }
    
        // <99>
        /// <summary></summary>
        public class StatusCodes : MessageDescriptions
        {
            /// <summary>Base id for datatype codes.</summary>
            public const int BaseCode = 0x20A10000;
            /// <summary>Singleton</summary>
            static Lazy<StatusCodes> instance = new Lazy<StatusCodes>(() => new StatusCodes().ReadSummaryXmls().LocalizeMessages(Localization.Default).SetAllReadOnly<StatusCodes>().SetReadOnly());
            /// <summary>Singleton</summary>
            public static StatusCodes Instance => instance.Value;
    
            /// <summary>Initialize fields</summary>
            public StatusCodes() : base() { this.AddRange(MessageDescriptionsExtensions.FieldReader(this)); }
    
            /// <summary>Create description</summary>
            static IMessageDescription Create(long id, string key, string text) => new MessageDescription($"Library.{key}", id, text).SetHResult(id);
    
            /// <summary>Captured unexpected <see cref="System.Exception"/>.</summary>
            public readonly IMessageDescription BadUnexpected = Create(0xA0A10001, nameof(BadUnexpected), "'{object}': Unexpected error");
            /// <summary>Captured unexpected <see cref="System.Exception"/>.</summary>
            public readonly IMessageDescription BadArgumentNull = Create(0xA0A10002, nameof(BadArgumentNull), "'{object}': Unexpected error");
            /// <summary>Good result.</summary>
            public readonly IMessageDescription GoodResult = Create(0x20A10003, nameof(GoodResult), "'{object}': Unexpected error");
    
        }
        // </99>
    }
    
    In This Article
    Back to top