• 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

    Introduction

    Message descriptions can be stored in IMessageDescriptions tables (Avalanche.Message.dll).

    public class DatabaseMessages : MessageDescriptions
    {
        /// <summary>Singleton</summary>
        static readonly Lazy<DatabaseMessages> instance = new Lazy<DatabaseMessages>(() => new DatabaseMessages().SetAllReadOnly().SetReadOnly());
        /// <summary>Singleton</summary>
        public static DatabaseMessages Instance => instance.Value;
        /// <summary>Exception factory for http errors</summary>
        static readonly Func<IMessage, Exception> httpExceptionFactory = (IMessage m) => new HttpRequestException(m.Print(), m.Error, (System.Net.HttpStatusCode)m.HttpStatusCode());
    
        /// <summary>Initialize fields</summary>
        public DatabaseMessages() : base() { this.AddRange(MessageDescriptionsExtensions.FieldReader(this)); }
    
        /// <summary></summary>
        public readonly IMessageDescription ChannelNotFound = Http(nameof(ChannelNotFound), "Channel {channelId} is not found", HttpStatusCode.NotFound);
        /// <summary>User is not authenticated (logged in)</summary>
        public readonly IMessageDescription UserNotAuthenticated = Http(nameof(UserNotAuthenticated), "User is not authenticated", HttpStatusCode.Forbidden);
        /// <summary>User is not (email) verified</summary>
        public readonly IMessageDescription UserNotConfirmedEmail = Http(nameof(UserNotConfirmedEmail), "User's {user} e-mail is not verified", HttpStatusCode.Forbidden);
        /// <summary>User not found in database</summary>
        public readonly IMessageDescription UserNotFound = Http(nameof(UserNotFound), "User {user} is not found", HttpStatusCode.NotFound);
        /// <summary>User is not subscribed on channel</summary>
        public readonly IMessageDescription UserNotSubscribed = Http(nameof(UserNotSubscribed), "User {user} is not subscribed on channel {channel}", HttpStatusCode.Forbidden);
    
        /// <summary>Create http message</summary>
        public static IMessageDescription Http(string key, string template, HttpStatusCode? httpCode)
        {
            // Create description
            MessageDescription messageDescription = new MessageDescription(key, null, TemplateFormat.BraceAlphaNumeric.Text[template])
                .SetCode(new FNVHash32().HashIn(key))
                .SetHttpStatusCode(httpCode)
                .SetException(httpExceptionFactory);
            // Error
            if (httpCode.HasValue && (int)httpCode.Value >= 300) messageDescription.SetHResult(0x80000000).SetSeverity(MessageLevel.Error);
            // Ok
            else messageDescription.SetHResult(0x00000000).SetSeverity(MessageLevel.Information);
            // Return
            return messageDescription;
        }
    }
    

    Tables can be added to dependency injection (Read more).

    // Service collection
    IServiceCollection serviceCollection = new ServiceCollection()
        .AddSingleton<ILocalization>(Localization.Default)
        .AddSingleton<DatabaseMessages>(sp => new DatabaseMessages().LocalizeMessages(sp.GetRequiredService<ILocalization>()));
    
    // Service provider
    using var service = serviceCollection.BuildServiceProvider();
    
    // Get messages
    DatabaseMessages messages = service.GetRequiredService<DatabaseMessages>();
    // Create message
    IMessage status = messages.ChannelNotFound.New("00000000-0000-0000-1000-000000000000");
    // Print message
    WriteLine(status.Print());
    

    .ToYamlText(), .ToYamlNode() and .ToYamlFile() prints tables as localization template file (Avalanche.Message.Localization.dll) (Read more). Translations to other languages can be written on the constructed template file.

    // Service collection
    IServiceCollection serviceCollection = new ServiceCollection()
        .AddSingleton<ILocalization>(Localization.Default)
        .AddSingleton<DatabaseMessages>(sp => new DatabaseMessages().LocalizeMessages(sp.GetRequiredService<ILocalization>()));
    
    // 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)!);
    
    // Print all tables
    WriteLine(list.ToYamlText());
    // Print one table
    WriteLine(list.First().ToYamlText());
    
    DatabaseMessages:
      Culture: ''
      TemplateFormat: BraceAlphaNumeric
      Items:
      - Key: ChannelNotFound
        Text: Channel {channelId} is not found
      - Key: UserNotFound
        Text: User {user} is not found
      - Key: UserNotConfirmedEmail
        Text: User's {user} e-mail is not verified
      - Key: UserNotAuthenticated
        Text: User is not authenticated
      - Key: UserNotSubscribed
        Text: User {user} is not subscribed on channel {channel}
    

    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.Diagnostics;
    using System.Globalization;
    using System.Net;
    using Avalanche.Localization;
    using Avalanche.Message;
    using Avalanche.Template;
    using Avalanche.Utilities;
    using Microsoft.Extensions.DependencyInjection;
    using static System.Console;
    
    public class printtemplate
    {
        public static void Run()
        {
            {
                // <01>
                // Service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddSingleton<ILocalization>(Localization.Default)
                    .AddSingleton<DatabaseMessages>(sp => new DatabaseMessages().LocalizeMessages(sp.GetRequiredService<ILocalization>()));
    
                // Service provider
                using var service = serviceCollection.BuildServiceProvider();
    
                // Get messages
                DatabaseMessages messages = service.GetRequiredService<DatabaseMessages>();
                // Create message
                IMessage status = messages.ChannelNotFound.New("00000000-0000-0000-1000-000000000000");
                // Print message
                WriteLine(status.Print());
                // </01>
            }
            {
                // <11>
                // Service collection
                IServiceCollection serviceCollection = new ServiceCollection()
                    .AddSingleton<ILocalization>(Localization.Default)
                    .AddSingleton<DatabaseMessages>(sp => new DatabaseMessages().LocalizeMessages(sp.GetRequiredService<ILocalization>()));
    
                // 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)!);
                
                // Print all tables
                WriteLine(list.ToYamlText());
                // Print one table
                WriteLine(list.First().ToYamlText());
                // </11>
    
                // <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>
            }
        }
    
        // <100>
        public class DatabaseMessages : MessageDescriptions
        {
            /// <summary>Singleton</summary>
            static readonly Lazy<DatabaseMessages> instance = new Lazy<DatabaseMessages>(() => new DatabaseMessages().SetAllReadOnly().SetReadOnly());
            /// <summary>Singleton</summary>
            public static DatabaseMessages Instance => instance.Value;
            /// <summary>Exception factory for http errors</summary>
            static readonly Func<IMessage, Exception> httpExceptionFactory = (IMessage m) => new HttpRequestException(m.Print(), m.Error, (System.Net.HttpStatusCode)m.HttpStatusCode());
    
            /// <summary>Initialize fields</summary>
            public DatabaseMessages() : base() { this.AddRange(MessageDescriptionsExtensions.FieldReader(this)); }
    
            /// <summary></summary>
            public readonly IMessageDescription ChannelNotFound = Http(nameof(ChannelNotFound), "Channel {channelId} is not found", HttpStatusCode.NotFound);
            /// <summary>User is not authenticated (logged in)</summary>
            public readonly IMessageDescription UserNotAuthenticated = Http(nameof(UserNotAuthenticated), "User is not authenticated", HttpStatusCode.Forbidden);
            /// <summary>User is not (email) verified</summary>
            public readonly IMessageDescription UserNotConfirmedEmail = Http(nameof(UserNotConfirmedEmail), "User's {user} e-mail is not verified", HttpStatusCode.Forbidden);
            /// <summary>User not found in database</summary>
            public readonly IMessageDescription UserNotFound = Http(nameof(UserNotFound), "User {user} is not found", HttpStatusCode.NotFound);
            /// <summary>User is not subscribed on channel</summary>
            public readonly IMessageDescription UserNotSubscribed = Http(nameof(UserNotSubscribed), "User {user} is not subscribed on channel {channel}", HttpStatusCode.Forbidden);
    
            /// <summary>Create http message</summary>
            public static IMessageDescription Http(string key, string template, HttpStatusCode? httpCode)
            {
                // Create description
                MessageDescription messageDescription = new MessageDescription(key, null, TemplateFormat.BraceAlphaNumeric.Text[template])
                    .SetCode(new FNVHash32().HashIn(key))
                    .SetHttpStatusCode(httpCode)
                    .SetException(httpExceptionFactory);
                // Error
                if (httpCode.HasValue && (int)httpCode.Value >= 300) messageDescription.SetHResult(0x80000000).SetSeverity(MessageLevel.Error);
                // Ok
                else messageDescription.SetHResult(0x00000000).SetSeverity(MessageLevel.Information);
                // Return
                return messageDescription;
            }
        }
        // </100>
    
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen