[IronPython] Monkey-patching CLR types

Dino Viehland dinov at microsoft.com
Mon Feb 15 01:58:01 CET 2010


You can define an extension property that gets/sets a value which supports in place addition / subtraction.  Something like this:

    [assembly: ExtensionType(typeof(HtmlElement), typeof(HtmlElementExtension))]
    public static class HtmlElementExtension {
        [SpecialName, PropertyMethod]
        public static MyEvent Getonclick(HtmlElement element) {
             return new MyEvent(element);
        }
        [SpecialName, PropertyMethod]
        public static void Setonclick(HtmlElement element, object value) {
		// You could return a value from InPlaceAdd and validate it here
		// to report an error on a direct assignment - this is what 
		// ReflectedEvent does in IronPython.		
        }
    }

    public class MyEvent {
         private readonly HtmlElement _element;
	   public MyEvent(HtmlElement element) {
              _element = element;
         }
	   [SpecialName]
         public object InPlaceAdd(EventHandler[HtmlEventArgs] handler) {
              _element.AttachEvent("onclick", handler);
		  return null;
         }
	   // also needs InPlaceSubtract
    }

-----Original Message-----
From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Jimmy Schementi
Sent: Sunday, February 14, 2010 2:06 PM
To: Discussion of IronPython
Subject: [IronPython] Monkey-patching CLR types

(Yes, I'm asking a question this time =P)

I want to know my options for adding functionality to an existing CLR type. Specifically I want to make hooking DOM events cleaner: in Silverlight today you cannot hook DOM events with the standard += syntax that IronPython uses for CLR events:

    object.onclick += foo

Instead you must do this:

    object.AttachEvent("onclick", EventHandler[HtmlEventArgs](foo))

In IronRuby I fixed that by just monkey-patching System.Windows.Browser.HtmlObject, but in IronPython I cannot monkey-patch built-in types. However, I do something similar with accessing DOM properties (instead of element.GetProperty("innerHTML") it's just element.innerHTML) with DLR's ExtensionType, which is the same way IronPython exposes special methods on CLR types as well:
 
    [assembly: ExtensionType(typeof(HtmlElement), typeof(HtmlElementExtension))]
    public static class HtmlElementExtension {
        [SpecialName]
        public static object GetBoundMember(HtmlElement element, string name) {
            return element.GetProperty(name);
        }
    }

But after looking through Python's Binder and the DLR's ActionBinder for how they use ExtensionTypes, I couldn't get a definitive answer on how to capture an method call plus an operator. Any ideas?

~Jimmy

_______________________________________________
Users mailing list
Users at lists.ironpython.com
http://lists.ironpython.com/listinfo.cgi/users-ironpython.com



More information about the Ironpython-users mailing list