Inheritance: System.Reflection.MemberInfo
		/// <summary>
		/// Gets the event handler.
		/// </summary>
		/// <param name="instance">
		/// The instance that is registering for the event notification.
		/// </param>
		/// <param name="info">
		/// Event metadata about the event.
		/// </param>
		/// <returns>
		/// The event handler.
		/// </returns>
		protected override Delegate GetHandler(object instance, EventInfo info)
		{
			MethodInfo methodMeta = ResolveHandlerMethod(
				ReflectionUtils.TypeOfOrType(instance),
				info.EventHandlerType,
				InstanceEventHandlerValue.InstanceMethodFlags);
			Delegate callback = null;
			if (methodMeta.IsStatic)
			{
				// case insensitive binding to a static method on an (irrelevant) instance
				callback = Delegate.CreateDelegate(
					info.EventHandlerType,
					methodMeta);
			}
			else
			{
				// case insensitive binding to an instance method on an instance
				callback =
					Delegate.CreateDelegate(
						info.EventHandlerType,
						instance,
						MethodName,
						true);
			}
			return callback;
		}
Ejemplo n.º 2
0
 /// <summary>
 /// Wires the event.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="event">The event.</param>
 /// <param name="handler">The handler.</param>
 public static void WireEvent(object sender, EventInfo @event, Action<object, EventArgs> handler)
 {
     @event.AddEventHandler(
         sender,
         Delegate.CreateDelegate(@event.EventHandlerType, handler.Target, handler.Method)
         );
 }
Ejemplo n.º 3
0
 public EventBuilder(TypeBuilder toType, FieldInfo objBase, EventInfo parentEvent)
     : base(toType, objBase)
 {
     ParentEvent = parentEvent;
     if (!CompareExchange.ContainsKey(ParentEvent.EventHandlerType))
         CompareExchange.TryAdd(ParentEvent.EventHandlerType, _CompareExchange.MakeGenericMethod(ParentEvent.EventHandlerType));
 }
Ejemplo n.º 4
0
        public static NameType TryGetName(TotemType dt, EventInfo ei, MethodInfo eventMethod, out string name)
        {
            name = ei.Name;
            NameType res = dt.IsTotemType ? NameType.TotemEvent : NameType.Event;

            return GetNameFromMethod(dt, eventMethod, res, ref name);
        }
Ejemplo n.º 5
0
        private static void GetDataForComInvocation(System.Reflection.EventInfo eventInfo, out Guid sourceIid, out int dispid)
        {
            object[] comEventInterfaces = eventInfo.DeclaringType.GetCustomAttributes(typeof(ComEventInterfaceAttribute), false);

            if (comEventInterfaces == null || comEventInterfaces.Length == 0)
            {
                // TODO: event strings need to be localizable
                throw new InvalidOperationException("event invocation for COM objects requires interface to be attributed with ComSourceInterfaceGuidAttribute");
            }

            if (comEventInterfaces.Length > 1)
            {
                // TODO: event strings need to be localizable
                throw new System.Reflection.AmbiguousMatchException("more than one ComSourceInterfaceGuidAttribute found");
            }

            Type sourceItf = ((ComEventInterfaceAttribute)comEventInterfaces[0]).SourceInterface;
            Guid guid      = sourceItf.GUID;

            System.Reflection.MethodInfo methodInfo = sourceItf.GetMethod(eventInfo.Name);
            Attribute dispIdAttribute = Attribute.GetCustomAttribute(methodInfo, typeof(DispIdAttribute));

            if (dispIdAttribute == null)
            {
                // TODO: event strings need to be localizable
                throw new InvalidOperationException("event invocation for COM objects requires event to be attributed with DispIdAttribute");
            }

            sourceIid = guid;
            dispid    = ((DispIdAttribute)dispIdAttribute).Value;
        }
Ejemplo n.º 6
0
 public CallInfoCacheItem(EventInfo ei)
 {
     this.Call = ei.CreateDynamicFunc();
     EI = ei;
     MI = ei.EventHandlerType.GetMethod("Invoke");
     SetParamInfo();
 }
        public DomEventInstance(DomNodeInstance node, EventInfo eventInfo)
        {
            Getter = new ClrFunctionInstance(node.Engine, (thisObject, arguments) => _function ?? JsValue.Null);
            Setter = new ClrFunctionInstance(node.Engine, (thisObject, arguments) =>
            {
                if (_handler != null)
                {
                    eventInfo.RemoveEventHandler(node.Value, _handler);
                    _handler = null;
                    _function = null;
                }

                if (arguments[0].Is<FunctionInstance>())
                {
                    _function = arguments[0].As<FunctionInstance>();
                    _handler = (s, ev) => 
                    {
                        var sender = s.ToJsValue(node.Context);
                        var args = ev.ToJsValue(node.Context);
                        _function.Call(sender, new [] { args });
                    };
                    eventInfo.AddEventHandler(node.Value, _handler);
                }

                return arguments[0];
            });
        }
Ejemplo n.º 8
0
        public void Init(string fullName, int flags, JsTypeFunction thisType, JsTypeFunction baseType, JsTypeFunction[] interfaces, JsTypeFunction[] typeArguments, FieldInfo[] fields, MethodInfo[] methods, ConstructorInfo[] constructors, PropertyInfo[] properties, EventInfo[] events, JsTypeFunction elementType, JsTypeFunction unconstructedType)
        {
            FullName = fullName;

            typeFlags = (TypeFlags)flags;

//            this.typeAttributes = typeAttributes;
            this.thisType = thisType;
            this.baseType = baseType;
            this.interfaces = interfaces;
            this.typeArguments = typeArguments;
            this.fields = fields ?? new FieldInfo[0];
            this.methods = methods ?? new MethodInfo[0];
            this.properties = properties ?? new PropertyInfo[0];
            this.constructors = constructors ?? new ConstructorInfo[0];
            this.events = events ?? new EventInfo[0];
            this.elementType = elementType;
            this.unconstructedType = unconstructedType;

            foreach (var field in this.fields)
                field.declaringType = this;
            foreach (var method in this.methods)
                method.declaringType = this;
            foreach (var property in this.properties)
            {
                property.declaringType = this;
                if (property.GetMethod != null)
                    property.GetMethod.declaringType = this;
                if (property.SetMethod != null)
                    property.SetMethod.declaringType = this;
            }
            foreach (var constructor in this.constructors)
                constructor.declaringType = this;
        }
        private EventBuilder CreateProxyEventBuilder(TypeBuilder typeBuilder, EventInfo contractEvent)
        {
            var builder = typeBuilder.DefineEvent(contractEvent.Name, contractEvent.Attributes,
                                                  contractEvent.EventHandlerType);

            return builder;
        }
        private void BuildPropertyProxy(TypeBuilder typeBuilder, EventInfo contractEvent)
        {
            var builder = CreateProxyEventBuilder(typeBuilder, contractEvent);

            BuildRemover(typeBuilder, contractEvent, builder);
            BuildAdder(typeBuilder, contractEvent, builder);
        }
