• 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

    ILocalizationFileSystem

    ILocalizationFileSystem is the interface for providing access to localization resources.

    /// <summary>Interface to file system, such as OS, Microsoft.Extensions.FileSystem, embedded resources file-system.</summary>
    public interface ILocalizationFileSystem
    {
        /// <summary>Try list files at <paramref name="path"/>.</summary>
        /// <param name="path">path, "" for root. Slash '/' is directory separator, e.g. "path/path".</param>
        /// <param name="files">File names relative to root.</param>
        /// <exception cref="Exception">On unexpected error.</exception>
        bool TryListFiles(string path, [NotNullWhen(true)] out string[]? files);
    
        /// <summary>Try list sub-directories of <paramref name="path"/>.</summary>
        /// <param name="path">path, "" for root. Slash '/' is directory separator, e.g. "path/path".</param>
        /// <param name="directories">Directory names relative to root.</param>
        /// <exception cref="Exception">On unexpected error.</exception>
        bool TryListDirectories(string path, [NotNullWhen(true)] out string[]? directories);
    
        /// <summary>Try open <paramref name="filepath"/>.</summary>
        /// <param name="filepath">Relative file path, "" for root. Slash '/' is directory separator, e.g. "path/path".</param>
        /// <exception cref="Exception">On unexpected error.</exception>
        bool TryOpen(string filepath, [NotNullWhen(true)] out Stream stream);
    }
    

    LocalizationFileSystem.ApplicationRoot represents all the files at the application root.

    // Create filesystem
    ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot;
    // Create localization
    ILocalization localization = new Localization().AddFileSystem(fs);
    

    .Cached(cacheLists, cacheFiles) decorates file system to cache listings and/or files.

    // Create filesystem
    ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(cacheLists: true, cacheFiles: true);
    // Create localization
    ILocalization localization = new Localization().AddFileSystem(fs);
    

    LocalizationFileSystem.ApplicationRootCached is the singleton where file lists are already cached.

    ILocalization localization = new Localization().AddFileSystem(LocalizationFileSystem.ApplicationRootCached);
    

    Localization.Default is preconfigured with LocalizationFileSystem.ApplicationRoot. The reference can be removed if it's not desired for the deployment.

    Localization.Default.Files.FileSystems.Remove(LocalizationFileSystem.ApplicationRoot);
    

    If application localization files are immutable, as they typically are, and the file tree is vast, then it may be better to replace filesystem with cached version.

    Localization.Default.Files.FileSystems.Remove(LocalizationFileSystem.ApplicationRoot);
    Localization.Default.Files.FileSystems.Add(LocalizationFileSystem.ApplicationRootCached);
    

    LocalizationFileSystem(path, name) constructs access to file tree at a specific path.

    // Create filesystem
    ILocalizationFileSystem fs = new LocalizationFileSystem("C:\\", name: "Root");
    // Create localization
    ILocalization localization = new Localization().AddFileSystem(fs);
    

    LocalizationMsFileSystem(fileProvider) (Avalanche.Localization.Extensions.dll) adapts IFileProvider to ILocalizationFileSystem.

    // Create file provider
    IFileProvider fileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
    // Adapt to localization file system
    ILocalizationFileSystem fs = new LocalizationMsFileSystem(fileProvider);
    // Create localization
    ILocalization localization = new Localization()
        .AddFileSystem(fs)
        .AddFilePatterns("Resources/{Key}", "Resources/{Culture}/{Key}");
    

    LocalizationFileSystemEmbedded(assemblies) adds access to embedded resources of one or more specific assemblies.

    // Get assembly reference
    Assembly assembly = typeof(localizationfilesystem).Assembly;
    // Create filesystem
    ILocalizationFileSystem fs = new LocalizationFileSystemEmbedded(assembly)
        .Cached(cacheLists: true, cacheFiles: true);
    // Create localization
    ILocalization localization = new Localization()
        .AddFileSystem(fs)
        .AddFilePatterns("*/*.Resources.{Key}", "*/*.Resources.{Culture}.{Key}", "*/{Key}", "*/{Key}.{Culture}");
    
    └── docs
        ├── docs/docs.Resources.fi.Namespace.l.yaml
        ├── docs/docs.Resources.sv.Namespace.l.yaml
        └── docs/docs.Resources.Namespace.l.yaml
    

    LocalizationFileSystemEmbedded.AppDomain provides access to all embedded resources of all assemblies in current AppDomain. Note that, if appdomain loads additional assemblies at run-time, then it shouldn't be cached.

    // Create filesystem
    ILocalizationFileSystem fs = LocalizationFileSystemEmbedded.AppDomain;
    // Create localization
    ILocalization localization = new Localization().AddFileSystem(fs);
    
    ├── System.Linq/
    │   ├── FxResources.System.Linq.SR.resources
    │   ├── ILLink.Descriptors.xml
    │   └── ILLink.Substitutions.xml
    ...
    

    .AddFileSystemWithPattern(filesystem, patterns) adds to .Files.FileProviders a file system with usage of specific patterns. Patterns are not applied to any other configured file system.

    // Create localization
    ILocalization localization = new Localization()
        .AddFileFormat(LocalizationFileFormatYaml.Instance)
        .AddFileSystemWithPattern(LocalizationFileSystemEmbedded.AppDomain, "*/*.Resources.{Key}", "*/*.Resources.{Culture}.{Key}", "*/{Key}", "*/{Key}.{Culture}");
    

    Listing files

    .ListFiles(path) lists files at path.

    foreach (string filename in LocalizationFileSystem.ApplicationRoot.ListFiles("")!)
        WriteLine(filename);
    

    .ListAllFiles(path) lists all files recursively starting at path.

    foreach (string filename in LocalizationFileSystem.ApplicationRoot.ListAllFiles("")!)
        WriteLine(filename);
    
    Resources/Namespace.sv.l.yaml
    Resources/Namespace.l.yaml
    

    .ListDirectories(path) lists directories path.

    foreach (string filename in LocalizationFileSystem.ApplicationRoot.ListDirectores("")!)
        WriteLine(filename);
    

    .ListAllDirectories(path) lists all directories recursively starting at path.

    ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(true, true);
    foreach (string filename in fs.ListAllDirectories("")!)
        WriteLine(filename);
    

    .VisitTree(path) visits tree of directories and files.

    ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(true, true);
    foreach (var line in fs.VisitTree(""))
        WriteLine(line);
    

    .PrintTree(path) prints as a tree.

    ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(true, true);
    WriteLine(fs.PrintTree(""));
    
    ├── Resources
    │   ├── fi
    │   │   └── Namespace.l.yaml
    │   ├── sv
    │   │   └── Namespace.l.yaml
    │   └── Namespace.l.yaml
    

    .PrintTree(path, format) prints as a tree with full paths names.

    ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(true, true);
    WriteLine(fs.PrintTree("", format: LocalizationFileSystemPrintTreeExtensions.PrintFormat.DefaultLong));
    
    ├── Resources/
    │   ├── Resources/fi/
    │   │   └── Resources/fi/Namespace.l.yaml
    │   ├── Resources/sv/
    │   │   └── Resources/sv/Namespace.l.yaml
    │   └── Resources/Namespace.l.yaml
    
    Note

    Path separator is forward slash '/'.

    Opening files

    .Open(path) opens a stream to a file.

    ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot;
    using Stream? stream = fs.Open("Resources/Namespace.l.yaml");
    

    .ReadFullypen(path) reads a file fully.

    ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot;
    byte[] data = fs.ReadFully("Resources/Namespace.l.yaml");
    

    Full Example

    Full example
    using System.Globalization;
    using System.Reflection;
    using Avalanche.Localization;
    using Avalanche.Utilities;
    using Avalanche.Utilities.Provider;
    using Microsoft.Extensions.FileProviders;
    using static System.Console;
    
    class localizationfilesystem
    {
        public static void Run()
        {
            {
                // <00>
                // Create filesystem
                ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot;
                // Create localization
                ILocalization localization = new Localization().AddFileSystem(fs);
                // </00>
            }
            {
                // <01>
                // Create filesystem
                ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(cacheLists: true, cacheFiles: true);
                // Create localization
                ILocalization localization = new Localization().AddFileSystem(fs);
                // </01>
            }
            {
                // <01B>
                ILocalization localization = new Localization().AddFileSystem(LocalizationFileSystem.ApplicationRootCached);
                // </01B>
            }
            {
                // <1C>
                Localization.Default.Files.FileSystems.Remove(LocalizationFileSystem.ApplicationRoot);
                // </1C>
            }
            {
                // <1D>
                Localization.Default.Files.FileSystems.Remove(LocalizationFileSystem.ApplicationRoot);
                Localization.Default.Files.FileSystems.Add(LocalizationFileSystem.ApplicationRootCached);
                // </1D>
            }
            {
                // <02>
                // Create filesystem
                ILocalizationFileSystem fs = new LocalizationFileSystem("C:\\", name: "Root");
                // Create localization
                ILocalization localization = new Localization().AddFileSystem(fs);
                // </02>
            }
            {
                // <03>
                // Create file provider
                IFileProvider fileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
                // Adapt to localization file system
                ILocalizationFileSystem fs = new LocalizationMsFileSystem(fileProvider);
                // Create localization
                ILocalization localization = new Localization()
                    .AddFileSystem(fs)
                    .AddFilePatterns("Resources/{Key}", "Resources/{Culture}/{Key}");
                // </03>
            }
            {
                // <04>
                // Get assembly reference
                Assembly assembly = typeof(localizationfilesystem).Assembly;
                // Create filesystem
                ILocalizationFileSystem fs = new LocalizationFileSystemEmbedded(assembly)
                    .Cached(cacheLists: true, cacheFiles: true);
                // Create localization
                ILocalization localization = new Localization()
                    .AddFileSystem(fs)
                    .AddFilePatterns("*/*.Resources.{Key}", "*/*.Resources.{Culture}.{Key}", "*/{Key}", "*/{Key}.{Culture}");
                // </04>
                WriteLine(fs.PrintTree("", format: LocalizationFileSystemPrintTreeExtensions.PrintFormat.DefaultLong));
                // Open each file in assembly
                foreach (string resourceName in fs.ListAllFiles("")) fs.ReadFully(resourceName);
            }
            {
                // <05>
                // Create filesystem
                ILocalizationFileSystem fs = LocalizationFileSystemEmbedded.AppDomain;
                // Create localization
                ILocalization localization = new Localization().AddFileSystem(fs);
                // </05>
                WriteLine(fs.PrintTree("", format: LocalizationFileSystemPrintTreeExtensions.PrintFormat.DefaultLong));
                // Open each file in appdomain
                foreach (string resourceName in fs.ListAllFiles("")) fs.ReadFully(resourceName);
            }
            {
                // <06>
                // Create localization
                ILocalization localization = new Localization()
                    .AddFileFormat(LocalizationFileFormatYaml.Instance)
                    .AddFileSystemWithPattern(LocalizationFileSystemEmbedded.AppDomain, "*/*.Resources.{Key}", "*/*.Resources.{Culture}.{Key}", "*/{Key}", "*/{Key}.{Culture}");
                // </06>
                // Print Text
                WriteLine(localization.LocalizedTextCached[("", "Namespace.Apples")].Print(CultureInfo.InvariantCulture, null)); // "You've got  apples."
            }
    
            {
                // <10>
                foreach (string filename in LocalizationFileSystem.ApplicationRoot.ListFiles("")!)
                    WriteLine(filename);
                // </10>
            }
            {
                // <11>
                foreach (string filename in LocalizationFileSystem.ApplicationRoot.ListAllFiles("")!)
                    WriteLine(filename);
                // </11>
            }
            {
                // <12>
                foreach (string filename in LocalizationFileSystem.ApplicationRoot.ListDirectores("")!)
                    WriteLine(filename);
                // </12>
            }
            {
                // <13>
                ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(true, true);
                foreach (string filename in fs.ListAllDirectories("")!)
                    WriteLine(filename);
                // </13>
            }
            WriteLine(); WriteLine();
            {
                // <14>
                ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(true, true);
                foreach (var line in fs.VisitTree(""))
                    WriteLine(line);
                // </14>
            }
            WriteLine(); WriteLine();
            {
                // <15>
                ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(true, true);
                WriteLine(fs.PrintTree(""));
                // </15>
            }
            WriteLine(); WriteLine();
            {
                // <16>
                ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot.Cached(true, true);
                WriteLine(fs.PrintTree("", format: LocalizationFileSystemPrintTreeExtensions.PrintFormat.DefaultLong));
                // </16>
            }
            WriteLine(); WriteLine();
            {
                // <20>
                ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot;
                using Stream? stream = fs.Open("Resources/Namespace.l.yaml");
                // </20>
            }
            {
                // <21>
                ILocalizationFileSystem fs = LocalizationFileSystem.ApplicationRoot;
                byte[] data = fs.ReadFully("Resources/Namespace.l.yaml");
                // </21>
            }
    
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen