/// <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); }
/// <summary> /// Unwires the event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="event">The event.</param> /// <param name="handler">The handler.</param> public static void UnwireEvent(object sender, EventInfo @event, Action<object, EventArgs> handler) { @event.RemoveEventHandler( 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]; }); }
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); } } } }
public override void RemoveEventHandler(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.Remove(target, sourceIid, dispid, handler); } else { // we are dealing with a managed object - just add the delegate through relection _innerEventInfo.RemoveEventHandler(target, handler); } }
/// <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); }
private void detachEventHandler(EventInfo @event, Delegate d, object realButton) { @event.RemoveEventHandler(realButton, 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(); } } }
/// <summary> /// Given an EventInfo for an event of the target instance's class, unhook it /// </summary> private void UnhookEvent(EventInfo eventInfo) { if (TheTarget != null && IsHookedEvent(eventInfo.Name)) { eventInfo.RemoveEventHandler(TheTarget, m_hooks[eventInfo.Name]); m_hooks.Remove(eventInfo.Name); } }
private void HookupVariablesWindow(Window GotFocus) { try { try { if (GotFocus == null) { return; } if (GotFocus.ObjectKind != SSIS_VARIABLES_TOOL_WINDOW_KIND) { return; //if not the variables window } } catch //ObjectKind property blows up on some windows { return; } //they've highlighted the Variables window, so add the extra toolbar buttons //find a package designer window IDesignerHost designer = null; foreach (Window w in this.ApplicationObject.Windows) { try { designer = w.Object as IDesignerHost; if (designer == null) { continue; } ProjectItem pi = w.ProjectItem; if (pi != null && !(pi.Name.ToLower().EndsWith(".dtsx"))) { designer = null; continue; } } catch { continue; } IDesignerToolWindowService service = (IDesignerToolWindowService)designer.GetService(typeof(IDesignerToolWindowService)); if (service == null) { continue; } IDesignerToolWindow toolWindow = service.GetToolWindow(new Guid(SSIS_VARIABLES_TOOL_WINDOW_KIND), 0); if (toolWindow == null) { continue; } variablesToolWindowControl = (UserControl)toolWindow.Client; //actually Microsoft.DataTransformationServices.Design.VariablesToolWindow which is internal serviceProvider = designer; changesvc = (IComponentChangeService)designer.GetService(typeof(IComponentChangeService)); // Get grid and toolbar #if DENALI || SQL2014 // "tableLayoutPanelMain" - "tableLayoutPanelVariable" - "dlgGridControl1" | "toolBarVariable" grid = (DlgGridControl)variablesToolWindowControl.Controls[0].Controls[0].Controls[0]; ToolBar toolbar = (ToolBar)variablesToolWindowControl.Controls[0].Controls[0].Controls[1]; #else grid = (DlgGridControl)variablesToolWindowControl.Controls["dlgGridControl1"]; ToolBar toolbar = (ToolBar)variablesToolWindowControl.Controls["toolBar1"]; #endif // If buttons already added, no need to do it again so exit if (this.moveCopyButton != null && toolbar.Buttons.Contains(this.moveCopyButton)) { return; } #if DENALI || SQL2014 // When you click the edit expression ellipsis button in the variables grid, we want to use our own expression editor, not the MS one. // The following section removes their event handler and adds our own // Get the type of the variables grid, and get the MouseButtonClicked clicked event info // Then get the private dlgGridControl1_MouseButtonClicked event handler method, and get an instance delegate Type gridType = grid.GetType(); System.Reflection.EventInfo eventInfo = gridType.GetEvent("MouseButtonClicked"); Type handlerType = eventInfo.EventHandlerType; MethodInfo legacyMethod = variablesToolWindowControl.GetType().GetMethod("dlgGridControl1_MouseButtonClicked", BindingFlags.NonPublic | BindingFlags.Instance); Delegate del = Delegate.CreateDelegate(handlerType, variablesToolWindowControl, legacyMethod, false); // Finally remove the interal MS event handler from the event, and add our own eventInfo.RemoveEventHandler(grid, del); grid.MouseButtonClicked += grid_MouseButtonClicked; #endif // Now build tool bar buttons and add them ToolBarButton separator = new ToolBarButton(); separator.Style = ToolBarButtonStyle.Separator; toolbar.Buttons.Add(separator); // Move/Copy button this.moveCopyButton = new ToolBarButton(); this.moveCopyButton.Style = ToolBarButtonStyle.PushButton; this.moveCopyButton.ToolTipText = "Move/Copy Variables to New Scope (BIDS Helper)"; toolbar.Buttons.Add(this.moveCopyButton); toolbar.ImageList.Images.Add(BIDSHelper.Resources.Common.Copy); this.moveCopyButton.ImageIndex = toolbar.ImageList.Images.Count - 1; // Edit Variable Expression button this.editExpressionButton = new ToolBarButton(); this.editExpressionButton.Style = ToolBarButtonStyle.PushButton; this.editExpressionButton.ToolTipText = "Edit Variable Expression (BIDS Helper)"; toolbar.Buttons.Add(this.editExpressionButton); toolbar.ImageList.Images.Add(BIDSHelper.Resources.Versioned.EditVariable); this.editExpressionButton.ImageIndex = toolbar.ImageList.Images.Count - 1; #if DENALI || SQL2014 // Find References button this.findReferencesButton = new ToolBarButton(); this.findReferencesButton.Style = ToolBarButtonStyle.PushButton; this.findReferencesButton.ToolTipText = "Find Variable References (BIDS Helper)"; toolbar.Buttons.Add(this.findReferencesButton); toolbar.ImageList.Images.Add(BIDSHelper.Resources.Versioned.VariableFindReferences); this.findReferencesButton.ImageIndex = toolbar.ImageList.Images.Count - 1; // Find Unused button this.findUnusedButton = new ToolBarButton(); this.findUnusedButton.Style = ToolBarButtonStyle.PushButton; this.findUnusedButton.ToolTipText = "Find Unused Variables (BIDS Helper)"; toolbar.Buttons.Add(this.findUnusedButton); toolbar.ImageList.Images.Add(BIDSHelper.Resources.Versioned.VariableFindUnused); this.findUnusedButton.ImageIndex = toolbar.ImageList.Images.Count - 1; #endif toolbar.ButtonClick += new ToolBarButtonClickEventHandler(toolbar_ButtonClick); toolbar.Wrappable = false; grid.SelectionChanged += new SelectionChangedEventHandler(grid_SelectionChanged); grid.Invalidated += new InvalidateEventHandler(grid_Invalidated); SetButtonEnabled(); RefreshHighlights(); return; } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace, DefaultMessageBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } }