AddEventHandler() private method

private AddEventHandler ( Object target, Delegate handler ) : void
target Object
handler Delegate
return void
Esempio n. 1
1
        /// <summary>
        /// Creates an Event Handler for the EventInfo Passed to Hook it the Event Up to an Event Recorder.
        /// </summary>
        private static EventRecorder Monitor(object eventSource, EventInfo eventInfo)
        {
            // Create EventRecorder
            var eventRecorder = new EventRecorder(eventSource, eventInfo.Name);

            // Subscribe EventRecorder to event
            var handler = EventSubscriber.GenerateHandler(eventInfo.EventHandlerType, eventRecorder);
            eventInfo.AddEventHandler(eventSource, handler);

            return eventRecorder;
        }
Esempio 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)
         );
 }
        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];
            });
        }
    	/// <summary>
		/// Adds specified <paramref name="listenerMethod"></paramref> as an event handler for 
		/// the <paramref name="sourceEvent"></paramref>.
    	/// </summary>
    	/// <param name="sourceEvent">Event on source object to which <paramref name="listenerMethod"></paramref> will be added.</param>
    	/// <param name="listenerMethod">Method to be added as event handler for <paramref name="listenerMethod"></paramref>.</param>
        public virtual void Bind(EventInfo sourceEvent, MethodInfo listenerMethod)
        {
            if (sourceEvent == null) throw new ArgumentNullException("sourceEvent");

            Delegate methodToBindTo =
                Delegate.CreateDelegate(sourceEvent.EventHandlerType, listener, listenerMethod);
            sourceEvent.AddEventHandler(source, methodToBindTo);            
        }
Esempio n. 5
0
        public EventPropegator(object instance, EventInfo evt, Action<object, EventArgs> handler)
        {
            _instance = instance;
            _evt = evt;
            _disposed = false;

            var methodInfo = handler.GetType().GetMethod("Invoke");
            _delegate = Delegate.CreateDelegate(evt.EventHandlerType, handler, methodInfo);

            evt.AddEventHandler(instance, _delegate);
        }
Esempio n. 6
0
 public void AddPublisher(string[] topics, object o, EventInfo evt)
 {
     if (o == null)
     {
         throw new ArgumentNullException ("o");
     }
     if (evt == null)
     {
         throw new ArgumentNullException ("evt");
     }
     var pub = new Publication {Topics = topics, Broker = this};
     var dg = Delegate.CreateDelegate (typeof(Action), pub, _pubmethod);
     evt.AddEventHandler (o, dg);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="instance"></param>
 /// <param name="eventInfo"></param>
 public void AddPublication( object instance, EventInfo eventInfo )
 {
     Delegate method = Delegate.CreateDelegate( eventInfo.EventHandlerType, this, BroadcastMethod );
     eventInfo.AddEventHandler( instance, method );
     lock ( _publications )
     {
         var publication = new Publication
                           {
                               Method = method,
                               Instance = new WeakReference( instance ),
                               Event = eventInfo
                           };
         _publications.Add( publication );
     }
 }
        // 原函数
        public static void AttachGeneralHandler(object target, EventInfo targetEvent)
        {
            //获得事件响应程序的委托类型
            var delegateType = targetEvent.EventHandlerType;

            //这个委托的Invoke方法有我们所需的签名信息
            MethodInfo invokeMethod = delegateType.GetMethod("Invoke");

            //按照这个委托制作所需要的参数
            ParameterInfo[] parameters = invokeMethod.GetParameters();
            ParameterExpression[] paramsExp = new ParameterExpression[parameters.Length];
            Expression[] argsArrayExp = new Expression[parameters.Length];

            //参数一个个转成object类型。有些本身即是object,管他呢……
            for (int i = 0; i < parameters.Length; i++)
            {
                paramsExp[i] = Expression.Parameter(parameters[i].ParameterType, parameters[i].Name);
                argsArrayExp[i] = Expression.Convert(paramsExp[i], typeof(Object));
            }

            //调用我们的GeneralHandler
            MethodInfo executeMethod = typeof(GeneralEventHandling).GetMethod(
                "GeneralHandler", BindingFlags.Static | BindingFlags.NonPublic);

            Expression lambdaBodyExp =
                Expression.Call(null, executeMethod, Expression.NewArrayInit(typeof(Object), argsArrayExp));

            //如果有返回值,那么将返回值转换成委托要求的类型
            //如果没有返回值就这样搁那里就成了
            if (!invokeMethod.ReturnType.Equals(typeof(void)))
            {
                //这是有返回值的情况
                lambdaBodyExp = Expression.Convert(lambdaBodyExp, invokeMethod.ReturnType);
            }

            //组装到一起
            LambdaExpression dynamicDelegateExp = Expression.Lambda(delegateType, lambdaBodyExp, paramsExp);

            //我们创建的Expression是这样的一个函数:
            //(委托的参数们) => GeneralHandler(new object[] { 委托的参数们 })

            //编译
            Delegate dynamiceDelegate = dynamicDelegateExp.Compile();

            //完成!
            targetEvent.AddEventHandler(target, dynamiceDelegate);
        }
Esempio n. 9
0
        public static void AddEventHandler(EventInfo eventInfo, object item, Action<object, EventArgs> action)
        {
            var parameters = eventInfo.EventHandlerType
            .GetMethod("Invoke")
            .GetParameters()
            .Select(parameter => Expression.Parameter(parameter.ParameterType))
            .ToArray();

              var invoke = action.GetType().GetMethod("Invoke");

              var handler = Expression.Lambda(
              eventInfo.EventHandlerType,
              Expression.Call(Expression.Constant(action), invoke, parameters[0], parameters[1]),
              parameters
            )
            .Compile();

              eventInfo.AddEventHandler(item, handler);
        }
Esempio n. 10
0
        public override void AddEventHandler(object target, Delegate handler)
        {
            if (Marshal.IsComObject(target))
            {
                // retrieve sourceIid and dispid
                Guid sourceIid;
                int  dispid;
                GetDataForComInvocation(_innerEventInfo, out sourceIid, out dispid);

                // now validate the caller can call into native and redirect to ComEventHelpers.Combine
                SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                perm.Demand();
                System.Runtime.InteropServices.ComEventsHelper.Combine(target, sourceIid, dispid, handler);
            }
            else
            {
                // we are dealing with a managed object - just add the delegate through reflection
                _innerEventInfo.AddEventHandler(target, handler);
            }
        }
Esempio n. 11
0
        public static AnonymousEventHandler RegisterEventHandler(EventInfo eventInfo, object target, Action handler)
        {
            ParameterInfo[] parameterInfos = eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters();

            if (parameterInfos.Length != 2)
                throw new ArgumentException("The given event info must have exactly two parameters.");

            Type argumentType = parameterInfos.Skip(1).First().ParameterType;
            Type type = typeof(AnonymousEventHandler<>).MakeGenericType(argumentType);

            MethodInfo method = type.GetMethod("Handler");
            var anonymousHandler = (AnonymousEventHandler)Activator.CreateInstance(type);
            anonymousHandler.Action = handler;
            anonymousHandler.eventHandler = Delegate.CreateDelegate(eventInfo.EventHandlerType, anonymousHandler, method);
            anonymousHandler.eventInfo = eventInfo;
            anonymousHandler.target = target;
            eventInfo.AddEventHandler(target, anonymousHandler.eventHandler);

            return anonymousHandler;
        }
Esempio n. 12
0
        internal void AddEventHandler(DependencyObject owner)
        {
            _owner = owner;
            _eventInfo = owner.GetType().GetEvent(Event);

            if(_eventInfo == null)
            {
                throw new ArgumentException("The given event does not exist for the element.", "Event");
            }

            _eventHandler = EventBuilder.Create(_eventInfo,
                                                () =>
                                                    {
                                                        if (Command.CanExecute(Parameter))
                                                        {
                                                            Command.Execute(Parameter);
                                                        }
                                                    });

            _eventInfo.AddEventHandler(owner, _eventHandler);
        }
Esempio n. 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandBinding"/> class.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="eventName">Name of the event.</param>
        /// <param name="command">The command.</param>
        /// <param name="commandParameterBinding">The command parameter binding.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="element"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">The <paramref name="eventName"/> is <c>null</c> or whitespace.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="command"/> is <c>null</c>.</exception>
        public CommandBinding(object element, string eventName, ICatelCommand command, Binding commandParameterBinding = null)
        {
            Argument.IsNotNull("element", element);
            Argument.IsNotNullOrWhitespace("eventName", eventName);
            Argument.IsNotNull("command", command);

            _element = element;
            _command = command;
            _commandParameterBinding = commandParameterBinding;

            var elementType = _element.GetType();
            _eventInfo = elementType.GetEventEx(eventName);
            if (_eventInfo == null)
            {
                throw Log.ErrorAndCreateException<InvalidOperationException>("Event '{0}.{1}' not found, cannot create command binding", elementType.Name, eventName);
            }

            _enabledPropertyInfo = elementType.GetPropertyEx("Enabled");

            _eventHandler = delegate
            {
                var commandParameter = _commandParameterBinding.GetBindingValue();
                if (_command.CanExecute(commandParameter))
                {
                    _command.Execute(commandParameter);
                }
            };
            _eventInfo.AddEventHandler(element, _eventHandler);

            _canExecuteChangedHandler = (sender, e) => UpdateEnabledState();
            command.CanExecuteChanged += _canExecuteChangedHandler;

            if (commandParameterBinding != null)
            {
                _commandBindingParameterValueChangedHandler = (sender, e) => UpdateEnabledState();
                commandParameterBinding.ValueChanged += _commandBindingParameterValueChangedHandler;
            }

            UpdateEnabledState();
        }
Esempio n. 14
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);
                            }
                        }
                    }
                }
            }
Esempio n. 15
0
        public CustomDataContextSetup(Type entityType)
        {
            Debug.Assert(entityType != null);

            this.entityType = entityType;
            this.dataServiceType = typeof(TypedCustomDataContext<>).MakeGenericType(entityType);

            this.handler = new EventHandler(TypedDataContextValuesRequested);
            this.valuesRequestedEvent = this.dataServiceType.GetEvent("ValuesRequested", BindingFlags.Static | BindingFlags.Public);
            Assert.IsNotNull(valuesRequestedEvent, "valuesRequestedEvent is not null");
            valuesRequestedEvent.AddEventHandler(this, handler);

            memberPropertyInfo = entityType.GetProperty("Member");
            if (entityType.GetGenericTypeDefinition() == typeof(TypedEntity<,>))
            {
                idPropertyInfo = entityType.GetProperty("ID");
            }
            else
            {
                Debug.Assert(entityType.GetGenericTypeDefinition() == typeof(DoubleKeyTypedEntity<,,>));
                idPropertyInfo = entityType.GetProperty("FirstKey");
                secondIdPropertyInfo = entityType.GetProperty("SecondKey");
            }
        }
Esempio n. 16
0
 public static void AddEventHandler(EventInfo eventinfo, object target, IApply func)
 {
     var type = eventinfo.EventHandlerType;
     var dlg = ConvertToDelegate(type, func);
     eventinfo.AddEventHandler(target, dlg);
 }
Esempio n. 17
0
        /// <SecurityNote>
        /// This function needs to demand reflection permission in order to add a delegate handler for an
        /// allowed\accessible internal event on an allowed\accessible type. If permission is granted, the
        /// parser will directly use reflection to add the event handler delegate. If not, it will call a
        /// method on a generated class in the user's code context in order to attempt adding the internal
        /// event handler delegate using the user app's security context.
        /// </SecurityNote>
        internal static bool AddInternalEventHandler(ParserContext pc, object rootElement, EventInfo eventInfo, object target, Delegate handler)
        {
            bool isPublicEvent = false;
            bool allowProtected = rootElement == target;
            bool isAllowedEvent = IsAllowedEvent(eventInfo, allowProtected, out isPublicEvent);

            if (isAllowedEvent)
            {
                // if public event on internal type or caller has member access permission, use reflection directly
                if (isPublicEvent || SecurityHelper.CallerHasMemberAccessReflectionPermission())
                {
                    eventInfo.AddEventHandler(target, handler);
                    return true;
                }
                else
                {
                    // else this must be an internal event on an accessible internal or public type --- call
                    // the generated helper in caller's secuirty context.

                    // In this case pc.StreamCreatedAssembly is guaranteed to be the assembly from which the current
                    // stream being read was created from. So even if the internal event ere not legitimate, the call
                    // to add a handler to it via ith.AddEventHandler would fail in PT.
                    InternalTypeHelper ith = GetInternalTypeHelperFromAssembly(pc);
                    if (ith != null)
                    {
                        ith.AddEventHandler(eventInfo, target, handler);
                        return true;
                    }
                }
            }

            return false;
        }
Esempio n. 18
0
 public virtual void Bind(EventInfo sourceEvent, MethodInfo listenerMethod)
 {
     Delegate handler = Delegate.CreateDelegate(sourceEvent.EventHandlerType, this.listener, listenerMethod);
     sourceEvent.AddEventHandler(this.source, handler);
 }
Esempio n. 19
0
        /// <summary>
        /// Attach static events using Metadata
        /// </summary>
        protected virtual void AttachEvents(MethodInfo clrMethod, EventInfo clrEvent)
        {
            if (clrMethod == null) { throw new ArgumentNullException("clrMethod"); }
            if (clrEvent == null) { throw new ArgumentNullException("clrEvent"); }

            Delegate newDelegate = Delegate.CreateDelegate(
                clrEvent.EventHandlerType,
                clrMethod);

            clrEvent.AddEventHandler(null, newDelegate);
        }
 private Delegate attachEventHandler(EventInfo @event, string methodName, object realButton)
 {
     MethodInfo method = GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
     Delegate d = Delegate.CreateDelegate(@event.EventHandlerType, this, method);
     @event.AddEventHandler(realButton, d);
     return d;
 }
        // 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();
            }
            }
        }
Esempio n. 22
0
 /// <summary>
 /// Adds specified <paramref name="listenerMethod"></paramref> as an event handler for 
 /// the <paramref name="sourceEvent"></paramref>.
 /// </summary>
 /// <param name="sourceEvent">Event on source object to which <paramref name="listenerMethod"></paramref> will be added.</param>
 /// <param name="listenerMethod">Method to be added as event handler for <paramref name="listenerMethod"></paramref>.</param>
 public virtual void Bind(EventInfo sourceEvent, MethodInfo listenerMethod)
 {
     Delegate methodToBindTo =
         Delegate.CreateDelegate(sourceEvent.EventHandlerType, listener, listenerMethod);
     sourceEvent.AddEventHandler(source, methodToBindTo);
 }
Esempio n. 23
0
 public WaitUntilDelegate(WaitUntilDelegateList re, EventInfo info, object instance)
 {
     parent = re;
     Event = info;
     Instance = instance;
     SetInstanceOfDelegateType(info.EventHandlerType);
     Event.AddEventHandler(instance, Delegate);
 }
        /// <summary>
        /// Given an EventInfo for an event of the target instance's class, hook it
        /// </summary>
        private void HookEvent(EventInfo eventInfo)
        {
            // Each event is only hooked once
            if (TheTarget != null && !IsHookedEvent(eventInfo.Name))
            {
                // To hook an event: Create an EventProxy for it, then create
                // a delegate to the EventProxy's OnEventXXX method, then add the
                // delegate to the event's list.

                int parameterCount = eventParamCount[eventInfo];
                Debug.Assert(0 <= parameterCount && parameterCount <= 10);

                EventProxy proxy = new EventProxy(this, TheTarget, eventInfo.Name);
                MethodInfo hookMethod = EventProxy.OnEventMethodInfos[parameterCount];
                Delegate d = Delegate.CreateDelegate(eventInfo.EventHandlerType,
                                                      proxy,
                                                      hookMethod);

                m_hooks[eventInfo.Name] = d;
                eventInfo.AddEventHandler(TheTarget, d);
            }
        }
Esempio n. 25
0
    /// <summary>
    /// Will create an event handler association for the current element, using a command markup extension as handler.
    /// </summary>
    /// <param name="obj">Object which defines the event to assign the event
    /// handler specified by <paramref name="cmdExtension"/> to.</param>
    /// <param name="evt">Event which is defined on the class of <paramref name="obj"/>.</param>
    /// <param name="cmdExtension">Command extension to be used as event handler.</param>
    protected void HandleEventAssignment(object obj, EventInfo evt, CommandBaseMarkupExtension cmdExtension)
    {
      try
      {
        // initialize command extension
        ((IEvaluableMarkupExtension)cmdExtension).Initialize(this);

        // get the delegate from the command extension
        var dlgt = cmdExtension.GetDelegate(evt.EventHandlerType);

        // add the event handler to the event
        evt.AddEventHandler(obj, dlgt);
      }
      catch (Exception e)
      {
        throw new XamlBindingException("Error assigning event handler", e);
      }
    }
Esempio n. 26
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);
                }
            }
        }
		/// <summary>
		/// Subscribes the event handler.
		/// </summary>
		/// <param name="eventInfo">The event information.</param>
		/// <param name="item">The item.</param>
		/// <param name="action">The action.</param>
		private void AddEventHandler(EventInfo eventInfo, object item, Action action)
		{
			//Got inspiration from here: http://stackoverflow.com/questions/9753366/subscribing-an-action-to-any-event-type-via-reflection
			//Maybe it is possible to pass Event arguments as CommanParameter

			var mi = eventInfo.EventHandlerType.GetRuntimeMethods().First(rtm => rtm.Name == "Invoke");
			List<ParameterExpression> parameters = mi.GetParameters().Select(p => Expression.Parameter(p.ParameterType)).ToList();
			MethodInfo actionMethodInfo = action.GetMethodInfo();
			Expression exp = Expression.Call(Expression.Constant(this), actionMethodInfo, null);
			this.handler = Expression.Lambda(eventInfo.EventHandlerType, exp, parameters).Compile();
			eventInfo.AddEventHandler(item, handler);
		}
Esempio n. 28
0
		void AddHandler (EventInfo evt, object target, HttpApplication app, MethodInfo method)
		{
			int length = method.GetParameters ().Length;

			if (length == 0) {
				NoParamsInvoker npi = new NoParamsInvoker (app, method);
				evt.AddEventHandler (target, npi.FakeDelegate);
			} else {
				if (method.IsStatic) {
					evt.AddEventHandler (target, Delegate.CreateDelegate (
						evt.EventHandlerType, method));
				} else {
					evt.AddEventHandler (target, Delegate.CreateDelegate (
								     evt.EventHandlerType, app,
								     method));
				}
			}
			
		}
 protected override void AddEventHandler(EventInfo eventInfo, object target, Delegate handler)
 {
     eventInfo.AddEventHandler(target, handler);
 }
Esempio n. 30
0
        private MethodInfo registerLocallyForEvent(EventInfo eventInfo, object target)
        {
            EventHandlerFactory factory = new EventHandlerFactory("testing");

            object handler = factory.GetEventHandler(eventInfo);

            // Create a delegate, which points to the custom event handler
            Delegate customEventDelegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, handler, "CustomEventHandler");
            // Link event handler to event
            eventInfo.AddEventHandler(target, customEventDelegate);

            // Map our own event handler to the common event
            EventInfo commonEventInfo = handler.GetType().GetEvent("CommonEvent");
            Delegate commonDelegate = Delegate.CreateDelegate(commonEventInfo.EventHandlerType, this, "MyEventCallback");
            commonEventInfo.AddEventHandler(handler, commonDelegate);

            return null;
        }