Ejemplo n.º 11
0
 public DocumentedEvent(Identifier name, XmlNode xml, EventInfo ev, Type targetType)
 {
     Name = name;
     Xml = xml;
     Event = ev;
     TargetType = targetType;
 }
 internal WorkflowMessageEventHandler(Type proxiedType, EventInfo eventInfo, IDeliverMessage enqueueWrapper)
 {
     this.proxiedType = proxiedType;
     this.eventName = eventInfo.Name;
     this.eventHandlerType = eventInfo.EventHandlerType;
     this.enqueueWrapper = enqueueWrapper;
 }
 internal EventInterceptionAspectDefinition(IAspect aspect, Type aspectDeclaringType, EventInfo @event, MemberInfo target)
 {
     Aspect = aspect;
     Member = @event;
     Target = target;
     AspectDeclaringType = aspectDeclaringType;
 }
Ejemplo n.º 14
0
		public ScriptObjectEventInfo (string name, ScriptObject callback, EventInfo ei)
		{
			Name = name;
			Callback = callback;
			EventInfo = ei;
			NativeMethods.html_object_retain (PluginHost.Handle, Callback.Handle);
		}
Ejemplo n.º 15
0
        private static void WriteExtensionMethod(Type type, EventInfo eventInfo, StringBuilder builder, SortedSet<string> usingNamespaces)
        {
            var eventType = eventInfo.EventHandlerType.Name; // e.g. MouseEventHandler
            var eventName = eventInfo.Name; // e.g. MouseMove
            var eventArgs = eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters()[1].ParameterType; // e.g. MouseEventArgs

            // TODO: Is event args ever generic? Might need to cope with that

            if (eventInfo.EventHandlerType.IsGenericType)
            {
                switch (eventInfo.EventHandlerType.Name)
                {
                    case "ReturnEventHandler`1":
                        eventType = string.Format("ReturnEventHandler<{0}>", eventArgs.Name);
                        break;
                    case "RoutedPropertyChangedEventHandler`1":
                        eventType = string.Format("RoutedPropertyChangedEventHandler<{0}>", eventArgs.Name);
                        break;
                    case "EventHandler`1":
                        eventType = string.Format("EventHandler<{0}>", eventArgs.Name);
                        break;
                    default:
                        throw new Exception("Can't cope with other generic types");
                }
            }

            usingNamespaces.Add(eventInfo.EventHandlerType.Namespace);
            usingNamespaces.Add(eventArgs.Namespace);

            builder.AppendLine(string.Format("\t\tpublic static IObservable<EventPattern<{0}>> {1}Observer(this {2} This)", eventArgs.Name, eventName, type.Name));
            builder.AppendLine("\t\t{");
            builder.AppendLine(string.Format("\t\t\treturn Observable.FromEventPattern<{0}, {1}>(h => This.{2} += h, h => This.{2} -= h);", eventType, eventArgs.Name, eventName));
            builder.AppendLine("\t\t}");
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="namespace"></param>
        /// <param name="name"></param>
        /// <param name="isGenericType"></param>
        /// <param name="basetype"></param>
        /// <param name="isValueType"></param>
        /// <param name="isByRef"></param>
        /// <param name="isEnum"></param>
        /// <param name="isPointer"></param>
        /// <param name="ElementType">
        /// Type of the object encompassed or referred to by the current array, pointer or reference type. It's what GetElementType() will return.
        /// Specify null when it is not needed
        /// </param>
        public ArtificialType(string @namespace, string name, bool isGenericType, Type basetype, 
                              bool isValueType, bool isByRef, bool isEnum, bool isPointer, Type ElementType,
                              bool isInterface,
                              bool isAbstract,
                              Type MReturnSynType
                            )
        {
            _Name = name;
            _Namespace = @namespace;
            _IsGenericType = isGenericType;
            _BaseType = basetype;
            _IsValueType = isValueType;
            _IsByRef = isByRef;
            _IsEnum = isEnum;
            _IsPointer = isPointer;
            _IsInterface = isInterface;
            _IsAbstract = isAbstract;


            _Method1 = new ArtificialMethodInfo("M", this, typeof(int[]), MethodAttributes.Public | (_IsAbstract ? MethodAttributes.PrivateScope | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Abstract : MethodAttributes.Static), null, false);
            _Method2 = new ArtificialMethodInfo("RaiseEvent1", this, typeof(void), MethodAttributes.Public | (_IsAbstract ? MethodAttributes.Abstract : 0), null, false);
            _Method3 = new ArtificialMethodInfo("M1", this, this, MethodAttributes.Public | MethodAttributes.Static | (_IsAbstract ? MethodAttributes.Abstract : 0), new[] { new ArtificialParamInfo("x1", basetype, false) }, false);
            _Method4 = new ArtificialMethodInfo("M2", this, this, MethodAttributes.Public | MethodAttributes.Static | (_IsAbstract ? MethodAttributes.Abstract : 0), new[] { new ArtificialParamInfo("y1", this, false) }, false);

            _Property1 = new ArtificialPropertyInfo("StaticProp1", this, typeof(decimal), true, false);
            _Property2 = new ArtificialPropertyInfo("StaticProp2", this, typeof(System.Tuple<int, int, int, int, int, int, int, System.Tuple<int, int, int>>), true, false);
            _Property3 = new ArtificialPropertyInfo("StaticProp3", this, typeof(System.Tuple<int, int, int>), true, false);
            _Event1 = new ArtificalEventInfo("Event1", this, typeof(EventHandler));
            _Ctor1 = new ArtificialConstructorInfo(this, new ParameterInfo[] {} );  // parameter-less ctor
            _ElementType = ElementType;
        }
Ejemplo n.º 17
0
 internal CLSEvent(String name, Type type, EventInfo eventInfo, Boolean isStatic)
 {
     this.isStatic = isStatic;
     this.eventInfo = eventInfo;
     this.type = type;
     this.name = name;
 }
Ejemplo n.º 18
0
 public RemoveEventDecoratorWeaver(IEventTypeBuilder eventTypeBuilder, EventInfo @event, IWeavingSettings weavingSettings)
     : base(@event.GetRemoveMethod(), weavingSettings)
 {
     MethodEndWeaver = new MethodEndWeaver();
     MethodScopeWeaver = new RemoveEventDecoratorScopeWeaver(method, weavingSettings);
     MethodDefintionWeaver = new RemoveEventMethodSignatureWeaver(eventTypeBuilder, weavingSettings.TypeDefinition);
 }
Ejemplo n.º 19
0
		internal EventMonitor(IRoutedMessageHandler messageHandler, EventInfo eventInfo)
		{
			_messageHandler = messageHandler;
			_triggersToNotify = new List<IMessageTrigger>();

			EventHelper.WireEvent(messageHandler.Unwrap(), eventInfo, ChangedEventHandler);
		}
 public DependencyPropertyProxy(object context, PropertyInfo property, EventInfo updateEvent)
     : base(context, updateEvent, _triggerMethodInfo)
 {
     _context = context;
     _property = property;
     DetectProperty();
 }
Ejemplo n.º 21
0
 internal EventHookupHelper(string handlerName, EventInfo eventInfo,
     string scriptVirtualPath)
 {
     _handlerName = handlerName;
     _eventInfo = eventInfo;
     _scriptVirtualPath = scriptVirtualPath;
 }
		// ReSharper restore UnusedMember.Local

		public override void RuntimeInitialize( EventInfo eventInfo )
		{
			// An event always has a declaring type.
			Contract.Assume( eventInfo.DeclaringType != null );

			base.RuntimeInitialize( eventInfo );

			Type declaringType = eventInfo.DeclaringType;
			_declaringGenericType = declaringType.IsGenericType ? declaringType.GetGenericTypeDefinition() : declaringType;

			_addEmptyEventHandlers = new CachedDictionary<Type, Action<object>>( type =>
			{
				// Find the type in which the constructor is defined.
				// Needed since events can be private, and those wouldn't be returned otherwise, even when searching a flattened hierarchy.
				Type baseType = type.GetMatchingGenericType( _declaringGenericType );

				EventInfo runtimeEvent = baseType.GetEvents( ReflectionHelper.ClassMembers ).Where( e => e.Name == eventInfo.Name ).First();

				MethodInfo delegateInfo = DelegateHelper.MethodInfoFromDelegateType( runtimeEvent.EventHandlerType );
				ParameterExpression[] parameters = delegateInfo.GetParameters().Select( p => Expression.Parameter( p.ParameterType ) ).ToArray();
				Delegate emptyDelegate
					= Expression.Lambda( runtimeEvent.EventHandlerType, Expression.Empty(), "EmptyDelegate", true, parameters ).Compile();

				// Create the delegate which adds the empty handler to an instance.
				MethodInfo addMethod = runtimeEvent.GetAddMethod( true );
				if ( addMethod.IsPublic )
				{
					return instance => runtimeEvent.AddEventHandler( instance, emptyDelegate );
				}

				return instance => addMethod.Invoke( instance, new object[] { emptyDelegate } );
			} );
		}
Ejemplo n.º 23
0
 protected Delegate CreateEventHandler(object target, View view, MethodMapping methodMapping, out EventInfo evnt)
 {
     Delegate del = null;
     evnt = null;
     if (view != null)
     {
         evnt = view.GetType().GetEvent(methodMapping.Attribute.EventName);
         if (evnt != null)
         {
             try
             {
                 del = CreateDelegate(target, methodMapping, evnt);
             }
             catch (Exception ex)
             {
                 Geneticist.HandleError(
                     ex,
                     "Error creating delegate from '{0}' for event '{1}'.",
                     methodMapping.Method.Name,
                     methodMapping.Attribute.EventName);
             }
         }
         else
         {
             Geneticist.HandleError(
                 "Unable to find event '{0}' for method '{1}'.",
                 methodMapping.Attribute.EventName,
                 methodMapping.Method.Name);
         }
     }
     return del;
 }
        private void UnsubscribeEvents(HandshakingInfo subscriber)
        {
            foreach (var eventInfor in subscriber.UnsubscribeEventList)
            {
                foreach (var dic in eventInfor.Value)
                {
                    if (dic.Value)
                    {
                        object qObj = ServerDictionaries.GetObjectFromTheDictionary(eventInfor.Key);
                        System.Reflection.EventInfo ei = qObj.GetType().GetEvent(dic.Key);

                        // Find corresponding CQG delegate
                        Type delType = QueryHandler.FindDelegateType(QueryHandler.CQGAssembly, dic.Key);

                        // Instantiate the delegate with our own handler
                        string handlerName = string.Concat("_ICQGCELEvents_", dic.Key, "EventHandlerImpl");

                        MethodInfo handlerInfo = typeof(CQGEventHandlers).GetMethod(handlerName);
                        Delegate   d           = Delegate.CreateDelegate(delType, handlerInfo);

                        // Unsubscribe our handler from CQG event
                        ei.RemoveEventHandler(qObj, d);
                    }
                }
            }
        }
Ejemplo n.º 25
0
 public ReflectedEvent(EventIdentifier name, EventInfo ev, Type targetType)
     : base(name, null, ev, targetType)
 {
     DeclaringName = ev.DeclaringType != targetType
         ? IdentifierFor.Event(ev, ev.DeclaringType)
         : name;
 }
Ejemplo n.º 26
0
            /// <summary>
            /// Remove all the eventhandlers from StateChanged event of original store (<see cref="_store"/>), and return them
            /// as a combined multi cast delegate.
            /// <a href="https://stackoverflow.com/a/16089998/605113">Reference</a>
            /// </summary>
            /// <param name="originalStore"></param>
            /// <returns>Combined Delegate of StateChanged event handlers attached to original store.</returns>
            private Delegate ShiftAllEvents(IStore <TState> originalStore)
            {
                // @ref: https://stackoverflow.com/a/16089998/605113
                Type     theType       = originalStore.GetType();
                Delegate finalDelegate = null;

                //Even though the events are public, the FieldInfo associated with them is private
                foreach (System.Reflection.FieldInfo field in theType.GetTypeInfo().DeclaredFields)
                {
                    //eventInfo will be null if this is a normal field and not an event.
                    System.Reflection.EventInfo eventInfo = theType.GetTypeInfo().GetDeclaredEvent(field.Name);
                    if (eventInfo != null && field.Name == nameof(StateChanged))
                    {
                        MulticastDelegate multicastDelegate = field.GetValue(originalStore) as MulticastDelegate;
                        if (multicastDelegate != null)
                        {
                            List <Delegate> oldHandlers = new List <Delegate>();
                            foreach (Delegate @delegate in multicastDelegate.GetInvocationList())
                            {
                                eventInfo.RemoveEventHandler(originalStore, @delegate);
                                oldHandlers.Add(@delegate);
                            }

                            if (oldHandlers.Count > 0)
                            {
                                finalDelegate = Delegate.Combine(oldHandlers.ToArray());
                            }
                        }
                    }
                }

                return(finalDelegate);
            }
Ejemplo n.º 27
0
		public static void RaiseEventImpl(object instance, EventInfo evt, object[] args)
		{
			if (evt == null)
				throw new MockException("Unable to deduce which event was specified in the parameter.");

			if (args.Length == 1
				&& (evt.EventHandlerType.IsGenericType && evt.EventHandlerType.GetGenericTypeDefinition() == typeof(EventHandler<>)
					|| evt.EventHandlerType == typeof(EventHandler)
					|| args[0] is EventArgs)
				)
			{
				args = new[] { instance, args[0] };
			}

			if (!(instance is IMockMixin))
			{
				var mockMixin = MocksRepository.GetMockMixin(instance, evt.DeclaringType);
				if (mockMixin != null)
					instance = mockMixin;
			}

			var mixin = instance as IEventsMixin;
			if (mixin != null)
			{
				mixin.RaiseEvent(evt, args);
			}
			else
			{
				MockingUtil.RaiseEventThruReflection(instance, evt, args);
			}
		}
Ejemplo n.º 28
0
 public CallInfoCacheItem(MethodInfo mi)
 {
     MI = mi;
     this.Call = mi.CreateDynamicFunc();
     EI = null;
     SetParamInfo();
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyPublication"/> class.
        /// </summary>
        /// <param name="topic">The event topic this publication belongs to.</param>
        /// <param name="publisher">The publisher.</param>
        /// <param name="eventInfo">The <see cref="EventInfo"/> of the publisher that registers this event topic.</param>
        /// <param name="handlerRestriction">The handler restriction.</param>
        /// <param name="publicationMatchers">The publication matchers.</param>
        public PropertyPublication(
            IEventTopic topic,
            object publisher,
            EventInfo eventInfo,
            HandlerRestriction handlerRestriction,
            IList<IPublicationMatcher> publicationMatchers) : 
                base(topic, publisher, handlerRestriction, publicationMatchers)
        {
            this.eventInfo = eventInfo;

            if (this.eventInfo.EventHandlerType == null)
            {
                throw new Exception("EventHandlerType on published event must not be null (internal EventBroker failure).");
            }

            ThrowIfInvalidEventHandler(this.eventInfo);
            ThrowIfEventIsStatic(this.eventInfo);

            this.eventArgsType = this.eventInfo.EventHandlerType == typeof(EventHandler)
                                     ? typeof(EventArgs)
                                     : this.eventInfo.EventHandlerType.GetGenericArguments()[0];

            Delegate handler = Delegate.CreateDelegate(
                this.eventInfo.EventHandlerType,
                this,
                GetType().GetMethod("PublicationHandler"));
            this.eventInfo.AddEventHandler(publisher, handler);
        }
Ejemplo n.º 30
0
 public EventPropertyDescriptor(object component, System.Reflection.EventInfo eventInfo, System.ComponentModel.EventHandlerList eventHandlerList) : base(eventInfo.Name)
 {
     this.component        = component;
     this.eventInfo        = eventInfo;
     this.eventHandlerList = eventHandlerList;
     this.converter        = new EventInfoConverter(this);
 }
Ejemplo n.º 31
0
 private static DynamicMethodDelegate GetEndTrigger(EventInfo info)
 {
   EndTriggerAttribute triggerAttribute = Enumerable.FirstOrDefault<object>((IEnumerable<object>) info.GetCustomAttributes(typeof (EndTriggerAttribute), false)) as EndTriggerAttribute;
   if (triggerAttribute == null)
     return (DynamicMethodDelegate) null;
   else
     return ReflectionHelper.CreateDelegate((MethodBase) info.DeclaringType.GetEvent(triggerAttribute.Trigger).GetAddMethod());
 }
Ejemplo n.º 32
0
 protected HandlerNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
     : base(info, context)
 {
     handler_name  = info.GetString("HandlerName");
     signal_name   = info.GetString("SignalName");
     evnt          = info.GetValue("Event", typeof(System.Reflection.EventInfo)) as System.Reflection.EventInfo;
     delegate_type = info.GetValue("DelegateType", typeof(Type)) as Type;
 }
Ejemplo n.º 33
0
        internal CompositeRaiseEventWeaver(IEventTypeBuilder eventTypeBuilder, EventInfo @event, MethodInfo method, IAspectDefinitionCollection aspectDefinitions, IAspectWeavingSettings aspectWeavingSettings)
            : base(eventTypeBuilder, method, aspectDefinitions, aspectWeavingSettings)
        {
            var typeBuilder = (IAspectTypeDefinition)aspectWeavingSettings.WeavingSettings.TypeDefinition;
            var eventFieldBuilder = typeBuilder.GetEventBrokerFielTypeDefinition(@event);

            methodSignatureWeaver = new RaiseEventMethodSignatureWeaver(eventTypeBuilder, typeBuilder, eventFieldBuilder);
        }
Ejemplo n.º 34
0
		/*----------------------------------------------------------------------------------------*/
		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="PublicationDirective"/> class.
		/// </summary>
		/// <param name="channel">The name of the channel that is to be published to.</param>
		/// <param name="evt">The event that will be published to the channel.</param>
		public PublicationDirective(string channel, EventInfo evt)
		{
			Ensure.ArgumentNotNullOrEmptyString(channel, "channel");
			Ensure.ArgumentNotNull(evt, "evt");

			_channel = channel;
			_evt = evt;
		}
Ejemplo n.º 35
0
 public CompositeEventWeaver(ITypeDefinition typeDefinition, EventInfo @event)
 {
     EventName = @event.Name;
     EventType = @event.EventHandlerType;
     lazyEventBuilder = new Core.Lib.Lazy<EventBuilder>(() => {
         return typeDefinition.TypeBuilder.DefineEvent(@event);
     });
 }
Ejemplo n.º 36
0
 public override void Initialize_PreGame()
 {
     // caching the reflection stuff should speed up stuff at least a little bit. Reflection isn't very fast, anyway. Try to avoid it in hot code.
     tabControlVarInfo              = typeof(Game.GUI.TabbedWindow).GetField("mTabControl", BindingFlags.NonPublic | BindingFlags.Instance);
     tabControlEventInfo            = typeof(Game.GUI.Controls.TabControl).GetEvent("PageChanged");
     tabControlPanelListVarInfo     = typeof(Game.GUI.TabbedWindow).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Single(field => field.FieldType == typeof(List <Game.GUI.TabbedWindowPanel>));
     controlScrollBarFieldsInfoList = typeof(Game.GUI.Controls.Container).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(field => field.FieldType == typeof(Game.GUI.Controls.ScrollBar)).ToArray();
     scrollBarOrientationFieldInfo  = typeof(Game.GUI.Controls.ScrollBar).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Single(field => field.FieldType == typeof(Game.GUI.Controls.Orientation));
 }
Ejemplo n.º 37
0
 public HandlerNotFoundException(string message, string handler_name, string signal_name,
                                 System.Reflection.EventInfo evnt, Type delegate_type)
     : base((message != null) ? message : "No handler " + handler_name + " found for signal " + signal_name,
            null)
 {
     this.handler_name  = handler_name;
     this.signal_name   = signal_name;
     this.evnt          = evnt;
     this.delegate_type = delegate_type;
 }
Ejemplo n.º 38
0
 public HandlerNotFoundException(string handler_name, string signal_name,
                                 System.Reflection.EventInfo evnt, Type delegate_type, Exception inner)
     : base("No handler " + handler_name + " found for signal " + signal_name,
            inner)
 {
     this.handler_name  = handler_name;
     this.signal_name   = signal_name;
     this.evnt          = evnt;
     this.delegate_type = delegate_type;
 }
Ejemplo n.º 39
0
            Event LoadEvent(System.Reflection.EventInfo refEvent)
            {
                Event eventObject = new Event
                {
                    Name             = refEvent.Name,
                    IsStatic         = refEvent.GetAddMethod().IsStatic,
                    EventHandlerType = GetTypeFullName(refEvent.EventHandlerType),
                    Attributes       = refEvent.Attributes,
                };

                return(eventObject);
            }
Ejemplo n.º 40
0
        public void PrintEvent(SysRef.EventInfo eventInfo)
        {
            if ((_flags & SignaturePrintingFlags.IgnoreMemberOwner) != SignaturePrintingFlags.IgnoreMemberOwner)
            {
                PrintType(eventInfo.DeclaringType);
                _builder.Append("::");
            }

            PrintIdentifier(eventInfo.Name);
            _builder.Append(" : ");
            PrintType(eventInfo.EventHandlerType, false);
        }
Ejemplo n.º 41
0
        internal static System.Delegate CreateEventHandlerDelegate <TDelegate>(System.Reflection.EventInfo evt, TDelegate d)
        {
            var handlerType = evt.EventHandlerType;
            var eventParams = handlerType.GetMethod("Invoke").GetParameters();

            ParameterExpression[] parameters = eventParams.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray();
            MethodCallExpression  body       = Expression.Call(Expression.Constant(d), d.GetType().GetMethod("Invoke"), parameters);
            var lambda = Expression.Lambda(body, parameters);

            // Diagnostics.Debug.Assert(false, lambda.ToString());
            return(System.Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false));
        }
Ejemplo n.º 42
0
        public Event(Class declaringType, SR.EventInfo tinfo)
        {
            this.declaringType = declaringType;

            ModifierEnum mod = (ModifierEnum)0;

            modifiers = mod;

            this.FullyQualifiedName = tinfo.Name;
            returnType      = new ReturnType(tinfo.EventHandlerType);
            this.region     = Class.GetRegion();
            this.bodyRegion = Class.GetRegion();

            LoadXml(declaringType);
        }
Ejemplo n.º 43
0
 public IDebuggerEvent GetEvent(SR.EventInfo evt) => debugger.Dispatcher.UI(() => {
     var comparer = new TypeComparer();
     foreach (var e in GetEvents(evt.Name, true))
     {
         var eventType = e.EventType;
         // EventType currently always returns null
         if (eventType == null)
         {
             return(e);
         }
         if (comparer.Equals(eventType, evt.EventHandlerType))
         {
             return(e);
         }
     }
     return(null);
 });
Ejemplo n.º 44
0
        /// <summary>
        /// Hack for compatibility RabbitMQ.Client library between 3.4.x and 3.5.x versions
        /// ConnectionShutdownEventHandler replaced by Eventhandler<ShutdownEventArgs> - https://github.com/rabbitmq/rabbitmq-dotnet-client/commit/84ca5552a338a86c9af124331adca230accf3be3
        /// using reflection for understand, what type of delegate we must use for IConnection.ConnectionShutdown:
        /// - EventHandler<ShutdownEventArgs> for 3.5.x version
        /// - ConnectionShutdownEventHandler for 3.4.x and early version
        /// </summary>
        private void PrepareConnectionShutdownEventHandler()
        {
            System.Reflection.EventInfo connectionShutdownEventInfo = typeof(IConnection).GetEvent("ConnectionShutdown");
            _connectionShutdownEventAddMethod = connectionShutdownEventInfo.GetAddMethod();

            Type delegateType = connectionShutdownEventInfo.EventHandlerType;

            System.Reflection.MethodInfo shutdownAmqpMethodInfo = null;

            if (delegateType.IsConstructedGenericType && delegateType.GetGenericTypeDefinition() == typeof(EventHandler <>))
            {
                shutdownAmqpMethodInfo = typeof(RabbitMQ).GetMethod("ShutdownAmqp35", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            }
            else
            {
                shutdownAmqpMethodInfo = typeof(RabbitMQ).GetMethod("ShutdownAmqp", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            }

            _connectionShutdownEventHandler = shutdownAmqpMethodInfo.CreateDelegate(delegateType, this);
        }
Ejemplo n.º 45
0
            /// <summary>
            /// Add back all events from sourceDelegate to StateChanged event of original store targetStore.
            /// </summary>
            /// <param name="sourceDelegate">Delegate which holds all the event handlers. This is returned by <see cref="ShiftAllEvents(IStore{TState})"/></param>
            /// <param name="targetStore">Store to which StateChanged event handlers needs to be added back.</param>
            private void UnShiftAllEvents(Delegate sourceDelegate, IStore <TState> targetStore)
            {
                Type theType = targetStore.GetType();

                foreach (System.Reflection.FieldInfo field in theType.GetTypeInfo().DeclaredFields)
                {
                    System.Reflection.EventInfo eventInfo = theType.GetTypeInfo().GetDeclaredEvent(field.Name);
                    if (eventInfo != null && field.Name == nameof(StateChanged))
                    {
                        MulticastDelegate multicastDelegate = sourceDelegate as MulticastDelegate;
                        if (multicastDelegate != null)
                        {
                            List <Delegate> oldHandlers = new List <Delegate>();
                            foreach (Delegate @delegate in multicastDelegate.GetInvocationList())
                            {
                                eventInfo.AddEventHandler(targetStore, @delegate);
                                Delegate.Remove(multicastDelegate, @delegate);
                            }
                        }
                    }
                }
            }
Ejemplo n.º 46
0
 public ComAwareEventInfo(Type type, string eventName)
 {
     _innerEventInfo = type.GetEvent(eventName);
 }
Ejemplo n.º 47
0
 public override CXXEventInfo Create(CXXTypeInfo declaringType, System.Reflection.EventInfo eventInfo)
 {
     return(EventCache.GetOrAdd(eventInfo, e => new CXXEventInfo(this, declaringType, e)));
 }
Ejemplo n.º 48
0
        private IEnumerable <string> GenerateEvent(short methodID, System.Reflection.EventInfo eventInfo)
        {
            var privateEvent = $"_{eventInfo.Name}";

            var codeLines = new List <string>();

            codeLines.Add($"private event EventHandler<{eventInfo.ArgsTypeName()}> {privateEvent};");
            codeLines.Add($"public event EventHandler<{eventInfo.ArgsTypeName()}> {eventInfo.Name}");
            codeLines.Add("{");

            codeLines.Add("add{");
            codeLines.Add($"Add_{eventInfo.Name}();");
            codeLines.Add($"{privateEvent} += value;");
            codeLines.Add("}");

            codeLines.Add("remove{");
            codeLines.Add($"Remove_{eventInfo.Name}();");
            codeLines.Add($"{privateEvent} -= value;");
            codeLines.Add("}");

            codeLines.Add("}");

            codeLines.Add($"private void Add_{eventInfo.Name}()");
            codeLines.Add("{");
            codeLines.Add($"if ({privateEvent} != null) return;");
            if (OutputDebug)
            {
                var msg = $"proxy: add_event {eventInfo.Name} id={methodID}";
                codeLines.Add($"System.Console.WriteLine(\"{msg}\");");
            }
            codeLines.Add("using var stream = new MemoryStream();");
            codeLines.Add($"_proxyItem.SendCallRequest({methodID}, stream.ToArray());");
            codeLines.Add("}");

            codeLines.Add($"private void Remove_{eventInfo.Name}()");
            codeLines.Add("{");
            codeLines.Add($"if ({privateEvent} == null) return;");
            if (OutputDebug)
            {
                var msg = $"proxy: remove_event {eventInfo.Name} id={methodID}";
                codeLines.Add($"System.Console.WriteLine(\"{msg}\");");
            }
            codeLines.Add("try {");
            codeLines.Add("using var stream = new MemoryStream();");
            codeLines.Add($"_proxyItem.SendCallRequest({methodID + 1}, stream.ToArray());");
            codeLines.Add("} catch {}"); //all exceptions need be caught here
            codeLines.Add("}");

            codeLines.Add($"private void Fire_{eventInfo.Name}(Stream dataStream)");
            codeLines.Add("{");
            if (OutputDebug)
            {
                var msg = $"proxy: on_event {eventInfo.Name} id={methodID}";
                codeLines.Add($"System.Console.WriteLine(\"{msg}\");");
            }
            codeLines.Add("var serializer = new Serializer(dataStream);");
            var argType = eventInfo.EventHandlerType.GenericTypeArguments[0];

            codeLines.Add($"var args = {SerializeStatement.DeserializeObject(argType)}");
            codeLines.Add($"var handler = {privateEvent};");
            codeLines.Add($"if (handler != null) handler(this, args);");
            codeLines.Add("}");

            return(codeLines);
        }
Ejemplo n.º 49
0
 IEventInfo IMetadataProvider.Create(ITypeInfo declaringType, System.Reflection.EventInfo eventInfo)
 {
     return(Create((TTypeInfo)declaringType, eventInfo));
 }
 public static System.Reflection.MethodInfo GetAddMethod(System.Reflection.EventInfo eventInfo, bool nonPublic)
 {
     throw null;
 }
 public static System.Reflection.MethodInfo GetRemoveMethod(System.Reflection.EventInfo eventInfo)
 {
     throw null;
 }
Ejemplo n.º 52
0
 private static void AddLoggingListener(ref EventController logController, object component, System.Reflection.EventInfo eventInfo, EventActionEnum action)
 {
     if (logController == null)
     {
         logController = ClassGenerator.Instance.GenerateHandler(eventInfo);
     }
     if (!logController.IsAttached)
     {
         logController.Attach(component, eventInfo, action);
     }
     ObjectEditor.Instance.ActiveEditor.ShowToolsWindow(ToolWindowEnum.EventLog);
 }
        // Main query processing method
        public void ProcessQuery(QueryInfo query)
        {
            // Object where the data obtained after query execution is placed
            // This object will be sent to the DB
            AnswerInfo answer;

            // Get a name of a symbol if it's CQGTimedBarsRequestClass object's request
            // and show it in MiniMonitor form
            if (query.ObjectType == "CQGTimedBarsRequestClass")
            {
                object qObj      = UsedObjs.Contains(query.ObjectKey) ? UsedObjs[query.ObjectKey] : ServerDictionaries.GetObjectFromTheDictionary(query.ObjectKey);
                string instrName = (string)qObj.GetType().InvokeMember("Symbol",
                                                                       BindingFlags.GetProperty, null, qObj, null);
                if (!DCMiniMonitor.symbolsList.Contains(instrName))
                {
                    DCMiniMonitor.symbolsList.Add(instrName);
                    Program.MiniMonitor.SymbolsListsUpdate();
                }
            }

            // Handling of the request depending on its kind
            switch (query.QueryType)
            {
            case QueryType.CallCtor:
            {
                try
                {
                    string key;

                    // Handling of the ctor calling request and creation of an object depending on its type
                    switch (query.MemberName)
                    {
                    // Handling of CQGCEL ctor calling request
                    case "CQG.CQGCELClass":
                        key = CqgDataManagement.CEL_key;
                        break;

                    // Common case
                    default:
                        object[] args = Core.GetArgsIntoArrayFromTwoDicts(query.ArgKeys, query.ArgValues);
                        object   qObj = CQGAssm.CreateInstance(query.MemberName, false,
                                                               BindingFlags.CreateInstance, null, args, null, null);
                        key = Core.CreateUniqueKey();

                        ServerDictionaries.PutObjectToTheDictionary(key, qObj);
                        UsedObjs.Add(key, qObj);
                        break;
                    }

                    answer = new AnswerInfo(query.QueryKey, query.ObjectKey, query.MemberName, valueKey: key);
                    PushAnswerAndDeleteQuery(answer);
                }
                catch
                {
                    try
                    {
                        AutoGenQueryProcessing(query);
                    }
                    catch (Exception ex)
                    {
                        answer = CreateExceptionAnswer(ex, query);
                        PushAnswerAndDeleteQuery(answer);
                    }
                }
            }
            break;

            case QueryType.CallDtor:
            {
                if (query.ObjectKey != CqgDataManagement.CEL_key)
                {
                    UsedObjs.Remove(query.ObjectKey);
                    ServerDictionaries.RemoveObjectFromTheDictionary(query.ObjectKey);
                }

                // Remove name of a symbol if it's CQG.CQGTimedBarsRequest object deleting
                // from MiniMonitor form
                if (query.MemberName == "CQG.CQGTimedBarsRequest")
                {
                    object qObj     = UsedObjs.Contains(query.ObjectKey) ? UsedObjs[query.ObjectKey] : ServerDictionaries.GetObjectFromTheDictionary(query.ObjectKey);
                    string symbName = (string)qObj.GetType().InvokeMember("Symbol",
                                                                          BindingFlags.GetProperty, null, qObj, null);
                    DCMiniMonitor.symbolsList.Remove(symbName);
                    Program.MiniMonitor.SymbolsListsUpdate();
                }

                answer = new AnswerInfo(query.QueryKey, query.ObjectKey, query.MemberName, value: true);

                PushAnswerAndDeleteQuery(answer);
            }
            break;

            case QueryType.GetProperty:
            {
                object qObj = UsedObjs.Contains(query.ObjectKey) ? UsedObjs[query.ObjectKey] : ServerDictionaries.GetObjectFromTheDictionary(query.ObjectKey);

                object[] args = Core.GetArgsIntoArrayFromTwoDicts(query.ArgKeys, query.ArgValues);

                try
                {
                    // Getting of property value
                    var propV = qObj.GetType().InvokeMember(query.MemberName, BindingFlags.GetProperty, null, qObj, args);

                    // Checking type of property value and returning value or value key
                    // (second, if it's not able to be transmitted through the database)
                    answer = Core.IsSerializableType(propV.GetType()) ?
                             CreateValAnswer(query.QueryKey, query.ObjectKey, query.MemberName, propV) :
                             CreateKeyAnswer(query.QueryKey, query.ObjectKey, query.MemberName, propV);

                    PushAnswerAndDeleteQuery(answer);
                }
                catch
                {
                    try
                    {
                        AutoGenQueryProcessing(query);
                    }
                    catch (Exception ex)
                    {
                        answer = CreateExceptionAnswer(ex, query);
                        PushAnswerAndDeleteQuery(answer);
                    }
                }
            }
            break;

            case QueryType.SetProperty:
            {
                object qObj = UsedObjs.Contains(query.ObjectKey) ? UsedObjs[query.ObjectKey] : ServerDictionaries.GetObjectFromTheDictionary(query.ObjectKey);

                object[] args = Core.GetArgsIntoArrayFromTwoDicts(query.ArgKeys, query.ArgValues);

                if (string.Concat(qObj.GetType()) == "CQG.CQGTimedBarsRequest" && query.MemberName == "Symbol")
                {
                    DCMiniMonitor.symbolsList.Add(string.Concat(args[0]));
                    Program.MiniMonitor.SymbolsListsUpdate();
                }

                try
                {
                    // Setting of property value
                    qObj.GetType().InvokeMember(query.MemberName, BindingFlags.SetProperty, null, qObj, args);
                    answer = new AnswerInfo(query.QueryKey, query.ObjectKey, query.MemberName, value: true);

                    PushAnswerAndDeleteQuery(answer);
                }
                catch
                {
                    try
                    {
                        AutoGenQueryProcessing(query);
                    }
                    catch (Exception ex)
                    {
                        answer = CreateExceptionAnswer(ex, query);
                        PushAnswerAndDeleteQuery(answer);
                    }
                }
            }
            break;

            case QueryType.CallMethod:
            {
                // Handling of Shutdown method calling by CQGCEL object. This method has not be called from client applications
                if (query.MemberName == "Shutdown")
                {
                    var returnKey = "true";
                    answer = new AnswerInfo(query.QueryKey, query.ObjectKey, query.MemberName, valueKey: returnKey);
                    PushAnswerAndDeleteQuery(answer);
                    break;
                }

                object qObj = UsedObjs.Contains(query.ObjectKey) ? UsedObjs[query.ObjectKey] : ServerDictionaries.GetObjectFromTheDictionary(query.ObjectKey);

                object[] args = Core.GetArgsIntoArrayFromTwoDicts(query.ArgKeys, query.ArgValues);

                try
                {
                    object returnV;

                    bool isGetter = query.MemberName.StartsWith("get_");
                    bool isSetter = query.MemberName.StartsWith("set_");
                    if (isGetter || isSetter)
                    {
                        // Access property instead of calling method
                        string       propName   = query.MemberName.Substring(4);
                        BindingFlags invokeAttr = isGetter ? BindingFlags.GetProperty : BindingFlags.SetProperty;
                        returnV = qObj.GetType().InvokeMember(propName, invokeAttr, null, qObj, args);
                    }
                    else
                    {
                        returnV = qObj.GetType().InvokeMember(query.MemberName, BindingFlags.InvokeMethod, null, qObj, args);
                    }

                    if (!object.ReferenceEquals(returnV, null))
                    {
                        // Handling method call request depending of return value type
                        answer = Core.IsSerializableType(returnV.GetType()) ?
                                 CreateValAnswer(query.QueryKey, query.ObjectKey, query.MemberName, returnV) :
                                 CreateKeyAnswer(query.QueryKey, query.ObjectKey, query.MemberName, returnV);
                    }
                    else
                    {
                        // Handling void method call
                        var returnKey = "true";
                        answer = new AnswerInfo(query.QueryKey, query.ObjectKey, query.MemberName, valueKey: returnKey);
                    }

                    PushAnswerAndDeleteQuery(answer);
                }
                catch
                {
                    try
                    {
                        AutoGenQueryProcessing(query);
                    }
                    catch (Exception ex)
                    {
                        answer = CreateExceptionAnswer(ex, query);
                        PushAnswerAndDeleteQuery(answer);
                    }
                }
            }
            break;

            case QueryType.SubscribeToEvent:
            case QueryType.UnsubscribeFromEvent:
            {
                object qObj = UsedObjs.Contains(query.ObjectKey) ? UsedObjs[query.ObjectKey] : ServerDictionaries.GetObjectFromTheDictionary(query.ObjectKey);

                try
                {
                    System.Reflection.EventInfo ei = qObj.GetType().GetEvent(query.MemberName);

                    if (EventHandler.EventAppsSubscribersNum.ContainsKey(query.MemberName))
                    {
                        EventHandler.EventAppsSubscribersNum[query.MemberName] =
                            query.QueryType == QueryType.SubscribeToEvent ?
                            EventHandler.EventAppsSubscribersNum[query.MemberName] + 1 :
                            EventHandler.EventAppsSubscribersNum[query.MemberName] - 1;
                    }
                    else
                    {
                        EventHandler.EventAppsSubscribersNum.Add(query.MemberName, 1);
                    }

                    // Find corresponding CQG delegate
                    Type delType = FindDelegateType(CQGAssm, query.MemberName);

                    // Instantiate the delegate with our own handler
                    var        eventHandlersMethods = typeof(CQGEventHandlers).GetMethods();
                    MethodInfo handlerInfo          = null;

                    for (int i = 0; i < eventHandlersMethods.Length; i++)
                    {
                        if (eventHandlersMethods[i].Name.Contains(query.MemberName))
                        {
                            handlerInfo = eventHandlersMethods[i];
                        }
                    }

                    Delegate d = Delegate.CreateDelegate(delType, handlerInfo);

                    if (query.QueryType == QueryType.SubscribeToEvent)
                    {
                        // Subscribe our handler to CQG event
                        ei.AddEventHandler(qObj, d);
                    }
                    else if (query.QueryType == QueryType.UnsubscribeFromEvent)
                    {
                        // Unsubscribe our handler from CQG event
                        ei.RemoveEventHandler(qObj, d);
                    }

                    answer = new AnswerInfo(query.QueryKey, query.ObjectKey, query.MemberName, value: true);

                    PushAnswerAndDeleteQuery(answer);
                }
                catch
                {
                    try
                    {
                        AutoGenQueryProcessing(query);
                    }
                    catch (Exception ex)
                    {
                        answer = CreateExceptionAnswer(ex, query);
                        PushAnswerAndDeleteQuery(answer);
                    }
                }

                if (query.QueryType == QueryType.SubscribeToEvent &&
                    query.MemberName == "DataConnectionStatusChanged")
                {
                    // Fire this event explicitly, because data collector connects to real CQG beforehand and does not fire it anymore
                    CQGEventHandlers._ICQGCELEvents_DataConnectionStatusChangedEventHandlerImpl(CqgDataManagement.currConnStat);
                }
            }
            break;

            default:
            {
                throw new ArgumentOutOfRangeException();
            }
            }
        }
Ejemplo n.º 54
0
 public abstract TEventInfo Create(TTypeInfo declaringType, System.Reflection.EventInfo eventInfo);
Ejemplo n.º 55
0
 public HandlerNotFoundException(string handler_name, string signal_name,
                                 System.Reflection.EventInfo evnt, Type delegate_type)
     : this(handler_name, signal_name, evnt, delegate_type, null)
 {
 }
Ejemplo n.º 56
0
 public override UnrealEventInfo Create(UnrealTypeInfo declaringType, EventInfo eventInfo)
 {
     return(EventCache.GetOrAdd(eventInfo, e => new UnrealEventInfo(this, declaringType, e)));
 }
 public static System.Reflection.MethodInfo GetRaiseMethod(this System.Reflection.EventInfo eventInfo)
 {
     throw null;
 }
 public static System.Reflection.MethodInfo GetRemoveMethod(this System.Reflection.EventInfo eventInfo, bool nonPublic)
 {
     throw null;
 }
Ejemplo n.º 59
0
 public LocalEventImplementation(System.Reflection.EventInfo eventInfo)
 {
     this.eventInfo = eventInfo;
     this.addMethod = this.eventInfo.GetAddMethod(true);
     this.access    = (this.addMethod != null ? PlatformTypeHelper.GetMemberAccess(this.addMethod) : MemberAccessType.Private);
 }
Ejemplo n.º 60
0
        private void AddEvent(WindowTabInfo tabInfo, object manager, WindowTabEventManagerType type)
        {
            var list = ADInfoBll.Instance.GetWindowTabEventInfos(tabInfo.Name, type);

            foreach (var info in list)
            {
                System.Reflection.EventInfo eventInfo = manager.GetType().GetEvent(info.EventName);

                Type handlerType = eventInfo.EventHandlerType;
                //MethodInfo invokeMethod = handlerType.GetMethod("Invoke");
                //ParameterInfo[] parms = invokeMethod.GetParameters();
                //Type[] parmTypes = new Type[parms.Length];
                //for (int i = 0; i < parms.Length; i++)
                //{
                //    parmTypes[i] = parms[i].ParameterType;
                //}
                //Type dType = Expression.GetActionType(parmTypes);
                Delegate d = null;
                switch (type)
                {
                case WindowTabEventManagerType.SearchManager:
                    switch (info.EventName)
                    {
                    case "DataLoaded":
                    {
                        EventHandler <DataLoadedEventArgs> d1 = (sender, e) =>
                        {
                            EventProcessUtils.ExecuteEventProcess(ADInfoBll.Instance.GetEventProcessInfos(info.EventProcessName), sender, e);
                        };
                        d = Delegate.CreateDelegate(handlerType, d1.Target, d1.Method);
                    }
                    break;

                    case "DataLoading":
                    {
                        EventHandler <DataLoadingEventArgs> d1 = (sender, e) =>
                        {
                            EventProcessUtils.ExecuteEventProcess(ADInfoBll.Instance.GetEventProcessInfos(info.EventProcessName), sender, e);
                        };
                        d = Delegate.CreateDelegate(handlerType, d1.Target, d1.Method);
                    }
                    break;

                    default:
                        throw new ArgumentException("invalid EventName of " + info.EventName);
                    }
                    break;

                case WindowTabEventManagerType.DisplayManager:
                    switch (info.EventName)
                    {
                    case "PositionChanging":
                    {
                        EventHandler <System.ComponentModel.CancelEventArgs> d1 = (sender, e) =>
                        {
                            EventProcessUtils.ExecuteEventProcess(ADInfoBll.Instance.GetEventProcessInfos(info.EventProcessName), sender, e);
                        };
                        d = Delegate.CreateDelegate(handlerType, d1.Target, d1.Method);
                    }
                    break;

                    case "PositionChanged":
                    {
                        EventHandler d1 = (sender, e) =>
                        {
                            EventProcessUtils.ExecuteEventProcess(ADInfoBll.Instance.GetEventProcessInfos(info.EventProcessName), sender, e);
                        };
                        d = Delegate.CreateDelegate(handlerType, d1.Target, d1.Method);
                    }
                    break;

                    case "SelectedDataValueChanged":
                    {
                        EventHandler <SelectedDataValueChangedEventArgs> d1 = (sender, e) =>
                        {
                            EventProcessUtils.ExecuteEventProcess(ADInfoBll.Instance.GetEventProcessInfos(info.EventProcessName), sender, e);
                        };
                        d = Delegate.CreateDelegate(handlerType, d1.Target, d1.Method);
                    }
                    break;

                    default:
                        throw new ArgumentException("invalid EventName of " + info.EventName);
                    }
                    break;

                case WindowTabEventManagerType.ControlManager:
                    switch (info.EventName)
                    {
                    case "BeginningEdit":
                    case "EditBegun":
                    case "EndingEdit":
                    case "EditEnded":
                    case "EditCanceled":
                    case "StateChanged":
                    {
                        EventHandler d1 = (sender, e) =>
                        {
                            EventProcessUtils.ExecuteEventProcess(ADInfoBll.Instance.GetEventProcessInfos(info.EventProcessName), sender, e);
                        };
                        d = Delegate.CreateDelegate(handlerType, d1.Target, d1.Method);
                    }
                    break;

                    case "CancellingEdit":
                    {
                        EventHandler <System.ComponentModel.CancelEventArgs> d1 = (sender, e) =>
                        {
                            EventProcessUtils.ExecuteEventProcess(ADInfoBll.Instance.GetEventProcessInfos(info.EventProcessName), sender, e);
                        };
                        d = Delegate.CreateDelegate(handlerType, d1.Target, d1.Method);
                    }
                    break;

                    default:
                        throw new ArgumentException("invalid EventName of " + info.EventName);
                    }

                    break;

                case WindowTabEventManagerType.BusinessLayer:
                    break;

                default:
                    throw new ArgumentException("invalid WindowTabEventManagerType of " + type);
                }
                if (d != null)
                {
                    eventInfo.AddEventHandler(manager, d);
                }
            }
        }