• Avalanche
  • Avalanche.Core
  • Lexical

    Show / Hide Table of Contents
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
        • AspNetCore
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR41
        • Unicode.CLDR40
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Logging
      • Validation
      • Localization
    • 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
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Service
      • Introduction
      • Service
        • IService
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Cast
        • Scope
        • Dispose
      • Handler
        • Introduction
        • IHandler
        • Cancel
        • Recursion
        • Cyclicity
        • Delegates
        • Casting
        • Invokable
        • Handlers
      • Request
        • Introduction
        • IRequest
        • [Request]
        • [ContextParameter]
        • Print Tree
      • Dependency Injection
        • Introduction
        • ServiceRequest<T>
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
      • Examples
        • Expression Example
        • Mapper Example
      • ServiceMessages
    • Avalanche.Writer
      • Introduction
      • Writer
      • Referer
      • TypeCast
      • DefaultConstructor
      • DelegateWriter
      • WriterPipe
      • ConstantWriter
      • PassthroughWriter
      • Context
      • WriterMessages
    • Avalanche.Accessor
      • Introduction
      • AccessorServices
      • List
        • ListAccessor
        • ListConstructor
        • ListDeconstructor
        • ListDefaultConstructor
        • ListGet
        • ListSet
        • ListAdd
        • ListInsert
        • ListClear
        • ListCount
        • ListIndexOf
        • ListRemoveAt
        • ListReferer
      • Map
        • MapAccessor
        • MapConstructor
        • MapDeconstructor
        • MapDefaultConstructor
        • MapSet
        • MapGet
        • MapRemove
        • MapClear
        • MapCount
        • MapReferer
      • Record
        • RecordAccessor
        • RecordConstructor
        • RecordDeconstructor
        • RecordDefaultConstructor
      • Field
        • FieldAccessor
        • FieldReader
        • FieldWriter
        • FieldReferer
      • Dependency Injection
        • Introduction
      • AccessorMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.DataType
      • Introduction
      • IDataTypeBase
      • IDataType
      • IRecordType
      • IFieldType
      • IUnionType
      • IListType
      • IMapType
      • IValueType
      • IEnumerationType
      • IIntegerType
      • IRealType
      • IStringType
      • IAnyType
      • DataTypeRequest
      • PrintTree
      • DataTypeMessages
    • 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.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
        • EnumerableCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Concatenation
        • Cache
        • ResultCapture
        • AsReadOnly
        • AsService
      • 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.Core
      • License
      • Order

    Introduction

    Avalanche.Message unifies various coding facets, [git], [www], [licensing].

    Add package reference to .csproj.

    <PropertyGroup>
        <RestoreAdditionalProjectSources>https://avalanche.fi/Avalanche.Core/nupkg/index.json</RestoreAdditionalProjectSources>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Avalanche.Message"/>
    </ItemGroup>
    

    Message is an argumentable record.

    IMessage message = new Message()
        .SetMessageDescription(SystemMessages.ArgumentNull.Generic)
        .SetArguments("argumentName")
        .SetNow()
        .SetId(123)
        .SetUserData("User-data", new object())
        .SetReadOnly();
    

    Messages are validation statuscodes.

    // Observable
    IObservable<IMessage> observable = new MyObservable();
    // Observer
    MyObserver observer = new MyObserver();
    // Observe 
    observable.Subscribe(observer);
    // Print status codes
    foreach (IMessage statuscode in observer.StatusCodes) WriteLine(statuscode);
    

    Messages are events.

    // Create event description
    IMessageDescription fileCreatedEventDescription = new MessageDescription("FileCreated", 0x20012301, "File '{filename}' was created.");
    // Create event
    IMessage @event = fileCreatedEventDescription
        .New("filename.txt")
        .SetTime(DateTime.Now)
        .SetId(IdGenerators.Guid.Next)
        .SetUserData("EventSource", "Server-45")
        .SetReadOnly();
    

    Messages are throwable.

    throw SystemMessages.ArgumentNull.Generic.New("argumentName").SetTime(DateTime.Now).NewException();
    

    Messages are string.Format() printable.

    // Create message
    IMessage message = SystemMessages.ArgumentNull.Generic.New("argumentName");
    // Get format text
    string formatText = message.MessageDescription.Template.Breakdown.FormatTemplate();
    // Formulate
    string formulation = string.Format(formatText, message.Arguments);
    // Print
    WriteLine(formulation);
    

    Messages are loggable.

    SystemMessages.Argument.EnumValueNotFound.New("Value").LogTo(logger);
    

    Log line

    Messages are localizable (with Avalanche.Localization).

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

    Message texts are pluralizable (with Avalanche.Localization).

    // Create message description.
    MessageDescription filesDeleted = new MessageDescription("System.IO.FilesDeleted", 0x25110001, "{count} file(s) were deleted.");
    // Create localization
    ILocalization localization = new Localization()
        .AddLine("", filesDeleted.Key, "Detect", "No files were deleted.", "Unicode.CLDR", "count:cardinal:zero:en")
        .AddLine("", filesDeleted.Key, "Detect", "One file was deleted.", "Unicode.CLDR", "count:cardinal:one:en")
        .AddLine("", filesDeleted.Key, "Detect", "{count} files were deleted.", "Unicode.CLDR", "count:cardinal:other:en");
    // Localize message description
    filesDeleted.Localize(localization).SetReadOnly();
    // "No files were deleted."
    WriteLine(filesDeleted.New(0).Print());
    // "One file was deleted."
    WriteLine(filesDeleted.New(1).Print());
    // "2 files were deleted."
    WriteLine(filesDeleted.New(2).Print());
    

    Messages can have HResult code.

    try
    {
        throw SystemMessages.InvalidOperation.Exception.NewException();
    }
    catch (Exception e) when (e.HResult == HResultIds.COR_E_INVALIDOPERATION)
    {
    }
    

    Messages are processable in-process and out-of-process.

    IMessage message = HResult.S_OK.New().SetId(IdGenerators.Integer.Next);
    // Serialize as csv line
    string[] cells = { message.MessageDescription.Code.ToString()!, message.Id!.ToString()!, Escaper.Comma.EscapeJoin(message.Arguments.Select(a=>a?.ToString()??"")) };
    string csvLine = Escaper.Semicolon.EscapeJoin(cells);
    

    The following global_includes.cs can be used to include extension methods.

    global using Avalanche.Message;
    global using Avalanche.Utilities;
    global using Avalanche.Template;
    
    Class libraries:
    • Avalanche.Message.dll contains implementations.
    • Avalanche.Message.Abstractions.dll contains interfaces.
    • Avalanche.Message.Logging.dll contains Microsoft.Extensions.Logging extensions.

    Dependency libraries, direct and indirect:

    • Avalanche.Template.dll
    • Avalanche.Template.Abstractions.dll
    • Avalanche.Tokenizer.dll
    • Avalanche.Tokenizer.Abstractions.dll
    • Avalanche.Utilities.dll
    • Avalanche.Utilities.Abstractions.dll

    Tangential libraries:

    • Avalanche.StatusCode.dll contains various public status codes (see more).
    • Avalanche.Localization.dll
    • Avalanche.Localization.Abstractions.dll
    • Avalanche.Message.Localization.dll

    Full Example

    Full example
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Globalization;
    using Avalanche.Service;
    using Avalanche.Utilities;
    using Avalanche.Message;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Serilog;
    using Serilog.Core;
    using Serilog.Events;
    using static System.Console;
    using Avalanche.StatusCode;
    using Avalanche.Template;
    using Avalanche.Localization;
    
    class index
    {
        public static void Run()
        {
            {
                // <01>
                IMessage message = new Message()
                    .SetMessageDescription(SystemMessages.ArgumentNull.Generic)
                    .SetArguments("argumentName")
                    .SetNow()
                    .SetId(123)
                    .SetUserData("User-data", new object())
                    .SetReadOnly();
                // </01>
            }
    
            {
                try
                {
                    // <08>
                    throw SystemMessages.ArgumentNull.Generic.New("argumentName").SetTime(DateTime.Now).NewException();
                    // </08>
                }
                catch (Exception) { }
            }
            {
                // <09>
                // Observable
                IObservable<IMessage> observable = new MyObservable();
                // Observer
                MyObserver observer = new MyObserver();
                // Observe 
                observable.Subscribe(observer);
                // Print status codes
                foreach (IMessage statuscode in observer.StatusCodes) WriteLine(statuscode);
                // </09>
            }
            {
                // <10>
                // Create message
                IMessage message = SystemMessages.ArgumentNull.Generic.New("argumentName");
                // Get format text
                string formatText = message.MessageDescription.Template.Breakdown.FormatTemplate();
                // Formulate
                string formulation = string.Format(formatText, message.Arguments);
                // Print
                WriteLine(formulation);
                // </10>
            }
            {
                // Service collection
                IServiceCollection serviceCollection = new ServiceCollection();
                // Add logging
                InitializeLogging(serviceCollection);
                // Services
                using var service = Services.Create((ServiceHandlers.Instance, serviceCollection));
                // Create ILogger
                var logger = service.GetRequiredService<Microsoft.Extensions.Logging.ILogger<index>>();
                // <11>
                SystemMessages.Argument.EnumValueNotFound.New("Value").LogTo(logger);
                // </11>
            }
    
            {
                // <14>
                // Create localization
                ILocalization localization = new Localization()
                    .AddLine("fi", HResult.S_OK.Key, "Detect", "Operaatio onnistui");
                // Decorate to localize
                IMessageDescription s_ok = HResult.S_OK.Localized(localization);
                // "Operation successful"
                WriteLine(s_ok.New().Print(CultureInfo.GetCultureInfo("en")));
                // "Operaatio onnistui"
                WriteLine(s_ok.New().Print(CultureInfo.GetCultureInfo("fi")));
                // </14>
            }
            {
                // <15>
                // Create message description.
                MessageDescription filesDeleted = new MessageDescription("System.IO.FilesDeleted", 0x25110001, "{count} file(s) were deleted.");
                // Create localization
                ILocalization localization = new Localization()
                    .AddLine("", filesDeleted.Key, "Detect", "No files were deleted.", "Unicode.CLDR", "count:cardinal:zero:en")
                    .AddLine("", filesDeleted.Key, "Detect", "One file was deleted.", "Unicode.CLDR", "count:cardinal:one:en")
                    .AddLine("", filesDeleted.Key, "Detect", "{count} files were deleted.", "Unicode.CLDR", "count:cardinal:other:en");
                // Localize message description
                filesDeleted.Localize(localization).SetReadOnly();
                // "No files were deleted."
                WriteLine(filesDeleted.New(0).Print());
                // "One file was deleted."
                WriteLine(filesDeleted.New(1).Print());
                // "2 files were deleted."
                WriteLine(filesDeleted.New(2).Print());
                // </15>
            }
            {
                // <21>
                // Create event description
                IMessageDescription fileCreatedEventDescription = new MessageDescription("FileCreated", 0x20012301, "File '{filename}' was created.");
                // Create event
                IMessage @event = fileCreatedEventDescription
                    .New("filename.txt")
                    .SetTime(DateTime.Now)
                    .SetId(IdGenerators.Guid.Next)
                    .SetUserData("EventSource", "Server-45")
                    .SetReadOnly();
                // </21>
            }
            {
                // <31>
                try
                {
                    throw SystemMessages.InvalidOperation.Exception.NewException();
                }
                catch (Exception e) when (e.HResult == HResultIds.COR_E_INVALIDOPERATION)
                {
                }
                // </31>
            }
            {
                // <41>
                IMessage message = HResult.S_OK.New().SetId(IdGenerators.Integer.Next);
                // Serialize as csv line
                string[] cells = { message.MessageDescription.Code.ToString()!, message.Id!.ToString()!, Escaper.Comma.EscapeJoin(message.Arguments.Select(a=>a?.ToString()??"")) };
                string csvLine = Escaper.Semicolon.EscapeJoin(cells);
                // </41>
                WriteLine(csvLine); // "0;0;"
            }
        }
    
        /// <summary></summary>
        public class MyObservable : IObservable<IMessage>
        {
            /// <summary></summary>
            public IDisposable Subscribe(IObserver<IMessage> observer)
            {
                observer.OnNext(new Message());
                observer.OnCompleted();
                return null!;
            }
        }
    
        /// <summary></summary>
        public class MyObserver : IObserver<IMessage>
        {
            /// <summary></summary>
            public readonly List<IMessage> StatusCodes = new();
            /// <summary></summary>
            public void OnCompleted() { }
            /// <summary></summary>
            public void OnError(Exception error) { }
            /// <summary></summary>
            public void OnNext(IMessage statusCode) { StatusCodes.Add(statusCode); }
        }
    
        static IServiceCollection InitializeLogging(IServiceCollection serviceCollection)
        {
            // Initial configuration
            MemoryConfiguration memConfig = new MemoryConfiguration()
                .Set("Logging:LogLevel:Default", "Debug")
                .Set("Serilog:WriteTo:0:Name", "Console")
                .Set("Serilog:WriteTo:0:Args:OutputTemplate", "[{EventIdHex} {Level:u1}] {Message:lj}{NewLine}{Exception}")
                .Set("Serilog:WriteTo:0:Args:RestrictedToMinimumLevel", "Verbose")
                .Set("Serilog:WriteTo:0:Args:Theme", "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console");
    
            // Read configuration
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .Add(memConfig)
                .Build();
    
            //
            var switchableLogger = new Serilog.SwitchableLogger();
            // Logging
            serviceCollection.AddLogging(loggingBuilder =>
                    loggingBuilder
    #if DEBUG
                        .SetMinimumLevel(LogLevel.Trace)
    #else
                        .SetMinimumLevel(LogLevel.Information)
    #endif
                        .AddSerilog(switchableLogger, true)
                        .AddSerilogConfigurationLoader(configuration, switchableLogger,
                            c => new Serilog.LoggerConfiguration()
    #if DEBUG
                                    .MinimumLevel.Verbose()
    #else
                                    .MinimumLevel.Information()
    #endif
                                    .Enrich.With(new EventIdEnricher())
                                .ReadFrom.Configuration(configuration)
                                .CreateLogger())
                    );
            //
            return serviceCollection;
        }
    
        /// <summary>Memory configuration</summary>
        public class MemoryConfiguration : ConfigurationProvider, IEnumerable<KeyValuePair<string, string>>, IConfigurationSource
        {
            /// <summary>Expose inner configuration data</summary>
            public new IDictionary<String, String> Data => base.Data;
            /// <summary>Configuration data</summary>
            public string this[string key] { get => base.Data[key]; set => base.Data[key] = value; }
    
            /// <summary>Create memory configuration</summary>
            public MemoryConfiguration() : base() { }
    
            /// <summary>Assign <paramref name="value"/> to <paramref name="key"/></summary>
            public new MemoryConfiguration Set(string key, string value) { base.Data[key] = value; return this; }
            /// <summary>Build configuration provider.</summary>
            public IConfigurationProvider Build(IConfigurationBuilder builder) => this;
            /// <summary>Enumerate</summary>
            public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => Data.GetEnumerator();
            /// <summary>Enumerate</summary>
            IEnumerator IEnumerable.GetEnumerator() => Data.GetEnumerator();
        }
    
        /// <summary>Serilog enricher that reduces "EventId" to its "id" field.</summary>
        public class EventIdEnricher : ILogEventEnricher
        {
            /// <summary>Reduce to EventId.id</summary>
            public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
            {
                // Get properties
                if (!logEvent.Properties.TryGetValue("EventId", out LogEventPropertyValue? eventIdStructure)) return;
                // Not structure field
                if (eventIdStructure is not StructureValue structureValue || structureValue.Properties == null) return;
                // Get list
                IReadOnlyList<LogEventProperty> list = structureValue.Properties;
                // Process each
                for (int i = 0; i < list.Count; i++)
                {
                    // Get property
                    LogEventProperty logEventProperty = list[i];
                    // Not id
                    if (logEventProperty.Name != "Id") continue;
                    // New property
                    LogEventProperty eventId = propertyFactory.CreateProperty("EventId", logEventProperty.Value);
                    // Add as new key
                    logEvent.AddOrUpdateProperty(eventId);
                    // Print as hex
                    string hex = logEventProperty.Value.ToString("X8", CultureInfo.InvariantCulture);
                    // New property
                    LogEventProperty eventIdHex = propertyFactory.CreateProperty("EventIdHex", hex);
                    // Add as new key
                    logEvent.AddOrUpdateProperty(eventIdHex);
                    // Completed
                    return;
                }
            }
        }
    }
    
    Back to top Copyright © 2022 Toni Kalajainen, contact@avalanche.fi