Esempio n. 31
0
 /// <summary>
 /// Will create an event handler association for the current element.
 /// </summary>
 /// <remarks>
 /// In contrast to method
 /// <see cref="HandleMemberAssignment"/>,
 /// this method can only be used for the current element, which is part of the
 /// visual tree. We do not support adding event handlers to markup extension
 /// instances.
 /// </remarks>
 /// <param name="obj">Object which defines the event to assign the event
 /// handler specified by <paramref name="value"/> to.</param>
 /// <param name="evt">Event which is defined on the class of
 /// <paramref name="obj"/>.</param>
 /// <param name="value">Name of the event handler to assign to the specified
 /// event.</param>
 protected void HandleEventAssignment(object obj, EventInfo evt, string value)
 {
   if (_getEventHandler == null)
     throw new XamlBindingException("Delegate 'GetEventHandler' is not assigned");
   Delegate dlgt = _getEventHandler(this, evt.EventHandlerType.GetMethod("Invoke"), value);
   try
   {
     evt.AddEventHandler(obj, dlgt);
   }
   catch (Exception e)
   {
     throw new XamlBindingException("Error assigning event handler", e);
   }
 }
Esempio n. 32
0
		private static void LoadEvent(Control control, XmlAttribute attr, EventInfo ei, object viewModel)
		{
			/// TODO: maybe store this in the frame class in case theres a bunch of stuff and we don't want to keep doing reflection
			var vmType = viewModel.GetType();

			// Handlers can be declared as public or private
			var handlerMethod = vmType.GetMethod(attr.Value, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (handlerMethod == null)
				return;

			var handler = Delegate.CreateDelegate(ei.EventHandlerType, viewModel, handlerMethod);

			ei.AddEventHandler(control, handler);
		}
Esempio n. 33
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="property"></param>
        /// <param name="eventInfo"></param>
        /// <param name="value0">Initial value</param>
        /// <param name="value1">Changed value</param>
        private static void TestProperty(object instance,PropertyInfo property, EventInfo eventInfo, object value0, object value1)
        {
            var eventTriggerCount = 0;
            var keepAliveHandler = true;

            object oldValue = null;
            object newValue = null;

            var handler = new PropertyChanged(
                (o, name, value, nValue) =>
                    {
                        eventTriggerCount++;
                        oldValue = value;
                        newValue = nValue;
                        return keepAliveHandler;
                    });

            property.SetValue(instance,value0);
            Assert.AreEqual(value0,property.GetValue(instance));
            Assert.AreEqual(0,eventTriggerCount);

            eventInfo.AddEventHandler(instance, handler);

            property.SetValue(instance,value1);
            Assert.AreEqual(value1,property.GetValue(instance));
            Assert.AreEqual(1,eventTriggerCount);
            Assert.AreEqual(value0, oldValue);
            Assert.AreEqual(value1, newValue);

            property.SetValue(instance,value1); //same value should not be triggered
            Assert.AreEqual(value1,property.GetValue(instance));
            Assert.AreEqual(1,eventTriggerCount);

            eventInfo.RemoveEventHandler(instance, handler);

            property.SetValue(instance,value0); //handler should not be triggered
            Assert.AreEqual(value0,property.GetValue(instance));
            Assert.AreEqual(1,eventTriggerCount);

            eventInfo.AddEventHandler(instance, handler);

            keepAliveHandler = false; //event should be removed after next trigger

            property.SetValue(instance,value1); //test event self remove from return false
            Assert.AreEqual(value1,property.GetValue(instance));
            Assert.AreEqual(2,eventTriggerCount);
            Assert.AreEqual(value0, oldValue);
            Assert.AreEqual(value1, newValue);

            property.SetValue(instance,value0); //should not trigger handler
            Assert.AreEqual(value0,property.GetValue(instance));
            Assert.AreEqual(2,eventTriggerCount);
        }
Esempio n. 34
0
 /// <summary>
 /// Given an EventInfo for an event of the target instance's class, hook it
 /// </summary>
 private void HookEvent(EventInfo eventInfo)
 {
     // Each event is only hooked once
     if (TheTarget != null && !IsHookedEvent(eventInfo.Name))
     {
         // To hook an event: Create an EventProxy for it, then create
         // a delegate to the EventProxy's OnEvent method, then add the
         // delegate to the event's list
         EventProxy proxy = new EventProxy(this, TheTarget, eventInfo.Name);
         Delegate d = Delegate.CreateDelegate(eventInfo.EventHandlerType,
                                               proxy,
                                               EventProxy.OnEventMethodInfo);
         m_hooks[eventInfo.Name] = d;
         eventInfo.AddEventHandler(TheTarget, d);
     }
 }