• 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.Configuration
      • Introduction
      • Configuration Binding
      • ConfigurationExtensions
      • MemoryConfiguration
      • PrintTree
      • Saving IOptions
      • Yaml
    • Avalanche.Converter
      • Introduction
      • EnumConverter
      • Func<,>
      • HexConverter
      • PrimitiveConverter
      • StringConverter
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • 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
        • FilterEnumerable
        • PollingFilterWatchToken
    • 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.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
        • IHostBuilder
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • StorageMessages
        • ItfMessages
        • Win32Messages
        • WindowsMessages
        • SspiMessages
        • CertMessages
        • MediaServerMessages
        • SetupApiMessages
        • ScardMessages
        • ComPlusMessages
        • ClrMessages
        • UserModeFilterManagerMessages
        • GraphicsMessages
        • TpmServicesMessages
        • TpmSoftwareMessages
        • PlaMessages
        • FveMessages
        • FwpMessages
        • NdisMessages
        • DltMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • 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
      • Reflection
        • EnumDescription
      • String
        • IEscaper
        • UnicodeString
        • Hex
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • ITreeNode
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Message Printing

    .Print(culture) prints to a string.

    // Create message description
    IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
    // Create message
    IMessage message = fileNotFoundFileName.New("MyFile.txt");
    // Print as string
    string printOut = message.Print(CultureInfo.InvariantCulture);
    // Write print
    WriteLine(printOut); // "Could not find file 'MyFile.txt'."
    

    .EstimatePrintLength(culture) counts the number of characters and .PrintTo(span, culture, args) writes to span. Estimation is needed for zero heap printing.

    // Create message description
    IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
    // Create message
    IMessage message = fileNotFoundFileName.New("MyFile.txt");
    // Estimate length
    int length = message.EstimatePrintLength(CultureInfo.InvariantCulture);
    // Allocate span
    Span<char> span = length < 512 ? stackalloc char[length] : new char[length];
    // Print to span
    length = message.PrintTo(span, CultureInfo.InvariantCulture);
    // Print to stdout, zero heap.
    Console.Out.Write(span.Slice(0, length));
    

    .TryPrintTo(span, culture) attempts to print to a Span<char> without possibility of throwing InvalidOperationException on too short allocation.

    // Create message description
    IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
    // Create message
    IMessage message = fileNotFoundFileName.New("MyFile.txt");
    // Estimate length
    int length = message.EstimatePrintLength(CultureInfo.InvariantCulture);
    // Allocate span
    Span<char> span = length < 512 ? stackalloc char[length] : new char[length];
    // Print to span
    if (message.TryPrintTo(span, out length, CultureInfo.InvariantCulture))
        Console.Out.Write(span.Slice(0, length));
    

    .AppendTo(stringbuilder, culture) appends to a string builder.

    // Create message description
    IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
    // Create message
    IMessage message = fileNotFoundFileName.New("MyFile.txt");
    // Create string builder
    StringBuilder sb = new(1024);
    // Append to string builder
    message.AppendTo(sb, CultureInfo.InvariantCulture);
    // Print
    WriteLine(sb); // "Could not find file 'MyFile.txt'."
    

    .WriteTo(textwriter, culture) writes to a text writer.

    // Create message description
    IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
    // Create message
    IMessage message = fileNotFoundFileName.New("MyFile.txt");
    // Assign text writer
    TextWriter textWriter = Console.Out;
    // Write to writer
    message.WriteTo(textWriter, CultureInfo.InvariantCulture); // "Could not find file 'MyFile.txt'."
    

    .LogTo(logger) outputs message to a logger.

    // Create message
    IMessage message = SystemMessages.ArgumentNull.Generic.New("argumentName");
    // Log message
    message.LogTo(logger);
    

    Message implements IFormattable and ISpanFormattable. Format provider is forwarded to arguments.

    // Create template
    ITemplateText text = TemplateFormat.BraceNumeric.Text["Time={0}."];
    // Create message description
    IMessageDescription messageDescription = new MessageDescription().SetTemplate(text);
    // Create message
    IMessage message = messageDescription.New(DateTime.Now);
    // Get cultures
    CultureInfo fi = CultureInfo.GetCultureInfo("fi"), en = CultureInfo.GetCultureInfo("en");
    // Use as IFormattable or ISpanFormattable
    WriteLine(String.Format(fi, "Message: {0}", message)); // "Message: Time=10.1.2022 18.53.06."
    WriteLine(String.Format(en, "Message: {0}", message)); // "Message: Time=1/10/2022 6:53:06 PM."
    
    Note

    Thank you C# 10 for Span, stackalloc, ISpanFormattable and MemoryPool which allow zero heap or near zero implementations.

    Full Example

    Full example
    using System.Globalization;
    using System.Text;
    using Avalanche.Message;
    using Avalanche.StatusCode;
    using Avalanche.Template;
    using static System.Console;
    
    class printing
    {
        public static void Run()
        {
            {
                // <01>
                // Create message description
                IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
                // Create message
                IMessage message = fileNotFoundFileName.New("MyFile.txt");
                // Print as string
                string printOut = message.Print(CultureInfo.InvariantCulture);
                // Write print
                WriteLine(printOut); // "Could not find file 'MyFile.txt'."
                // </01>
            }
            {
                // <03>
                // Create message description
                IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
                // Create message
                IMessage message = fileNotFoundFileName.New("MyFile.txt");
                // Estimate length
                int length = message.EstimatePrintLength(CultureInfo.InvariantCulture);
                // Allocate span
                Span<char> span = length < 512 ? stackalloc char[length] : new char[length];
                // Print to span
                length = message.PrintTo(span, CultureInfo.InvariantCulture);
                // Print to stdout, zero heap.
                Console.Out.Write(span.Slice(0, length));
                // </03>
                WriteLine();
            }
    
            {
                // <04>
                // Create message description
                IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
                // Create message
                IMessage message = fileNotFoundFileName.New("MyFile.txt");
                // Estimate length
                int length = message.EstimatePrintLength(CultureInfo.InvariantCulture);
                // Allocate span
                Span<char> span = length < 512 ? stackalloc char[length] : new char[length];
                // Print to span
                if (message.TryPrintTo(span, out length, CultureInfo.InvariantCulture))
                    Console.Out.Write(span.Slice(0, length));
                // </04>
                WriteLine();
            }
    
            {
                // <11>
                // Create message description
                IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
                // Create message
                IMessage message = fileNotFoundFileName.New("MyFile.txt");
                // Create string builder
                StringBuilder sb = new(1024);
                // Append to string builder
                message.AppendTo(sb, CultureInfo.InvariantCulture);
                // Print
                WriteLine(sb); // "Could not find file 'MyFile.txt'."
                // </11>
            }
            {
                // <13>
                // Create message description
                IMessageDescription fileNotFoundFileName = new MessageDescription("mscorlib.IO.FileNotFound_FileName", 0xA345040F, "Could not find file '{0}'.").SetHResult(0x80070002).SetSeverity(MessageLevel.Error).SetException(typeof(FileNotFoundException));
                // Create message
                IMessage message = fileNotFoundFileName.New("MyFile.txt");
                // Assign text writer
                TextWriter textWriter = Console.Out;
                // Write to writer
                message.WriteTo(textWriter, CultureInfo.InvariantCulture); // "Could not find file 'MyFile.txt'."
                // </13>
                WriteLine();
            }
    
            {
                // <21>
                // Create template
                ITemplateText text = TemplateFormat.BraceNumeric.Text["Time={0}."];
                // Create message description
                IMessageDescription messageDescription = new MessageDescription().SetTemplate(text);
                // Create message
                IMessage message = messageDescription.New(DateTime.Now);
                // Get cultures
                CultureInfo fi = CultureInfo.GetCultureInfo("fi"), en = CultureInfo.GetCultureInfo("en");
                // Use as IFormattable or ISpanFormattable
                WriteLine(String.Format(fi, "Message: {0}", message)); // "Message: Time=10.1.2022 18.53.06."
                WriteLine(String.Format(en, "Message: {0}", message)); // "Message: Time=1/10/2022 6:53:06 PM."
                // </21>
            }
    
    
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen