• 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

    ContextParameterAttribute

    [ContextParameter(string name)] indicates that value in a field can be assigned from context dictionary during evaluation.

    /// <summary>Request to add line to list</summary>
    public record AddLineRequest([Request] object Line) : IRequestFor<List<string>>, IRequestNotToBeCached
    {
        /// <summary>List to modify.</summary>
        [ContextParameter("List")]
        public List<string> List { get; init; } = null!;
    }
    

    Handler

    When handler receives the request, it should test whether value has been assigned to the field with [ContextParameter] attribute.

    /// <summary>Add a line to list</summary>
    public class AddLineHandler : IHandler<AddLineRequest, List<string>>
    {
        /// <summary>Add line to list</summary>
        public void Handle(IQuery<AddLineRequest, List<string>> query)
        {
            // Already handled
            if (query.Handled()) return;
            // Get list
            if (query.Request.List is not List<string> list) return;
            // Get line
            if (query.Request.Line is not string line) return;
    
            // Add line
            list.Add(line);
            // Done
            query.Response.SetValue(list);
        }
    }
    

    Context-Assigned Request

    ServiceHandlers must be included in the service stack for context parameter binding to work.

    IService service = Services.Create((ServiceHandlers.Instance, new AddLineHandler()));
    

    Request can be instantiated context-free.

    // Create request to add line
    IRequest addLineRequest = new AddLineRequest("Hello");
    
    AddLineRequest
    └── Line = "Hello"
    

    Contextual environment is carried in an IDictionary<string, object>.

    // Create list
    List<string> list = new List<string>();
    // Create context
    Dictionary<string, object> ctx = new() { { "List", list } };
    

    Dictionary can be passed down in 'context' argument of IService methods.

    // Invoke request and provide explicit context
    service.TryInvoke(addLineRequest, context: ctx);
    

    Context-Environment Request

    ContextRequest and ContextRequest<T> are requests that evaluate a batch of subrequests in an environment where one context parameter is bound to a source of value that is to be evaluated.

    // Request to evaluate in a context where "List" is bound to 'list'
    ContextRequest contextRequest = new ContextRequest("List", list, addLineRequest);
    
    ContextRequest<Object>
    ├── Key = "List"
    ├── Value = System.Collections.Generic.List`1[System.String]
    └── Requests[0] = AddLineRequest
        └── Line = "Hello"
    

    Service is invoked without need for context dictionary.

    // Invoke request
    service.TryInvoke(contextRequest);
    

    No Contextual Environment

    If reference to 'list' is known at time of instantiation, it can be assigned directly into the request and no contextual environment is needed.

    // Create request to add line to a list
    IRequest addLineRequest2 = new AddLineRequest("Hello") { List = list };
    // Invoke request
    service.TryInvoke(addLineRequest2);
    
    AddLineRequest
    ├── Line = "Hello"
    └── List = System.Collections.Generic.List`1[System.String]
    

    Full Example

    Full example
    using System;
    using System.Collections.Generic;
    using Avalanche.Service;
    
    public class request_contextparameter
    {
        public static void Run()
        {
            // Create service
            // <01>
            IService service = Services.Create((ServiceHandlers.Instance, new AddLineHandler()));
            // </01>
            // <02>
            // Create request to add line
            IRequest addLineRequest = new AddLineRequest("Hello");
            // </02>
            // <03>
            // Create list
            List<string> list = new List<string>();
            // Create context
            Dictionary<string, object> ctx = new() { { "List", list } };
            // </03>
            // <04>
            // Invoke request and provide explicit context
            service.TryInvoke(addLineRequest, context: ctx);
            // </04>
            // Print request
            Console.WriteLine(addLineRequest.PrintTree());
    
            // <11>
            // Request to evaluate in a context where "List" is bound to 'list'
            ContextRequest contextRequest = new ContextRequest("List", list, addLineRequest);
            // </11>
            // <12>
            // Invoke request
            service.TryInvoke(contextRequest);
            // </12>
            // Print request
            Console.WriteLine(contextRequest.PrintTree());
    
            // <13>
            // Create request to add line to a list
            IRequest addLineRequest2 = new AddLineRequest("Hello") { List = list };
            // Invoke request
            service.TryInvoke(addLineRequest2);
            // </13>
            // Print request
            Console.WriteLine(addLineRequest2.PrintTree());
        }
    }
    
    // <20>
    /// <summary>Request to add line to list</summary>
    public record AddLineRequest([Request] object Line) : IRequestFor<List<string>>, IRequestNotToBeCached
    {
        /// <summary>List to modify.</summary>
        [ContextParameter("List")]
        public List<string> List { get; init; } = null!;
    }
    // </20>
    
    // <21>
    /// <summary>Add a line to list</summary>
    public class AddLineHandler : IHandler<AddLineRequest, List<string>>
    {
        /// <summary>Add line to list</summary>
        public void Handle(IQuery<AddLineRequest, List<string>> query)
        {
            // Already handled
            if (query.Handled()) return;
            // Get list
            if (query.Request.List is not List<string> list) return;
            // Get line
            if (query.Request.Line is not string line) return;
    
            // Add line
            list.Add(line);
            // Done
            query.Response.SetValue(list);
        }
    }
    // </21>
    
    
    In This Article
    Back to top Copyright © Toni Kalajainen