• 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

    PropertyBuilder

    PropertyBuilderRequest is a request to create PropertyBuilder.

    // Create service
    IService service = Services.Create((ServiceHandlers.Instance, EmitHandlers.Instance), CachePolicies.Default);
    // Request to create type builder
    IRequestFor<TypeBuilder> typeBuilder = new TypeBuilderRequest("MyClassWithProperty", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass);
    
    // Initialize property request
    IRequestFor<PropertyBuilder> property = new PropertyBuilderRequest(
        Name: "MyProperty",
        Attributes: PropertyAttributes.None,
        PropertyType: typeof(int),
        ParameterTypes: null);
    

    In this example we create a backing field.

    // Request to create backing field
    IRequestFor<FieldBuilder> field = new FieldBuilderRequest("MyField", typeof(int), FieldAttributes.Public);
    // Add backing field to type request
    typeBuilder = typeBuilder.Append(field);
    

    PropertyBuilderSetSetter is a request to attach a setter method to property.

    // Create set method
    IRequestFor<MethodBuilder> setter = new MethodBuilderRequest(
        Name: "set_MyProperty",
        Attributes: MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
        ReturnType: null,
        ParameterTypes: typeof(int));
    // Create op codes
    IRequestFor<ILGenerator> il = ILGeneratorRequest.Default
        .Append(OpCodes.Ldarg_0)
        .Append(OpCodes.Ldarg_1)
        .Append(OpCodes.Stfld, field)
        .Append(OpCodes.Ret);
    // Add opcodes to method request
    setter = setter.Append(il);
    // Add setter request to type
    typeBuilder.Append(setter);
    // Assign setter to property
    property = property.Append(new PropertyBuilderSetSetter(setter));
    

    And PropertyBuilderSetGetter is a request to attach a getter method.

    // Create get method
    IRequestFor<MethodBuilder> getter = new MethodBuilderRequest(
        Name: "get_MyProperty",
        Attributes: MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
        ReturnType: typeof(int));
    // Create op codes
    IRequestFor<ILGenerator> il = ILGeneratorRequest.Default
        .Append(OpCodes.Ldarg_0)
        .Append(OpCodes.Ldfld, field)
        .Append(OpCodes.Ret);
    // Add opcodes to method request
    getter = getter.Append(il);
    // Add getter request to type
    typeBuilder.Append(getter);
    // Assign setter to property
    property = property.Append(new PropertyBuilderSetGetter(getter));
    

    Once property request is complete, add it to type request.

    // Add property to type request
    typeBuilder = typeBuilder.Append(property);
    

    Request an instance and try it.

    // Request to build type
    IRequestFor<Type> type = new TypeRequest(typeBuilder);
    // Request to create new instance
    IRequestFor<Object> newRequest = type.NewRequest();
    // Print 
    Console.WriteLine(newRequest.PrintTree());
    // Get instance
    object instance = service.GetRequired<IRequestFor<object>, object>(newRequest);
    // Get property with reflection
    PropertyInfo pi = instance.GetType().GetProperty("MyProperty")!;
    // Write with reflection
    pi.SetValue(instance, 9);
    // Read with reflection
    int value = (int)pi.GetValue(instance)!;
    
    View complete request
    NewRequest
    └── Type = TypeRequest
        └── Key = ContextRequest
            ├── Key = "System.Reflection.Emit.TypeBuilder"
            ├── Value = TypeBuilderRequest
            │   ├── Name = "MyClassWithProperty"
            │   └── Attributes = AutoLayout, AnsiClass, Class, Public, AutoClass
            ├── Requests[0] = FieldBuilderRequest
            │   ├── Name = "MyField"
            │   ├── Attributes = Public
            │   └── FieldType = System.Int32
            └── Requests[1] = ContextRequest
                ├── Key = "System.Reflection.Emit.PropertyBuilder"
                ├── Value = PropertyBuilderRequest
                │   ├── Name = "MyProperty"
                │   ├── Attributes = None
                │   └── PropertyType = System.Int32
                ├── Requests[0] = PropertyBuilderSetSetter
                │   └── Setter = ContextRequest
                │       ├── Key = "System.Reflection.Emit.Builder"
                │       ├── Value = MethodBuilderRequest
                │       │   ├── Name = "set_MyProperty"
                │       │   ├── Attributes = PrivateScope, Public, HideBySig, SpecialName
                │       │   └── ParameterTypes[0] = System.Int32
                │       └── Requests[0] = ContextRequest
                │           ├── Key = "System.Reflection.Emit.ILGenerator"
                │           ├── Value = ILGeneratorRequest
                │           ├── Requests[0] = Emit
                │           │   └── Opcode = ldarg.0
                │           ├── Requests[1] = Emit
                │           │   └── Opcode = ldarg.1
                │           ├── Requests[2] = Emit
                │           │   ├── Opcode = stfld
                │           │   └── Parameters[0] = FieldBuilderRequest
                │           └── Requests[3] = Emit
                │               └── Opcode = ret
                └── Requests[1] = PropertyBuilderSetGetter
                    └── Getter = ContextRequest
                        ├── Key = "System.Reflection.Emit.Builder"
                        ├── Value = MethodBuilderRequest
                        │   ├── Name = "get_MyProperty"
                        │   ├── Attributes = PrivateScope, Public, HideBySig, SpecialName
                        │   └── ReturnType = System.Int32
                        └── Requests[0] = ContextRequest
                            ├── Key = "System.Reflection.Emit.ILGenerator"
                            ├── Value = ILGeneratorRequest
                            ├── Requests[0] = Emit
                            │   └── Opcode = ldarg.0
                            ├── Requests[1] = Emit
                            │   ├── Opcode = ldfld
                            │   └── Parameters[0] = FieldBuilderRequest
                            └── Requests[2] = Emit
                                └── Opcode = ret
    

    Full Example

    Full example
    using System;
    using System.Reflection;
    using System.Reflection.Emit;
    using Avalanche.Emit;
    using Avalanche.Service;
    
    public class propertybuilder
    {
        public static void Run()
        {
            {
                // <1>
                // Create service
                IService service = Services.Create((ServiceHandlers.Instance, EmitHandlers.Instance), CachePolicies.Default);
                // Request to create type builder
                IRequestFor<TypeBuilder> typeBuilder = new TypeBuilderRequest("MyClassWithProperty", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass);
    
                // Initialize property request
                IRequestFor<PropertyBuilder> property = new PropertyBuilderRequest(
                    Name: "MyProperty",
                    Attributes: PropertyAttributes.None,
                    PropertyType: typeof(int),
                    ParameterTypes: null);
                // </1>
                // <2>
                // Request to create backing field
                IRequestFor<FieldBuilder> field = new FieldBuilderRequest("MyField", typeof(int), FieldAttributes.Public);
                // Add backing field to type request
                typeBuilder = typeBuilder.Append(field);
                // </2>
                {
                    // <3>
                    // Create set method
                    IRequestFor<MethodBuilder> setter = new MethodBuilderRequest(
                        Name: "set_MyProperty",
                        Attributes: MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
                        ReturnType: null,
                        ParameterTypes: typeof(int));
                    // Create op codes
                    IRequestFor<ILGenerator> il = ILGeneratorRequest.Default
                        .Append(OpCodes.Ldarg_0)
                        .Append(OpCodes.Ldarg_1)
                        .Append(OpCodes.Stfld, field)
                        .Append(OpCodes.Ret);
                    // Add opcodes to method request
                    setter = setter.Append(il);
                    // Add setter request to type
                    typeBuilder.Append(setter);
                    // Assign setter to property
                    property = property.Append(new PropertyBuilderSetSetter(setter));
                    // </3>
                }
                {
                    // <4>
                    // Create get method
                    IRequestFor<MethodBuilder> getter = new MethodBuilderRequest(
                        Name: "get_MyProperty",
                        Attributes: MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
                        ReturnType: typeof(int));
                    // Create op codes
                    IRequestFor<ILGenerator> il = ILGeneratorRequest.Default
                        .Append(OpCodes.Ldarg_0)
                        .Append(OpCodes.Ldfld, field)
                        .Append(OpCodes.Ret);
                    // Add opcodes to method request
                    getter = getter.Append(il);
                    // Add getter request to type
                    typeBuilder.Append(getter);
                    // Assign setter to property
                    property = property.Append(new PropertyBuilderSetGetter(getter));
                    // </4>
                }
                // <5>
                // Add property to type request
                typeBuilder = typeBuilder.Append(property);
                // </5>
                // <6>
                // Request to build type
                IRequestFor<Type> type = new TypeRequest(typeBuilder);
                // Request to create new instance
                IRequestFor<Object> newRequest = type.NewRequest();
                // Print 
                Console.WriteLine(newRequest.PrintTree());
                // Get instance
                object instance = service.GetRequired<IRequestFor<object>, object>(newRequest);
                // Get property with reflection
                PropertyInfo pi = instance.GetType().GetProperty("MyProperty")!;
                // Write with reflection
                pi.SetValue(instance, 9);
                // Read with reflection
                int value = (int)pi.GetValue(instance)!;
                // </6>
                // Print 
                Console.WriteLine(newRequest.PrintTree());
            }
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen