• 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

    Localization errors

    ILocalizationError holds localization error information such as parse error.

    /// <summary>Localization error</summary>
    public interface ILocalizationError
    {
        /// <summary>Key</summary>
        string Key { get; set; }
        /// <summary>Culture</summary>
        string Culture { get; set; }
        /// <summary>Error message</summary>
        string Message { get; set; }
        /// <summary>The text span where the error occurs. Can have reference to source file, line, column, and position index.</summary>
        MarkedText Text { get; set; }
        /// <summary>Error code, see <see cref="LocalizationMessageIds"/>.</summary>
        int Code { get; set; }
    }
    

    ILocalizationErrorHandler processes errors.

    /// <summary></summary>
    public interface ILocalizationErrorHandler
    {
        /// <summary></summary>
        void Handle(ILocalizationError error);
    }
    

    ILocalizedText.Errors holds related parse and file read errors.

    // File reader
    var lines = new LocalizationReaderYaml.File(@"localizationerror\error.l.yaml");
    // Create line database
    LocalizationLines db = new LocalizationLines().AddLines(lines);
    // Create provider
    var localizedTextProvider = new LocalizedTextProvider(db.Query, LocalizationLinesInfoProvider.Cached);
    // Get localization text
    ILocalizedText localizedText = localizedTextProvider[("en", "Namespace.CatsDogs")];
    // Print parse errors
    foreach (ILocalizationError error in localizedText.Errors)
        WriteLine(error);
    
    # Error case: Text malformed
    TemplateFormat: BraceAlphaNumeric
    PluralRules: Unicode.CLDR41
    
    English:
    - Culture: en
      Items:
      - Key: Namespace.CatsDogs
        Text: "{cats} cats and {dogs dogs"
    #      Malformed text here ^^^^^
    
    Malformed Text="{cats} cats and {dogs dogs" en Namespace.CatsDogs localizationfile\error.l.yaml [Ln 9, Col 27, Ix 174 - Ln 9, Col 28, Ix 175]

    ILocalizationError contains code, source filename, line, column, key, culture. Note that, .l.json parser does not supply line and column information.

    WriteLine(error.Code);
    WriteLine(error.Message);
    WriteLine(error.Key);
    WriteLine(error.Culture);
    WriteLine(error.Text.Position.FileName);
    WriteLine(error.Text.Position.Start.Line);
    WriteLine(error.Text.Position.Start.Column);
    WriteLine(error.Text.Position.End.Line);
    WriteLine(error.Text.Position.End.Column);
    

    Action<ILocalizationError> handler can be attached to LocalizedTextProvider to capture errors as they occur.

    // Create localization
    ILocalization localization = new Localization().AddLines(new LocalizationReaderYaml.File(@"localizationerror\error.l.yaml"));
    // Create error handler (Typically logger)
    ILocalizationErrorHandler errorHandler = new LocalizationErrorHandler(error => Console.WriteLine(error));
    // Add error handler
    localization.ErrorHandlers.Add(errorHandler);
    // Get localization text
    ILocalizedText text = localization.LocalizedTextCached[("en", "Namespace.CatsDogs")];
    // Print errors
    foreach (ILocalizationError error in text.Errors) WriteLine(error);
    

    Localizations are parsed lazily. To validate all localization errors, all localization lines must be queried.

    // Create localization
    ILocalization localization = new Localization().AddLines(new LocalizationReaderYaml.File(@"localizationerror\error.l.yaml"));
    // Validate all sources
    IEnumerable<ILocalizationError> errors = localization.LocalizationLinesInfosQuery[(culture: null, key: null)].SelectMany(info => info.Errors);
    // Print errors
    foreach (ILocalizationError error in errors) WriteLine(error);
    

    .AsMessage(error) extension method (Avalanche.Messages.Localization.dll) converts ILocalizationError to IMessage.

    // Create localization
    ILocalization localization = new Localization().AddLines(new LocalizationReaderYaml.File(@"localizationerror\error.l.yaml"));
    // Create error handler (Typically logger)
    ILocalizationErrorHandler errorHandler = new LocalizationErrorHandler(error => Console.WriteLine(error));
    // Add error handler
    localization.ErrorHandlers.Add(errorHandler);
    // Get localization text
    ILocalizedText text = localization.LocalizedTextCached[("en", "Namespace.CatsDogs")];
    // Print parse errors
    foreach (ILocalizationError error in text.Errors)
    {
        IMessage message = error.AsMessage();
        WriteLine(message); // TextMalformed Malformed Text="{cats} cats and {dogs dogs" en Namespace.CatsDogs localizationfile\error.l.yaml [Ln 9, Col 27, Ix 174 - Ln 9, Col 28, Ix 175]
    }
    

    LocalizationMessages (Avalanche.Messages.Localization.dll) and LocalizationMessageIds (Avalanche.Localization.Abstractions.dll) contains localization error codes.

    Key StatusCode Description Message Template
    Avalanche.Localization.NoKey A0AAC031 No "Key=..." key-value in localization line (error may be omited) NoKey {Message} {Culture} {Key} {Position}
    Avalanche.Localization.NoText A0AAC032 No "Text=..." key-value in localization line NoText {Message} {Culture} {Key} {Position}
    Avalanche.Localization.NoTemplateFormat A0AAC033 No "TemplateFormat=..." key-value in localization line NoTemplateFormat {Message} {Culture} {Key} {Position}
    Avalanche.Localization.NoCulture A0AAC034 No "Culture=..." key-value in localization line NoCulture {Message} {Culture} {Key} {Position}
    Avalanche.Localization.TemplateFormatNotFound A0AAC035 Template format not found TemplateFormatNotFound {Message} {Culture} {Key} {Position}
    Avalanche.Localization.TextMalformed A0AAC036 Text malformed TextMalformed {Message} {Culture} {Key} {Position}
    Avalanche.Localization.TextParseFailed A0AAC037 Template format could not parse text TextParseFailed {Message} {Culture} {Key} {Position}
    Avalanche.Localization.PluralRulesNotFound A0AAC038 Plural rules not found. PluralRulesNotFound {Message} {Culture} {Key} {Position}
    Avalanche.Localization.PluralsParseFailed A0AAC039 Plurals failed to parse, "parameterName:category:case[:culture], ..." expected PluralsParseFailed {Message} {Culture} {Key} {Position}
    Avalanche.Localization.PluralsParameterNotFound A0AAC03A Plurals refered to parameter that is not found in any localization line for the key PluralsParameterNotFound {Message} {Culture} {Key} {Position}
    Avalanche.Localization.PluralsDuplicateAssignment A0AAC03B Duplicate line with same "Plurals" value PluralsDuplicateAssignment {Message} {Culture} {Key} {Position}
    Avalanche.Localization.PluralsParameterDuplicateAssignment A0AAC03C Duplicate "Plurals" assignment on a specific parameter name PluralsParameterDuplicateAssignment {Message} {Culture} {Key} {Position}
    Avalanche.Localization.PluralsMissingCases A0AAC03D Missing required plurality cases. PluralsMissingCases {Message} {Culture} {Key} {Position}
    Avalanche.Localization.KeyNotFound A0AAC03E Key was not found. Localization line/file was not found: Key={Key}, Culture={Culture}
    Avalanche.Localization.Unexpected A0AAC03F Unexpected exception Unexpected {Message} {Culture} {Key} {Position}

    Full Example

    Full example
    using Avalanche.Localization;
    using Avalanche.Localization.Internal;
    using Avalanche.Message;
    using Avalanche.Template;
    using Avalanche.Utilities;
    using static System.Console;
    
    class localizationerror
    {
        public static void Run()
        {
            {
                // <00>
                WriteLine(LocalizationMessages.Instance.ReadSummaryXmls());
                // </00>
            }
            {
                // <01>
                // File reader
                var lines = new LocalizationReaderYaml.File(@"localizationerror\error.l.yaml");
                // Create line database
                LocalizationLines db = new LocalizationLines().AddLines(lines);
                // Create provider
                var localizedTextProvider = new LocalizedTextProvider(db.Query, LocalizationLinesInfoProvider.Cached);
                // Get localization text
                ILocalizedText localizedText = localizedTextProvider[("en", "Namespace.CatsDogs")];
                // Print parse errors
                foreach (ILocalizationError error in localizedText.Errors)
                    WriteLine(error);
                // </01>
                foreach (ILocalizationError error in localizedText.Errors)
                {
                    // <02>
                    WriteLine(error.Code);
                    WriteLine(error.Message);
                    WriteLine(error.Key);
                    WriteLine(error.Culture);
                    WriteLine(error.Text.Position.FileName);
                    WriteLine(error.Text.Position.Start.Line);
                    WriteLine(error.Text.Position.Start.Column);
                    WriteLine(error.Text.Position.End.Line);
                    WriteLine(error.Text.Position.End.Column);
                    // </02>
                }
            }
            {
                // <03>
                // Create localization
                ILocalization localization = new Localization().AddLines(new LocalizationReaderYaml.File(@"localizationerror\error.l.yaml"));
                // Create error handler (Typically logger)
                ILocalizationErrorHandler errorHandler = new LocalizationErrorHandler(error => Console.WriteLine(error));
                // Add error handler
                localization.ErrorHandlers.Add(errorHandler);
                // Get localization text
                ILocalizedText text = localization.LocalizedTextCached[("en", "Namespace.CatsDogs")];
                // Print errors
                foreach (ILocalizationError error in text.Errors) WriteLine(error);
                // </03>
            }
            {
                // <04>
                // Create localization
                ILocalization localization = new Localization().AddLines(new LocalizationReaderYaml.File(@"localizationerror\error.l.yaml"));
                // Validate all sources
                IEnumerable<ILocalizationError> errors = localization.LocalizationLinesInfosQuery[(culture: null, key: null)].SelectMany(info => info.Errors);
                // Print errors
                foreach (ILocalizationError error in errors) WriteLine(error);
                // </04>
            }
            {
                // <05>
                // Create localization
                ILocalization localization = new Localization().AddLines(new LocalizationReaderYaml.File(@"localizationerror\error.l.yaml"));
                // Create error handler (Typically logger)
                ILocalizationErrorHandler errorHandler = new LocalizationErrorHandler(error => Console.WriteLine(error));
                // Add error handler
                localization.ErrorHandlers.Add(errorHandler);
                // Get localization text
                ILocalizedText text = localization.LocalizedTextCached[("en", "Namespace.CatsDogs")];
                // Print parse errors
                foreach (ILocalizationError error in text.Errors)
                {
                    IMessage message = error.AsMessage();
                    WriteLine(message); // TextMalformed Malformed Text="{cats} cats and {dogs dogs" en Namespace.CatsDogs localizationfile\error.l.yaml [Ln 9, Col 27, Ix 174 - Ln 9, Col 28, Ix 175]
                }
                // </05>
            }
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen