Friday, 23 May 2014

How to determine event subscriptions at runtime

Forgot this again, so thought I'd repost it...

http://consultingblogs.emc.com/merrickchaffer/archive/2011/02/02/how-to-determine-event-subscriptions-at-runtime.aspx

((System.Delegate)myObject.MyEventName).GetInvocationList()

Executing that in the immediate window will spawn you out a list of the attached event handlers to your event at runtime.

Also, if you're trying extract the invocation list of a dotNetBar 11.8.0.1 ButtonItem control's click handler, then the following code is necessary due to the obsfucation of the code that dotNetBar controls have within them. The strange Convert.ToChar(2694) is required in order to ensure that the code page of the C# file remains as ANSI (or Windows 1252), instead of asking you to switch to UTF-8 if you use the actual character code that the private event is stored as.

image

var buttonItem = sender as ButtonItem;
            var clickHandler = string.Empty;
            if (buttonItem != null)
            {

                var clickEvent = typeof(BaseItem).GetField(Convert.ToChar(2694).ToString(CultureInfo.InvariantCulture), BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

                if (clickEvent != null)
                {
                    var clickEventDelegate = clickEvent.GetValue(buttonItem) as Delegate;
                    if (clickEventDelegate != null)
                    {
                        var invocationList = clickEventDelegate.GetInvocationList();
                        if (invocationList.Length > 0)
                        {
                            clickHandler = invocationList[0].Method.Name;
                        }
                    }
                }
            }

            MessageBox.Show(
                string.Format(
                    "The click event {0} is yet to be implemented. If you're attached the debugger will now launch",
                    clickHandler), "Click event handler not yet implemented yet", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Debugger.Break();

No comments:

Post a Comment

Android mediaserver process killing battery life

If this happens to you, then do the following Force stop on Settings, Applications, All, Media Storage. Clear Cache and Clear Data, fo...