• 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

    TemplateFormats

    TemplateFormats.All is a singleton that contains the built-in formats.

    ITemplateFormats templateFormats = TemplateFormats.All;
    

    TemplateFormat.BraceNumeric represents string.Format() compatible format that uses numeric parameter indices in brace enclosements "{0}".

    ITemplateFormat templateFormat = TemplateFormat.BraceNumeric;
    ITemplateBreakdown breakdown1 = templateFormat.Breakdown["Today is {1}. Welcome, {0}"];
    

    TemplateFormat.BraceAlphaNumeric represents Microsoft.Extensions.Logging compatible format that uses alpha numeric parameter names in brace enclosements, e.g. "{user}".

    ITemplateFormat templateFormat = TemplateFormat.BraceAlphaNumeric;
    ITemplateBreakdown breakdown2 = templateFormat.Breakdown["Today is {time}. Welcome, {user}"];
    

    TemplateFormat.Brace detects which parameter convention to use, numeric "{0}" or alphanumeric "{user}".

    ITemplateFormat templateFormat = TemplateFormat.Brace;
    ITemplateBreakdown breakdown2 = templateFormat.Breakdown["Today is {time}. Welcome, {user}"];
    

    For BraceNumeric arguments are provided in order of parameter index, and for BraceAlphaNumeric in order of occurance in the template text.

    ITemplateBreakdown breakdown1 = TemplateFormat.BraceNumeric.Breakdown["Today is {1}. Welcome, {0}"];
    ITemplateBreakdown breakdown2 = TemplateFormat.BraceAlphaNumeric.Breakdown["Today is {time}. Welcome, {user}"];
    WriteLine(breakdown1.Print(null, new object?[] { "User", DateTime.Now })); // "Today is 5.1.2022 20.02.40. Welcome, User"
    WriteLine(breakdown2.Print(null, new object?[] { DateTime.Now, "User" })); // "Today is 5.1.2022 20.02.40. Welcome, User"
    

    Brace formats use following placeholder notation: "{parameter[,alignment][:formatting]}".

    ITemplateBreakdown breakdown = TemplateFormat.BraceAlphaNumeric.Breakdown["Error 0x{code:X8}."];
    WriteLine(breakdown.Print(CultureInfo.InvariantCulture, new object?[] { 0x100 })); // "Error 0x00000100."
    

    Alignment determines padding. Positive value for left side padding and negative for right side.

    ITemplateBreakdown breakdown = TemplateFormat.BraceAlphaNumeric.Breakdown["User \"{user,13}\""];
    WriteLine(breakdown.Print(CultureInfo.InvariantCulture, new object?[] { "Donald Duck" })); // "User "  Donald Duck""
    

    Brace format unescapes "{{" as '{' and "}}" as '}'.

    ITemplateBreakdown breakdown = TemplateFormat.BraceAlphaNumeric.Breakdown["Welcome, {{{user}}}"];
    WriteLine(breakdown.Print(CultureInfo.InvariantCulture, new object?[] { "Donald Duck" })); // "Welcome, {Donald Duck}"
    

    TemplateFormat.Percent represents format that uses "%1" as placeholder. Index starts at 1.

    ITemplateBreakdown breakdown1 = TemplateFormat.Percent.Breakdown["Today is %2. Welcome, %1"];
    WriteLine(breakdown1.Print(null, new object?[] { "User", DateTime.Now })); // "Today is 5.1.2022 20.02.40. Welcome, User"
    

    TemplateFormat.Parameterless parses into light-weight wrapper that has no parameters.

    ITemplateBreakdown breakdown = TemplateFormat.Parameterless.Breakdown["void Main() {}"];
    WriteLine(breakdown.Print(null, arguments: (object?[]?)null)); // "void Main() {}"
    

    Re-assemble to another format is escaped.

    ITemplateBreakdown breakdown = TemplateFormat.Parameterless.Breakdown["void Main() {}"];
    // Reassembled is escaped
    WriteLine(TemplateFormat.Brace.Assemble[breakdown]); // "void Main() {{}}"
    

    TemplateFormats.All.Detect detects which template format is best suited for given text.

    ITemplateBreakdown breakdown0 = TemplateFormats.All.Detect.Breakdown["Today is now. Welcome, user"];
    ITemplateBreakdown breakdown1 = TemplateFormats.All.Detect.Breakdown["Today is {0}. Welcome, {1}"];
    ITemplateBreakdown breakdown2 = TemplateFormats.All.Detect.Breakdown["Today is {time}. Welcome, {user}"];
    ITemplateBreakdown breakdown3 = TemplateFormats.All.Detect.Breakdown["Today is %1. Welcome, %2"];
    
    WriteLine(breakdown0.TemplateFormat!.Name); // "Parameterless"
    WriteLine(breakdown1.TemplateFormat!.Name); // "BraceNumeric"
    WriteLine(breakdown2.TemplateFormat!.Name); // "BraceAlphaNumeric"
    WriteLine(breakdown3.TemplateFormat!.Name); // "Percent"
    

    DetectTemplateFormat aggregates formats into detecting one. Note that the order of components matter, lighter implementations go first, and heavier later. For example Parameterless is first because it is simple string wrapper.

    // Create detect format
    ITemplateFormat detect = new DetectTemplateFormat("FormatName", TemplateFormat.Parameterless, TemplateFormat.BraceNumeric);
    // Parse string and detect template format
    ITemplateText templateText = detect.TextCached["Today is {0}. Welcome, {1}."];
    // Print straight to console
    templateText.WriteTo(Console.Out, CultureInfo.InvariantCulture, new object?[] { DateTime.Now, "User" });
    

    TemplateFormats.All is a singleton for builtin template formats table with following formats:

    // Builtin template formats
    ITemplateFormats templateFormats = TemplateFormats.All;
    // Get by name
    ITemplateFormat templateFormat = templateFormats.ByName["BraceNumeric"];
    

    TemplateFormats.All contains following template formats:

    Name Description
    Detect Detect format
    Parameterless No placeholders.
    BraceNumeric "Hello {0}."
    BraceAlphaNumeric "Hello {name}."
    Brace Detect
    Percent "Hello %1."

    Full Example

    Full example
    using System.Globalization;
    using Avalanche.Template;
    using static System.Console;
    
    public class templateformats
    {
        public static void Run()
        {
            {
                // <01>
                ITemplateFormats templateFormats = TemplateFormats.All;
                // </01>
                var format = templateFormats.ByName["Detect"];
            }
            {
                // <02>
                ITemplateFormat templateFormat = TemplateFormat.BraceNumeric;
                ITemplateBreakdown breakdown1 = templateFormat.Breakdown["Today is {1}. Welcome, {0}"];
                // </02>
            }
            {
                // <03>
                ITemplateFormat templateFormat = TemplateFormat.BraceAlphaNumeric;
                ITemplateBreakdown breakdown2 = templateFormat.Breakdown["Today is {time}. Welcome, {user}"];
                // </03>
            }
            {
                // <03B>
                ITemplateFormat templateFormat = TemplateFormat.Brace;
                ITemplateBreakdown breakdown2 = templateFormat.Breakdown["Today is {time}. Welcome, {user}"];
                // </03B>
            }
            {
                // <04>
                ITemplateBreakdown breakdown1 = TemplateFormat.BraceNumeric.Breakdown["Today is {1}. Welcome, {0}"];
                ITemplateBreakdown breakdown2 = TemplateFormat.BraceAlphaNumeric.Breakdown["Today is {time}. Welcome, {user}"];
                WriteLine(breakdown1.Print(null, new object?[] { "User", DateTime.Now })); // "Today is 5.1.2022 20.02.40. Welcome, User"
                WriteLine(breakdown2.Print(null, new object?[] { DateTime.Now, "User" })); // "Today is 5.1.2022 20.02.40. Welcome, User"
                // </04>
            }
            {
                // <05>
                ITemplateBreakdown breakdown1 = TemplateFormat.Percent.Breakdown["Today is %2. Welcome, %1"];
                WriteLine(breakdown1.Print(null, new object?[] { "User", DateTime.Now })); // "Today is 5.1.2022 20.02.40. Welcome, User"
                // </05>
                WriteLine(TemplateFormat.BraceNumeric.Assemble[breakdown1]); // "Today is {1}. Welcome, {0}"
            }
    
            {
                // <06>
                ITemplateBreakdown breakdown = TemplateFormat.BraceAlphaNumeric.Breakdown["Error 0x{code:X8}."];
                WriteLine(breakdown.Print(CultureInfo.InvariantCulture, new object?[] { 0x100 })); // "Error 0x00000100."
                // </06>
            }
            {
                // <07>
                ITemplateBreakdown breakdown = TemplateFormat.BraceAlphaNumeric.Breakdown["User \"{user,13}\""];
                WriteLine(breakdown.Print(CultureInfo.InvariantCulture, new object?[] { "Donald Duck" })); // "User "  Donald Duck""
                // </07>
            }
            {
                // <09>
                ITemplateBreakdown breakdown = TemplateFormat.BraceAlphaNumeric.Breakdown["Welcome, {{{user}}}"];
                WriteLine(breakdown.Print(CultureInfo.InvariantCulture, new object?[] { "Donald Duck" })); // "Welcome, {Donald Duck}"
                // </09>
            }
            {
                // <10>
                ITemplateBreakdown breakdown = TemplateFormat.Parameterless.Breakdown["void Main() {}"];
                WriteLine(breakdown.Print(null, arguments: (object?[]?)null)); // "void Main() {}"
                // </10>
            }
            {
                // <11>
                ITemplateBreakdown breakdown = TemplateFormat.Parameterless.Breakdown["void Main() {}"];
                // Reassembled is escaped
                WriteLine(TemplateFormat.Brace.Assemble[breakdown]); // "void Main() {{}}"
                // </11>
            }
            {
                // <21>
                ITemplateBreakdown breakdown0 = TemplateFormats.All.Detect.Breakdown["Today is now. Welcome, user"];
                ITemplateBreakdown breakdown1 = TemplateFormats.All.Detect.Breakdown["Today is {0}. Welcome, {1}"];
                ITemplateBreakdown breakdown2 = TemplateFormats.All.Detect.Breakdown["Today is {time}. Welcome, {user}"];
                ITemplateBreakdown breakdown3 = TemplateFormats.All.Detect.Breakdown["Today is %1. Welcome, %2"];
    
                WriteLine(breakdown0.TemplateFormat!.Name); // "Parameterless"
                WriteLine(breakdown1.TemplateFormat!.Name); // "BraceNumeric"
                WriteLine(breakdown2.TemplateFormat!.Name); // "BraceAlphaNumeric"
                WriteLine(breakdown3.TemplateFormat!.Name); // "Percent"
                // </21>
    
                WriteLine(TemplateFormats.All.Detect.Assemble[breakdown1]);
            }
            {
                // <22>
                // Create detect format
                ITemplateFormat detect = new DetectTemplateFormat("FormatName", TemplateFormat.Parameterless, TemplateFormat.BraceNumeric);
                // Parse string and detect template format
                ITemplateText templateText = detect.TextCached["Today is {0}. Welcome, {1}."];
                // Print straight to console
                templateText.WriteTo(Console.Out, CultureInfo.InvariantCulture, new object?[] { DateTime.Now, "User" });
                // </22>
            }
            {
                // <30>
                // Builtin template formats
                ITemplateFormats templateFormats = TemplateFormats.All;
                // Get by name
                ITemplateFormat templateFormat = templateFormats.ByName["BraceNumeric"];
                // </30>
            }
        }
    }
    
    
    In This Article
    Back to top Copyright © Toni Kalajainen