• 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

    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"
    

    Printing localization template

    Message descriptions can be printed into a template file, which can be used as a localization file template for translations to other languages.

    IMessageDescriptions can be scanned from dependency injection.

    // Service collection
    IServiceCollection serviceCollection = new ServiceCollection()
        .AddSingleton<StatusCodes>(StatusCodes.Instance);
    
    // Service provider
    using var services = serviceCollection.BuildServiceProvider();
    
    // Get all message description tables in dependency injection
    IEnumerable<IMessageDescriptions> list = serviceCollection
        .Where(sd => sd.ServiceType.IsAssignableTo(typeof(IMessageDescriptions)))
        .Select(sd => (IMessageDescriptions)services.GetService(sd.ServiceType)!);
    

    .ToYamlText() and .ToYamlNode() prints IMessageDescriptions (Avalanche.Message.Localization.dll) into Yaml text.

    // Print all tables
    WriteLine(list.ToYamlText());
    // Print one table
    WriteLine(list.First().ToYamlText());
    

    .ToYamlFile(filepath) writes to file.

    list.ToYamlFile("template.l.yaml");
    list.First().ToYamlFile("template-statuscodes.l.yaml");
    
    StatusCodes:
      Culture: ''
      TemplateFormat: BraceAlphaNumeric
      Items:
      - Key: Library.BadUnexpected
        Text: "'{object}': Unexpected error"
      - Key: Library.BadArgumentNull
        Text: "'{object}': Unexpected error"
      - Key: Library.GoodResult
        Text: "'{object}': Unexpected error"
    

    On Asp.Net in Program.cs, before "app.Run();"

    // Print localization template
    string localizationTemplate = builder.Services
        .Where(sd => sd.ServiceType.IsAssignableTo(typeof(IMessageDescriptions)))
        .Select(sd => (IMessageDescriptions)app.Services.GetService(sd.ServiceType)!)
        .ToYamlText();
    // Write to console
    System.Console.WriteLine(localizationTemplate);
    

    The following snippet creates a .template.l.yaml when running from IDE in Debug mode. Template can be maintained in source control.

    // Print localization template.l.yaml when running from IDE in Debug
    if (Debugger.IsAttached && MessageDescriptionsPrintingExtensions.TryGetSourcePath(out string sourcePath) && Path.Exists(sourcePath))
    {
        // Derive template file
        string localizationTemplateFilePath = Path.Combine(sourcePath, "template.l.yaml");
        // Write to file
        serviceCollection // 'builder.Services' in Asp.Net
            .Where(sd => sd.ServiceType.IsAssignableTo(typeof(IMessageDescriptions)))
            .Select(sd => (IMessageDescriptions)services.GetService(sd.ServiceType)!) // 'app.Services' in Asp.Net
            .ToYamlFile(localizationTemplateFilePath);
    }
    

    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_index
    {
        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>
            }
    
            {
                // <11>
                // Service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddSingleton<StatusCodes>(StatusCodes.Instance);
    
                // Service provider
                using var services = serviceCollection.BuildServiceProvider();
    
                // Get all message description tables in dependency injection
                IEnumerable<IMessageDescriptions> list = serviceCollection
                    .Where(sd => sd.ServiceType.IsAssignableTo(typeof(IMessageDescriptions)))
                    .Select(sd => (IMessageDescriptions)services.GetService(sd.ServiceType)!);
                // </11>
                // <12>
                // Print all tables
                WriteLine(list.ToYamlText());
                // Print one table
                WriteLine(list.First().ToYamlText());
                // </12>
                // Write to file
                // <13>
                list.ToYamlFile("template.l.yaml");
                list.First().ToYamlFile("template-statuscodes.l.yaml");
                // </13>
                // <14>
                // Print localization template.l.yaml when running from IDE in Debug
                if (Debugger.IsAttached && MessageDescriptionsPrintingExtensions.TryGetSourcePath(out string sourcePath) && Path.Exists(sourcePath))
                {
                    // Derive template file
                    string localizationTemplateFilePath = Path.Combine(sourcePath, "template.l.yaml");
                    // Write to file
                    serviceCollection // 'builder.Services' in Asp.Net
                        .Where(sd => sd.ServiceType.IsAssignableTo(typeof(IMessageDescriptions)))
                        .Select(sd => (IMessageDescriptions)services.GetService(sd.ServiceType)!) // 'app.Services' in Asp.Net
                        .ToYamlFile(localizationTemplateFilePath);
                }
                // </14>
            }
        }
    
        // <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 Copyright © Toni Kalajainen