• 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

    YamlConfigurationProvider

    YamlConfigurationProvider represents a .yaml file as configuration source.

    // IConfigurationSource
    var configurationSource = new YamlConfigurationProvider.Source
    {
        FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()),
        Path = "appsettings.yaml",
        ReloadOnChange = true,
        Optional = true
    };
    // IConfigurationProvider
    IConfigurationProvider configurationProvider = new YamlConfigurationProvider(configurationSource);
    // Create configuration
    IConfiguration configuration = new ConfigurationBuilder()
        .Add(configurationSource)
        .Build();
    

    YamlConfigurationExtensions

    .AddYamlFile(path, optional, reloadOnChange) extension method adds a yaml file to IConfigurationBuilder.

    // Create configuration
    IConfiguration configuration = new ConfigurationBuilder()
        .AddYamlFile("appsettings.yaml", optional: true, reloadOnChange: true)
        .Build();
    

    Same extension method works with IHostBuilder.

    // Create host
    IHost host =
        new HostBuilder()
            .ConfigureDefaults(null)
            .ConfigureAppConfiguration(cb => cb.AddYamlFile("appsettings.yaml", optional: true, reloadOnChange: true))
            .Build();
    // Get configuration
    IConfiguration configuration = host.Services.GetRequiredService<IConfiguration>();
    

    YamlNodeExtensions

    .ToYaml(properties, policy, targetRoot?, delimiter) is creates a YamlNode to match contents of 'properties'.

    // Create properties
    var properties = new Dictionary<string, string?>
    {
            { "Cars:0:License", "ABC-123" },
            { "Cars:0:Owner", "Donald" },
            { "Cars:0:PreviousOwners:0", "Mickey" },
            { "Cars:0:PreviousOwners:1", "Goofy" },
            { "Cars:1:License", "XYZ-456" },
            { "Cars:1:Owner", "Mickey" },
            { "Cars:1:PreviousOwners:0", "Pluto" },
            { "Cars:2:License", "YYY-444" },
            { "Cars:2:Owner", "Scrooge" },
    };
    
    // Convert 'properties' to a YamlNode
    YamlNode root = YamlNodeExtensions.ToYaml(
        properties: properties,
        policy: YamlNodeExtensions.CorrelatePolicy.RemoveUnusedNodes | YamlNodeExtensions.CorrelatePolicy.RemoveAmbiguentNodes,
        targetRoot: null,
        delimiter: ':');
    
    // Convert to yaml document
    var stringWriter = new StringWriter();
    YamlDocument yamlDocument = new YamlDocument(root);
    YamlStream yamlStream = new YamlStream(yamlDocument);
    yamlStream.Save(stringWriter, assignAnchors: false);
    string text = stringWriter.ToString();
    // Print
    Console.WriteLine(text);
    
    Cars:
    - License: ABC-123
      Owner: Donald
      PreviousOwners:
      - Mickey
      - Goofy
    - License: XYZ-456
      Owner: Mickey
      PreviousOwners:
      - Pluto
    - License: YYY-444
      Owner: Scrooge
    ...
    

    Method can also synchronize an existing 'targetRoot' to match with the contents of 'properties' key-values.

    // Donald sells car to Minnie
    properties["Cars:0:Owner"] = "Minnie";
    properties["Cars:0:PreviousOwners:2"] = "Donald";
    // Scrooge's car is scrapped
    properties.Remove("Cars:2:License");
    properties.Remove("Cars:2:Owner");
    
    // Synchronize modifications to the already existing 'root' node
    root = YamlNodeExtensions.ToYaml(
        properties: properties,
        policy: YamlNodeExtensions.CorrelatePolicy.RemoveUnusedNodes | YamlNodeExtensions.CorrelatePolicy.RemoveAmbiguentNodes,
        targetRoot: root,
        delimiter: ':');
    
    // Reprint document
    stringWriter = new StringWriter();
    yamlDocument = new YamlDocument(root);
    yamlStream = new YamlStream(yamlDocument);
    yamlStream.Save(stringWriter, assignAnchors: false);
    text = stringWriter.ToString();
    // Print
    Console.WriteLine(text);
    
    Cars:
    - License: ABC-123
      Owner: Minnie
      PreviousOwners:
      - Mickey
      - Goofy
      - Donald
    - License: XYZ-456
      Owner: Mickey
      PreviousOwners:
      - Pluto
    ...
    

    CorrelatePolicy determines synchronization policy.

    [Flags]
    public enum CorrelatePolicy
    {
        RemoveUnusedNodes = 1,
        RemoveAmbiguentNodes = 2,
    }
    

    Full Example

    Full example
    using Avalanche.Configuration;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.FileProviders;
    using Microsoft.Extensions.Hosting;
    using YamlDotNet.RepresentationModel;
    
    public class yaml
    {
        public static void Run()
        {
            {
                // <01>
                // IConfigurationSource
                var configurationSource = new YamlConfigurationProvider.Source
                {
                    FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()),
                    Path = "appsettings.yaml",
                    ReloadOnChange = true,
                    Optional = true
                };
                // IConfigurationProvider
                IConfigurationProvider configurationProvider = new YamlConfigurationProvider(configurationSource);
                // Create configuration
                IConfiguration configuration = new ConfigurationBuilder()
                    .Add(configurationSource)
                    .Build();
                // </01>
                Console.WriteLine(configuration.PrintTree());
            }
    
            {
                // <11>
                // Create configuration
                IConfiguration configuration = new ConfigurationBuilder()
                    .AddYamlFile("appsettings.yaml", optional: true, reloadOnChange: true)
                    .Build();
                // </11>
                // Print configuration
                Console.WriteLine(configuration.PrintTree());
            }
            {
                // <12>
                // Create host
                IHost host =
                    new HostBuilder()
                        .ConfigureDefaults(null)
                        .ConfigureAppConfiguration(cb => cb.AddYamlFile("appsettings.yaml", optional: true, reloadOnChange: true))
                        .Build();
                // Get configuration
                IConfiguration configuration = host.Services.GetRequiredService<IConfiguration>();
                // </12>
                // Print configuration
                Console.WriteLine(configuration.PrintTree());
            }
    
            {
                // <21>
                // Create properties
                var properties = new Dictionary<string, string?>
                {
                        { "Cars:0:License", "ABC-123" },
                        { "Cars:0:Owner", "Donald" },
                        { "Cars:0:PreviousOwners:0", "Mickey" },
                        { "Cars:0:PreviousOwners:1", "Goofy" },
                        { "Cars:1:License", "XYZ-456" },
                        { "Cars:1:Owner", "Mickey" },
                        { "Cars:1:PreviousOwners:0", "Pluto" },
                        { "Cars:2:License", "YYY-444" },
                        { "Cars:2:Owner", "Scrooge" },
                };
    
                // Convert 'properties' to a YamlNode
                YamlNode root = YamlNodeExtensions.ToYaml(
                    properties: properties,
                    policy: YamlNodeExtensions.CorrelatePolicy.RemoveUnusedNodes | YamlNodeExtensions.CorrelatePolicy.RemoveAmbiguentNodes,
                    targetRoot: null,
                    delimiter: ':');
    
                // Convert to yaml document
                var stringWriter = new StringWriter();
                YamlDocument yamlDocument = new YamlDocument(root);
                YamlStream yamlStream = new YamlStream(yamlDocument);
                yamlStream.Save(stringWriter, assignAnchors: false);
                string text = stringWriter.ToString();
                // Print
                Console.WriteLine(text);
                // </21>
    
                // <22>
                // Donald sells car to Minnie
                properties["Cars:0:Owner"] = "Minnie";
                properties["Cars:0:PreviousOwners:2"] = "Donald";
                // Scrooge's car is scrapped
                properties.Remove("Cars:2:License");
                properties.Remove("Cars:2:Owner");
    
                // Synchronize modifications to the already existing 'root' node
                root = YamlNodeExtensions.ToYaml(
                    properties: properties,
                    policy: YamlNodeExtensions.CorrelatePolicy.RemoveUnusedNodes | YamlNodeExtensions.CorrelatePolicy.RemoveAmbiguentNodes,
                    targetRoot: root,
                    delimiter: ':');
    
                // Reprint document
                stringWriter = new StringWriter();
                yamlDocument = new YamlDocument(root);
                yamlStream = new YamlStream(yamlDocument);
                yamlStream.Save(stringWriter, assignAnchors: false);
                text = stringWriter.ToString();
                // Print
                Console.WriteLine(text);
                // </22>
            }
        }
    }
    
    
    In This Article
    Back to top Copyright © Toni Kalajainen