• 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

    ILocalizationFile

    ILocalizationFile describes a file reference of a localization resource, text or binary.

    /// <summary>Localization resource, typically a file.</summary>
    public interface ILocalizationFile : ILocalizationFileName, ILocalizationKeyProvider, ICultureProvider
    {
        /// <summary>File format.</summary>
        ILocalizationFileFormat FileFormat { get; set; }
    
        /// <summary>Try open <paramref name="stream"/> to resource.</summary>
        /// <exception cref="Exception">On unexpected error.</exception>
        bool TryOpen([NotNullWhen(true)] out Stream? stream);
    }
    
    /// <summary>Interface for resources that have an assigned filename.</summary>
    public interface ILocalizationFileName
    {
        /// <summary>Resource file name, relative to file provider root, e.g. applicatin root</summary>
        string? FileName { get; set; }
    }
    
    /// <summary>Interface for classes that represent a localization resource.</summary>
    public interface ILocalizationKeyProvider
    {
        /// <summary>Key that identifies the resource. Typically in format of "Namespace.Name". The last dot '.' separates namespaces from name part. If null, then unassigned or resource contains multiple keys.</summary>
        string Key { get; set; }
    }
    
    /// <summary>Culture and format provider.</summary>
    public interface ICultureProvider
    {
        /// <summary>Culture (ISO 649-1)[-(ISO 3166-2)], e.g. "en" or "en-UK". "" for invariant culture. If null, then unassigned or resource is assigned to multiple cultures.</summary>
        string Culture { get; set; }
        /// <summary>Format provider</summary>
        IFormatProvider Format { get; set; }
    }
    

    LocalizationFile describes a file of specific format in a filesystem. Files can be explicitly added to localization.Files.Files.

    // Create localization
    ILocalization localization = new Localization();
    // Create file reference
    ILocalizationFile localizationFile = new LocalizationFile
    {
        FileSystem = LocalizationFileSystem.ApplicationRoot,
        FileName = "Resources/Namespace.l.yaml",
        FileFormat = LocalizationFileFormatYaml.Instance,
        Culture = "",           // File contributes to Invariant culture "". Use null if file contributes to all Cultures
        Key = "Namespace"       // File contributes to "Namespace" prefix. Use null if file contributes to all Namespaces.
    }.SetReadOnly();
    // Add localization file (reference)
    localization.Files.Files.Add(localizationFile);
    
    // Query line
    ITemplateFormatPrintable printable = localization.LocalizableTextCached["Namespace.Apples"];
    // Print
    WriteLine(printable.Print(CultureInfo.GetCultureInfo("en"), new object[] { 2 })); // You've got 2 apples.
    WriteLine(printable.Print(CultureInfo.GetCultureInfo("fi"), new object[] { 2 })); // Sinulla on 2 omenaa.
    

    File can refer to a resource in a file provider.

    // Create localization
    ILocalization localization = new Localization();
    // Create file provider
    IFileProvider fileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
    // Create file-system
    ILocalizationFileSystem filesystem = new LocalizationMsFileSystem(fileProvider);
    // Create file reference
    ILocalizationFile localizationFile = new LocalizationFile
    {
        FileSystem = filesystem,
        FileName = "Resources/Namespace.l.yaml",
        FileFormat = LocalizationFileFormatYaml.Instance,
        Culture = "",
        Key = "Namespace"
    }.SetReadOnly();
    // Add localization file (reference)
    localization.Files.Files.Add(localizationFile);
    
    // Query line
    ITemplateFormatPrintable printable = localization.LocalizableTextCached["Namespace.Apples"];
    // Print
    WriteLine(printable.Print(CultureInfo.GetCultureInfo("en"), new object[] { 2 })); // You've got 2 apples.
    WriteLine(printable.Print(CultureInfo.GetCultureInfo("fi"), new object[] { 2 })); // Sinulla on 2 omenaa.
    

    LocalizationFileInMemory is in-memory resource.

    // Create localization
    ILocalization localization = new Localization();
    // Create file reference
    ILocalizationFile localizationFile = new LocalizationFileInMemory(new byte[] { 0, 1, 2, 3 })
    {
        FileName = "Resources/en/logo.svg",
        FileFormat = new LocalizationFileFormat(".svg"),
        Culture = "en",
        Key = "logo"
    }.SetReadOnly();
    // Add localization file (explicit)
    localization.Files.Files.Add(localizationFile);
    

    localization.Files.Query is provider where files can be queried.

    // Query file
    IEnumerable<ILocalizationFile> files = localization.Files.QueryCached[("en", "logo")];
    

    .TryOpen(out stream) tries to open a stream to a file.

    // Read file
    if (file!.TryOpen(out Stream? stream)) 
    {
        // ...
    
        // Close 
        stream.Dispose();
    }
    

    .Open() opens a stream.

    // Read file
    using Stream stream = file!.Open();
    

    .ReadFully() reads file fully into memory.

    // Read file
    byte[] data = file!.ReadFully();
    

    Full Example

    Full example
    using System.Globalization;
    using Avalanche.Localization;
    using Avalanche.Template;
    using Avalanche.Utilities;
    using Microsoft.Extensions.FileProviders;
    using static System.Console;
    
    public class localizationfile
    {
        public static void Run()
        {
            {
                // <01> 
                // Create localization
                ILocalization localization = new Localization();
                // Create file reference
                ILocalizationFile localizationFile = new LocalizationFile
                {
                    FileSystem = LocalizationFileSystem.ApplicationRoot,
                    FileName = "Resources/Namespace.l.yaml",
                    FileFormat = LocalizationFileFormatYaml.Instance,
                    Culture = "",           // File contributes to Invariant culture "". Use null if file contributes to all Cultures
                    Key = "Namespace"       // File contributes to "Namespace" prefix. Use null if file contributes to all Namespaces.
                }.SetReadOnly();
                // Add localization file (reference)
                localization.Files.Files.Add(localizationFile);
    
                // Query line
                ITemplateFormatPrintable printable = localization.LocalizableTextCached["Namespace.Apples"];
                // Print
                WriteLine(printable.Print(CultureInfo.GetCultureInfo("en"), new object[] { 2 })); // You've got 2 apples.
                WriteLine(printable.Print(CultureInfo.GetCultureInfo("fi"), new object[] { 2 })); // Sinulla on 2 omenaa.
                // </01>
            }
            {
                // <02> 
                // Create localization
                ILocalization localization = new Localization();
                // Create file provider
                IFileProvider fileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
                // Create file-system
                ILocalizationFileSystem filesystem = new LocalizationMsFileSystem(fileProvider);
                // Create file reference
                ILocalizationFile localizationFile = new LocalizationFile
                {
                    FileSystem = filesystem,
                    FileName = "Resources/Namespace.l.yaml",
                    FileFormat = LocalizationFileFormatYaml.Instance,
                    Culture = "",
                    Key = "Namespace"
                }.SetReadOnly();
                // Add localization file (reference)
                localization.Files.Files.Add(localizationFile);
    
                // Query line
                ITemplateFormatPrintable printable = localization.LocalizableTextCached["Namespace.Apples"];
                // Print
                WriteLine(printable.Print(CultureInfo.GetCultureInfo("en"), new object[] { 2 })); // You've got 2 apples.
                WriteLine(printable.Print(CultureInfo.GetCultureInfo("fi"), new object[] { 2 })); // Sinulla on 2 omenaa.
                // </02>
            }
    
            {
                // <10> 
                // Create localization
                ILocalization localization = new Localization();
                // Create file reference
                ILocalizationFile localizationFile = new LocalizationFileInMemory(new byte[] { 0, 1, 2, 3 })
                {
                    FileName = "Resources/en/logo.svg",
                    FileFormat = new LocalizationFileFormat(".svg"),
                    Culture = "en",
                    Key = "logo"
                }.SetReadOnly();
                // Add localization file (explicit)
                localization.Files.Files.Add(localizationFile);
                // </10> 
                {
                    // <11>
                    // Query file
                    IEnumerable<ILocalizationFile> files = localization.Files.QueryCached[("en", "logo")];
                    // </11>
                }
                {
                    // Query file
                    ILocalizationFile? file = localization.Files.QueryCached[("en", "logo")].FirstOrDefault();
                    // <12>
                    // Read file
                    if (file!.TryOpen(out Stream? stream)) 
                    {
                        // ...
    
                        // Close 
                        stream.Dispose();
                    }
                    // </12>
                }
                {
                    // Query file
                    ILocalizationFile? file = localization.Files.QueryCached[("en", "logo")].FirstOrDefault();
                    // <13>
                    // Read file
                    using Stream stream = file!.Open();
                    // </13>
                }
                {
                    // Query file
                    ILocalizationFile? file = localization.Files.QueryCached[("en", "logo")].FirstOrDefault();
                    // <14> 
                    // Read file
                    byte[] data = file!.ReadFully();
                    // </14>
                }
            }
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen