John Lam 1997 — 2026

Method interception

I’m trying to think of some simple scenarios where Ruby’s dynamic nature could be put to good use in writing .NET applications. Here’s one off the top of my head:

class TextBox
import Text=
alias  old_set_Text Text=
def Text=(value)
puts "Changed value from #{self.Text} to #{value}"
old_set_Text(value)
end
end

The TextBox class that you see is a Windows Forms TextBox. Here’s a case where I can intercept all calls to change the Text property of any TextBox control in the application (I can also do this per-control as well).

Of course, it only works if you call from Ruby – this can’t be used, for example, to monitor how C# code changes the Text property of TextBox controls.

The import directive / method that you see is some hypothetical syntax to force my bridge to generate the method shim for Text= (this is done automatically the first time you try to use the property in normal usage scenarios).

Another idea is to monitor SqlConnection opens and closes to make sure that they are balanced. I did this example many years ago when I wrote my AOP weaver for the CLR.

If folks could leave some comments about how they could see using method interception via Ruby, I’d be very interested in seeing if I can code it up using my bridge.

2 archived reader comments

Justin (2006/02/16)

Two ideas: 1) Intercepting when blocks/methods are attached to events (to report attach/unattach events). Not really useful except for obscure memory leaks, but would be an intersting challenge. 2) C# index properties might stretch your syntax (i.e. those properties declare ‘int this[] { get { … } set { … }’)

John Lam (2006/02/16)

I don’t actually have tests right now for C# indexers. I’ll take a look at it tomorrow to see if I have code that covers that case already. Thanks for the suggestion!