public void raise(params object[] eventParams) // only for initial 'obj' for now { Debug.assert(eventInfo.IsMulticast); eventDelegate ??= eventInfo.DeclaringType.field(eventInfo.Name)?.GetValue(obj) as MulticastDelegate; eventDelegate?.GetInvocationList().forEach(dlg => dlg.Method.Invoke(dlg.Target, eventParams)); }
private IEnumerable <NotifyCollectionChangedEventHandler> GetHandlers() { FieldInfo info = typeof(ObservableCollection <T>).GetField(nameof(CollectionChanged), BindingFlags.Instance | BindingFlags.NonPublic); MulticastDelegate @event = (MulticastDelegate)info.GetValue(this); return(@event?.GetInvocationList().Cast <NotifyCollectionChangedEventHandler>().Distinct() ?? Enumerable.Empty <NotifyCollectionChangedEventHandler>()); }
private static T Invoke(MulticastDelegate dlg, T value) { foreach (Func <T, T> evnt in dlg?.GetInvocationList() ?? Enumerable.Empty <Delegate>()) { value = evnt(value); } return(value); }
public void Unregister() { //finds any delegate referencing ConsoleWritten and dereferences it FieldInfo eventFieldInfo = typeof(ConsoleEx).GetField("ConsoleWritten", BindingFlags.NonPublic | BindingFlags.Instance); MulticastDelegate eventInstance = (MulticastDelegate)eventFieldInfo.GetValue(ConsoleEx.singularity); Delegate[] invocationList = eventInstance?.GetInvocationList() ?? new Delegate[] { }; MethodInfo eventRemoveMethodInfo = typeof(ConsoleEx).GetEvent("ConsoleWritten").GetRemoveMethod(true); foreach (Delegate eventHandler in invocationList) { eventRemoveMethodInfo.Invoke(ConsoleEx.singularity, new object[] { eventHandler }); } }
public void UnregisterUpdateAction() { //finds any delegate referencing SpecUpdated and dereferences it FieldInfo eventFieldInfo = typeof(FullSpec).GetField("SpecUpdated", BindingFlags.NonPublic | BindingFlags.Instance); MulticastDelegate eventInstance = (MulticastDelegate)eventFieldInfo.GetValue(this); Delegate[] invocationList = eventInstance?.GetInvocationList() ?? new Delegate[] { }; MethodInfo eventRemoveMethodInfo = typeof(FullSpec).GetEvent("SpecUpdated").GetRemoveMethod(true); foreach (Delegate eventHandler in invocationList) { eventRemoveMethodInfo.Invoke(this, new object[] { eventHandler }); } }
/// <summary> /// Instance has one or more event recipients /// </summary> /// <param name="instance">target instance</param> /// <param name="type">target instance type</param> /// <returns>true if one or more event is active, otherwise false</returns> public static bool HasEventRecipients(ICOMObject instance, Type type) { foreach (EventInfo item in type.GetEvents()) { // public events already have "Event" suffix, we just need to add the _ prefix used by private fields FieldInfo field = type.GetField("_" + item.Name, BindingFlags.Instance | BindingFlags.NonPublic); MulticastDelegate eventDelegate = field?.GetValue(instance) as MulticastDelegate; if (eventDelegate?.GetInvocationList().Length > 0) { return(true); } } return(false); }
/// <summary> /// Custom handler for firing a WMI event to a list of delegates. We use /// the process thread pool to handle the firing. /// </summary> /// <param name="md">The MulticastDelegate representing the collection /// of targets for the event</param> /// <param name="args">The accompanying event arguments</param> internal void FireEventToDelegates(MulticastDelegate md, ManagementEventArgs args) { try { if (null != md) { foreach (Delegate d in md.GetInvocationList()) { try { d.DynamicInvoke(new object[] { this.sender, args }); } catch { } } } } catch { } }
public int GetCountOfEventRecipients(string eventName) { if (null == _thisType) { _thisType = this.GetType(); } MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField( "_" + eventName + "Event", NetRuntimeSystem.Reflection.BindingFlags.Instance | NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this); if (null != eventDelegate) { Delegate[] delegates = eventDelegate.GetInvocationList(); return(delegates.Length); } else { return(0); } }
public static object Raise(this MulticastDelegate multicastDelegate, object sender, EventArgs e) { object retVal = null; MulticastDelegate threadSafeMulticastDelegate = multicastDelegate; if (threadSafeMulticastDelegate != null) { foreach (Delegate d in threadSafeMulticastDelegate.GetInvocationList()) { var synchronizeInvoke = d.Target as ISynchronizeInvoke; if (synchronizeInvoke != null && synchronizeInvoke.InvokeRequired) { retVal = synchronizeInvoke.EndInvoke(synchronizeInvoke.BeginInvoke(d, new[] { sender, e })); } else { retVal = d.DynamicInvoke(new[] { sender, e }); } } } return(retVal); }
/// <summary> Raise the event </summary> internal static void RaiseEvent(MulticastDelegate evt, object sender, WuReadingEventArgs e) { try { if (null != evt) { object[] args = new object[] { sender, e }; foreach (MulticastDelegate d in evt.GetInvocationList()) { //if (d.Target is System.Windows.Forms.Control) //{ // Control c = d.Target as System.Windows.Forms.Control; // c.Invoke(d, args); //} //else //{ d.DynamicInvoke(args); //} } } } catch { } }
/// <summary> /// Raise an instance event /// </summary> /// <param name="instance">target instance</param> /// <param name="type">target instance type</param> /// <param name="eventName">name of the event without 'Event' at the end</param> /// <param name="paramsArray">custom arguments for the event</param> /// <returns>count of called event recipients</returns> public static int RaiseCustomEvent(ICOMObject instance, Type type, string eventName, ref object[] paramsArray) { string fieldName = MakeEventFieldName(eventName); FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic); if (field == null) { throw new ArgumentOutOfRangeException(nameof(eventName), eventName, $"Event with name '{eventName}' does not exist."); } MulticastDelegate eventDelegate = field.GetValue(instance) as MulticastDelegate; if (null != eventDelegate) { Delegate[] delegates = eventDelegate.GetInvocationList(); foreach (var item in delegates) { try { item.Method.Invoke(item.Target, paramsArray); } catch (Exception exception) { instance.Console.WriteException(exception); } } if (instance.Settings.EnableAutoDisposeEventArguments) { Invoker.ReleaseParamsArray(paramsArray); } return(delegates.Length); } return(0); }
private void WriteDelegate(XElement element, object obj, ObjectHeader header) { bool multi = obj is MulticastDelegate; // Write the delegates type if (multi) { element.SetAttributeValue("multi", XmlConvert.ToString(multi)); } if (!multi) { XElement methodElement = new XElement("method"); XElement targetElement = new XElement("target"); element.Add(methodElement); element.Add(targetElement); Delegate objAsDelegate = obj as Delegate; this.WriteObjectData(methodElement, objAsDelegate.GetMethodInfo()); this.WriteObjectData(targetElement, objAsDelegate.Target); } else { XElement methodElement = new XElement("method"); XElement targetElement = new XElement("target"); XElement invocationListElement = new XElement("invocationList"); element.Add(methodElement); element.Add(targetElement); element.Add(invocationListElement); MulticastDelegate objAsDelegate = obj as MulticastDelegate; Delegate[] invokeList = objAsDelegate.GetInvocationList(); this.WriteObjectData(methodElement, objAsDelegate.GetMethodInfo()); this.WriteObjectData(targetElement, objAsDelegate.Target); this.WriteObjectData(invocationListElement, invokeList); } }
/// <summary> /// Event delegates are invoked asynchronously. /// Any exceptions thrown by individual subscribers are /// caught and passed to the input exceptionHandler. /// </summary> public static void PublishWithExceptionStrategyAsync(this MulticastDelegate eventDelegate, object[] parameters, IExceptionStrategy exceptionHandler) { if (eventDelegate != null) { foreach (Delegate subscriber in eventDelegate.GetInvocationList()) { Delegate eventHandler = subscriber; //Uses MethodInfo.Invoke method to publish event because //Delegate.DynamicInvoke method is not available in Compact Framework 3.5. ThreadPool.QueueUserWorkItem( state => { try { eventHandler.Method.Invoke(eventHandler.Target, parameters); } catch (Exception exception) { // Method.Invoke() wraps any exceptions thrown within the method in a // "TargetInvocationException". We unwrap it here. if (exception.InnerException != null) { exceptionHandler.ProcessException(exception.InnerException); } else { exceptionHandler.ProcessException(exception); } } }); } } }
private void InvokeHandler(MulticastDelegate handlerList, EventArgs e) { if (handlerList == null) { return; } object[] args = new object[] { e }; foreach (Delegate handler in handlerList.GetInvocationList()) { object target = handler.Target; System.Windows.Forms.Control control = target as System.Windows.Forms.Control; if (control != null && control.InvokeRequired) { control.Invoke(handler, args); } else { handler.Method.Invoke(target, args); } } }
internal static void ThrowIfUnitialised ( this MulticastDelegate checkedDelegate, string delegateName, string callerName, string predecessorName ) { bool isDelegateUninitalised = checkedDelegate.GetInvocationList().Any ( checkedInvocation => (checkedInvocation == null) ); if (isDelegateUninitalised) { throw new InvalidOperationException ( string.Format("'{0}' is null. '{1}' may be called without previous '{2}' call.", delegateName, callerName, predecessorName) ); } }
public static T ConvertDelegate <T>(Delegate d) { if (!(typeof(T).IsSubclassOf(typeof(Delegate)))) { throw new ArgumentException("T is no Delegate"); } if (d == null) { throw new ArgumentNullException(); } MulticastDelegate md = d as MulticastDelegate; Delegate[] invList = null; int invCount = 1; if (md != null) { invList = md.GetInvocationList(); } if (invList != null) { invCount = invList.Length; } if (invCount == 1) { return((T)(object)Delegate.CreateDelegate(typeof(T), d.Target, d.Method)); } else { for (int i = 0; i < invList.Length; i++) { invList[i] = (Delegate)(object)ConvertDelegate <T>(invList[i]); } return((T)(object)MulticastDelegate.Combine(invList)); } }
/// <summary>Raises the event (on the UI thread if available).</summary> /// <param name="multicastDelegate">The event to raise.</param> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> /// <returns>The return value of the event invocation or null if none.</returns> /// <summary> /// Safely raises any EventHandler event asynchronously. /// </summary> /// <param name="sender">The object raising the event (usually this).</param> /// <param name="e">The EventArgs for this event.</param> public static void Raise(this MulticastDelegate thisEvent, object sender, EventArgs e) { EventHandler uiMethod; ISynchronizeInvoke target; AsyncCallback callback = new AsyncCallback(EndAsynchronousEvent); foreach (Delegate d in thisEvent.GetInvocationList()) { uiMethod = d as EventHandler; if (uiMethod != null) { target = d.Target as ISynchronizeInvoke; if (target != null) { target.BeginInvoke(uiMethod, new[] { sender, e }); } else { uiMethod.BeginInvoke(sender, e, callback, uiMethod); } } } }
/// <summary> /// Writes the specified <see cref="System.Delegate"/>, including references objects. /// </summary> /// <param name="obj">The object to write.</param> /// <param name="objSerializeType">The <see cref="Duality.Serialization.SerializeType"/> describing the object.</param> /// <param name="id">The objects id.</param> protected void WriteDelegate(object obj, SerializeType objSerializeType, uint id = 0) { bool multi = obj is MulticastDelegate; // Write the delegates type this.writer.Write(objSerializeType.TypeString); this.writer.Write(id); this.writer.Write(multi); if (!multi) { Delegate objAsDelegate = obj as Delegate; this.WriteObjectData(objAsDelegate.Method); this.WriteObjectData(objAsDelegate.Target); } else { MulticastDelegate objAsDelegate = obj as MulticastDelegate; Delegate[] invokeList = objAsDelegate.GetInvocationList(); this.WriteObjectData(objAsDelegate.Method); this.WriteObjectData(objAsDelegate.Target); this.WriteObjectData(invokeList); } }
public static void RegisterProcessExitHandlerAndMakeItFirstInLineToExecute(EventHandler eventHandler) { // Here we subscribe to AppDomain.CurrentDomain.ProcessExit event in order to trace a message when process is exiting // The problem is that NLOG subscribed to that event before us and therefore is going to shutdown logging subsystem // before our handler is called and tries to trace its message. // Getting to private field AppDomain.CurrentDomain._processExit FieldInfo field = typeof(AppDomain).GetField("_processExit", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); if (field == null || !field.FieldType.IsSubclassOf(typeof(MulticastDelegate))) { // If the field is not simple MulticastDelegate, then just add our handler to the end of the list AppDomain.CurrentDomain.ProcessExit += eventHandler; return; } // Get the list of existing AppDomain.CurrentDomain.ProcessExit event subscribers MulticastDelegate multicastDelegate = field.GetValue(AppDomain.CurrentDomain) as MulticastDelegate; Debug.Assert(multicastDelegate != null, "multicastDelegate != null"); Delegate[] subscribers = multicastDelegate.GetInvocationList(); // Remove all subscriptions foreach (var subscriber in subscribers) { AppDomain.CurrentDomain.ProcessExit -= (EventHandler)subscriber; } Delegate[] newSubscriptions = new Delegate[subscribers.Length + 1]; // Create new subscriptions list newSubscriptions[0] = eventHandler; // Put our delegate first to the new subscriptions list Array.Copy(subscribers, 0, newSubscriptions, 1, subscribers.Length); // Move the rest of the old subscriptions list after ours Delegate combinedDelegate = Delegate.Combine(newSubscriptions); // Combine subscriptions list to Delegate field.SetValue(AppDomain.CurrentDomain, combinedDelegate); // Inject new delegate into event }
public void RaisePostBackEvent(String eventName) { LoadPostData(); Type type = Widget.GetType(); foreach (EventDescriptor @event in TypeDescriptor.GetEvents(type).OfType <EventDescriptor>()) { WidgetEventAttribute attribute = @event.Attributes.OfType <WidgetEventAttribute>().SingleOrDefault(); if (attribute == null || attribute.Name != eventName) { continue; } FieldInfo delegateField = type.GetField(@event.Name, BindingFlags.Instance | BindingFlags.NonPublic); MulticastDelegate @delegate = delegateField.GetValue(Widget) as MulticastDelegate; if (@delegate != null && @delegate.GetInvocationList().Length > 0) { @delegate.DynamicInvoke(new object[] { Widget, EventArgs.Empty }); } } }
public static int GetLength(this MulticastDelegate self) { return((object)self == null || self.GetInvocationList() == null ? 0 : self.GetInvocationList().Length); }
private bool RaiseEvents(MouseEvent mouseEvent, MouseLLParam param) { try { _semaphore.Wait(); try { var(x, y) = param.pt; MulticastDelegate e = null; MouseEventArgs args = null; switch (mouseEvent) { case MouseEvent.MouseMove: e = MouseMove; args = new MouseEventArgs(x, y); break; case MouseEvent.LeftButtonDown: e = ButtonDown; args = new ButtonEventArgs(x, y, MouseButton.Left); break; case MouseEvent.LeftButtonUp: e = ButtonUp; args = new ButtonEventArgs(x, y, MouseButton.Left); break; case MouseEvent.LeftButtonDoubleClick: e = ButtonDoubleClick; args = new ButtonEventArgs(x, y, MouseButton.Left); break; case MouseEvent.RightButtonDown: e = ButtonDown; args = new ButtonEventArgs(x, y, MouseButton.Right); break; case MouseEvent.RightButtonUp: e = ButtonUp; args = new ButtonEventArgs(x, y, MouseButton.Right); break; case MouseEvent.RightButtonDoubleClick: e = ButtonDoubleClick; args = new ButtonEventArgs(x, y, MouseButton.Right); break; case MouseEvent.MiddleButtonDown: e = ButtonDown; args = new ButtonEventArgs(x, y, MouseButton.Middle); break; case MouseEvent.MiddleButtonUp: e = ButtonUp; args = new ButtonEventArgs(x, y, MouseButton.Middle); break; case MouseEvent.MiddleButtonDoubleClick: e = ButtonDoubleClick; args = new ButtonEventArgs(x, y, MouseButton.Middle); break; case MouseEvent.XButtonDown: e = ButtonDown; args = new ButtonEventArgs(x, y, MouseButton.Fourth + (byte)(param.mouseData / 0x10000) - 1); break; case MouseEvent.XButtonUp: e = ButtonUp; args = new ButtonEventArgs(x, y, MouseButton.Fourth + (byte)(param.mouseData / 0x10000) - 1); break; case MouseEvent.XButtonDoubleClick: e = ButtonDoubleClick; args = new ButtonEventArgs(x, y, MouseButton.Fourth + (byte)(param.mouseData / 0x10000) - 1); break; case MouseEvent.MouseWheel: e = Wheel; args = new WheelEventArgs(x, y, param.mouseData > 0); break; case MouseEvent.MouseHorizontalWheel: e = HorizontalWheel; args = new WheelEventArgs(x, y, param.mouseData > 0); break; default: break; } var l = e?.GetInvocationList(); if (l != null) { for (var i = l.Length; i-- > 0;) { try { var d = l[i]; d.Method.Invoke(d.Target, new object[] { this, args }); } catch { } if (args.Suppress) { return(true); } } } } finally { _semaphore.Release(); } } catch (ObjectDisposedException) { } return(false); }
/************************************************************************************************************************/ private static Delegate[] GetInvocationListIfMulticast(MulticastDelegate del) => AnimancerUtilities.TryGetInvocationListNonAlloc(del, out var delegates) ? delegates : del.GetInvocationList();
internal Delegate[] GetDelegatesWithNonTransientTargets(MulticastDelegate mDelegate) { return(mDelegate.GetInvocationList().Where(x => x.Target == null || !Helpers.IsTransient(x.Target)).ToArray()); }
/// <summary> /// デリゲートが登録されていない場合 true を返します /// </summary> public static bool IsNullOrEmpty(this MulticastDelegate self) { return(self == null || self.GetInvocationList() == null || self.GetInvocationList().Length <= 0); }
/// <summary> /// 登録されているデリゲートの数を返します /// </summary> public static int GetLength(this MulticastDelegate self) { return(self.GetInvocationList().Length); }
public static bool IsNullOrEmpty(this MulticastDelegate self) => self == null || self.GetInvocationList() == null || self.GetInvocationList().Length == 0;
private static bool HasHandler(MulticastDelegate multicast) { return(multicast != null && multicast.GetInvocationList().Any()); }
private static int GetNumDelegates(MulticastDelegate d) { return(d == null ? 0 : d.GetInvocationList().Length); }
/// <summary> /// Runs whenever the locale is loaded\changed. This should allow it to work in any language. /// Works by loading and replacing all dialogs and then using reflection to call the onlanguagechanged event on the localization manager to update all dialog to the correct text. /// </summary> /// <param name="orig"></param> /// <param name="self"></param> /// <param name="language"></param> public static void LoadDialogs_Elanguage(On.DialogManager.orig_LoadDialogs_ELanguage orig, DialogManager self, ELanguage language) { //Loads all the original dialog orig(self, language); if (RandomizerStateManager.Instance.IsRandomizedFile && RandomizerStateManager.Instance.CurrentLocationDialogtoRandomDialogMapping != null) { //Sets the field info so we can use reflection to get and set the private field. FieldInfo dialogByLocIDField = typeof(DialogManager).GetField("dialogByLocID", BindingFlags.NonPublic | BindingFlags.Instance); //Gets all loaded dialogs and makes a copy Dictionary <string, List <DialogInfo> > Loc = dialogByLocIDField.GetValue(self) as Dictionary <string, List <DialogInfo> >; Dictionary <string, List <DialogInfo> > LocCopy = new Dictionary <string, List <DialogInfo> >(Loc); //Before we randomize get some fixed GOT ITEM text to replace text for Phoebekins List <DialogInfo> awardTextDialogList = Manager <DialogManager> .Instance.GetDialog("AWARD_GRIMPLOU"); string awardText = awardTextDialogList[0].text; int replaceindexstart = awardText.IndexOf(">", 1); int replaceindexend = awardText.IndexOf("<", replaceindexstart); string toreplace = awardText.Substring(replaceindexstart + 1, replaceindexend - replaceindexstart - 1); //Phobekin text string phobeText = Manager <LocalizationManager> .Instance.GetText("UI_PHOBEKINS_TITLE").ToLower(); phobeText = char.ToUpper(phobeText[0]) + phobeText.Substring(1); //Ugly way to uppercase the first letter. //Load the randomized mappings for an IF check so it doesn't run randomizer logic and replace itself with itself. Dictionary <string, string> dialogMap = RandomizerStateManager.Instance.CurrentLocationDialogtoRandomDialogMapping; //Loop through each dialog replacement - Will output the replacements to log for debugging foreach (KeyValuePair <string, List <DialogInfo> > KVP in Loc) { string tobereplacedKey = KVP.Key; string replacewithKey = DialogChanger.getDialogMapping(tobereplacedKey); if (dialogMap.ContainsKey(tobereplacedKey)) { //Replaces the entire dialog if ("AWARD_TIMESHARD".Equals(replacewithKey)) { //Timeshards don't have their own dialog. Gonna try to fake it. DialogInfo timeShardDialog = new DialogInfo(); timeShardDialog.text = "Got a timeshard for your troubles."; LocCopy[tobereplacedKey] = new List <DialogInfo>(); LocCopy[tobereplacedKey].Add(timeShardDialog); } else { LocCopy[tobereplacedKey] = Loc[replacewithKey]; } //Sets them to be all center and no portrait (This really only applies to phobekins but was LocCopy[tobereplacedKey][0].autoClose = false; LocCopy[tobereplacedKey][0].autoCloseDelay = 0; LocCopy[tobereplacedKey][0].characterDefinition = null; LocCopy[tobereplacedKey][0].forcedPortraitOrientation = 0; LocCopy[tobereplacedKey][0].position = EDialogPosition.CENTER; LocCopy[tobereplacedKey][0].skippable = true; //This will replace the dialog for a phobekin to be its name in an award text switch (replacewithKey) { case "FIND_ACRO": string acro = Manager <LocalizationManager> .Instance.GetText("PHOBEKIN_ACRO_NAME"); acro = acro.Replace("<color=#00fcfc>", ""); acro = acro.Replace("</color>", ""); LocCopy[tobereplacedKey][0].text = awardText.Replace(toreplace, acro + " " + phobeText); break; case "FIND_PYRO": string pyro = Manager <LocalizationManager> .Instance.GetText("PHOBEKIN_PYRO_NAME"); pyro = pyro.Replace("<color=#00fcfc>", ""); pyro = pyro.Replace("</color>", ""); LocCopy[tobereplacedKey][0].text = awardText.Replace(toreplace, pyro + " " + phobeText); break; case "FIND_CLAUSTRO": string claustro = Manager <LocalizationManager> .Instance.GetText("PHOBEKIN_CLAUSTRO_NAME"); claustro = claustro.Replace("<color=#00fcfc>", ""); claustro = claustro.Replace("</color>", ""); LocCopy[tobereplacedKey][0].text = awardText.Replace(toreplace, claustro + " " + phobeText); break; case "NECRO_PHOBEKIN_DIALOG": string necro = Manager <LocalizationManager> .Instance.GetText("PHOBEKIN_NECRO_NAME"); necro = necro.Replace("<color=#00fcfc>", ""); necro = necro.Replace("</color>", ""); LocCopy[tobereplacedKey][0].text = awardText.Replace(toreplace, necro + " " + phobeText); break; } //This will remove all additional dialog that comes after the initial reward text for (int i = LocCopy[tobereplacedKey].Count - 1; i > 0; i--) { LocCopy[tobereplacedKey].RemoveAt(i); } } } //Sets the replacements dialogByLocIDField.SetValue(self, LocCopy); //There is probably a better way to do this but I chose to use reflection to call all onLanguageChanged events to update the localization completely. if (Manager <LocalizationManager> .Instance != null) { Type type = typeof(LocalizationManager); FieldInfo field = type.GetField("onLanguageChanged", BindingFlags.NonPublic | BindingFlags.Instance); MulticastDelegate eventDelegate = field.GetValue(Manager <LocalizationManager> .Instance) as MulticastDelegate; if (eventDelegate != null) { foreach (Delegate eventHandler in eventDelegate.GetInvocationList()) { eventHandler.Method.Invoke(eventHandler.Target, null); } } } } }