<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>I had this idea once...</title>
	<atom:link href="http://ihadthisideaonce.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ihadthisideaonce.com</link>
	<description>... no guarantee when I&#039;ll have another.</description>
	<lastBuildDate>Thu, 02 May 2013 17:21:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='ihadthisideaonce.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>I had this idea once...</title>
		<link>http://ihadthisideaonce.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://ihadthisideaonce.com/osd.xml" title="I had this idea once..." />
	<atom:link rel='hub' href='http://ihadthisideaonce.com/?pushpress=hub'/>
		<item>
		<title>Beyond the Event Horizon: WinForms Plumbing</title>
		<link>http://ihadthisideaonce.com/2012/09/29/beyond-the-event-horizon-winforms-plumbing/</link>
		<comments>http://ihadthisideaonce.com/2012/09/29/beyond-the-event-horizon-winforms-plumbing/#comments</comments>
		<pubDate>Sat, 29 Sep 2012 18:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[ApprovalTests; Reflection; Events; WinForms]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=764</guid>
		<description><![CDATA[In my last post in this series about testing event configurations, I discovered that my code base thus far doesn’t work with the WinForms event system.  After examining the classes in the System.Windows.Forms namespace, I figured out that I’m going to need to put some plumbing in place before I can even think about writing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=764&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsplumbing.jpg"><img style="background-image:none;float:left;padding-top:0;padding-left:0;margin:10px 10px 0 0;display:inline;padding-right:0;border-width:0;" title="WinFormsPlumbing" src="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsplumbing_thumb.jpg?w=166&#038;h=166" alt="WinFormsPlumbing" width="166" height="166" align="left" border="0" /></a>In my last post in this series about testing event configurations, I discovered that my code base thus far doesn’t work with the WinForms event system.  After examining the classes in the <code>System.Windows.Forms</code> namespace, I figured out that I’m going to need to put some plumbing in place before I can even think about writing a query to lock down the event configuration for WinForms.</p>
<p>This article might not make a lot of sense if you haven’t read the previous entry, and that article might be confusing if you haven’t read them all, so here’s a table of contents describing where we’ve been so far:</p>
<ol>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=639">Beyond the Event Horizon: Delegate Basics</a>” — Explores the useful <code>Delegate.GetInvocationList </code>method.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=669">Beyond the Event Horizon: Event Basics</a>” — Explains the relationship between Delegates and Events, and how the compiler implements simple events.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=688">Beyond the Event Horizon: Events You Don’t Own</a>” — Shows how to use reflection to retrieve delegates for events declared on classes you can’t or won’t change.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=711" target="_blank">Beyond the Event Horizon: Event Complications</a>” — Completes the toolset introduced in part 3 by handling inherited events and events of any delegate type.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=742" target="_blank">Beyond the Event Horizon: WinForms Event System</a>” — In which we discover that part 4 did not complete the toolset after all.  <!--EndFragment--></li>
</ol>
<p>You can download the code associated with these articles from <a href="https://github.com/jamesrcounts/EventReflection" target="_blank">GitHub</a>.  While I hope the code is interesting to you, it’s only a reimplementation of features already available the the <a href="http://approvaltests.sourceforge.net/">ApprovalTests</a> library.  You can download ApprovalTests from SourceForge or NuGet and start using these features immediately.  If you need help getting started with ApprovalTests, check out Llewellyn Falco’s <a href="http://www.youtube.com/watch?v=bg8GOmlwqYY&amp;hd=1" target="_blank">video series</a> on YouTube.</p>
<p>To pick up on where we left off, I need to make some plumbing.  First I need to create a public wrapper for the inaccessible <code>ListEntry</code> class.  Then I need to create an enumerable adapter for the <code>EventHandlerList</code> class.</p>
<h1>Speaking the Unspeakable</h1>
<p>I&#8217;ll start with creating the public wrapper for <code>ListEntry</code> that will take care of all the reflection necessary to access it&#8217;s fields. First, I&#8217;ll need to figure out how to get an instance of <code>ListEntry</code> so I can write tests for the wrapper implementation. Here is my test skeleton:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> RetrieveListEntryWithReflection()
{
    <span class="rem">// Create an object which should contain a EventHandlerList with something in it</span>
    <span class="rem">// Get the private property Component.Events</span>
    <span class="rem">// Get the private field head</span>
    <span class="rem">// Assert that head's type is named "ListEntry"</span>
}</pre>
<p>I know that <code>ListEntry</code> is nested in <code>EventHandlerList</code> and that <code>EventHandlerList.head</code> is the only direct reference to a <code>ListEntry</code> value on <code>EventHandlerList</code>. I also want to guard against the possibility that a random type happens to have a field called &#8220;events&#8221; which has nothing to do with <code>events</code>. Here&#8217;s a prototype:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> RetrieveListEntryWithReflection()
{
    <span class="rem">// Create an object which should contain a EventHandlerList with something in it</span>
    var <span class="kwrd">value</span> = <span class="kwrd">new</span> DemoForm();

    <span class="rem">// Get the private field Component.events</span>
    BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
    var listInfo = <span class="kwrd">value</span>.GetType().EnumerateFieldsWithInherited(bindingFlags).SingleOrDefault(fi =&gt; fi.Name == <span class="str">"events"</span> &amp;&amp; <span class="kwrd">typeof</span>(EventHandlerList).IsAssignableFrom(fi.FieldType));
    Assert.IsNotNull(listInfo);
    var eventHandlerList = listInfo.GetValue(<span class="kwrd">value</span>);
    Assert.IsNotNull(eventHandlerList);

    <span class="rem">// Get the private field head</span>
    var headInfo = eventHandlerList.GetType().GetField(<span class="str">"head"</span>, bindingFlags);
    Assert.IsNotNull(headInfo);
    var head = headInfo.GetValue(eventHandlerList);
    Assert.IsNotNull(head);

    <span class="rem">// Assert that head's type is named "ListEntry"</span>
    Assert.AreEqual(<span class="str">"ListEntry"</span>, head.GetType().Name);
}</pre>
<p>This isn’t pretty, but it works.  I see a couple groupings that I can make into methods.  It makes sense to pull out a method that gets the <code>EventHandlerList</code> and one that extracts the <code>ListEntry</code> called “head”.</p>
<p>Here are some tests for a new method, <code>GetEventHandlerList</code>:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetEventHandlerList()
{
    Assert.IsNotNull(<span class="kwrd">new</span> DemoForm().GetEventHandlerList());
}

[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> PocoHasNoEventHandlerList()
{
    Assert.IsNull(<span class="kwrd">new</span> Poco().GetEventHandlerList());
}

[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> SpoilerHasNoEventHandlerList()
{
    Assert.IsNull(<span class="kwrd">new</span> Spoiler().GetEventHandlerList());
}

[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> NullHasNoEventHandlerList()
{
    Assert.IsNull(ReflectionUtility.GetEventHandlerList(<span class="kwrd">null</span>));
}</pre>
<p><code>Spoiler</code> is a little class that contains a field called “events” which has noting to do with raising events.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Spoiler
{
    <span class="kwrd">private</span> <span class="kwrd">string</span> events = <span class="str">"I spoil ur reflektion."</span>;
}</pre>
<p>Now I need to create the method to get these tests to compile.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> EventHandlerList GetEventHandlerList(<span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">return</span> <span class="kwrd">null</span>;
}</pre>
<p>With this change stub, the <code>null</code>, <code>Poco</code> and <code>Spoiler</code> tests pass.  To get the <code>DemoForm </code>test to pass I will need to copy some code from <code>RetrieveListEntryWithReflection</code>.  After copying the relevant section and deleting this calls to <code>Assert</code> I get this:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> EventHandlerList GetEventHandlerList(<span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
    var listInfo = <span class="kwrd">value</span>.GetType().EnumerateFieldsWithInherited(bindingFlags)
        .SingleOrDefault(fi =&gt; fi.Name == <span class="str">"events"</span> &amp;&amp;
                         <span class="kwrd">typeof</span>(EventHandlerList).IsAssignableFrom(fi.FieldType));
    var eventHandlerList = listInfo.GetValue(<span class="kwrd">value</span>);
    <span class="kwrd">return</span> (EventHandlerList)eventHandlerList;
}</pre>
<p>With this implementation my <code>DemoForm</code> tests pass but my other three fail.  There is also some redundancy with methods and constants already provided by <code>ReflectionUtility</code>.  So, after a little refactoring I get this:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> EventHandlerList GetEventHandlerList(<span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    var lists = from fieldInfo <span class="kwrd">in</span> GetType(<span class="kwrd">value</span>).EnumerateFieldsWithInherited(NonPublicInstance)
                <span class="kwrd">where</span> 
                    fieldInfo.Name == <span class="str">"events"</span> &amp;&amp;
                    <span class="kwrd">typeof</span>(EventHandlerList).IsAssignableFrom(fieldInfo.FieldType)
                select fieldInfo.GetValue&lt;EventHandlerList&gt;(<span class="kwrd">value</span>);

    <span class="kwrd">return</span> lists.SingleOrDefault();
}</pre>
<p>This implementation passes all four of the tests (<code>DemoForm</code>, <code>Poco</code>, <code>Spoiler </code>and <code>Null</code>).  So what did I do?  First I eliminated the local declaration of the binding flags and used the constant already defined by <code>ReflectionUtility</code>.  To get past the first null reference exception (caused by the <code>Null </code>test), I used my customized version of <code>GetType</code>, which returns <code>typeof(void)</code> when the input is null.  The where clause survived intact, but I modified the select clause.  I used my own custom <code>GetValue&lt;&gt;</code> method to handle casting from object. to the <code>EventHandlerList </code>type.  For <code>Null</code>, <code>Poco </code>and <code>Spoiler</code>, nothing on the type matches the constraints, so the select statement never executes, so I don’t need additional null checking there.  Finally I unpack the matching value, or return null if there were no matches.</p>
<p>Now I can update <code>RetrieveListEntryWithReflection </code>to use this method.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> RetrieveListEntryWithReflection()
{
    <span class="rem">// Create an object which should contain a EventHandlerList with something in it</span>
    var <span class="kwrd">value</span> = <span class="kwrd">new</span> DemoForm();

    <span class="rem">// Get the private field Component.events</span>
    var eventHandlerList = <span class="kwrd">value</span>.GetEventHandlerList();
    Assert.IsNotNull(eventHandlerList);

    <span class="rem">// Get the private field head</span>
    BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
    var headInfo = eventHandlerList.GetType().GetField(<span class="str">"head"</span>, bindingFlags);
    Assert.IsNotNull(headInfo);
    var head = headInfo.GetValue(eventHandlerList);
    Assert.IsNotNull(head);

    <span class="rem">// Assert that head's type is named "ListEntry"</span>
    Assert.AreEqual(<span class="str">"ListEntry"</span>, head.GetType().Name);
}</pre>
<p>The next chunk of <code>RetrieveListEntryWithReflection</code> pulls the head field from the <code>EventHandlerList</code>. When it comes to extracting the head, I have the advantage of being able to restrict the input to <code>EventHandlerList</code> instances. This means I don&#8217;t have to worry so much about spoilers, but I still need to check for nulls.  Here are some tests:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> DemoFormEventHandlerListHasHead()
{
    var eventHandlerList = <span class="kwrd">new</span> DemoForm().GetEventHandlerList();
    Assert.AreEqual(<span class="str">"ListEntry"</span>, eventHandlerList.GetHead().GetType().Name);
}

[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> ButtonHasNoHead()
{
    Assert.IsNull(<span class="kwrd">new</span> Button().GetEventHandlerList().GetHead());
}

[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> NullHasNoHead()
{
    Assert.IsNull(ReflectionUtility.GetHead(<span class="kwrd">null</span>));
}</pre>
<p>Note the second test <code>ButtonHasNoHead</code>. <code>Button</code> is a control and has many things in common with <code>Form</code>, but in this case <code>GetEventHandlerList</code> returns null because I haven&#8217;t wired up any of <code>Button</code>&#8216;s events.</p>
<p>Here&#8217;s a first draft of <code>GetHead </code>copied from  <code>RetrieveListEntryWithReflection:</code></p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">object</span> GetHead(<span class="kwrd">this</span> EventHandlerList <span class="kwrd">value</span>)
{
    BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
    var headInfo = <span class="kwrd">value</span>.GetType().GetField(<span class="str">"head"</span>, bindingFlags);
    var head = headInfo.GetValue(<span class="kwrd">value</span>);
    <span class="kwrd">return</span> head;
}</pre>
<p>With <code>GetHead</code> I have no choice but to return an <code>object</code>, because the <code>ListEntry</code> type remains un-nameable.  This method is not well protected from null reference exceptions and two of my tests are failing because of that.  More refactoring is in order.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">object</span> GetHead(<span class="kwrd">this</span> EventHandlerList <span class="kwrd">value</span>)
{
    var headInfo = GetType(<span class="kwrd">value</span>).GetField(<span class="str">"head"</span>, NonPublicInstance);
    <span class="kwrd">return</span> headInfo == <span class="kwrd">null</span> ? <span class="kwrd">null</span> : headInfo.GetValue(<span class="kwrd">value</span>);
}</pre>
<p>Again I used the binding flags defined by <code>ReflectionUtility, </code>and the customized <code>GetType </code>method.  One more null check and all my tests are good to go.</p>
<p>I now have a method to retrieve objects of the right type (<code>ListEntry</code>) that I can use for testing.  I can also update <code>RetrieveListEntryWithReflection</code> to use the new method.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> RetrieveListEntryWithReflection()
{
    <span class="rem">// Create an object which should contain a EventHandlerList with something in it</span>
    var <span class="kwrd">value</span> = <span class="kwrd">new</span> DemoForm();

    <span class="rem">// Get the private field head</span>
    var head = <span class="kwrd">value</span>.GetEventHandlerList().GetHead();
    Assert.IsNotNull(head);

    <span class="rem">// Assert that head's type is named "ListEntry"</span>
    Assert.AreEqual(<span class="str">"ListEntry"</span>, head.GetType().Name);
}</pre>
<p>In fact, I can use ApprovalTests to make this test not only more explicit, but shorter too.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> RetrieveListEntryWithReflection()
{
    var head = <span class="kwrd">new</span> DemoForm().GetEventHandlerList().GetHead();
    ApprovalTests.Approvals.Verify(head.GetType().FullName);
}</pre>
<p>By approving the the full name, I feel more confident I&#8217;m getting the right type instead of some other type which might happen to have the same name in a different namespace.</p>
<h2>Wrapping ListEntry</h2>
<p>Because <code>ListEntry </code>is unspeakable outside an <code>EventHandlerList </code>instance, I’m forced to start my wrapper with a constructor that takes an object as its input.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> ListEntryWrapper
{
    <span class="kwrd">public</span> ListEntryWrapper(<span class="kwrd">object</span> <span class="kwrd">value</span>)
    {

    }
}</pre>
<p>Since I must pass an <code>object</code> I can&#8217;t rely on the compiler to require that it is a <code>ListEntry</code>. I need to verify this at runtime, then decide what I should do if something other than a <code>ListEntry</code> instance is provided.  I’ll do this by getting my hands on <code>ListEntry’s </code><code>Type </code>using reflection, and comparing it to the type passed into the constructor.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> Lazy&lt;Type&gt; ListEntryType =
    <span class="kwrd">new</span> Lazy&lt;Type&gt;(() =&gt; <span class="kwrd">typeof</span>(EventHandlerList).GetNestedType(<span class="str">"ListEntry"</span>, BindingFlags.NonPublic));

<span class="kwrd">public</span> ListEntryWrapper(<span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">if</span> (ReflectionUtility.GetType(<span class="kwrd">value</span>) == ListEntryType.Value)
    {
        <span class="rem">// Do something with a genuine ListEntry instance.</span>
    }
}</pre>
<p>Since I know the nested type’s name, getting a reference to its <code>Type </code>is not too difficult.  Since every <code>ListEntryWrapper </code>will need access to this information and the information doesn’t change, I store the <code>Type </code>in a static, read only and Lazy field.  Using <code>Lazy </code>might be premature optimization, but I haven’t had much chance to play with <code>Lazy </code>and this seems like a good learning opportunity.</p>
<p>I don&#8217;t want to put the burden of type-checking on the caller, so I&#8217;ll use the <code>NullObject</code> pattern if the wrong type is passed in.  When the caller gives me the wrong kind of object I will just let the reference pass out of scope and implement appropriate &#8220;do-nothing&#8221; behavior in the wrapper’s properties. Since the <code>ListEntry</code> is part of a single-linked list, do-nothing implies that <code>ListEntryWrapper’s</code> properties should return null.</p>
<p>On the other hand, if the object really is a <code>ListEntry</code> I should store a reference to it so that I can reflect over the value later.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">readonly</span> <span class="kwrd">object</span> listEntry;

<span class="kwrd">public</span> ListEntryWrapper(<span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">if</span> (ReflectionUtility.GetType(<span class="kwrd">value</span>) == ListEntryType.Value)
    {
        <span class="kwrd">this</span>.listEntry = <span class="kwrd">value</span>;
    }
}</pre>
<p>Since <code>ListEntry</code> is unspeakable, all it&#8217;s members are unspeakable, and each member must be accessed through reflection.  Here’s a test I can use to get feedback, while I build with the correct type, and one which shows the result when the type is incorrect. I also pulled the ceremony around getting a <code>ListEntry</code> instance into a convenience method.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> ListEntryIsWrapped()
{
    var listEntryWrapper = <span class="kwrd">new</span> ListEntryWrapper(GetListEntry());
    ApprovalTests.Approvals.Verify(listEntryWrapper.WritePropertiesToString());
}

[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> WrongObjectIsntWrapped()
{
    var listEntryWrapper = <span class="kwrd">new</span> ListEntryWrapper(<span class="kwrd">new</span> <span class="kwrd">object</span>());
    ApprovalTests.Approvals.Verify(listEntryWrapper.WritePropertiesToString());
}</pre>
<p>At the moment, both tests produce the same uninteresting results:</p>
<pre class="csharpcode">ListEntryWrapper
{
}</pre>
<p>I should see some differentiation once I create accessors for each of <code>ListEntry’s</code> members: <code>key</code>, <code>handler</code> and <code>next</code>.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> Lazy&lt;FieldInfo&gt; KeyInfo =
    <span class="kwrd">new</span> Lazy&lt;FieldInfo&gt;(
        () =&gt; ListEntryType.Value.GetField(<span class="str">"key"</span>, BindingFlags.NonPublic | BindingFlags.Instance));

<span class="kwrd">public</span> <span class="kwrd">object</span> Key
{
    get
    {
        <span class="kwrd">return</span> <span class="kwrd">this</span>.listEntry == <span class="kwrd">null</span> ? 
            <span class="kwrd">null</span> :
            KeyInfo.Value.GetValue(<span class="kwrd">this</span>.listEntry);
    }
}</pre>
<p>Here is the result for the actual list entry:</p>
<pre class="csharpcode">ListEntryWrapper
{
    Key: System.Object
}</pre>
<p>And the result for the <code>NullObject</code> scenario:</p>
<pre class="csharpcode">ListEntryWrapper
{
    Key: NULL
}</pre>
<p>I can repeat this technique to implement the remaining properties. Things go fine for <code>Handler</code>, but I run into a problem implementing <code>Next</code>. To keep the linked list going, I need to wrap <code>ListEntry.next</code> in a new <code>ListEntryWrapper</code>. But, if the <code>ListEntry</code> is a singleton or the last link in the list, then &#8220;next&#8221; should be null.  The <code>ListEntryWrapper</code> constructor uses the customized <code>GetType </code>method to retrieve <code>typeof(void)</code> when value is null.  Since <code>typeof(void)</code> is not <code>ListEntry’s </code>type, the wrapper reverts to it’s <code>NullObject </code>behavior… and the linked list terminates with a NullObject <em>followed by</em> a null.  There is one extra link in the chain.  To avoid having to remember this whenever I use the wrapper, <code>Next </code>needs some special logic.</p>
<pre class="csharpcode"><span class="kwrd">public</span> ListEntryWrapper Next
{
    get
    {
        <span class="kwrd">if</span> (<span class="kwrd">this</span>.listEntry == <span class="kwrd">null</span>)
        {
            <span class="kwrd">return</span> <span class="kwrd">null</span>;
        }

        <span class="kwrd">object</span> nextValue = NextInfo.Value.GetValue(<span class="kwrd">this</span>.listEntry);
        <span class="kwrd">return</span> nextValue == <span class="kwrd">null</span> ? <span class="kwrd">null</span> : <span class="kwrd">new</span> ListEntryWrapper(nextValue);
    }
}</pre>
<p>Now, if an object of the wrong type is passed in, <code>listEntry </code>will be null and <code>Next </code>will be null.  If the correct type is passed in, <code>listEntry </code>will be populated, but <code>GetValue </code>will return null when <code>listEntry </code>is the last link in the list.  When that happens, the property will return null; otherwise it will wrap the non-null value and return it.  This behavior is more intuitive and now the results look correct.  Here are the final results for the wrapped <code>ListEntry</code>.</p>
<pre class="csharpcode">ListEntryWrapper
{
    Key: System.Object
    Handler: System.EventHandler
    Next: NULL
}</pre>
<p>To round out my tests, I should add one that covers the case where the <code>ListEntry </code>is <em>not</em> a singleton.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> ListHasMoreThanOneEntry()
{
    var button = <span class="kwrd">new</span> Button();
    button.Click += (s, e) =&gt; { <span class="kwrd">return</span>; };
    button.LostFocus += (s, e) =&gt; { <span class="kwrd">return</span>; };
    var wrapper = <span class="kwrd">new</span> ListEntryWrapper(button.GetEventHandlerList().GetHead());
    ApprovalTests.Approvals.Verify(wrapper.WritePropertiesToString());
}</pre>
<p>This test works as expected, and produces these results:</p>
<pre class="csharpcode">ListEntryWrapper
{
    Handler: System.EventHandler
    Key: System.Object
    Next: EventReflection.Demo.ListEntryWrapper
}</pre>
<p>With this last bit, I have a wrapper for <code>ListEntry</code> that allows me to manipulate these objects like normal public types.  Now, I can turn to the next problem, which is that <code>EventHandlerList</code> doesn&#8217;t implement an <code>IEnumerable</code> interface.</p>
<h2>Making EventHandlerList into a&#8230; List</h2>
<p>Other than a few CRUD operations (add/remove/find) <code>EventHandlerList</code> is just a reference to one <code>ListEntry</code>, called &#8220;head&#8221;. To access any other list entries beyond &#8220;head&#8221;, you have to go through &#8220;head&#8221;. I&#8217;ll know that I&#8217;ve visited all the entries when I find a <code>ListEntry</code> where the &#8220;next&#8221; parameter is a null reference.</p>
<p>The procedure outlined about is called &#8220;walking&#8221; the list. It should be fairly easy to implement now that I have <code>ListEntryWrapper</code> to work with, and because I also already wrote the reflection to retrieve the &#8220;head&#8221; as part of testing <code>ListEntryWrapper</code>. Rather than creating a wrapper class that implements <code>IEnumerable&lt;ListEntryWrapper&gt;</code> I can simply take advantage of the <code>yield</code> statement and have the compiler generate the enumerable class for me.</p>
<p>I&#8217;ll create a method to produce the <code>Button</code> from <code>ListHasMoreThanOneEntry</code>, and reuse it in my next test. If I&#8217;m successful, a test like this should show two <code>ListEntryWrappers</code> in the result.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> AsEnumerableMethodAdaptsEventHandlerList()
{
    var button = GetTestButton();
    ApprovalTests.Approvals.VerifyAll(
        button.GetEventHandlerList().AsEnumerable(),
        e =&gt; e.WritePropertiesToString());
}</pre>
<p>I stub out a new extension method and call it <code>AsEnumerable</code> because that describes what the method does. Although there are methods called <code>AsEnumerable</code> in the framework, their parameters do not have types compatible with <code>EventHandlerList</code>, so I will need to provide the implementation. Of course, before I get too far ahead of myself, I should make sure my <code>AsEnumerable</code> implementation can handle nulls.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> NullListIsEmpty()
{
    var button = <span class="kwrd">new</span> Button();
    Assert.IsFalse(button.GetEventHandlerList().AsEnumerable().Any());
}</pre>
<p>I&#8217;ve decided to handle null by returning an empty set rather than throwing an exception or returning null. This will save me the trouble of checking for null when querying, since LINQ can handle empty sets just fine.</p>
<p>Here is an <code>AsEnumerable</code> implementation that satisfies both tests:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;ListEntryWrapper&gt; AsEnumerable(<span class="kwrd">this</span> EventHandlerList source)
{
    <span class="kwrd">object</span> <span class="kwrd">value</span> = source.GetHead();
    <span class="kwrd">if</span> (<span class="kwrd">value</span> == <span class="kwrd">null</span>)
    {
        <span class="kwrd">yield</span> <span class="kwrd">break</span>;
    }

    <span class="kwrd">for</span> (var head = <span class="kwrd">new</span> ListEntryWrapper(<span class="kwrd">value</span>); head != <span class="kwrd">null</span>; head = head.Next)
    {
        <span class="kwrd">yield</span> <span class="kwrd">return</span> head;
    }
}</pre>
<p>And the results show two items in the list.</p>
<pre class="csharpcode">ListEntryWrapper
{
    Handler: System.EventHandler
    Key: System.Object
    Next: EventReflection.Demo.ListEntryWrapper
}

ListEntryWrapper
{
    Handler: System.EventHandler
    Key: System.Object
    Next: NULL
}</pre>
<p>A just like that, I can now bring all the power of LINQ to bear on <code>EventHandlerList</code>.</p>
<h1>Relationship With EventApprovals</h1>
<p>The classes in ApprovalTests track pretty closely to what I’ve shown here.  The enumerable adapter is hosted in <code>ApprovalUtilities.Reflection.HandlerListHelper</code>.  This class also contains the <code>GetHead </code>method.  The <code>AsEnumerable </code>method is implemented with a <code>while </code>loop, but this detail has no effect.  ILSpy shows that the compiler converts this loop into a <code>for </code>loop like I’ve shown above.</p>
<p>In ApprovalTests, you can find the wrapper class in <code>ApprovalUtilities.Reflection.HandlerListEntry</code>.  Because the ApprovalTests libraries target .NET 3.5, <code>Lazy&lt;T&gt;</code> isn’t available.  The properties are still lazy, but the laziness is implemented by hand.  I created a <code>GetField&lt;T&gt;</code> method which took the field name as a parameter and leveraged the methods in <code>ReflectionUtilities </code>rather than specifying the binding flags a second time.  Conceptually, both wrappers work the same, including the extra null checking in the <code>Next </code>property.</p>
<h1>Up Next</h1>
<p>The plumbing is done and I can return to the domain problem of querying for events that have handlers attached.  Check back soon for the thrilling conclusion to this blog series: “Beyond the Event Horizon: Testing WinForms”.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/764/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/764/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=764&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/09/29/beyond-the-event-horizon-winforms-plumbing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsplumbing_thumb.jpg" medium="image">
			<media:title type="html">WinFormsPlumbing</media:title>
		</media:content>
	</item>
		<item>
		<title>Beyond the Event Horizon: WinForms Event System</title>
		<link>http://ihadthisideaonce.com/2012/09/13/beyond-the-event-horizon-winforms-event-system/</link>
		<comments>http://ihadthisideaonce.com/2012/09/13/beyond-the-event-horizon-winforms-event-system/#comments</comments>
		<pubDate>Thu, 13 Sep 2012 14:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[ApprovalTests]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=742</guid>
		<description><![CDATA[You remember WinForms don&#8217;t you? WinForms applications are still around, in huge quantities. Some of us still need to maintain or rehabilitate WinForms applications, and testing events is particularly important when working with WinForms. The WinForms designer takes responsibility for wiring up many events for you, then discourages you from thinking too hard about what [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=742&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/09/winforms.jpg"><img style="background-image:none;float:left;padding-top:0;padding-left:0;margin:10px 10px 0 0;display:inline;padding-right:0;border-width:0;" title="OLYMPUS DIGITAL CAMERA" src="http://ihadthisideaonce.files.wordpress.com/2012/09/winforms_thumb.jpg?w=162&#038;h=162" alt="OLYMPUS DIGITAL CAMERA" width="162" height="162" align="left" border="0" /></a>You remember WinForms don&#8217;t you? WinForms applications are still around, in huge quantities. Some of us still need to maintain or rehabilitate WinForms applications, and testing events is particularly important when working with WinForms. The WinForms designer takes responsibility for wiring up many events for you, then discourages you from thinking too hard about what it did. Not only does it put the event wiring code in a semi-hidden <code>Designer</code> file, it also encloses the code it doesn&#8217;t want you touch in a region and adds a large comment explaining that you really should slowly back away before you hurt yourself.</p>
<p>Even if you heed all of the warnings and stay out of that code, its still far too easy to add useless empty handlers from within the designer, or worse—accidentally unhook your events.  Unit testing your handler implementations wont help, nothing in the internal implementation changes when a handler is wired (or unwired) from an event.  You need something like the event tests I&#8217;ve been working on to make sure that the proper code is invoked when you perform an action on the GUI (for example, clicking a button).</p>
<p>To build a system for inventorying events on WinForms controls, you should have a good idea how events work elsewhere in the .NET Framework.  Here’s a short list of posts on this blog which should get you up to speed:</p>
<ol>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=639">Beyond the Event Horizon: Delegate Basics</a>” — Explores the useful <code>Delegate.GetInvocationList</code>method.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=669">Beyond the Event Horizon: Event Basics</a>” — Explains the relationship between Delegates and Events, and how the compiler implements simple events.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=688">Beyond the Event Horizon: Events You Don’t Own</a>” — Shows how to use reflection to retrieve delegates for events declared on classes you can’t or won’t change.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=711" target="_blank">Beyond the Event Horizon: Event Complications</a>” — Completes the toolset introduced in part 3 by handling inherited events and events of any delegate type.</li>
</ol>
<p>I’ve made the code associated with these articles available on <a href="https://github.com/jamesrcounts/EventReflection" target="_blank">GitHub</a>.  The code described in this article is a reimplementation of features available in a free, open source testing library called <a href="http://approvaltests.sourceforge.net/">ApprovalTests</a>, which you can download from SourceForge or NuGet and start using immediately.  By using ApprovalTests, you can save yourself the bother of cut-and-paste, and the maintenance headache of keeping your own copy of the code.  Need help getting started with ApprovalTests?  Check out Llewellyn Falco’s <a href="http://www.youtube.com/watch?v=bg8GOmlwqYY&amp;hd=1" target="_blank">fantastic series</a> on YouTube and you will be up to speed in no time.</p>
<p>So, will my event testing system work on <code>WinForms</code>? On the surface it seems like it will, but lets give it a try and see what happens.</p>
<h1>Start With A Failing Test</h1>
<p>First I&#8217;ll create a simple <code>Form</code>.  I won’t be using the designer.  Some of you might have never ventured into the “forbidden zone” inside the Designer file.  I’ll implement the Form by hand, and this will give you your first bit of insight into how events work in WinForms.</p>
<p>First I need to add a reference to <code>System.Windows.Forms</code> and import the namespace having the same name.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.Windows.Forms;

<span class="kwrd">public</span> <span class="kwrd">class</span> DemoForm : Form
{
}</pre>
<p>While I design, I’ll use <code>WinFormsApprovals.Verify</code> to get feedback as I work.</p>
<pre class="csharpcode">[TestClass]
<span class="kwrd">public</span> <span class="kwrd">class</span> WinFormsDemo
{
    [TestMethod]
    <span class="kwrd">public</span> <span class="kwrd">void</span> VerifyDemoFormView()
    {
        WinFormsApprovals.Verify(<span class="kwrd">new</span> DemoForm());
    }
}</pre>
<p>This test will continue to fail until I approve it, so each time I run it I’ll see what <code>DemoForm </code>looks like.  Now that I can see what I&#8217;m doing I can quickly add a few controls to the form. For example, here I add a <code>Button</code>.</p>
<pre class="csharpcode"><span class="kwrd">private</span> Button button1;

<span class="kwrd">public</span> DemoForm()
{
    <span class="kwrd">this</span>.button1 = <span class="kwrd">new</span> Button();
    <span class="kwrd">this</span>.button1.Text = <span class="str">"Click Me!"</span>;
    <span class="kwrd">this</span>.Controls.Add(<span class="kwrd">this</span>.button1);
}</pre>
<p>And I can see what this looks like in TortoiseIDiff:</p>
<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="WinFormsEvents" src="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents_thumb.png?w=1028&#038;h=536" alt="WinFormsEvents" width="1028" height="536" border="0" /></a></p>
<p>And here&#8217;s a <code>CheckBox</code>:</p>
<pre class="csharpcode"><span class="kwrd">private</span> CheckBox checkBox1;

<span class="kwrd">public</span> DemoForm()
{
    <span class="kwrd">this</span>.button1 = <span class="kwrd">new</span> Button();
    <span class="kwrd">this</span>.button1.Text = <span class="str">"Click Me!"</span>;
    <span class="kwrd">this</span>.Controls.Add(<span class="kwrd">this</span>.button1);

    <span class="kwrd">this</span>.checkBox1 = <span class="kwrd">new</span> CheckBox();
    <span class="kwrd">this</span>.checkBox1.Text = <span class="str">"Check Me!"</span>;
    <span class="kwrd">this</span>.checkBox1.Location = <span class="kwrd">new</span> Point(
        <span class="kwrd">this</span>.button1.Location.X + <span class="kwrd">this</span>.button1.Width + 10,
        <span class="kwrd">this</span>.button1.Location.Y);
    <span class="kwrd">this</span>.Controls.Add(<span class="kwrd">this</span>.checkBox1);
}</pre>
<p>The layout code is ugly, but it gets the job done.</p>
<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents2.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="WinFormsEvents2" src="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents2_thumb.png?w=360&#038;h=372" alt="WinFormsEvents2" width="360" height="372" border="0" /></a></p>
<p>Finally, I’ll have a <code>ListBox</code> too:</p>
<pre class="csharpcode"><span class="kwrd">public</span> DemoForm()
{
    <span class="kwrd">this</span>.button1 = <span class="kwrd">new</span> Button();
    <span class="kwrd">this</span>.button1.Text = <span class="str">"Click Me!"</span>;
    <span class="kwrd">this</span>.Controls.Add(<span class="kwrd">this</span>.button1);

    <span class="kwrd">this</span>.checkBox1 = <span class="kwrd">new</span> CheckBox();
    <span class="kwrd">this</span>.checkBox1.Text = <span class="str">"Check Me!"</span>;
    <span class="kwrd">this</span>.checkBox1.Location = <span class="kwrd">new</span> Point(
        <span class="kwrd">this</span>.button1.Location.X + <span class="kwrd">this</span>.button1.Width + 10,
        <span class="kwrd">this</span>.button1.Location.Y);
    <span class="kwrd">this</span>.Controls.Add(<span class="kwrd">this</span>.checkBox1);

    <span class="kwrd">this</span>.listBox1 = <span class="kwrd">new</span> ListBox();
    <span class="kwrd">this</span>.listBox1.Location = <span class="kwrd">new</span> Point(
        10,
        <span class="kwrd">this</span>.button1.Location.Y + <span class="kwrd">this</span>.button1.Height + 10);
    <span class="kwrd">this</span>.listBox1.Size = <span class="kwrd">new</span> Size(
        <span class="kwrd">this</span>.Width - 40,
        <span class="kwrd">this</span>.Height - <span class="kwrd">this</span>.button1.Height - 40);
    <span class="kwrd">this</span>.Controls.Add(<span class="kwrd">this</span>.listBox1);
}</pre>
<p>And here’s my final <code>Form</code>.  Fantastic design if you ask me.  I’ll apply a <code>ClipboardReporterAttribute</code> to the test method and approve the result.  Doing this locks down the look and feel.</p>
<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents3.png"><img style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" title="WinFormsEvents3" src="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents3_thumb.png?w=360&#038;h=358" alt="WinFormsEvents3" width="360" height="358" border="0" /></a></p>
<p>Now I want to add another failing test to lock down the event handlers for the form.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> VerifyDemoFormEvents()
{
    EventUtility.VerifyEventCallbacks(<span class="kwrd">new</span> DemoForm());
}</pre>
<p>And here are the results:</p>
<pre class="csharpcode">Event callbacks <span class="kwrd">for</span> DemoForm</pre>
<p>Throughout these posts I’ve been implying that this code base wont work with WinForms but we haven’t proved that yet.  Before I can say that its not working, I need to wire up some events!</p>
<pre class="csharpcode"><span class="kwrd">public</span> DemoForm()
{
    <span class="rem">// ...</span>

    <span class="kwrd">this</span>.button1.Click += <span class="kwrd">this</span>.ButtonClick;
    <span class="kwrd">this</span>.checkBox1.CheckedChanged += <span class="kwrd">this</span>.HandleCheckedChanged;
    <span class="kwrd">this</span>.Load += <span class="kwrd">this</span>.HandleFormLoad;
}</pre>
<p>I’ve wired up three events but none of them show up in the results.  Right away I can see that there might be a problem with the <code>Button</code> and <code>CheckBox</code>, those events are wired up to child objects, and I’ve never tried to do anything other than get events off the top level object.  However, the <code>HandleFormLoad</code> method is wired up to the <code>Form.Load</code> event, which <em>is</em> part of the top-level object and <em>isn’t</em> showing up either.</p>
<p>Now I’ve got a TODO list:</p>
<ol>
<li>Figure out why the handler attached to Load is missing.</li>
<li>Detect events wired up to child controls.</li>
</ol>
<h1>WinForms Event Implementation</h1>
<p>In my last post, I thought I had discovered the end-all-be-all technique for finding events of any type, but the missing <code>Load</code> event proves me wrong.  According to <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.load.aspx" target="_blank">MSDN</a>, Form.Load has this signature:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler Load</pre>
<p>That doesn&#8217;t seem very exotic.  When I debug my test and query the type in the Immediate window, I get the following output:</p>
<pre class="csharpcode"><span class="kwrd">typeof</span>(DemoForm).GetEvents()
{System.Reflection.EventInfo[91]}
    [0]: {System.EventHandler AutoSizeChanged}
    [1]: {System.EventHandler AutoValidateChanged}
    [2]: {System.ComponentModel.CancelEventHandler HelpButtonClicked}
    [3]: {System.EventHandler MaximizedBoundsChanged}
    [4]: {System.EventHandler MaximumSizeChanged}
    [5]: {System.EventHandler MarginChanged}
    [6]: {System.EventHandler MinimumSizeChanged}
    [7]: {System.EventHandler TabIndexChanged}
    [8]: {System.EventHandler TabStopChanged}
    [9]: {System.EventHandler Activated}
    [10]: {System.ComponentModel.CancelEventHandler Closing}
    [11]: {System.EventHandler Closed}
    [12]: {System.EventHandler Deactivate}
    [13]: {System.Windows.Forms.FormClosingEventHandler FormClosing}
    [14]: {System.Windows.Forms.FormClosedEventHandler FormClosed}
    [15]: {System.EventHandler Load}
    <span class="rem">// Many more events...</span></pre>
<p>Maybe something is wrong with the way I&#8217;m building my type collection in <code>GetEventCallbacks</code>. I&#8217;ll use <code>Extract Method</code> to break out the type collection query so that I can test it in isolation.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;EventCallback&gt; GetEventCallbacks(
    <span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">return</span> <span class="kwrd">value</span>.GetEventsForTypes(GetEventTypes(<span class="kwrd">value</span>).ToArray());
}

<span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;Type&gt; GetEventTypes(<span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">return</span> GetType(<span class="kwrd">value</span>).GetEvents().Select(ei =&gt; ei.EventHandlerType).Distinct();
}</pre>
<p>This change doesn’t break any existing tests.  I’ll add a test to see what happens when this method queries <code>DemoForm</code>.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetEventTypeForDemoForm()
{
    ApprovalTests.Approvals.VerifyAll(
        ReflectionUtility.GetEventTypes(<span class="kwrd">new</span> DemoForm()), <span class="kwrd">string</span>.Empty);
}</pre>
<p>The results look and <code>EventHandler</code>, the delegate type backing <code>Form.Load,</code> is right there in slot 0.</p>
<pre class="csharpcode">[0] = System.EventHandler
[1] = System.ComponentModel.CancelEventHandler
[2] = System.Windows.Forms.FormClosingEventHandler
[3] = System.Windows.Forms.FormClosedEventHandler
[4] = System.Windows.Forms.InputLanguageChangedEventHandler
[5] = System.Windows.Forms.InputLanguageChangingEventHandler
[6] = System.Windows.Forms.ScrollEventHandler
[7] = System.Windows.Forms.ControlEventHandler
[8] = System.Windows.Forms.DragEventHandler
[9] = System.Windows.Forms.GiveFeedbackEventHandler
[10] = System.Windows.Forms.HelpEventHandler
[11] = System.Windows.Forms.InvalidateEventHandler
[12] = System.Windows.Forms.PaintEventHandler
[13] = System.Windows.Forms.QueryContinueDragEventHandler
[14] = System.Windows.Forms.QueryAccessibilityHelpEventHandler
[15] = System.Windows.Forms.KeyEventHandler
[16] = System.Windows.Forms.KeyPressEventHandler
[17] = System.Windows.Forms.LayoutEventHandler
[18] = System.Windows.Forms.MouseEventHandler
[19] = System.Windows.Forms.PreviewKeyDownEventHandler
[20] = System.Windows.Forms.UICuesEventHandler</pre>
<p>The next logical problem could be that the <code>GetEventsForTypes</code> method is not finding any fields assignable to <code>EventHandler</code> on <code>Form</code> or any of its ancestors.  I’ll write another test to focus in on that possibility.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetEventsForDemoFormEventHandlers()
{
    ApprovalTests.Approvals.VerifyAll(
        <span class="kwrd">new</span> DemoForm().GetEventsForTypes(<span class="kwrd">typeof</span>(EventHandler)),
        <span class="kwrd">string</span>.Empty);
}</pre>
<p>ApprovalTests reports that the result set is empty.  That’s a problem.  Why isn’t it finding the field backing <code>Form.Load</code>?  <em>Is</em> there a field backing <code>Form.Load</code>?  My testing assumes that every event is implemented by the compiler, and as a result, every event should have a delegate backing the event, declared as a private field.  What if WinForms uses custom add/remove methods instead of compiler implemented events?</p>
<p>I can use ILSpy to figure out what’s going on.  Sure enough, ILSpy shows a custom add/remove implementation.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler Load
{
    add
    {
        <span class="kwrd">base</span>.Events.AddHandler(Form.EVENT_LOAD, <span class="kwrd">value</span>);
    }
    remove
    {
        <span class="kwrd">base</span>.Events.RemoveHandler(Form.EVENT_LOAD, <span class="kwrd">value</span>);
    }
}</pre>
<p>Instead of adding and removing delegates from a private instance field on <code>Form</code>, these add and remove methods make calls to a protected property called <code>Events</code>. ILSpy tells me that <code>Events</code> is an instance of <code>EventHandlerList</code>. I don&#8217;t know what that is yet, but before I try to figure it out I want to spend a little more time inside <code>Form</code>. The purpose of <code>value</code> is easy to understand, it is the delegate to add or remove, but what about <code>Form.EVENT_LOAD</code>?</p>
<p><code>EVENT_LOAD</code> refers to a private static read-only object, initialized to <code>new object()</code>. This argument it is just a reference to some unique chunk of memory on the managed heap, it can&#8217;t be changed, and every instance of <code>Form</code> has access to the same unique reference. I notice that there are many more static objects like this on <code>Form</code>. For example, <code>Form</code> has <code>EVENT_MENUCOMPLETE</code>, <code>EVENT_MENUSTART</code>, <code>EVENT_RESIZEBEGIN</code>, and so on. Presumably there is a static object which corresponds to each event implemented with custom add/remove methods similar to <code>Form.Load</code>.</p>
<p>If I navigate to the <code>Events</code> property declaration I find it declared on <code>System.ComponentModel.Component</code>:</p>
<pre class="csharpcode"><span class="kwrd">protected</span> EventHandlerList Events
{
    get
    {
        <span class="kwrd">if</span> (<span class="kwrd">this</span>.events == <span class="kwrd">null</span>)
        {
            <span class="kwrd">this</span>.events = <span class="kwrd">new</span> EventHandlerList(<span class="kwrd">this</span>);
        }
        <span class="kwrd">return</span> <span class="kwrd">this</span>.events;
    }
}</pre>
<p>The property lazily instantiates an <code>EventHandlerList</code> when needed, and that’s about it. <code>EventHandlerList</code> also lives in the <code>System.ComponentModel</code> namespace. Despite it&#8217;s name, it does not derive from <code>List</code>, nor does it implement any list or collection interfaces.  I&#8217;ll look at <code>AddHandler</code> to see what it does when it receives the static object and handler delegate.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> AddHandler(<span class="kwrd">object</span> key, Delegate <span class="kwrd">value</span>)
{
    EventHandlerList.ListEntry listEntry = <span class="kwrd">this</span>.Find(key);
    <span class="kwrd">if</span> (listEntry != <span class="kwrd">null</span>)
    {
        listEntry.handler = Delegate.Combine(listEntry.handler, <span class="kwrd">value</span>);
        <span class="kwrd">return</span>;
    }
    <span class="kwrd">this</span>.head = <span class="kwrd">new</span> EventHandlerList.ListEntry(key, <span class="kwrd">value</span>, <span class="kwrd">this</span>.head);
}</pre>
<p>From this method&#8217;s point of view, the static object is called <code>key</code> and the delegate is called <code>value</code>. So, <code>EventHandlerList</code> is logically closer to a dictionary than a list.  When <code>AddHandler </code>executes, the dictionary attempts to find an existing value with that key. When found, the new delegate is combined with the existing delegates, otherwise the method creates a new dictionary entry. The last line of the method might give some insight into how <code>EventHandlerList</code> stores its data, if I knew how <code>EventHandlerList.ListEntry</code> was implemented.</p>
<p>Here is <code>ListEntry</code>&#8216;s entire implementation:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">sealed</span> <span class="kwrd">class</span> ListEntry
{
    <span class="kwrd">internal</span> EventHandlerList.ListEntry next;
    <span class="kwrd">internal</span> <span class="kwrd">object</span> key;
    <span class="kwrd">internal</span> Delegate handler;
    <span class="kwrd">public</span> ListEntry(<span class="kwrd">object</span> key, Delegate handler, EventHandlerList.ListEntry next)
    {
        <span class="kwrd">this</span>.next = next;
        <span class="kwrd">this</span>.key = key;
        <span class="kwrd">this</span>.handler = handler;
    }
}</pre>
<p>In a typical .NET dictionary, each entry provides a key and a value. <code>ListEntry</code> provides these members, but also a reference to the next entry. So, <code>EventHandlerList</code> is a hybrid dictionary/linked-list.</p>
<h1>Missing Pieces</h1>
<p>After finding <code>ListEntry</code> I don&#8217;t need to look any further. Since <code>WinForms</code> has taken us deep into a rabbit hole, I&#8217;ll restate my goals:</p>
<blockquote><p>Given a Form to examine, make one call that will inventory the event handlers attached to the Form and each of the Form&#8217;s controls. Display the inventory where each invocation list is associated with the event it&#8217;s attached to, and each event is associated with the type it is declared on.</p></blockquote>
<p>Let&#8217;s compare how I solved each part of this problem in the <code>Poco</code> example with how I will need to solve it in the <code>WinForms</code> example.</p>
<ul>
<li>Find Invocation List
<ul>
<li>Poco: Find the delegate field backing the event; call <code>GetInvocationList</code></li>
<li>WinForms: Find the <code>ListEntry</code> instance in <code>Events</code>; access the <code>handler</code> field and call <code>GetInvocationList</code></li>
</ul>
</li>
<li>Associate Invocation List with Event
<ul>
<li>Poco: Use the delegate field name.</li>
<li>WinForms: Use the name of the static object used as the <code>ListEntry</code> key.</li>
</ul>
</li>
<li>Associate Event with Object
<ul>
<li>Poco: Use the Type name.</li>
<li>WinForms: Use the <code>Form </code>type name for <code>Form</code> Events.  Use the <code>Control</code> type name for each child control.</li>
</ul>
</li>
</ul>
<p>I think the biggest difference while constructing a query will be the way the invocation list is associated with an event name.  With POCO events I could get both the invocation list and the name from the same delegate reference.  By the time a <code>Component</code> stores an event delegate in a <code>ListEntry</code> the event name is lost and everything is called <code>key</code>. The CLR doesn&#8217;t care about the name because it checks the key with a reference comparison, it just needs the pointer.</p>
<p>Besides the query, I&#8217;m going to need a lot of plumbing just to make the data structure queryable. <code>ListEntry</code> is private, nested and sealed. The compiler wont even acknowledge it&#8217;s existence:</p>
<pre class="csharpcode">EventHandlerList.ListEntry entry;  // Won't compile</pre>
<p>Error:</p>
<pre class="csharpcode">Error   1   The type name <span class="str">'ListEntry'</span> does not exist <span class="kwrd">in</span> the type <span class="str">'System.ComponentModel.EventHandlerList'</span></pre>
<p>And since <code>EventHandlerList</code> doesn&#8217;t implement <code>IEnumerable</code> or <code>IEnumerable&lt;T&gt;</code>, it doesn&#8217;t play nice with LINQ:</p>
<pre class="csharpcode">EventHandlerList ehl = <span class="kwrd">new</span> EventHandlerList();
var q = from e <span class="kwrd">in</span> ehl select e; // Wont compile</pre>
<p>Error:</p>
<pre class="csharpcode">Error   1   Could not find an implementation of the query pattern <span class="kwrd">for</span> source type <span class="str">'System.ComponentModel.EventHandlerList'</span>.  <span class="str">'Select'</span> not found.</pre>
<p>So, before I can write my queries, I&#8217;ll need to get under there and do some plumbing.</p>
<h1></h1>
<h1>Relationship With EventApprovals</h1>
<p>This article has been a bit of a tease.  While I hope I’ve provided some useful information, I haven’t really produced any solutions.  The relationship with EventApprovals is that all of these problems are already solved in ApprovalTests!  When you call <code>ApprovalTests.Events.EventApprovals.VerifyEvents</code>, WinForms events are supported and will appear in your inventory.</p>
<h1>Up Next</h1>
<p>In this article’s next installment: “<a title="Beyond the Event Horizon: WinForms Plumbing" href="http://ihadthisideaonce.com/2012/09/29/beyond-the-event-horizon-winforms-plumbing/">Beyond the Event Horizon: WinForms Plumbing</a>”, I will use what I’ve learned about WinForms to build up the plumbing pieces necessary to make a usable wrapper for <code>ListEntry</code> and an enumerable adapter for <code>EventHandlerList</code>.  With those pieces of plumbing out of the way then I can return to my TODO list, find the missing <code>Form.Load</code> event, and figure out how I want to capture the events declared on child controls.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/742/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=742&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/09/13/beyond-the-event-horizon-winforms-event-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/09/winforms_thumb.jpg" medium="image">
			<media:title type="html">OLYMPUS DIGITAL CAMERA</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents_thumb.png" medium="image">
			<media:title type="html">WinFormsEvents</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents2_thumb.png" medium="image">
			<media:title type="html">WinFormsEvents2</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/09/winformsevents3_thumb.png" medium="image">
			<media:title type="html">WinFormsEvents3</media:title>
		</media:content>
	</item>
		<item>
		<title>Beyond the Event Horizon: Event Complications</title>
		<link>http://ihadthisideaonce.com/2012/09/09/beyond-the-event-horizon-event-complications/</link>
		<comments>http://ihadthisideaonce.com/2012/09/09/beyond-the-event-horizon-event-complications/#comments</comments>
		<pubDate>Sun, 09 Sep 2012 16:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[ApprovalTests]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=711</guid>
		<description><![CDATA[This article will continue to expand the capabilities of my reflection based event tests.  Although my VerifyEventCallbacks test method can inventory collections of EventHandler based events declared directly on a class, it only works on events backed by EventHandler delegates, and it won’t detect events declared on base classes.   To be truly useful, these shortcomings [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=711&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/09/pb040015.jpg"><img style="background-image:none;margin:10px 10px 0 0;padding-left:0;padding-right:0;display:inline;float:left;padding-top:0;border-width:0;" title="PB040015" src="http://ihadthisideaonce.files.wordpress.com/2012/09/pb040015_thumb.jpg?w=158&#038;h=158" alt="PB040015" width="158" height="158" align="left" border="0" /></a>This article will continue to expand the capabilities of my reflection based event tests.  Although my <code>VerifyEventCallbacks </code>test method can inventory collections of EventHandler based events declared directly on a class, it only works on events backed by EventHandler delegates, and it won’t detect events declared on base classes.   To be truly useful, these shortcomings need to be addressed.</p>
<p>If you have read the previous articles in this series, then I hope you have gained a decent grasp of some fundamental event system concepts.  Here is a short table of contents for where we’ve been so far:</p>
<ol>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=639" target="_blank">Beyond the Event Horizon: Delegate Basics</a>” — Explores the useful <code>Delegate.GetInvocationList</code>method.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=669" target="_blank">Beyond the Event Horizon: Event Basics</a>” — Explains the relationship between Delegates and Events, and how the compiler implements simple events.</li>
<li>“<a href="https://ihadthisideaonce.wordpress.com/?p=688" target="_blank">Beyond the Event Horizon: Events You Don’t Own</a>” — Shows how to use reflection to retrieve delegates for events declared on classes you can’t or won’t change.</li>
</ol>
<p>For your enjoyment and education, you can can get the code associated with these articles from <a href="https://github.com/jamesrcounts/EventReflection" target="_blank">GitHub</a>.  However, remember that this code is nothing more than a reimplementation of features already available in the <a href="http://approvaltests.sourceforge.net/">ApprovalTests</a> library, which is a free, open source library you can use to enhance your tests.  If your primary interest is to use these features, then don’t bother with cut-and-paste, just get yourself a copy of ApprovalTests from SourceForge or NuGet.</p>
<p>Don’t know what ApprovalTests are?  You will get more out of this article if you take a moment to watch a few videos in Llewellyn Falco’s ApprovalTests <a href="http://www.youtube.com/watch?v=bg8GOmlwqYY&amp;hd=1" target="_blank">tutorial series</a> on YouTube.</p>
<h1>A Comprehensive Inventory</h1>
<p>So far my tests against <code>Poco</code> look pretty nice. I tried to keep the test general, because it would be nice to reuse my extension methods on objects besides <code>Poco</code> instances. I&#8217;m worried that <code>Poco</code> doesn’t represent objects I might find in the real world.</p>
<p>Here are a couple traits of <code>Poco</code> that indicate it may not be complicated enough to model real world classes:</p>
<ol>
<li><code>Poco</code>&#8216;s events are only based on <code>EventHandler</code>. I should add some events based on <code>EventHandler&lt;T&gt;</code> or the always popular (hated?) <code>PropertyChangedEventHandler</code>.</li>
<li><code>Poco</code>&#8216;s events are all declared on <code>Poco</code>. I should introduce a class that inherits from some of its events from a base class.</li>
</ol>
<p>I&#8217;ll create a class with both these features by inheriting from <code>Poco</code> and implementing <code>INotifyPropertyChanged</code> on the descendant.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.ComponentModel;
<span class="kwrd">public</span> <span class="kwrd">class</span> PocoExtension : Poco, INotifyPropertyChanged
{
    <span class="kwrd">public</span> <span class="kwrd">event</span> PropertyChangedEventHandler PropertyChanged;

    <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnPropertyChanged(<span class="kwrd">object</span> sender, PropertyChangedEventArgs e)
    {
        var handler = <span class="kwrd">this</span>.PropertyChanged;
        <span class="kwrd">if</span> (handler != <span class="kwrd">null</span>)
        {
            handler(sender, e);
        }
    }
}</pre>
<p>And I&#8217;ll write a test for this class.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> PocoExtensionTest()
{
    var target = <span class="kwrd">new</span> PocoExtension();
    target.ProcessStarted += Domain.HandleProcessStarted;
    target.PropertyChanged += Domain.HandlePropertyChanged;
    EventUtility.VerifyEventCallbacks(target);
}</pre>
<p>As a developer using <code>PocoExtension</code> I can wire up a handler to <code>ProcessStarted</code> (which is inherited from <code>Poco</code>) just as easily as I can wire up a handler to <code>PropertyChanged</code> (which is declared on <code>PocoExtension</code>). Both events are part of the same object, so why should I need to worry about whether they are part of the same class? My intuition is that both events should show up in the inventory. Likewise, I wire up my handlers in the exact same manner, even though <code>ProcessStarted</code> and <code>PropertyChanged</code> leverage different delegate types to specify compatible handlers. They are both events, why should I have to worry about the delegate type? My intuition remains that both events should show up in the inventory. The test results do not meet my intuitive expectation:</p>
<pre class="csharpcode">Event callbacks <span class="kwrd">for</span> PocoExtension</pre>
<p>With all the preamble in this article, it shouldn&#8217;t surprise you that neither event was found, but here is the final proof.  More importantly, I have a failing test that I can use to guide me toward a solution.  I have two problems to solve:</p>
<ol>
<li>Detect inherited events.</li>
<li>Detect events not based on <code>EventHandler</code></li>
</ol>
<p>Which one to attack first?  The second requirement seems harder because all delegates inherit from <code>MulticastDelegate</code> whether they are associated with events or not.  It’s natural to think that <code>EventHandler&lt;T&gt; </code>derives from <code>EventHandler</code> but other than similar names (and sharing <code>MulticastDelegate</code> as a base type) these two delegates have no relationship.  Remember, delegates are their own types, and one of the rules for the delegate type is that they are all implicitly sealed (at the language level, the compiler can do what it likes when implementing delegates in IL).  So, there is no least derived type that I could use to find all the “event” delegates because none of them can even derive from each other in the first place.</p>
<p>So, without inheritance to lean on, I&#8217;ll need some other way to filter for delegates that are related to events. I&#8217;ll come back to this problem after dealing with the easier problem of detecting inherited events on <code>PocoExtension</code>.</p>
<h1>Inherited Events</h1>
<p>I wired up two event handlers in my test: <code>ProcessStarted</code> and <code>PropertyChanged</code>.  Neither was detected.  With <code>ProcessStarted</code> I know that the problem is not the delegate type, because it is backed by an <code>EventHandler</code> delegate.   So, the problem with this event must be inheritance.  In other words, my test does not detect <code>ProcessStarted</code> because it is declared on the base class (<code>Poco</code>).</p>
<p>Nothing has changed about the backing field I’m looking for, it’s still a private instance field on the declaring class.  Although the reflection API provides a <code>BindingFlag</code> that will flatten class hierarchies, private fields are not included, so this field is not showing up in my query.  I need to implement this capability myself.</p>
<p>The procedure seems straightforward.  Given an instance of <code>Type</code>, I can use the <code>Type.BaseType</code> property to get the less derived type.  I can crawl up this inheritance chain in a loop until it ends, collecting private fields as I go.  My guess is that I’m probably not the first developer to come up with this idea, and I wonder if maybe someone out there has a better solution than simple iteration.  However, after some research, it looks like everyone is just iterating so that’s what I’ll do.</p>
<p>Here is my current <code>GetEventHandlers</code> implementation.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;EventCallback&gt; GetEventHandlers(<span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">if</span> (<span class="kwrd">value</span> == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span> <span class="kwrd">null</span>;
    }

    <span class="kwrd">return</span> from fieldInfo <span class="kwrd">in</span> <span class="kwrd">value</span>.GetType().GetFields(NonPublicInstance)
           <span class="kwrd">where</span> <span class="kwrd">typeof</span>(EventHandler).IsAssignableFrom(fieldInfo.FieldType)
           let callback = fieldInfo.GetValue&lt;EventHandler&gt;(<span class="kwrd">value</span>)
           <span class="kwrd">where</span> callback != <span class="kwrd">null</span>
           select <span class="kwrd">new</span> EventCallback(fieldInfo.Name, callback);
}</pre>
<p>The problem is that <code>GetFields</code> does not include inherited private fields (“inherited private” is a weird thing to say—all that I mean is these fields exist at runtime and have values).  I can’t change the behavior of <code>GetFields</code>, so I need to replace it.  I’ll create an extension method on <code>Type</code> that does what I need:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;FieldInfo&gt; EnumerateFieldsWithInherited(
    <span class="kwrd">this</span> Type typeInfo,
    BindingFlags bindingFlags)
{
    <span class="kwrd">for</span> (var type = typeInfo; type != <span class="kwrd">null</span>; type = type.BaseType)
    {
        <span class="kwrd">foreach</span> (var fieldInfo <span class="kwrd">in</span> type.GetFields(bindingFlags))
        {
            <span class="kwrd">yield</span> <span class="kwrd">return</span> fieldInfo;
        }
    }
}</pre>
<p>This method is more or less implements the procedure described above, but instead of collecting the private fields, it streams them out as they are needed.  Now I can test whether updating <code>GetEventHandlers</code> to use this method will result in any changes to my results.</p>
<p>New results:</p>
<pre class="csharpcode">Event callbacks <span class="kwrd">for</span> PocoExtension

ProcessStarted
    [0] Void HandleProcessStarted(System.Object, System.EventArgs)</pre>
<p>The test found the inherited event, excellent. My previous tests still pass, so I haven&#8217;t broken anything either. That&#8217;s one down, on to the next challenge.</p>
<h1>Find events of any type</h1>
<p>The current <code>GetEventHandlers</code> method does just what it advertises. It gets fields declared as <code>EventHandler</code>. Unfortunately, nothing requires that events be declared as <code>EventHandler</code> and there are many other options. Because delegates have no meaningful inheritance relationships, these other options don&#8217;t even inherit from <code>EventHandler</code>.</p>
<p>I&#8217;ll approach this problem by refactoring the out the &#8220;defective&#8221; part of <code>GetEventHandlers</code>. I&#8217;ll end up with two methods, <code>GetEventHandlers</code> will continue to work as advertised, but it will use a new method, <code>GetEventsForType</code>, for the heavy lifting.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;EventCallback&gt; GetEventHandlers(<span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">return</span> <span class="kwrd">value</span>.GetEventsForType(<span class="kwrd">typeof</span>(EventHandler));
}

<span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;EventCallback&gt; GetEventsForType(
    <span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>, 
    Type type)
{
    <span class="kwrd">if</span> (<span class="kwrd">value</span> == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span> <span class="kwrd">null</span>;
    }

    <span class="kwrd">return</span> from fieldInfo <span class="kwrd">in</span> <span class="kwrd">value</span>.GetType().EnumerateFieldsWithInherited(NonPublicInstance)
           <span class="kwrd">where</span> type.IsAssignableFrom(fieldInfo.FieldType)
           let callback = fieldInfo.GetValue&lt;EventHandler&gt;(<span class="kwrd">value</span>)
           <span class="kwrd">where</span> callback != <span class="kwrd">null</span>
           select <span class="kwrd">new</span> EventCallback(fieldInfo.Name, callback);
}</pre>
<p>After making this change, my existing test on <code>Poco</code> still passes, and the output for my new test on <code>PocoExtension</code> is the same. Technically, <code>PocoExtensionTest</code> is failing, but that&#8217;s only because I haven&#8217;t approved anything yet. So this change hasn&#8217;t broken anything.</p>
<p>To get my test into a state where I can approve the result, I need to keep working on <code>GetEventsForType</code>.  In it’s current form, <code>GetEventsForType</code> lets me specify a type to filter for, but I know that <code>PocoExtension</code> uses more than one delegate type for its events.  I would rather pass a collection of delegate types to <code>GetEventsForType</code> (and pluralize the name).  Once I have a collection of types, I can change the query to collect backing fields for any type in the collection.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;EventCallback&gt; GetEventsForTypes(
    <span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>,
    <span class="kwrd">params</span> Type[] types)
{
    <span class="kwrd">if</span> (<span class="kwrd">value</span> == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span> <span class="kwrd">null</span>;
    }

    <span class="kwrd">return</span> from fieldInfo <span class="kwrd">in</span> <span class="kwrd">value</span>.GetType().EnumerateFieldsWithInherited(NonPublicInstance)
            <span class="kwrd">where</span> types.Any(t =&gt; t == fieldInfo.FieldType)
            let callback = fieldInfo.GetValue&lt;EventHandler&gt;(<span class="kwrd">value</span>)
            <span class="kwrd">where</span> callback != <span class="kwrd">null</span>
            select <span class="kwrd">new</span> EventCallback(fieldInfo.Name, callback);
}</pre>
<p>Keeping in mind that delegate inheritance is restricted, the old query’s use of <code>IsAssignableFrom</code> started to smell.  If there are no inheritance chains for delegates, then a simple equality check should suffice.  My existing tests are happy with this change, but <code>PocoExtensionTest</code> still doesn’t detect the <code>PropertyChanged</code> handlers.</p>
<p>The last piece of the puzzle is to create the collection of delegate types associated with <code>PocoExtension</code>’s backing fields and pass it to <code>GetEventsForTypes</code>.  I know the reflection API has <code>GetProperties</code>, <code>GetConstructors</code>, <code>GetFields</code>, why not <code>GetEvents</code>?  As a matter of fact, such a method exists. It returns an <code>EventInfo</code> array, and each member includes an <code>EventHandlerType</code> property that I can use to create a collection of types. Another extension method is in order, but naming it is hard.  <code>GetEventHandlers</code> still seems like the best name because its so general, but it implies a false relationship with the <code>EventHandler</code> delegate. So, I&#8217;ll go with <code>Callback</code>.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;EventCallback&gt; GetEventCallbacks(
    <span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    var types = <span class="kwrd">value</span>.GetType().GetEvents()
        .Select(ei =&gt; ei.EventHandlerType).Distinct();
    <span class="kwrd">return</span> <span class="kwrd">value</span>.GetEventsForTypes(types.ToArray());
}</pre>
<p>Notice that I don&#8217;t pass any binding flags to <code>GetEvents</code>. Events <em>should</em> be public. They could be protected or perhaps even private but that seems kind of weird, so I&#8217;m not going to worry too much about it. I update <code>VerifyEventCallbacks</code> to use this new method:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> VerifyEventCallbacks(<span class="kwrd">object</span> <span class="kwrd">value</span>)
{
        <span class="rem">// ...</span>
        <span class="kwrd">foreach</span> (var callback <span class="kwrd">in</span> <span class="kwrd">value</span>.GetEventCallbacks())
        {
            buffer.AppendLine(callback.ToString());
        }
        <span class="rem">// ...</span>
}</pre>
<p>Making this change doesn’t break any passing tests, but it does “break” the test I haven’t approved yet.  Instead of showing me any results, that test now throws an <code>InvalidCastException</code>.  Turns out that I did not pay enough attention when I let my refactoring tool extract <code>GetEventsForTypes</code>.</p>
<p>Although the method takes an array of types, the query still attempts to cast everything to <code>EventHandler</code>.  Again, since inheritance relationships don’t exist between delegate types, <code>PropertyChangedEventHandler</code> can’t cast to <code>EventHandler</code>.  My only choices are to use <code>Delegate</code> or <code>MulticastDelegate</code> for my cast.  <code>Delegate</code> will work fine because the only thing I need to do is call <code>GetInvocationList</code>.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;EventCallback&gt; GetEventsForTypes(
    <span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>,
    <span class="kwrd">params</span> Type[] types)
{
    <span class="rem">// ...</span>
    <span class="kwrd">return</span> from fieldInfo <span class="kwrd">in</span> <span class="kwrd">value</span>.GetType().EnumerateFieldsWithInherited(NonPublicInstance)
            <span class="kwrd">where</span> types.Any(t =&gt; t == fieldInfo.FieldType)
            let callback = fieldInfo.GetValue&lt;Delegate&gt;(<span class="kwrd">value</span>)
            <span class="kwrd">where</span> callback != <span class="kwrd">null</span>
            select <span class="kwrd">new</span> EventCallback(fieldInfo.Name, callback);
}</pre>
<p>Now my test makes it all the way to the call to <code>Approvals.Verify</code> and produces output:</p>
<pre class="csharpcode">Event callbacks <span class="kwrd">for</span> PocoExtension

PropertyChanged
    [0] Void HandlePropertyChanged(System.Object, System.ComponentModel.PropertyChangedEventArgs)

ProcessStarted
    [0] Void HandleProcessStarted(System.Object, System.EventArgs)</pre>
<p>More importantly, it’s output that I can approve.  Cue Borat: “Great Success!”</p>
<h1>Cleanup</h1>
<p>Hopefully cleanup will be easier this time when compared to the “Making it Better” section in the last segment of this series.  But a little cleanup is necessary because once again <code>GetType</code> is called before making a null check, this time in <code>GetEventCallbacks</code>.</p>
<p>Here’s a test to detect the defect:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> NullHasNoEventCallbacks()
{
    Assert.IsFalse(ReflectionUtility.GetEventCallbacks(<span class="kwrd">null</span>).Any());
}</pre>
<p>For previous null-checks I used a if-null-return-null pattern to handle the null case.  However, as these null checks multiply I’m getting tired of writing the same code over and over again, simple as it may be.  So in this test I’m not going to look for null when null is returned, I’m going to look for an empty collection.  If I can come up with a <a href="http://en.wikipedia.org/wiki/Null_Object_pattern" target="_blank">NullObject</a> solution to the null cases that I like, then I’ll refactor my null checks to use that instead of returning null.</p>
<p>I want a NullObject that is a do-nothing implementation of <code>Type</code>.  The <code>NullType</code> should respond to <code>GetFields</code> and <code>GetEvents</code> calls with empty arrays.  Before I run off an create one, I should see if the framework already has a <code>Type</code> that would work as a <code>NullType</code>.  Turns out that a suitable type does exist: <code><a href="http://stackoverflow.com/questions/5450748/what-is-system-void" target="_blank">typeof(void)</a></code>.  MSDN says <code>System.Void</code> is rarely useful in a typical application and that it is used by classes in <code>System.Reflection</code>.  I’m doing reflection, so I’ll use it too.  I just need to make sure that when I try to get a value’s type, that <code>System.Void</code> is used when that value is null.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> Type GetType(<span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">return</span> <span class="kwrd">value</span> == <span class="kwrd">null</span> ? <span class="kwrd">typeof</span>(<span class="kwrd">void</span>) : <span class="kwrd">value</span>.GetType();
}</pre>
<p>Notice that this method is <em>not</em> an extension method.  Now I change <code>GetEventCallbacks</code> to use the new method.  That gets me past my first null reference exception, but my test is still hitting a null reference when it tries to call <code>Any</code> on the results from <code>GetEventCallbacks</code>.  I need to follow the execution a little further an make sure that <code>GetEventCallbacks</code> never returns null.  (By the way <a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx" target="_blank">Code Contracts</a> would be a great way to help diagnose and resolve this type of issue, but I’ll just investigate it “by hand” for this example.)</p>
<p>Remember that <code>GetEventsForTypes</code> will return null when value is null.  I’ll update this method to use the new <code>GetType</code> method instead of a local null check and see what happens.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;EventCallback&gt; GetEventsForTypes(
    <span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>,
    <span class="kwrd">params</span> Type[] types)
{
    <span class="kwrd">return</span> from fieldInfo <span class="kwrd">in</span> GetType(<span class="kwrd">value</span>).EnumerateFieldsWithInherited(NonPublicInstance)
        <span class="rem">// ...</span>
}</pre>
<p><code>NullHasNoEventCallbacks</code> passes after making this update!  However, an older test, <code>NullHasNoProcessCompletedHandler</code>, fails now.  This test is expecting <code>GetEventHandlers</code> to return null, so I need to update its expectation.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> NullHasNoProcessCompletedHandler()
{
    Assert.IsFalse(ReflectionUtility.GetEventHandlers(<span class="kwrd">null</span>).Any());
}</pre>
<p>This new version of the test passes.  Now I’ll just search for any more null-checks and see if I can use the new method there.  The last candidate null check is in <code>VerifyEventCallbacks</code>.  I put a null check in there to make it safe to retrieve the type name.  If I use <code>System.Void</code> then instead of verifying an empty result I’ll get a result like this:</p>
<pre class="csharpcode">Event callbacks <span class="kwrd">for</span> Void</pre>
<p>I’m on the fence on whether that is better than the empty result, but I lean toward the empty result.  I think that seeing an empty result is more likely to make me consider that I passed in a null value rather than seeing “Void”.  So I leave <code>VerifyEventCallbacks</code> alone.</p>
<h1>Relationship with EventApprovals</h1>
<p>Unfortunately these scenarios are not supported in ApprovalTests 2.0.  When I wrote EventApprovals, I needed to inventory the event handlers on a WinForms application.   Neither inheritance problems nor problems with delegate types surfaced while using EventApprovals against a WinForms target, because of the custom event implementation WinForms uses.</p>
<p>Eventually, when I used EventApprovals with a POCO class which extended an <code>INotifyPropertyChanged</code> implementer, I  encountered these problems and figured this stuff out.  The good news is that Llewellyn and I got together recently and these fixes have made their way upstream into ApprovalTests 2.0+.  As of this writing, you should compile ApprovalTests from source if you need these features immediately.  If you&#8217;re reading this later on, and you have ApprovalTests 2.1 or greater, then you already have these features.  Once you have a version of ApprovalTests with these fixes, you don&#8217;t have to do anything special.  <code>EventApprovals.VerifyEvents</code> takes advantage of them automatically.</p>
<p>In terms of implementation, the delegate type issue is solved almost identically to what I&#8217;ve shown here.  For inheritance, Llewellyn thought it would be fun to solve the problem with recursion, so that&#8217;s a little different.</p>
<h1>Up Next</h1>
<p>I&#8217;m feeling better about my tools now. To review, these extension methods can dynamically find all event-backing delegates, regardless of type. And they can find delegates no matter where they are declared in the class hierarchy. It looks like this set of extension methods can handle all my event testing needs for any object, but is that really so?</p>
<p>It turns out that there is large and important set of events which these methods will completely fail to find events for.  I’ve mentioned it a couple times already: Windows Forms.  I&#8217;ll take a look at WinForms events next time in: “<a title="Beyond the Event Horizon: WinForms Event System" href="http://ihadthisideaonce.com/2012/09/13/beyond-the-event-horizon-winforms-event-system/">Beyond the Event Horizon: WinForms Event System</a>”</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/711/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=711&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/09/09/beyond-the-event-horizon-event-complications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/09/pb040015_thumb.jpg" medium="image">
			<media:title type="html">PB040015</media:title>
		</media:content>
	</item>
		<item>
		<title>Beyond the Event Horizon: Events You Don&#8217;t Own</title>
		<link>http://ihadthisideaonce.com/2012/09/05/beyond-the-event-horizon-events-you-dont-own/</link>
		<comments>http://ihadthisideaonce.com/2012/09/05/beyond-the-event-horizon-events-you-dont-own/#comments</comments>
		<pubDate>Thu, 06 Sep 2012 04:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[ApprovalTests]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=688</guid>
		<description><![CDATA[It’s easy to retrieve an invocation list when you have a delegate instance in hand.  When it comes to events, its easy to get your hands on the backing delegate instance when you own the class where the event is declared. However, there is a whole universe of events that you don’t own.   These events [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=688&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>It’s easy to retrieve an invocation list when you have a delegate instance in hand.  When it comes to events, its easy to get your hands on the backing delegate instance when you own the class where<a href="http://ihadthisideaonce.files.wordpress.com/2012/09/pa310020.jpg"><img style="background-image:none;float:left;padding-top:0;padding-left:0;margin:10px 10px 0 0;display:inline;padding-right:0;border:0;" title="PA310020" src="http://ihadthisideaonce.files.wordpress.com/2012/09/pa310020_thumb.jpg?w=158&#038;h=159" alt="PA310020" width="158" height="159" align="left" border="0" /></a> the event is declared.</p>
<p>However, there is a whole universe of events that you don’t own.   These events are declared on BCL classes, third party components, or on that one God class that your boss won’t let you change.  Or maybe you’re picky about encapsulation and want to get your hand on the delegate without adapting your production code to the needs of your tests.  If you find yourself in any of these situations, .NET reflection provides everything you need to get your hands on the delegate and write tests.  This article will show you how to extract the delegates backing POCO events, and in later posts I’ll cover more difficult scenarios—including the WinForms event system.</p>
<p>“What’s a POCO event?” you ask.  POCO events are just my term for the simplest possible event you could write.  Find out more about what the compiler does when you declare an event by visiting the previous posts in this article.  In Part One: “<a href="https://ihadthisideaonce.wordpress.com/?p=639" target="_blank">Beyond the Event Horizon: Delegate Basics</a>” I introduced some relevant aspects of .NET delegates.  In part Two: “<a href="https://ihadthisideaonce.wordpress.com/?p=669" target="_blank">Beyond the Event Horizon: Event Basics</a>” I defined POCO events and covered their implementation.</p>
<p>In a roundabout way, this series of posts is about <a href="http://approvaltests.sourceforge.net/">ApprovalTests</a>.  If you haven’t heard of ApprovalTests, it’s a great open source library which you can use to enhance your tests.  I gave a 10,000 foot overview of ApprovalTests in part one of this series, but if you want to get the most out of reading this article, check out Llewellyn Falco’s series on <a href="http://www.youtube.com/watch?v=bg8GOmlwqYY&amp;hd=1" target="_blank">YouTube</a>.</p>
<p>If you are really interested in the nitty-gritty and playing around with the ideas in this article, check out the accompanying  code repository on <a href="https://github.com/jamesrcounts/EventReflection" target="_blank">GitHub</a>.  Also remember that the codebase I’m building in these articles is  a <em>reimplementation </em>of features <em>already</em> available in ApprovalTests 2.0.  If you want to use these features, don’t waste your time with cut-and-paste, go grab ApprovalTests.</p>
<p>With all that intro out of the way, lets talk about reflection.</p>
<h2>Testing Events You Don&#8217;t Own</h2>
<p>In the previous article, I created a class called <code>Poco. </code> This simple class declares an event that signals when Poco completes it’s (imaginary) work.  As the example progressed, I started to make some assumptions about <code>Poco</code>’s behavior and add restrictions to what I could change about <code>Poco</code>’s implementation.  For this example, I&#8217;ll keep all the previous assumptions:</p>
<ul>
<li><code>Poco</code> is part of a primitive layer, meant to be accessed through a higher-level API.</li>
<li><code>Poco</code>’s main activity is performed by <code>DoWork</code>, which is too expensive/inconvenient to call.</li>
<li><code>PocoClient</code> is part of the high-level API and must listen to the <code>Poco.ProcessCompleted</code> event.</li>
<li>I don&#8217;t control <code>Poco</code>, so simply changing it’s implementation is not an option.</li>
</ul>
<p>For a simple class like <code>Poco</code> it&#8217;s not hard to retrieve the handler using reflection.  First I&#8217;ll get rid of the <code>GetProcessCompletedHandler</code> method I added to <code>Poco</code> in the previous example. I&#8217;ll implement it as an extension method instead and make no changes to the test.  The extension method isn&#8217;t strictly necessary but it will keep the reflection code from cluttering up the test.</p>
<p>I&#8217;ll create a static class to host the extension method.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Linq;
<span class="kwrd">using</span> System.Reflection;

<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> ReflectionUtility
{
    <span class="kwrd">public</span> <span class="kwrd">const</span> BindingFlags NonPublicInstance = BindingFlags.Instance | BindingFlags.NonPublic;

    <span class="kwrd">public</span> <span class="kwrd">static</span> EventHandler GetProcessCompletedHandler(<span class="kwrd">this</span> Poco poco)
    {
        var matchingFields = from fieldInfo <span class="kwrd">in</span> poco.GetType().GetFields(NonPublicInstance)
                             <span class="kwrd">where</span> <span class="kwrd">typeof</span>(EventHandler).IsAssignableFrom(fieldInfo.FieldType)
                             &amp;&amp; fieldInfo.Name == <span class="str">"ProcessCompleted"</span>
                             select (EventHandler)fieldInfo.GetValue(poco);
        <span class="kwrd">return</span> matchingFields.Single();
    }
}</pre>
<p>This extension method allows the <code>GetPocoEventInvocationList</code> test to pass without altering <code>Poco</code>.  I’ll add a test for <code>PocoClient</code> now, which should verify the scenario that got us here, then spend some time examining how <code>GetProcessCompletedHandler</code> works.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> PocoClientListensToPoco()
{
    Poco poco = <span class="kwrd">new</span> Poco();
    PocoClient client = <span class="kwrd">new</span> PocoClient(poco);
    DelegateUtility.VerifyInvocationList(poco.GetProcessCompletedHandler());
}</pre>
<p>The results confirm that <code>PocoClient</code> is doing its job:</p>
<pre class="csharpcode">[0] = Void LogCompletionTime(System.Object, System.EventArgs)</pre>
<h2>Reflection Anatomy</h2>
<p>Let’s get into <code>GetProcessCompletedHandler</code> guts.  My goal is to get my hands on the event’s backing field.  I know from using Reflector that the field is a private instance field, and although it is invisible, I know the name the compiler will choose for the field—it’s the same name I gave to the simple event declaration.</p>
<p>I can use reflection to get any information I want off the type, as long as I know how its declared and what its name is.  By default, reflection methods supply public instance members.  If you want to include the private members, you have to be specific about the <code>BindingFlags</code> you pass in.  So I create a <code>const</code> in <code>ReflectionUtility</code> to specify the non-public (i.e., private, protected, internal) and instance flags.  My primary reason for giving these flags a name is to increase readability, but as <code>ReflectionUtility</code> grows, this <code>const</code> will also save me a lot of typing.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">const</span> BindingFlags NonPublicInstance = BindingFlags.Instance | BindingFlags.NonPublic;</pre>
<p>With that out of the way, I can request information about the <code>poco </code>instance’s private fields.  First, I need to get a <code>Type</code> object which corresponds to <code>Poco</code> (the class) which I can obtain by calling <code>GetType</code> on <code>poco</code> (the object).  The <code>Type</code> object describes the <code>Poco</code> class, and I use <code>GetFields</code> with my binding flags to get the collection of descriptors for the <code>Type</code>’s private fields.</p>
<pre class="csharpcode">from fieldInfo <span class="kwrd">in</span> poco.GetType().GetFields(NonPublicInstance)</pre>
<p>Next, I filter for <code>EventHandler</code>s:</p>
<pre class="csharpcode"><span class="kwrd">where</span> <span class="kwrd">typeof</span>(EventHandler).IsAssignableFrom(fieldInfo.FieldType)</pre>
<p>Then I filter by name:</p>
<pre class="csharpcode">&amp;&amp; fieldInfo.Name == <span class="str">"ProcessCompleted"</span></pre>
<p><code>FieldInfo </code>instances describe fields, but I want the actual field value from the <code>poco</code> instance.  To retrieve the actual instance value, I use the <code>GetValue</code> method, which returns an object reference to the actual value from <code>poco</code>.  I don’t want an <code>object</code>, I want an <code>EventHandler</code>.  I can safely make that cast because my first filter ensures that this object is castable to <code>EventHandler</code>.  This is what I end up selecting:</p>
<pre class="csharpcode">select (EventHandler)fieldInfo.GetValue(poco);</pre>
<p>Because there can only be one field named “ProcessCompleted”, the name filter ensures that there is only one member in the collection returned by this query.  So, I pull that member out of the collection using <code>Single:</code></p>
<pre class="csharpcode"><span class="kwrd">return</span> matchingFields.Single();</pre>
<p>And that, it would seem, is all you need to know about retrieving the delegate field backing an event..</p>
<h1>Making it Better</h1>
<p>The best part about having green tests is that you can stop thinking so hard and just play.<code>  GetProcessCompletedHandler</code> is OK, but it can be improved.  I’ll start by fixing the most obvious defect, the method doesn’t check its input.  What happens when I throw a null in there?</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> NullHasNoProcessCompletedHandler()
{
    Assert.IsNull(ReflectionUtility.GetProcessCompletedHandler(<span class="kwrd">null</span>));
}</pre>
<p>Not surprisingly, this test throws a <code>NullReferenceException</code> before even reaching the assertion.  The exception occurs when the query calls <code>GetType</code> on the null value.   This check should fix the problem for now.</p>
<div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> EventHandler GetProcessCompletedHandler(<span class="kwrd">this</span> Poco poco)
{
    <span class="kwrd">if</span> (poco == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span> <span class="kwrd">null</span>;
    }</pre>
</div>
<p>Now that the most obvious problem is out of the way, my biggest complaint is the magic string &#8220;ProcessCompleted&#8221;.  If events were (even) more like properties, I could use an expression tree to specify the member with a lambda.  Alas events are not properties, and they <a href="http://stackoverflow.com/questions/564961/events-in-lambda-expressions-c-sharp-compiler-bug">don&#8217;t work well (at all?) with expression trees</a>.  Perhaps I can make the magic string palatable by promoting it to a parameter.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> EventHandler GetProcessCompletedHandler(<span class="kwrd">this</span> Poco poco, <span class="kwrd">string</span> eventName)
{
    <span class="kwrd">if</span> (poco == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span> <span class="kwrd">null</span>;
    }

    var matchingFields = from fieldInfo <span class="kwrd">in</span> poco.GetType().GetFields(NonPublicInstance)
                         <span class="kwrd">where</span> <span class="kwrd">typeof</span>(EventHandler).IsAssignableFrom(fieldInfo.FieldType)
                         &amp;&amp; fieldInfo.Name == eventName
                         select (EventHandler)fieldInfo.GetValue(poco);
    <span class="kwrd">return</span> matchingFields.Single();
}</pre>
<p>I used my refactoring tool to introduce the new parameter, and it automatically updated the test call sites to look something like this:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> PocoClientListensToPoco()
{
    Poco poco = <span class="kwrd">new</span> Poco();
    PocoClient client = <span class="kwrd">new</span> PocoClient(poco);
    DelegateUtility.VerifyInvocationList(poco.GetProcessCompletedHandler(<span class="str">"ProcessCompleted"</span>));
}</pre>
<p>That seems like a small improvement but I’m not really satisfied with it.  I’ll file away the magic string for a moment, because now I notice something else about the extension method.  The only <code>Poco</code>-specific piece of data was the event name, and now that I have moved the magic string, this method should now work as an extension on <code>object</code>.  After making that change I also rename the parameter to “value”, since the instance is not necessarily a <code>Poco </code>anymore.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> EventHandler GetProcessCompletedHandler(<span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>, <span class="kwrd">string</span> eventName)</pre>
<p><code><span style="font-family:helvetica;">My test still pass, so this change is all good.  Now I notice that the method name still has “ProcessCompleted” in it.  That name no longer reflects what the method does, so I rename to “GetEventHandler'” with my refactoring tool.</span></code></p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> EventHandler GetEventHandler(<span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>, <span class="kwrd">string</span> eventName)</pre>
<p>My test still pass.  Now I’m wondering if I can make it even more generic.  I’m still not happy with my magic string either.  Instead of one magic string in one extension method, I now have a magic string in every test.  So, promoting the string to a parameter made the extension method look nicer, but at the expense of making everything else uglier.</p>
<p>The other problem with this method is that I can only retrieve the delegate for one event at a time.  <code>Poco</code> is simple, it has one event handler.  <code>PocoClient</code> has a simple relationship with <code>Poco</code>. What if both objects were more complex? <code>Poco</code> might have many handlers, and <code>PocoClient</code> might subscribe to some subset of those handlers. Querying event handlers 1 by 1 would be tedious in a scenario like that.  I would need to know their names (and spell them correctly), and each would require its own test. If I introduced new events to <code>Poco</code>, I&#8217;d have to remember to add a test each time.  Chances are good that sometime down the line an event will be missed, and end up uncovered.</p>
<p>I can eliminate both maintenance problems in one (big) step, just by getting rid of the name filter.  Instead of retrieving just one event delegate, I could get the inventory of all the <code>EventHandler</code> delegates on <code>Poco</code>.  When <code>Poco</code> gets new events, they will show up in the test as soon as they’re introduced, without writing any new test code.  Instead of using the <code>Name</code> property as a filter, I could include it as part of the return value.  However, without the filter on the field name, I can’t use <code>Single</code> to pull the result from the collection, because there might be more than one field with handlers attached.  So I’ll have to change the return type as well.  Here is what my method looks like after making these changes.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> IEnumerable&lt;Tuple&lt;<span class="kwrd">string</span>, EventHandler&gt;&gt; GetEventHandler(<span class="kwrd">this</span> <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">if</span> (<span class="kwrd">value</span> == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span> <span class="kwrd">null</span>;
    }

    <span class="kwrd">return</span> from fieldInfo <span class="kwrd">in</span> <span class="kwrd">value</span>.GetType().GetFields(NonPublicInstance)
           <span class="kwrd">where</span> <span class="kwrd">typeof</span>(EventHandler).IsAssignableFrom(fieldInfo.FieldType)
           select <span class="kwrd">new</span> Tuple&lt;<span class="kwrd">string</span>, EventHandler&gt;(fieldInfo.Name, (EventHandler)fieldInfo.GetValue(<span class="kwrd">value</span>));
}</pre>
<p>This breaks the build, since my tests are expecting a single <code>EventHandler</code>, not a collection of <code>Tuples</code>.  I could go try to fix the tests at this point, but how can I?  The tests all use <code></code><code>VerifyInvocationList</code>, which also expects a single <code>Delegate</code>.   It looks like I’m going to end up either refactoring my <code>Verify</code> method or creating another <code>Verify</code> method to handle a <code>Tuple</code> collection.  Also this line is starting to bother me, its too long and it has too much punctuation.</p>
<pre class="csharpcode">select <span class="kwrd">new</span> Tuple&lt;<span class="kwrd">string</span>, EventHandler&gt;(fieldInfo.Name, (EventHandler)fieldInfo.GetValue(<span class="kwrd">value</span>));</pre>
<p>Looking at this line, I want to create a data transfer class to hold onto my two pieces of data, getting rid of the Tuple.  If I follow that urge, then I should do it now, before updating the tests, otherwise I’ll end up changing the tests twice.</p>
<p>The DTO doesn’t need to be complicated, this should suffice for now.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EventCallback
{
    <span class="kwrd">public</span> EventCallback(<span class="kwrd">string</span> name, Delegate callback)
    {
        <span class="kwrd">this</span>.Name = name;
        <span class="kwrd">this</span>.Callback = callback;
    }

    <span class="kwrd">public</span> Delegate Callback { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; }
}</pre>
<p>After this modification, the projection is cleaner, but I think it still suffers from an excess of parens.</p>
<pre class="csharpcode">select <span class="kwrd">new</span> EventCallback(fieldInfo.Name, (EventHandler)fieldInfo.GetValue(<span class="kwrd">value</span>));</pre>
<p>I’ll create an extension method that lets me replace some of those parens with angles.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> T GetValue&lt;T&gt;(<span class="kwrd">this</span> FieldInfo fi, <span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    <span class="kwrd">return</span> (T)fi.GetValue(<span class="kwrd">value</span>);
}</pre>
<p>Now I can rewrite my projection like this.</p>
<pre class="csharpcode">select <span class="kwrd">new</span> EventCallback(fieldInfo.Name, fieldInfo.GetValue&lt;EventHandler&gt;(<span class="kwrd">value</span>));</pre>
<p>Ok that was fun, but my build is still broken.  I’ll give the tests some love next, but I need to make one more update to this extension method.  I’ll change its name to <code>GetEventHandlers</code> to reflect that it returns a collection.</p>
<p>As mentioned above, the most immediate problem with the tests are that they are not expecting collections.  In some tests, I resolve this issue by switching to the <code>var</code> keyword, and in others I need to introduce a local variable to hold onto the new collection.  But, as expected, the build is still broken because the <code>Verify</code> method wont take a collection.  I’ll stop using my custom verifier and go back to ApprovalTest basics.  Here is a new version of <code>GetPocoEventInvocationList</code>.<code></code></p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetPocoEventInvocationList()
{
    var poco = <span class="kwrd">new</span> Poco();
    poco.ProcessCompleted += Domain.HandleProcessCompleted;

    var pocoDelegates = poco.GetEventHandlers();
    Approvals.VerifyAll(pocoDelegates, <span class="kwrd">string</span>.Empty);
}</pre>
<p>II have to comment out a line in a broken test so that I can run this and I don’t like the result, it doesn’t tell me any useful information.</p>
<pre class="csharpcode">[0] = EventReflection.Demo.EventCallback</pre>
<p>I can pass a formatter to <code>VerifyAll, </code>or I can override <code>EventCallback.ToString</code> to provide a nicely formatted string representation.  The ability to override <code>ToString</code> is an advantage I gained when I decided to use a custom DTO, that I wouldn’t have if I had stuck with the <code>Tuple</code>.  Eventually, I will override <code>ToString</code>, but for now I’ll just use a formatter until I get the formatting I want, then I’ll move that formatter into <code>EventCallback</code>.</p>
<p>Here are the results from my first attempt:</p>
<pre class="csharpcode">ProcessCompleted =&gt; [Void HandleProcessCompleted(System.Object, System.EventArgs)]</pre>
<p>And the code which produces it:</p>
<pre class="csharpcode">Approvals.VerifyAll(
    pocoDelegates, 
    e =&gt; <span class="str">"{0} =&gt; {1}"</span>.FormatWith(e.Name, e.Callback.GetInvocationList().Select(d =&gt; d.Method).ToReadableString()));</pre>
<p>This is an improvement, but both the result and the code are a little complicated for my taste.  I liked the vertical spacing that <code>VerifyInvocationList</code> provided more than the horizontal formatting <code>ToReadableString</code> provides.  The formatter is too long, an it repeats code already in <code>VerifyInvocationList.</code></p>
<p>Second attempt looks much nicer.  It takes better advantage of vertical space and retains the index numbers for each method in the invocation list.  This is actually important information, since the delegates will be executed in the order that they appear in the invocation list:</p>
<pre class="csharpcode">ProcessCompleted
    [0] Void HandleProcessCompleted(System.Object, System.EventArgs)</pre>
<p>Here is the formatter which produces this output.</p>
<pre class="csharpcode">e =&gt;
{
    var buffer = <span class="kwrd">new</span> StringBuilder();
    buffer.AppendLine(e.Name);
    var delegates = e.Callback.GetInvocationList();
    <span class="kwrd">for</span> (<span class="kwrd">int</span> index = 0; index &lt; delegates.Length; index++)
    {
        var d = delegates[index];
        buffer.AppendLine(<span class="str">"\t[{0}] {1}"</span>.FormatWith(index, d.Method));
    }
    <span class="kwrd">return</span> buffer.ToString();
}</pre>
<p>I use a buffer to hold onto the data as I build the results.  It’s pretty straightforward, although you might not be familiar with the extension method <code>FormatWith</code>.  This extension ships with the <code>ApprovalUtilities</code> library that accompanies <code>ApprovalTests, </code>and I find it’s a cleaner way to call <code>string.Format</code>.  I like the new formatting, so I’ll make this formatter into the <code>ToString</code> implementation for <code>EventCallback</code>.  Then I can simplify my test, I keep a simple formatter, to prevent <code>VerifyAll</code> from prefixing additional index numbers to each result.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetPocoEventInvocationList()
{
    var poco = <span class="kwrd">new</span> Poco();
    poco.ProcessCompleted += Domain.HandleProcessCompleted;

    var pocoDelegates = poco.GetEventHandlers();
    Approvals.VerifyAll(pocoDelegates, e =&gt; e.ToString());
}</pre>
<p>And I can update my other failing test as well:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> PocoClientListensToPoco()
{
    Poco poco = <span class="kwrd">new</span> Poco();
    PocoClient client = <span class="kwrd">new</span> PocoClient(poco);
    var eventHandlers = poco.GetEventHandlers();
    Approvals.VerifyAll(eventHandlers, e =&gt; e.ToString());
}</pre>
<p>Of course, now I have duplication, and I have a weird little formatter there, which I’ll need to remember if I want to get these results every time.  So I should encapsulate that duplication so I don’t need to remember it anymore.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> ApprovalTests;

<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> EventUtility
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> VerifyEventCallbacks(IEnumerable&lt;EventCallback&gt; callbacks)
    {
        Approvals.VerifyAll(callbacks, c =&gt; c.ToString());
    }
}</pre>
<p>And I can update my tests.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> PocoClientListensToPoco()
{
    Poco poco = <span class="kwrd">new</span> Poco();
    PocoClient client = <span class="kwrd">new</span> PocoClient(poco);
    EventUtility.VerifyEventCallbacks(poco.GetEventHandlers());
}</pre>
<p>That was a bit of work to get rid of the magic string.  However, it should be worth it because the new query will also detect new event handlers when they’re added.  My current tests don’t verify this behavior.  Also, I had some tests against <code>VerifyInvocationList </code>that showed multiple handlers wired up to one delegate, but that scenario isn’t covered yet with <code>VerifyEventCallbacks</code>.</p>
<p>To get these scenarios covered, I’ll add another event to <code>Poco</code>.  I’m still assuming that I don’t control <code>Poco</code>, but we just transitioned into an alternate reality where <code>Poco</code> always had more than one event.  I’ll call the new event <code>ProcessStarted</code>, so here’s what we’ve got now.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler ProcessCompleted;
<span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler ProcessStarted;</pre>
<p>Simply adding this event declaration is enough to break two of my tests.  My first thought is that it is an approval failure because the new event is already detected even though I hadn’t wired anything up yet.  However, it turns out that <code>EventCallback.ToString</code> is throwing a null reference exception.  Of course, this is because the backing field for an event will be null until the first event is wired up.  The event was detected, but since it was null, the <code>Callback</code> property was also null.  Because the delegate is null, I get a null reference exception on <code>GetInvocationList</code>.</p>
<p>After considering my options, I decide to filter out the nulls in the query.  I don’t want to list any events that aren’t wired up anyway, they would just be noise.  To avoid reflecting into my object twice, I’ll introduce a new variable in the query using the <code>let</code> keyword, then filter out nulls.</p>
<pre class="csharpcode">from fieldInfo <span class="kwrd">in</span> <span class="kwrd">value</span>.GetType().GetFields(NonPublicInstance)
<span class="kwrd">where</span> <span class="kwrd">typeof</span>(EventHandler).IsAssignableFrom(fieldInfo.FieldType)
let callback = fieldInfo.GetValue&lt;EventHandler&gt;(<span class="kwrd">value</span>)
<span class="kwrd">where</span> callback != <span class="kwrd">null</span>
select <span class="kwrd">new</span> EventCallback(fieldInfo.Name, callback);</pre>
<p>This fixes my existing tests, but I still need to cover my missing scenarios.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> MultipleEvents()
{
    var poco = <span class="kwrd">new</span> Poco();
    poco.ProcessCompleted += Domain.HandleProcessCompleted;
    poco.ProcessStarted += Domain.HandleProcessStarted;
    EventUtility.VerifyEventCallbacks(poco.GetEventHandlers());
}</pre>
<p>This test produces these results, which look good so I approve them</p>
<pre class="csharpcode">ProcessCompleted
    [0] Void HandleProcessCompleted(System.Object, System.EventArgs)

ProcessStarted
    [0] Void HandleProcessStarted(System.Object, System.EventArgs)</pre>
<p>And one more test to cover the multicast scenario.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> MulticastEvent()
{
    var poco = <span class="kwrd">new</span> Poco();
    poco.ProcessCompleted += Domain.HandleProcessCompleted;
    poco.ProcessCompleted += Domain.HandleProcessStarted;
    EventUtility.VerifyEventCallbacks(poco.GetEventHandlers());
}</pre>
<p>And this test produces good results too.</p>
<pre class="csharpcode">ProcessCompleted
    [0] Void HandleProcessCompleted(System.Object, System.EventArgs)
    [1] Void HandleProcessStarted(System.Object, System.EventArgs)</pre>
<p>I&#8217;m pretty happy with that result. But I still have a problem, I have to look at the test to figure out which object these event handlers are attached to. The result could be improved if they included some description where they came from. This shouldn&#8217;t be too hard to fix.</p>
<p>First I’ll change the <code>VerifyEventCallbacks</code> implementation to take the object itself, rather than the collection of callbacks.  Once I have the object I can query it for the type name, then query it for the callbacks, then collect it all into a buffer.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> VerifyEventCallbacks(<span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    var buffer = <span class="kwrd">new</span> StringBuilder();
    buffer.AppendLine(<span class="str">"Event callbacks for {0}"</span>.FormatWith(<span class="kwrd">value</span>.GetType().Name)).AppendLine();
    <span class="kwrd">foreach</span> (var callback <span class="kwrd">in</span> <span class="kwrd">value</span>.GetEventHandlers())
    {
        buffer.AppendLine(callback.ToString());
    }

    Approvals.Verify(buffer);
}</pre>
<p>Then I need to update my tests to pass the object instead of a collection.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetPocoEventInvocationList()
{
    var poco = <span class="kwrd">new</span> Poco();
    poco.ProcessCompleted += Domain.HandleProcessCompleted;
    EventUtility.VerifyEventCallbacks(poco);
}</pre>
<p>Which produces results that indicate where the events are are attached:</p>
<pre class="csharpcode">Event callbacks <span class="kwrd">for</span> Poco

ProcessCompleted
    [0] Void HandleProcessCompleted(System.Object, System.EventArgs)</pre>
<p>That’s pretty nice.  There’s always another problem though.  The new implementation queries for the value’s type before the null check in <code>GetEventHandlers</code>.   It probably can’t handle nulls.  I’ll write a test to confirm and fix.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> NullHasNoEvents()
{
    EventUtility.VerifyEventCallbacks(<span class="kwrd">null</span>);
}</pre>
<p>As expected this generates a null reference exception.  <code>Approvals.Verify</code> can actually handle null just fine, so if value is null, I just need to make sure that a null gets verified.  This update to <code>VerifyEventCallbacks</code> does the trick.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> VerifyEventCallbacks(<span class="kwrd">object</span> <span class="kwrd">value</span>)
{
    StringBuilder buffer = <span class="kwrd">null</span>;
    <span class="kwrd">if</span> (<span class="kwrd">value</span> != <span class="kwrd">null</span>)
    {
        buffer = <span class="kwrd">new</span> StringBuilder();

        buffer.AppendLine(<span class="str">"Event callbacks for {0}"</span>.FormatWith(<span class="kwrd">value</span>.GetType().Name)).AppendLine();
        <span class="kwrd">foreach</span> (var callback <span class="kwrd">in</span> <span class="kwrd">value</span>.GetEventHandlers())
        {
            buffer.AppendLine(callback.ToString());
        }
    }

    Approvals.Verify(buffer);
}</pre>
<p>This works as expected, which is to say that when <code>Approvals.Verify</code> receives the null buffer, it produces an empty result file. With this last change I think I’m done for now.  There might still be ways to make this code better, but nothing it popping out at the moment.  This is a good time to pause and review.</p>
<p>When I create my test target and call <code>VerifyEventCallbacks </code>the results tell me this:</p>
<ol>
<li>The target type.</li>
<li>Of all the possible events on the type, which had handlers attached.</li>
<li>For each event, the handlers are listed in the order they execute.</li>
</ol>
<h1>Relationship with EventApprovals</h1>
<p>The <code>EventApprovals</code> DTO is a little different than <code>EventCallback</code>.  Its called <code>CallbackDescriptor</code> and while it also includes the event’s name, it holds on to the projected <code>MethodInfo</code> collection  instead of holding on to the delegate.</p>
<p>In <code>EventApprovals</code>, you can get the collection of POCO event callbacks using <code>ApprovalUtilities.Reflection.GetPocoEvents</code>.  Normally you don’t need to access the event collection at that level.  If you just want to verify the event inventory, the closest method is <code>ApprovalTests.Events.EventApprovals.VerifyEvents</code>, its not exactly the same because it actually does more than shown here—it can inventory WinForm events as well.</p>
<h1>Up Next</h1>
<p>As I mentioned at the top, the reflection necessary to retrieve the backing delegate seems fairly simple.  In the case of <code>Poco</code>, it turned out to be straightforward.  But things might not be as simple as they seem.  All the events on <code>Poco</code> are based on <code>EventHandler</code>, what about other delegate types?  Furthermore, all the events on <code>Poco</code> are declared directly on <code>Poco</code>, what if we also had to find events inherited from a base class?  I probably wouldn’t bring it up if what I’ve shown so far worked in those scenarios, so in the next installment “<a title="Beyond the Event Horizon: Event Complications" href="http://ihadthisideaonce.com/2012/09/09/beyond-the-event-horizon-event-complications/">Beyond the Event Horizon: Event Complications</a>” I’ll see if I can overcome these obstacles.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/688/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/688/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=688&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/09/05/beyond-the-event-horizon-events-you-dont-own/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/09/pa310020_thumb.jpg" medium="image">
			<media:title type="html">PA310020</media:title>
		</media:content>
	</item>
		<item>
		<title>Beyond the Event Horizon: Event Basics</title>
		<link>http://ihadthisideaonce.com/2012/09/02/beyond-the-event-horizon-event-basics/</link>
		<comments>http://ihadthisideaonce.com/2012/09/02/beyond-the-event-horizon-event-basics/#comments</comments>
		<pubDate>Sun, 02 Sep 2012 18:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[ApprovalTests]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=669</guid>
		<description><![CDATA[At the heart of every .NET event is a Delegate. In part one of this series: “Beyond the Event Horizon: Delegate Basics”, I introduced my motivation for writing EventApprovals (part of ApprovalTests 2.0).  I briefly touched on ApprovalTests basics (a woefully inadequate introduction, visit Llewellyn&#8217;s YouTube series for a thorough overview).  After this preamble, I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=669&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/08/simpleevents-640x640.jpg"><img style="background-image:none;float:left;padding-top:0;padding-left:0;margin:10px 10px 0 0;display:inline;padding-right:0;border-width:0;" title="OLYMPUS DIGITAL CAMERA" src="http://ihadthisideaonce.files.wordpress.com/2012/08/simpleevents-640x640_thumb.jpg?w=158&#038;h=158" alt="OLYMPUS DIGITAL CAMERA" width="158" height="158" align="left" border="0" /></a>At the heart of every .NET event is a <code>Delegate.</code></p>
<p>In part one of this series: “<a href="http://ihadthisideaonce.com/2012/08/28/beyond-the-event-horizon-delegate-basics/" target="_blank">Beyond the Event Horizon: Delegate Basics</a>”, I introduced my motivation for writing EventApprovals (part of <a href="http://approvaltests.sourceforge.net/">ApprovalTests</a> 2.0).  I briefly touched on ApprovalTests basics (a woefully inadequate introduction, visit Llewellyn&#8217;s <a href="http://www.youtube.com/watch?v=bg8GOmlwqYY&amp;hd=1" target="_blank">YouTube</a> series for a thorough overview).  After this preamble, I covered the basic method for extracting invocation lists from delegates, then looked at some potential confusion which could be caused by the dual unicast/multicast nature of the .NET delegate implementation.</p>
<p>In this part of the series I’ll cover “simple” events or what I’ll often refer to as POCO events.  It may be helpful to define what I mean by POCO event, since it’s a term I made up.  To me a POCO event is what you get when you are writing your own class and you create an event like this:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler ProcessCompleted;</pre>
<p>Declaring an event this way is similar to declaring an auto property, the compiler sees that you want to setup an event and generates a default implementation for you.  In this article I’ll cover what the compiler generates and how to test the compiler implementation.  In a later article we’ll see the custom event implementation which backs events in Windows Forms.</p>
<p>This article should cover some useful techniques, but remember that I’m re-implementing a system similar to EventApprovals, I’m not actually covering the internals of what made it into ApprovalTests.  The code for this demo is available on <a href="https://github.com/jamesrcounts/EventReflection" target="_blank">GitHub</a>, but if you just need to <em>do</em> what this article describes, don’t waste your time with cut and paste, go straight to ApprovalTests and let it do the heavy lifting for you.</p>
<h1>Simple Events</h1>
<p>Before jumping headfirst into the .NET event implementation and the reflection required to retrieve the subscriber list, it is worthwhile to consider whether doing any of that is even necessary.  If a more simple testing approach can verify your requirements then you shouldn’t hesitate to use that approach.  Here, I’ll give an example of a scenario that doesn’t require reflection and consider when this approach is better replaced with a reflection-based approach.</p>
<h2>Was the Event Raised When Expected?</h2>
<p>Consider my simple business object <code>Poco</code>:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Poco
{
    <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler ProcessCompleted;

    <span class="kwrd">public</span> <span class="kwrd">int</span> DoWork()
    {
        <span class="rem">// ...Do very hard work...</span>
        OnProcessCompleted(<span class="kwrd">this</span>, EventArgs.Empty);
        <span class="kwrd">return</span> result;
    }

    <span class="kwrd">protected</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> OnProcessCompleted(<span class="kwrd">object</span> sender, EventArgs e)
    {
        EventHandler handler = ProcessCompleted;
        <span class="kwrd">if</span> (handler != <span class="kwrd">null</span>)
        {
            handler(sender, e);
        }
    }
}</pre>
<p>In this scenario I want to ensure that <code>Poco</code> raises the process completed event when the process completes.  Assuming that the tasks <code>Poco</code> performs in <code>DoWork</code> are sufficiently amenable to mocking, then you could write a test that verified the call to <code>OnProcessCompleted</code> in isolation.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> RaiseCompletedEventWhenProcessCompletes()
{
    <span class="kwrd">bool</span> raisedEvent = <span class="kwrd">false</span>;
    Poco poco = <span class="kwrd">new</span> Poco();
    poco.ProcessCompleted += (s, e) =&gt; raisedEvent = <span class="kwrd">true</span>;
    poco.DoWork();
    Assert.IsTrue(raisedEvent);
}</pre>
<p>This test works because it only requires access to operations that are externally accessible. I create a flag and set it to <code>false</code>. Later, I&#8217;ll assert that the flag is true. The test will only pass if something in <code>DoWork</code> causes the flag to become true. I set this up by assigning an anonymous event handler to <code>ProcessCompleted</code>. If the event handler is invoked, then my flag changes, and the test passes. I don&#8217;t care if there are any other methods in the invocation list, I just care that my test handler has been invoked.</p>
<h2>Testing Events Without Raising Events</h2>
<p>I may not be able to raise the event so easily. The tasks in <code>DoWork</code> might <em>not</em> be amenable to mocking. The method might have undesirable side effects, dependencies which I can’t satisfy, or the task simply takes longer than I&#8217;m willing to allow when testing.   Lets assume that one of the conditions listed above is true for <code>DoWork</code>.  If this is the case, then I can’t test by raising the event.</p>
<p>If ensuring that <code>DoWork</code> raises the <code>ProcessCompleted</code> event is my only concern, then the invocation list can&#8217;t help me either.  Membership in the invocation list only indicates that some subscriber is <em>listening</em> to some event when its raised, but listening to an event doesn’t imply the event will ever be raised.</p>
<p>I know that <code>Poco</code> uses “POCO” events.  If I forget that I wrote <code>Poco</code> and begin to worry that <code>Poco</code> has a custom event implementation that doesn&#8217;t register handlers in the expected fashion, it might make sense to hook up a dummy handler then check the invocation list to see if my handler is there.  However, knowing that <code>ProcessCompleted</code> doesn’t hide any secrets, testing the invocation list would only prove that <code>Delegate.Combine</code> works correctly.  I usually trust the framework to have correct implementations. .</p>
<p>If ensuring that <code>DoWork</code> raises the event is part of a requirement that must be satisfied and delivered, then I need to refactor <code>DoWork</code> until it&#8217;s testable. I won’t cover that here, but you should check out Llewellyn Falco&#8217;s <a href="http://www.youtube.com/watch?v=p0tILwRZH5Q" target="_blank">video on the &#8220;Peel&#8221; technique</a>.</p>
<p>Ok, so there are some scenarios where raising the event is the best way to test.  When raising the event is impractical, there are still scenarios where you shouldn’t go after the subscriber list, because it won’t actually verify your requirements.  Is there any point in reading on?  Can’t I—the person who has wanted this functionality for 3 years—even come up with an example of when it’s useful?</p>
<p>Actually, I can describe a couple scenarios involving WinForms where this is very useful, but introducing WinForms into the equation without first understanding the basic technique would just introduce complications that would hurt your brain.  So I’ll dream up a scenario where this is useful without talking about WinForms and I’ll talk about WinForms later.</p>
<p>Start by assuming that <code>Poco</code> is not part of the top-level API, but instead is part of a &#8220;primitives&#8221; layer.  The purpose of the primitive API is to enable multiple programming models against the same functionality (MEF, for example, has a primitive layer).  Suppose I have a class called <code>PocoClient</code> that is part of a specific programming model built on top of the more primitive layer. Part of <code>PocoClient</code>&#8216;s job is to hide details like the <code>ProcessCompleted</code> event. <code>PocoClient</code> must subscribe to the <code>ProcessCompleted</code> event and provide a default handler.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> PocoClient
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> Poco primitive;

    <span class="kwrd">public</span> PocoClient(Poco primitive)
    {
        <span class="kwrd">this</span>.primitive = primitive;
        <span class="kwrd">this</span>.primitive.ProcessCompleted += <span class="kwrd">this</span>.LogCompletionTime;
    }

    <span class="kwrd">private</span> <span class="kwrd">void</span> LogCompletionTime(<span class="kwrd">object</span> sender, EventArgs e)
    {
        <span class="rem">// write to log...</span>
    }
}</pre>
<p>Now the question my test needs to ask is a little different. I’m still assuming that <code>DoWork</code> remains too expensive to call, but I want to know that <code>PocoClient</code> correctly wires itself up to <code>Poco</code>. Observing <code>PocoClient</code>&#8216;s logger for activity is not an option, because <code>DoWork</code> is too expensive. However, if I could see <code>Poco.ProcessCompleted</code>&#8216;s subscriber list, and test that <code>LogCompletionTime</code> is in the invocation list, then I could verify the requirement statically, without running any code other than the constructor.</p>
<h1>Quick and Dirty Solution</h1>
<p>At the heart of every event is a delegate.  Although you can use any delegate (including <code>Func</code> or <code>Action</code>) when declaring an <code>event</code> the most common practice is to use <code>EventHandler</code>, <code>EventHandler&lt;T&gt;</code> or some pre-defined delegate type like <code>PropertyChangedEventHandler</code>. At the language level, delegates are types, which means they are their own things (with their own rules) and they are peers with classes, structs and interfaces.  However, the compiler implements delegates as special classes that all derive from <code>MulticastDelegate</code>.  This can be confusing because delegates can share some behavior with classes in certain coding contexts.</p>
<p>I’ll start with my simple <code>Poco </code>class.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Poco
{
    <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler ProcessCompleted;
   <span class="rem">// ... the rest of Poco ...</span>
}</pre>
<p><code>Poco</code> has a &#8220;<a href="http://msdn.microsoft.com/en-us/library/aa664455%28v=vs.71%29.aspx">Field-like event</a>&#8221; which is a horrible name for a concept which shouldn’t be hard to explain.  I alluded to this a few paragraphs ago, but here is an analogy:</p>
<pre class="csharpcode"><span class="str">"Field-like Event"</span> : Delegate Field :: <span class="str">"Auto-Implemented Property"</span> : Data Field</pre>
<p>An automatically implemented property consists of a compiler generated field, and a pair of compiler generated methods (<code>get </code>and <code>set</code>).  A better name for “Field-like Event” might have been “Automatically-Implemented Event”.  At least we can be happy that they didn’t call autoproperties “Field-Like Properties”.</p>
<h2>The Implementation</h2>
<p>So, what do I get when I declare <code>Poco</code> this way?  I can use <a href="http://wiki.sharpdevelop.net/ILSpy.ashx" target="_blank">ILSpy</a> to see what the compiler did in IL, but the C# view looks just like what I wrote in Visual Studio.  In this case <a href="http://www.reflector.net/" target="_blank">Reflector</a> can provide better insight if you drill into the event node.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Poco
{
    <span class="rem">// Fields</span>
    <span class="kwrd">private</span> EventHandler ProcessCompleted;

    <span class="rem">// Events</span>
    <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler ProcessCompleted
    {
        add
        {
            EventHandler handler2;
            EventHandler processCompleted = <span class="kwrd">this</span>.ProcessCompleted;
            <span class="kwrd">do</span>
            {
                handler2 = processCompleted;
                EventHandler handler3 = (EventHandler)Delegate.Combine(handler2, <span class="kwrd">value</span>);
                processCompleted = Interlocked.CompareExchange&lt;EventHandler&gt;(<span class="kwrd">ref</span> <span class="kwrd">this</span>.ProcessCompleted, handler3, handler2);
            }
            <span class="kwrd">while</span> (processCompleted != handler2);
        }

        remove
        {
            EventHandler handler2;
            EventHandler processCompleted = <span class="kwrd">this</span>.ProcessCompleted;
            <span class="kwrd">do</span>
            {
                handler2 = processCompleted;
                EventHandler handler3 = (EventHandler)Delegate.Remove(handler2, <span class="kwrd">value</span>);
                processCompleted = Interlocked.CompareExchange&lt;EventHandler&gt;(<span class="kwrd">ref</span> <span class="kwrd">this</span>.ProcessCompleted, handler3, handler2);
            }
            <span class="kwrd">while</span> (processCompleted != handler2);
        }
    }
}</pre>
<p>There is a lot going on there for one line of code.  The good news is that a lot of it is ceremony around ensuring an atomic update to the backing field, and we don’t need to remember it.  I can simplify this code to something roughly equivalent, which just contains the parts that matter to the discussion at hand:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Poco
{
    <span class="rem">// Fields</span>
    <span class="kwrd">private</span> EventHandler ProcessCompleted;

    <span class="rem">// Events</span>
    <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler ProcessCompleted
    {
        add
        {
            <span class="kwrd">this</span>.ProcessCompleted = (EventHandler)Delegate.Combine(<span class="kwrd">this</span>.ProcessCompleted, <span class="kwrd">value</span>);
        }

        remove
        {
            <span class="kwrd">this</span>.ProcessCompleted = (EventHandler)Delegate.Remove(<span class="kwrd">this</span>.ProcessCompleted, <span class="kwrd">value</span>);
        }
    }
}</pre>
<p>Once again, I’ll refer you to the autoproperty analogy.  The compiler gives us a backing field, and two methods.  One interesting (and useful) difference between the autoproperty implementation and the autoevent implementation is the name the compiler chooses for the backing field.  If the compiler used the same rules for autoevents as it uses for autoproperties, the declaration might look something like this:</p>
<pre class="csharpcode"><span class="kwrd">private</span> EventHandler &lt;ProcessCompleted&gt;k_BackingField;</pre>
<p>However, instead of using this unspeakable and potentially un-guessable generated name, we have this declaration:</p>
<pre class="csharpcode"><span class="kwrd">private</span> EventHandler ProcessCompleted;</pre>
<p>This name is much nicer because its easy to guess, it has the exact same name as the event.  Why do I like that this field’s name is easy to guess?  Simple, this field is just a reference to a delegate.  In other words, this field is the thing I want and although it is private and compiler-generated, guessing it’s identity is trivial.  I’ll file that useful fact away for now, and take a look at the compiler-generated add/remove methods.</p>
<h2>Compiler Tricks – An Aside</h2>
<p>I can’t help but comment on the expanded, Reflector-generated code shown above.  It doesn’t compile because the event and the field have the same name.  This is a trick the compiler can do when writing IL, but we can’t do when writing C#.  When the compiler requests the member field, it uses the <code>ldfld</code> IL instruction.  According to MSDN, this instruction loads the value of a field onto the stack.  It doesn’t load the value of a property, it doesn’t load the value of a local, it doesn’t load the value of an event (whatever that would mean).  It loads the value of a field.  So it seems that IL only cares that the backing field as a unique name among other fields, while C# insists that the name be unique among all <em>members </em>whether they are fields, properties, events, etc.</p>
<p>So C#’s rules appear more restrictive, which also prevents us from accidentally creating some unrelated field with the same name as our event and usurping the name the compiler wants to use.  I’m not sure why they chose to use unspeakable names when creating autoproperties, it seems like the same trick they used on events would have also worked for that feature.</p>
<h2>The Add/Remove Methods</h2>
<p>As you’ve seen, the compiler generates a few lines of code that use <code>Delegate.Combine</code> or <code>Delegate.Remove</code> (depending on which method you are looking at) to create a new <code>Delegate</code>, then atomically updates the backing field to point at the new delegate.  I could replace this implementation with whatever I want, as long as I follow the language rules enforced by C# (meaning, as long as I use a compatible backing field name).  Because anyone (including Microsoft) could decide to use a custom event implementation, you can’t assume that events will <em>always</em> be constructed this way.</p>
<p>For example, suppose I needed to create a unicast event.  Because all delegates are multicast by default, I would need to create custom add/remove events to implement an event that replaced its backing field rather than using <code>Delegate.Combine</code> to update the backing field.  (Of course, a mischievous reader might point out that this wouldn’t prevent a caller from <em>passing in</em> a multicast delegate).</p>
<p>On the other hand, most people probably need a reason to do extra work the compiler could do instead.  I think its safe to assume, that out in the universe, there are many, many compiler implemented events.</p>
<h2>A Test that Doesn’t Work and Why</h2>
<p>I’ll write a test that wires up a handler then see if I can get the invocation list.  Notice that I’m using <code>DelegateUtility</code> and <code>Domain</code>, which I created in part one of this article.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetPocoEventInvocationList()
{
    Poco poco = <span class="kwrd">new</span> Poco();
    poco.ProcessCompleted += Domain.HandleProcessCompleted;

    EventHandler pocoDelegate = poco.ProcessCompleted;  <span class="rem">// does not compile.</span>
    DelegateUtility.VerifyInvocationList(pocoDelegate);
}</pre>
<p>In case you missed the comment, this test wont compile. The compiler produces an error when we try to assign <code>ProcessCompleted</code> to <code>pocoDelegate</code></p>
<blockquote><p>The event ‘ProcessCompleted&#8217; can only appear on the left hand side of += or -= (except when used from within the type ‘Poco&#8217;)</p></blockquote>
<p>Not to beat a dead horse, but events are a lot like properties.  Remembering this helps us to make sense of the compiler error.  The local <code>pocoDelegate</code> is null, waiting to get a reference to a delegate.  If I have a compatible method, I can use the method group syntax to assign a value to <code>pocoDelegate</code>.  An event is just a pair of methods used to update a delegate (usually&#8211;they <em>could</em> do something weird or nothing at all).  Regardless of what they actually <em>do</em>, they are methods, why can’t we assign them to <code>pocoDelegate</code>?</p>
<p>For starters, the event represents a <em>pair</em> of methods.  How can the compiler determine which method to assign to the delegate?  The compiler can make the distinction between property getters and setters by looking at which side of the statement the property appears on—<code>get</code> appears on the right side, while <code>set</code> appears on the left.  One of the points that the compiler error makes is that events can only appear on the left-hand side of the <code>+=</code> or <code>–=</code> operator.  The operator used determines which method you want when you try to <em>use</em> add or remove, but you can’t use those operators to help the compiler make a decision about which delegate to generate and assign to the local variable.  Finally, even if you could tell the compiler which method to use, <em>it wouldn’t matter.</em>  Neither add or remove can be assigned to the local variable: the methods do not have signatures compatible with <code>EventHandler</code>.</p>
<p>It all comes down to this: the only thing you can do with an event is choose between calling add or remove and the only way to make that choice is by writing down the appropriate operator.</p>
<h2>Confusing Duality</h2>
<p>Its easy to get confused about what an event is because the compiler/IDE is &#8220;helpful&#8221; in other ways. From within the class, I can still use <code>+=</code> or <code>-=</code> (or <code>AddHandler</code> and <code>RemoveHandler</code> if you&#8217;re writing VB). But, inside the class I&#8217;m also allowed to use assignment in either direction:</p>
<pre class="csharpcode">var handler = <span class="kwrd">this</span>.ProcessCompleted;</pre>
<p>The compiler can see that this statement doesn&#8217;t map in any logical way to <code>add</code> or <code>remove</code>. So, it helpfully treats the event like a property  (or a field if you prefer) and <code>gets</code> a reference to the invisible, private, backing field and puts it into <code>handler</code>. I&#8217;m not saying it <em>is</em> a property. It just looks a hell of a lot like one when you are writing code inside your class. Likewise, this statement feels a lot like a property setter:</p>
<pre class="csharpcode"><span class="kwrd">this</span>.ProcessCompleted = <span class="kwrd">null</span>;</pre>
<p>This detaches <code>ProcessCompleted</code>&#8216;s handler into the void, and is perfectly legal. So this is the what the second half of the compiler error means.</p>
<blockquote><p>except when used from within the type ‘Poco&#8217;</p></blockquote>
<p>The illegal statement that I made in my test would be perfectly legal if I did it from within the class. With that insight, I can think of a way to rewrite my class so that my test could run.  I&#8217;ll add a public method that exposes the delegate.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Poco
{
    <span class="kwrd">public</span> <span class="kwrd">event</span> EventHandler ProcessCompleted;

    <span class="kwrd">public</span> EventHandler GetProcessCompletedHandler()
    {
        <span class="kwrd">return</span> <span class="kwrd">this</span>.ProcessCompleted;
    }

    <span class="rem">// ...</span></pre>
<p>I&#8217;ll go ahead and admit up front that this is a degenerate solution with an odor of indecent exposure, but for now my interest is only whether it works. An update to the test should reveal the answer:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetPocoEventInvocationList()
{
    Poco poco = <span class="kwrd">new</span> Poco();
    poco.ProcessCompleted += Domain.HandleProcessCompleted;

    EventHandler pocoDelegate = poco.GetProcessCompletedHandler();  
    DelegateUtility.VerifyInvocationList(pocoDelegate);
}</pre>
<p>This test compiles and runs, so far&#8211;so good. Here are the results:</p>
<pre class="csharpcode">[0] = Void HandleProcessCompleted(System.Object, System.EventArgs)</pre>
<p>While exposing the event handler hardly qualifies as a best-practice, I can see that the test works as expected. I can verify that the functionality in <code>PocoClient</code> is implemented correctly without attempting to call <code>DoWork</code>. It&#8217;s quick and dirty, emphasis on the dirty. But I&#8217;m not done, because this quick and dirty method only works when I control both ends of the subscription. What if I don&#8217;t?</p>
<p>If you don’t control the class the class the event is declared on, you’ll have to use reflection to get your hand on the delegate.  This will be the subject of the next post in this series.</p>
<h1>Relationship with EventApprovals</h1>
<p>There isn’t a strong relationship between this quick and dirty technique and what you will find in EventApprovals.  Exposing the delegate is only necessary if you don’t know how to retrieve it with reflection, EventApprovals uses the reflection approach, and you can too by calling <code>ApprovalTests.Events.EventApprovals.VerifyEvents</code>.</p>
<h1>Up Next</h1>
<p>The next article in this series will be “<a title="Beyond the Event Horizon: Events You Don’t Own" href="http://ihadthisideaonce.com/2012/09/05/beyond-the-event-horizon-events-you-dont-own/">Beyond the Event Horizon: Events You Don’t Own</a>”.  That article will cover how to retrieve event handlers using reflection and then expand the technique to include taking a complete inventory of an object’s events.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/669/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/669/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=669&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/09/02/beyond-the-event-horizon-event-basics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/08/simpleevents-640x640_thumb.jpg" medium="image">
			<media:title type="html">OLYMPUS DIGITAL CAMERA</media:title>
		</media:content>
	</item>
		<item>
		<title>Beyond the Event Horizon: Delegate Basics</title>
		<link>http://ihadthisideaonce.com/2012/08/28/beyond-the-event-horizon-delegate-basics/</link>
		<comments>http://ihadthisideaonce.com/2012/08/28/beyond-the-event-horizon-delegate-basics/#comments</comments>
		<pubDate>Tue, 28 Aug 2012 23:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[ApprovalTests]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=639</guid>
		<description><![CDATA[With the release of ApprovalTests 2.0 we can now use EventApprovals to catalog the event handlers attached to our objects.  Using this feature of ApprovalTests, Stack Overflow questions like this one: How do I retrieve the Subscriber List for an Event at runtime? now have a real answer. I asked that question almost 3 years [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=639&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/08/eventhorizon.jpg"><img style="background-image:none;float:left;padding-top:0;padding-left:0;margin:10px 10px 0 0;display:inline;padding-right:0;border-width:0;" title="OLYMPUS DIGITAL CAMERA" src="http://ihadthisideaonce.files.wordpress.com/2012/08/eventhorizon_thumb.jpg?w=158&#038;h=158" alt="OLYMPUS DIGITAL CAMERA" width="158" height="158" align="left" border="0" /></a>With the release of <a href="http://approvaltests.sourceforge.net/" target="_blank">ApprovalTests</a> 2.0 we can now use EventApprovals to catalog the event handlers attached to our objects.  Using this feature of ApprovalTests, Stack Overflow questions like this one: <a href="http://stackoverflow.com/questions/1930374/how-do-i-retrieve-the-subscriber-list-for-an-event-at-runtime" target="_blank">How do I retrieve the Subscriber List for an Event at runtime?</a> now have a real answer.</p>
<p>I asked that question almost 3 years ago.  After none other than Marc Gravell told me, “It usually means that you are doing something wrong (sorry, but it does),”  I worked out another way to test the code that led me to ask that question.  Although I accepted Marc’s answer on Stack Overflow, I think it is safe to say that I never accepted the answer in my heart.  Fast forward a few years, and yet again I found myself wishing that I could simply retrieve the subscriber list and verify it in a test.  But this time things were different.  I’m not afraid of reflection anymore, and now I have ApprovalTests available to process the potentially large amount of data that retrieving subscriber lists might produce.</p>
<p>So this time I wrote EventApprovals and got what I had wanted all along, the runtime subscriber list.  This CodeProject article by Alejandro Miralles was a great help getting started:  <a href="http://www.codeproject.com/Articles/308536/How-to-copy-event-handlers-from-one-control-to-ano" target="_blank">How to copy event handlers from one control to another at runtime</a>.  With that jumping off point, I went through several revisions before telling Llewellyn, “I think I have something that might interest you…”</p>
<p>Along the way, I learned more about events and delegates than I ever thought I would need to know.  Indeed, my working title for this article was “More than you ever wanted to know about .NET events.”  Even though you can use ApprovalTests without knowing any of what follows, I felt like sharing some of the process that went into creating EventApprovals while it was still relatively fresh in my mind.  I thought it might be fun to re-implement a system similar to EventApprovals from memory.  You can find the code for this article on <a href="https://github.com/jamesrcounts/EventReflection" target="_blank">GitHub</a>.  I figured I would make a lot of the same mistakes I made the first few times around.  I always learn better from an example that shows mistakes and how to correct them than I do from a clean implementation.  Hopefully you will too.</p>
<p>Along the way I’ll try to relate the concepts in this article to the parts of EventApprovals that can give you the same information without having to do the heavy lifting yourself.  So, lets get started with delegates in .NET.</p>
<h1></h1>
<h1>Delegates</h1>
<p>Delegates are at the heart of the event system in .NET.  And the “subscriber list” for an event is identical to the delegate’s invocation list.  When I have a direct reference to some delegate, this information is trivial to retrieve.  Here’s how.</p>
<p>Assume I have an instance of some delegate type:</p>
<pre class="csharpcode">Func&lt;<span class="kwrd">bool</span>&gt; truth = () =&gt; <span class="kwrd">true</span>;</pre>
<p>In this example, our delegate is a <code>Func&lt;bool&gt;</code>, to determine the list of methods assigned to the delegate use the method called <code>GetInvocationList</code>.  This method returns an array of <code>Delegate </code>instances, and each <code>Delegate </code>has a <code>Method </code>property, which is a <code>MethodInfo </code>from the reflection namespace.  I’ll use a LINQ extension to project these <code>Delegate</code>s into a collection of <code>MethodInfo</code>s.</p>
<p>Something like this:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetInvocationList()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = () =&gt; <span class="kwrd">true</span>;
    IEnumerable&lt;MethodInfo&gt; methods = truth.GetInvocationList().Select(d =&gt; d.Method);
    Approvals.VerifyAll(methods, <span class="kwrd">string</span>.Empty);
}</pre>
<h2>Introduction to ApprovalTests</h2>
<p>If you are already familiar with ApprovalTests, you can probably skip this section.  For those of you who are new to this testing library, read on for a brief introduction.  I also recommend that you watch this short video, where Llewellyn Falco, the creator of ApprovalTests, introduces the library.</p>
<div id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:30e7c4c1-c455-48b5-9fed-bacc5b54c644" class="wlWriterEditableSmartContent" style="float:none;margin:0 auto;display:block;width:448px;padding:0;">
<div><span class='embed-youtube' style='text-align:center; display: block;'><iframe class='youtube-player' type='text/html' width='448' height='252' src='http://www.youtube.com/embed/bg8GOmlwqYY?version=3&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;showinfo=1&#038;iv_load_policy=1&#038;hd=1&#038;wmode=transparent' frameborder='0'></iframe></span></div>
<div style="width:448px;clear:both;font-size:.8em;">Using ApprovalTests in .Net 01 MsTest</div>
</div>
<p>In the delegate example I wrote above, I use a call to <code>Approvals.VerifyAll</code> instead of using one of MSTest’s built in <code>Assert</code> methods.  <code>VerifyAll</code> will iterate over the <code>MethodInfo</code> collection and call <code>ToString</code> on each member.  These strings are collected into a buffer, then ApprovalTests shows me the results using whatever reporter I’ve specified with the UseReporter attribute.  In this case, I choose a DiffReporter.</p>
<p>The first time I run the test, ApprovalTests displays the results, then I can approve the results if they look right to me.  Once I have approved results, ApprovalTests will check the approved result against each subsequent test run result.  ApprovalTests will only alert me (with a failing test) if the test run produces different results from the approved results.</p>
<h2>Invocation List Results</h2>
<p>ApprovalTests reports these results after executing my first example:</p>
<pre class="csharpcode">[0] = Boolean &lt;GetInvocationList&gt;b__0()</pre>
<p>I can see that only one method is assigned to this delegate. Its return type is <code>Boolean</code>, its name is <code>&lt;GetInvocationList&gt;b__0</code> and it takes no parameters (indicated by the empty parenthesis<code>()</code>). The method has a strange compiler-generated name because it is anonymous. The list might be easier to read if I assign a ordinary named method to the delegate.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Domain
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> AlwaysTrue()
    {
        <span class="kwrd">return</span> <span class="kwrd">true</span>;
    }
}</pre>
<p><code>AlwaysTrue</code> is a method which has a signature compatible with the type of the <code>truth</code> delegate instance, which means I can assign it to the delegate.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetInvocationList()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = Domain.AlwaysTrue;
    IEnumerable&lt;MethodInfo&gt; methods = truth.GetInvocationList().Select(d =&gt; d.Method);
    Approvals.VerifyAll(methods, <span class="kwrd">string</span>.Empty);
}</pre>
<p>After assigning <code>AlwaysTrue</code> to <code>truth</code> I get the following output:</p>
<pre class="csharpcode">[0] = Boolean AlwaysTrue()</pre>
<p>If I declare a <code>Delegate</code> instance I can use the static <code>Delegate.Combine</code> method to assign more than one method to a delegate:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetMultiInvocationList()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = Domain.AlwaysTrue;
    Func&lt;<span class="kwrd">bool</span>&gt; truthy = Domain.NeverFalse;
    Delegate multicast = Delegate.Combine(truth, truthy);
    IEnumerable&lt;MethodInfo&gt; methods = multicast.GetInvocationList().Select(d =&gt; d.Method);
    Approvals.VerifyAll(methods, <span class="kwrd">string</span>.Empty);
}</pre>
<p>Here are the results:</p>
<pre class="csharpcode">[0] = Boolean AlwaysTrue()
[1] = Boolean NeverFalse()</pre>
<h2>Cleanup</h2>
<p>Now that I have two tests which contain some code duplication, I’ll extract the duplication into a utility class called DelegateUtility for reuse.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DelegateUtility
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> VerifyInvocationList(Delegate <span class="kwrd">value</span>)
    {
        Approvals.VerifyAll(
            <span class="kwrd">value</span>.GetInvocationList().Select(d =&gt; d.Method),
            <span class="kwrd">string</span>.Empty);
    }
}</pre>
<p>After updating my tests they look like this, and they still pass:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetInvocationList()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = Domain.AlwaysTrue;
    DelegateUtility.VerifyInvocationList(truth);
}

[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> GetMultiInvocationList()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = Domain.AlwaysTrue;
    Func&lt;<span class="kwrd">bool</span>&gt; truthy = Domain.NeverFalse;
    DelegateUtility.VerifyInvocationList(Delegate.Combine(truth, truthy));
}</pre>
<p>This was a trivial refactoring and only saved a few lines of code.  But its worth doing.  Its better to do it now when I only have two tests in my suite, than it is to wait until the suite is large and cumbersome to update.</p>
<h1>Delegate Oddities</h1>
<p>You may have heard that delegates are types.  This means that they are in the same category as classes, structs and interfaces.</p>
<p>What does it mean to be a “type”?  Well, lets look at some more familiar types: classes and interfaces.  A class and an interface are similar to each other in many ways, but they are not the same.  You can’t instantiate an interface, or define bodies for the members declared on an interface.  There are other differences, but this is enough to get an idea about what types are in .NET.  The language applies (and complier enforces) different rules about what you can and can’t do with each “type” of type.  So, delegates are not a special kind of class, they are not a special kind of interface.  Delegates are their own things with their own set of rules.  One of the rules is that the actual implementation is always compiler generated.</p>
<p>Lets look at what happens when the compiler encounters a delegate type definition like this:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">int</span> Operation(<span class="kwrd">int</span> a, <span class="kwrd">int</span> b);</pre>
<p>The compiler generates a class derived from <code>MulticastDelegate</code>, which in turn derives from <code>Delegate</code>.  But only the complier can do this.  Just like you or I can’t create a method with a name like this: &lt;GetInvocationList&gt;b__0, we’re also prevented from inheriting from <code>MulticastDelegate</code>.  I’m bringing this up to explain a part of the <code>VerifyInvocationList</code> method that might be confusing.</p>
<p>Each generated <code>MulticastDelegate </code>descendant inherits a <code>GetInvocationList</code> method and a property called <code>Method</code>.  These two members are always related.  When the <code>MulticastDelegate </code>only has one method to invoke, the relationship looks like this:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> UnicastDelegateHasInvocationList()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = Domain.AlwaysTrue;
    Assert.AreEqual(
        truth.Method, 
        truth.GetInvocationList().Select(i =&gt; i.Method).Single());
}</pre>
<p>As you can see, the <code>Method</code> property is also returned as a member of the <code>Delegate</code> array returned by <code>GetInvocationList</code>.  In the case of a logically unicast delegate, <code>Method</code> is the one and only array member.  In the case of a truly multicast delegate, things are a little different.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> MulticastDelegateInvocationListContainsMethod()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = Domain.AlwaysTrue;
    Func&lt;<span class="kwrd">bool</span>&gt; truthy = Domain.NeverFalse;
    Delegate combined = Delegate.Combine(truth, truthy);
    Assert.AreEqual(
        combined.Method,
        combined.GetInvocationList().Select(i =&gt; i.Method).Last());
}</pre>
<p>In the case of a delegate that actually needs to multicast, the <code>MethodInfo</code> pointed at by the <code>Method</code> property is actually the last member of the invocation list.  In other words, when you call <code>Delegate.Combine</code> repeatedly, <code>Method</code> will always point at the last method you added to the delegate.</p>
<p>Here is some code that will never finish executing.</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> InfiniteLoop()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = Domain.AlwaysTrue;
    <span class="kwrd">this</span>.Body(truth.GetInvocationList());
}

<span class="kwrd">public</span> <span class="kwrd">void</span> Body(Delegate[] delegates)
{
    <span class="kwrd">foreach</span> (var del <span class="kwrd">in</span> delegates)
    {
        <span class="kwrd">this</span>.Body(del.GetInvocationList());
    }
}</pre>
<p>So we can’t crawl into each <code>Delegate</code> looking for more delegates, that leads to infinite recursion.  However, we don’t need to worry about it.  <code>Delegate.Combine</code> flattens invocation lists before combining them.  Here’s a test to demonstrate:</p>
<pre class="csharpcode">[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> CombinedDelegatesAreFlattened()
{
    Func&lt;<span class="kwrd">bool</span>&gt; truth = Domain.AlwaysTrue;
    Func&lt;<span class="kwrd">bool</span>&gt; truthy = Domain.NeverFalse;
    Func&lt;<span class="kwrd">bool</span>&gt; answer43 = Domain.AlwaysTrue;
    Delegate combined = Delegate.Combine(truthy, answer43);
    Delegate flattened = Delegate.Combine(truth, combined);
    DelegateUtility.VerifyInvocationList(flattened);
}</pre>
<p>And these are the results:</p>
<pre class="csharpcode">[0] = Boolean AlwaysTrue()
[1] = Boolean NeverFalse()
[2] = Boolean AlwaysTrue()</pre>
<p>So, after playing with these tests we can see that the <code>VerifyInvocationList</code> implementaion is correct.</p>
<pre class="csharpcode"><span class="kwrd">value</span>.GetInvocationList().Select(d =&gt; d.Method)</pre>
<p>First, I call <code>GetInvocationList</code> to get the flattened array of delegates.  Because these delegates are flattened, all the array members are logically unicast, so I can access the <code>Method</code> property to get the only member, rather than dereferencing through the array returned by <code>GetInvocationList</code>.</p>
<h1>Relationship with EventApprovals</h1>
<p>Like I said at the top, delegates are at the core of the .NET event system.  Likewise, the projection from a delegate into a collection of <code>MethodInfo</code>s,(shown here as part of <code>VerifyInvocationList)</code> is at the heart of EventApprovals.</p>
<p>We didn’t extract <code>VerifyInvocationList</code> as a separate verification method the way I have done here.  If you have a delegate in hand, getting data from it isn’t very hard at all, and you can just use <code>Approvals.VerifyAll</code> instead of getting into the more specialized methods in <code>ApprovalTests.Events</code> or <code>ApprovalUtilities.ReflectionUtilities</code>.</p>
<h1>Up Next</h1>
<p>The next installment of this article is “<a title="Beyond the Event Horizon: Event Basics" href="http://ihadthisideaonce.com/2012/09/02/beyond-the-event-horizon-event-basics/">Beyond the Event Horizon: Event Basics</a>”  We’ll look at how events are implemented by the compiler and how they relate to delegates.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/639/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/639/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=639&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/08/28/beyond-the-event-horizon-delegate-basics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/08/eventhorizon_thumb.jpg" medium="image">
			<media:title type="html">OLYMPUS DIGITAL CAMERA</media:title>
		</media:content>
	</item>
		<item>
		<title>What&#8217;s New in CompositionTests 1.3</title>
		<link>http://ihadthisideaonce.com/2012/08/13/whats-new-in-compositiontests-1-3/</link>
		<comments>http://ihadthisideaonce.com/2012/08/13/whats-new-in-compositiontests-1-3/#comments</comments>
		<pubDate>Mon, 13 Aug 2012 16:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[ApprovalTests]]></category>
		<category><![CDATA[CompositionTests]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=636</guid>
		<description><![CDATA[I hope you are all as excited as I am about the latest ApprovalTests release, 2.0.  This release polishes some rough edges, and adds some exciting new test scenarios.  Check out Llewellyn&#8217;s release notes for details.  I&#8217;ve been experimenting with CompositionTests 1.3 for a month or so, and now that ApprovalTests has released, I&#8217;m releasing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=636&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ihadthisideaonce.files.wordpress.com/2012/08/compositiontestsv-1-3-0-640x640.jpg"><img style="background-image:none;margin:0 10px 0 0;padding-left:0;padding-right:0;display:inline;float:left;padding-top:0;border:0;" title="CompositionTestsv.1.3.0 (640x640)" src="http://ihadthisideaonce.files.wordpress.com/2012/08/compositiontestsv-1-3-0-640x640_thumb.jpg?w=154&#038;h=154" alt="CompositionTestsv.1.3.0 (640x640)" width="154" height="154" align="left" border="0" /></a>I hope you are all as excited as I am about the latest <a href="http://approvaltests.sourceforge.net/">ApprovalTests</a> release, 2.0.  This release polishes some rough edges, and adds some exciting new test scenarios.  Check out Llewellyn&#8217;s <a href="http://blog.approvaltests.com/2012/08/whats-new-in-approvaltestsnet-v20.html" target="_blank">release notes</a> for details.  I&#8217;ve been experimenting with CompositionTests 1.3 for a month or so, and now that ApprovalTests has released, I&#8217;m releasing 1.3 to go with it.  Other than versioning compatibility, CompositionTests 1.3 doesn&#8217;t have any specific dependencies on ApprovalTests 2.0, but it seemed like a good time to release.  Enjoy.</p>
<h2>Generic VerifyCatalog Implementation</h2>
<p>CompositionTests 1.2 introduced customized <code>Verify*Catalog</code> convenience methods that automatically provide scrubbers that make sense with each catalog type. Although this worked fine, using the convenience methods meant that you needed to make an extra change to your test if you decided to change the catalog type&#8230; not very convenient!</p>
<p>The new <code>VerifyCatalog&lt;T&gt;</code> method addresses this shortcoming. The new method will take any catalog descended from <code>ComposablePartCatalog</code> and attempt to find an appropriate <code>Verify*Catalog</code> implementation. When the method cannot find an appropriate implementation, the default is to use <code>VerifyCompositionInfo</code> with no scrubbers.</p>
<h2>ApprovalTests 2.0</h2>
<p>This version of CompositionTests is built against <a title="ApprovalTests Blog" href="http://blog.approvaltests.com/2012/08/whats-new-in-approvaltestsnet-v20.html">ApprovalTests 2.0</a>. The CompositionTests 1.2.0 NuGet package incorrectly specified the ApprovalTests dependency as <code>x &gt;= 1.9</code>. Because the ApprovalTest assemblies are signed, dependent assemblies (like CompositionTests) will only load the ApprovalTests assembly which they are built against, so &#8220;greater than or equal to&#8221; should have been &#8220;exactly equal to&#8221;. The package for CompositionTests 1.3.0 correctly specifies the dependency as <code>x == 2.0</code>.</p>
<p>If CompostionTests stopped working for you after upgrading to ApprovalTests 2.0, this release should fix that for you.</p>
<h2>Reminder</h2>
<p>Remember <code>DiscoverParts</code> and <code>Composition</code> are obsolete and will be removed in a future release. Please migrate to <code>Verify*</code> and <code>MefComposition</code>.</p>
<h2>Go Get It</h2>
<p>As usual you can get the bits from github or NuGet!</p>
<p><a href="http://www.compositiontests.com/" target="_blank">http://www.compositiontests.com/</a></p>
<p><a href="https://nuget.org/packages/CompositionTests" target="_blank">https://nuget.org/packages/CompositionTests</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/636/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=636&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/08/13/whats-new-in-compositiontests-1-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/08/compositiontestsv-1-3-0-640x640_thumb.jpg" medium="image">
			<media:title type="html">CompositionTestsv.1.3.0 (640x640)</media:title>
		</media:content>
	</item>
		<item>
		<title>How Hard Can It Be?</title>
		<link>http://ihadthisideaonce.com/2012/07/16/how-hard-can-it-be/</link>
		<comments>http://ihadthisideaonce.com/2012/07/16/how-hard-can-it-be/#comments</comments>
		<pubDate>Tue, 17 Jul 2012 03:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[ApprovalTests]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=610</guid>
		<description><![CDATA[Unit Testing ASP.NET MVC Views with ApprovalTests How Hard Can It Be? &#124; aspConf 2012 &#124; 7/22/2012 If you missed it, aspConf happened July 17 -18, 2012.  I presented a demo of the MVC View testing technique I&#8217;ve written about on this blog. My session was July 18 from 1-2:15 PM PST in Room 3.  If [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=610&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h2>Unit Testing ASP.NET MVC Views with ApprovalTests</h2>
<div style="margin:0 auto;width:549px;display:block;float:none;padding:0;">
<div><span style="text-align:center;display:block;"><a href="http://channel9.msdn.com/Events/aspConf/aspConf/Testing-ASP-NET-MVC-Views-from-New-Project-to-the-Build-Server?format=html5" target="_blank"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="videothumbnail" src="http://ihadthisideaonce.files.wordpress.com/2012/07/videothumbnail.png?w=553&#038;h=313" alt="videothumbnail" width="553" height="313" border="0" /></a></span></div>
<div style="width:549px;clear:both;font-size:.8em;">How Hard Can It Be? | aspConf 2012 | 7/22/2012</div>
</div>
<p>If you missed it, <a href="http://live.aspconf.net/sessions#49">aspConf</a> happened July 17 -18, 2012.  I presented a demo of the MVC View testing technique I&#8217;ve written about on this blog. My session was July 18 from 1-2:15 PM PST in Room 3.  If you missed the live show, I hope you will watch the screencast now posted on <a href="http://channel9.msdn.com/Events/aspConf/aspConf/Testing-ASP-NET-MVC-Views-from-New-Project-to-the-Build-Server?format=html5" target="_blank">channel9</a>.  Don&#8217;t miss the next aspConf (I presume next year), it’s a virtual, on-line conference and it’s free!  You don’t even have to get out of your chair.</p>
<p>In addition to the screencast (linked above), here are a few resources for the talk:</p>
<ul>
<li><a href="https://github.com/jamesrcounts/aspConf-demo">GitHub Repository</a></li>
<li>Videos
<ul>
<li>Llewellyn Falco (<a href="https://twitter.com/LlewellynFalco" target="_blank">@LlewellynFalco</a>): <a href="http://www.youtube.com/watch?v=SttlPzwJw3U&amp;hd=1">Using ApprovalTests in .Net 20 Asp.Mvc Views</a></li>
<li>Chris Scripca (<a href="https://twitter.com/DeadlyApps" target="_blank">@DeadlyApps</a>): <a href="http://www.youtube.com/watch?v=5gIeJ6z82Pk&amp;hd=1">Approval Tests ILoader Example</a></li>
</ul>
</li>
<li>Posts on This Blog
<ul>
<li><a title="ApprovalTests and MVC Views: Getting Started" href="http://ihadthisideaonce.com/2012/05/15/approvaltests-and-mvc-views-getting-started/">Getting Started</a></li>
<li><a title="ApprovalTests and MVC Views: Working With Data" href="http://ihadthisideaonce.com/2012/05/16/approvaltests-and-mvc-views-working-with-data/">Working with Data</a></li>
<li><a title="ApprovalTests and MVC Views: Tackling the Build Server" href="http://ihadthisideaonce.com/2012/05/17/approvaltests-and-mvc-views-tackling-the-build-server/">Tackling the Build Server</a></li>
</ul>
</li>
<li><a href="https://speakerdeck.com/u/jrc1800/p/how-hard-can-it-be-unit-testing-asp-dot-net-mvc-views">Slides</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/610/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/610/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=610&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/07/16/how-hard-can-it-be/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://ihadthisideaonce.files.wordpress.com/2012/07/videothumbnail.png" medium="image">
			<media:title type="html">videothumbnail</media:title>
		</media:content>
	</item>
		<item>
		<title>Use Closures to Put C# on a Diet</title>
		<link>http://ihadthisideaonce.com/2012/07/07/use-closures-to-put-c-on-a-diet/</link>
		<comments>http://ihadthisideaonce.com/2012/07/07/use-closures-to-put-c-on-a-diet/#comments</comments>
		<pubDate>Sun, 08 Jul 2012 00:30:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Closure]]></category>
		<category><![CDATA[Coding4Fun]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=603</guid>
		<description><![CDATA[I enjoy playing with state machines. They are simple enough to implement quickly, and complex enough to give the implementation language a little workout. Followers of this blog will know that I&#8217;ve enjoyed using Finite State Machines to explore CoffeeScript. But, when I look at the search terms leading to my blog, I see that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=603&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I enjoy playing with state machines. They are simple enough to implement quickly, and complex enough to give the implementation language a little workout. Followers of this blog will know that I&#8217;ve enjoyed using Finite State Machines to explore CoffeeScript.</p>
<p>But, when I look at the search terms leading to my blog, I see that people want to see FSMs implemented in C#, C++, or even VB. About the only language I haven&#8217;t seen people looking for is CoffeeScript. I&#8217;m not too surprised, since most people searching for FSM implementations are probably students trying to <span style="text-decoration:line-through;">cheat</span> get help on their homework. I doubt any professors are accepting CoffeeScript implementations.</p>
<p>When I see these search results, I consider quickly posting a solution in the requested language. I don&#8217;t mind if students crib solutions from me. I&#8217;m a big believer in learning by example. Certainly if by looking at my FSMs I can save one student from writing a <code>switch</code> statement, then I&#8217;ll consider it a public service. On the other hand, I&#8217;m not really interested in producing solutions by language on demand. Its not so much that I&#8217;m worried about students reading my solutions, as much as it is that implanting FSMs over and over again in different languages isn&#8217;t very interesting on its own merits.</p>
<p>While I was refactoring the <code>String.Contains</code> FSM for my previous post, I saved a few lines by taking advantage of closure. My inspiration for this refactoring came from a question one of the attendee&#8217;s asked at my CoffeeScript Crash Course presentation at SoCalCodeCamp. If you watch the video you will hear him ask, &#8220;Does the <code>@</code> imply closure, and if so why?&#8221; As I said in my presentation and on this blog, I&#8217;m no expert at CoffeeScript or JavaScript, so I can&#8217;t claim to have instantly grasped the context of his question. However, as I listened to it again, and listened to his comments to another attendee, I began to understand why he asked the question. The result was the new implementation I wrote about in my last post.</p>
<p>C# also supports closure, so I began to wonder what a C# <code>String.Contains</code> implementation would look like if we wanted to use as much closure as possible. I&#8217;ve implemented this machine in C# and C++ before, but I&#8217;m intrigued enough by the closure idea to try C# again.</p>
<h2>Getting Started</h2>
<p>This sample should be simple, Visual Studio seems like overkill, so I&#8217;m going to code it in Sublime Text 2 and use the C# compiler on the command line.</p>
<pre><code>csc .\StringCompare.cs </code></pre>
<p>If <code>StringCompare.cs</code> contains this skeleton program, it should compile to a do-nothing program:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Program
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">params</span> <span class="kwrd">string</span>[] args)
    {
    }
}</pre>
<h2>Rules</h2>
<p>In our CoffeeScript implementation we have a class called <code>Rule</code> with two subclasses. Lets see how this looks in C#:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Rule
{
    <span class="kwrd">public</span> Rule(<span class="kwrd">int</span> currentState, <span class="kwrd">char</span> inputChar, <span class="kwrd">int</span> nextState)
    {
        <span class="kwrd">this</span>.NextState = nextState;
        <span class="kwrd">this</span>.Match = (machineState, readChar) =&gt;
        {
            <span class="kwrd">return</span> currentState == machineState &amp;&amp; readChar == inputChar; 
        };
    }

    <span class="kwrd">public</span> <span class="kwrd">int</span> NextState { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Func&lt;<span class="kwrd">int</span>, <span class="kwrd">char</span>, <span class="kwrd">bool</span>&gt; Match { get; <span class="kwrd">private</span> set; }
}</pre>
<p>Remember, our goal is to use as much closure as possible, so if we can avoid declaring data properties, we will. All of our data comes in through the constructor, so we can create a lambda expression that closes over the <code>currentState</code> and <code>inputChar</code> and use it as our <code>Match</code> function. We still need to declare the <code>Match</code> function and its signature, but there is no need to create instance properties for the data. For <code>NextState</code> we could define a <code>Func&lt;int&gt;</code>, but that would have no benefit compared to a simple <code>int</code> property, so we&#8217;ll use a property.</p>
<p>That&#8217;s all fine in theory, but does it work? Let&#8217;s write a little test in the <code>Main</code> function.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Program
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">params</span> <span class="kwrd">string</span>[] args)
    {
        var myRule = <span class="kwrd">new</span> Rule(0, <span class="str">'1'</span>, 1);
        Console.WriteLine(myRule.Match(0,<span class="str">'1'</span>));
        Console.WriteLine(myRule.Match(1,<span class="str">'1'</span>));
    }
}</pre>
<p>As expected, this test prints <code>True</code> followed by <code>False</code>. It&#8217;s clear from this test that closure works just as well in constructors as anywhere else. Having satisfied my intuition, I can delete this test code If I want to and move on to implementing the specialized <code>TrapRule</code> and <code>ReturnRule</code> classes.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> TrapRule : Rule
{
    <span class="kwrd">public</span> TrapRule(<span class="kwrd">int</span> currentState)
        : <span class="kwrd">base</span>(currentState, (<span class="kwrd">char</span>)0, currentState)
    {
        <span class="kwrd">this</span>.Match = (machineState, readChar) =&gt;
        {
            <span class="kwrd">return</span> currentState == machineState;
        };
    }
}</pre>
<p>Like the CoffeeScript implementation, I pass <code>currentState</code> to the base implementation twice. However, I can&#8217;t pass <code>null</code> for a <code>char</code> value in C#. Instead, I pass in the null character <code>0</code>. Its also interesting to note that I don&#8217;t need to make <code>Match</code> virtual, and I don&#8217;t need to override it. All I need to do is make the setter <code>protected</code> so that the subclass can replace the implementation. We can update the test in <code>Main</code> to verify that this subclass works.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Program
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">params</span> <span class="kwrd">string</span>[] args)
    {
        var myRule = <span class="kwrd">new</span> TrapRule(0);
        Console.WriteLine(myRule.Match(0,<span class="str">'1'</span>));
        Console.WriteLine(myRule.Match(1,<span class="str">'1'</span>));
    }
}</pre>
<p>As expected, we see <code>True</code> printed, followed by <code>False</code>. Next, we can implement the <code>ReturnRule</code>.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> ReturnRule : Rule
{
    <span class="kwrd">public</span> ReturnRule(<span class="kwrd">int</span> currentState, <span class="kwrd">char</span> inputChar)
        : <span class="kwrd">base</span>(currentState, inputChar, 0)
    {
        <span class="kwrd">this</span>.Match = (machineState, readChar) =&gt;
        {
            <span class="kwrd">return</span> currentState == machineState &amp;&amp; readChar != inputChar;
        };
    }
}</pre>
<p>We actually don&#8217;t need to pass <code>currentState</code> and <code>inputChar</code> to the base class, because it only needs to know the <code>nextState</code>. However, it doesn&#8217;t hurt to pass it either. Once again, the child class replaces the <code>Match</code> implementation with one appropriate for the return rule. As before, we can update our test to verify the <code>ReturnRule</code> behavior.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">params</span> <span class="kwrd">string</span>[] args)
{
    var myRule = <span class="kwrd">new</span> ReturnRule(0, <span class="str">'0'</span>);
    Console.WriteLine(myRule.Match(0,<span class="str">'0'</span>));
    Console.WriteLine(myRule.Match(0,<span class="str">'1'</span>));
}</pre>
<p>As expected, this prints <code>False</code> followed by <code>True</code>. In theory, we&#8217;ve implemented <code>Rule</code> classes that should work with a <code>String.Contains</code> implementation. We need to see how this works with a machine implementation.</p>
<h2>Machine</h2>
<p>In the CoffeeScript implementation, I saw no benefit in converting the <code>createMachine</code> function into a class. In C#, I thought I might be able to do something similar with <code>dynamic</code>. It turns out that this doesn&#8217;t work though. The C# compiler produces error <code>CS0828</code> because you <code>cannot assign a lambda expression to an anonymous type property</code>. I don&#8217;t use <code>dynamic</code> very often, so this is news to me. It seems I&#8217;m already learning more about C# through this exercise.</p>
<p>So, with this restriction in place, I will need to create a class to implement the machine.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Machine 
{
    <span class="kwrd">public</span> Machine(Rule[] transitionRules, <span class="kwrd">int</span> currentState, <span class="kwrd">int</span>[] acceptanceStates)
    {
        <span class="kwrd">this</span>.ReadAll = (input) =&gt;
        {
            <span class="kwrd">foreach</span>(var inputChar <span class="kwrd">in</span> input)
            {
                Read(inputChar);
            }
        };
        <span class="kwrd">this</span>.Read = (inputChar) =&gt; 
        {
            <span class="kwrd">foreach</span>(var rule <span class="kwrd">in</span> transitionRules) 
            {
                <span class="kwrd">if</span> (rule.Match(currentState, inputChar))
                {
                    currentState = rule.NextState;
                    <span class="kwrd">return</span>;
                }
            }
            currentState = -1;
        };
        <span class="kwrd">this</span>.AcceptedInput = () =&gt; Array.IndexOf(acceptanceStates, currentState) &gt;= 0;
    }

    <span class="kwrd">public</span> Action&lt;<span class="kwrd">string</span>&gt; ReadAll { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Action&lt;<span class="kwrd">char</span>&gt; Read { get; <span class="kwrd">private</span> set; }
    <span class="kwrd">public</span> Func&lt;<span class="kwrd">bool</span>&gt; AcceptedInput { get; <span class="kwrd">private</span> set; }
}</pre>
<p>This implementation compiles, but does it work? We&#8217;ll need some test code to determine for sure. To do that we&#8217;ll need to implement <code>createSearchMachine</code> and <code>testMachine</code>. These implementations should be possible using <code>Func&lt;&gt;</code> instances in <code>Main</code> without having to create classes.</p>
<p>Here is <code>createSearchMachine</code>:</p>
<pre class="csharpcode">Func&lt;<span class="kwrd">string</span>, Machine&gt; createSearchMachine = (searchString) =&gt;
{
    var source = searchString.ToCharArray();
    var states = Enumerable.Range(0, source.Length);
    var rules = states.Select(x =&gt; <span class="kwrd">new</span> Rule(x, source[x], x + 1))
        .Concat(states.Where(x =&gt; x != source.Length).Select(x =&gt; <span class="kwrd">new</span> ReturnRule(x, source[x])))
        .Concat(<span class="kwrd">new</span> []{ <span class="kwrd">new</span> TrapRule(source.Length) });
    <span class="kwrd">return</span> <span class="kwrd">new</span> Machine(rules.ToArray(), 0, <span class="kwrd">new</span>[]{ source.Length });
};</pre>
<p>It’s interesting that, while slightly more verbose and noisy, C# supports a nearly identical implementation as CoffeeScript. Here is <code>testMachine</code>:</p>
<pre class="csharpcode">Action&lt;<span class="kwrd">string</span>, <span class="kwrd">string</span>&gt; testMachine = (input, searchString) =&gt;
{
    var machine = createSearchMachine(searchString);
    machine.ReadAll(input);
    Console.WriteLine(<span class="str">"{0}--{1}"</span>, machine.AcceptedInput(), input);
};</pre>
<p>Now we can finally run the machine and see how it works.</p>
<pre class="csharpcode">var target = <span class="str">"operating system"</span>;
testMachine(<span class="str">"Windows is an operating system installed on many machines."</span>, target);
testMachine(<span class="str">"Welcome to the operating room, the Doctor is just finishing his martini."</span>, target);</pre>
<p>And our output is just what we expect:</p>
<pre><code>C:\...\gist-3063755&gt; .\StringContains.exe </code>
<code>True--Windows is an operating system installed on many machines. </code>
<code>False--Welcome to the operating room, the Doctor is just finishing his martini. </code></pre>
<h2>Great, Closure All The Things!</h2>
<p><img style="display:block;float:none;margin-left:auto;margin-right:auto;" src="http://cdn.memegenerator.net/instances/400x/23128327.jpg" alt="" /></p>
<p>No, not really.  In CoffeeScript/JavaScript closures are the norm and expected.  In C# the question you have to ask yourself is why <em>would</em> you close over everything.  Keep in mind that, although you do not declare classes with data members, they still exist.  The compiler generates them for you, so its not like you’ve “saved” anything by using closure.  Maybe closures make your code harder to reflect into, since the compiler will use unspeakable names to refer to the classes it generates.  This obscurity might appeal to some, but for me it’s simply a learning exercise.  I hope you learned something too.</p>
<p>You can check out the finished code at this <a href="https://gist.github.com/3063755#file_string_contains.cs" target="_blank">gist</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/603/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/603/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=603&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/07/07/use-closures-to-put-c-on-a-diet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="http://cdn.memegenerator.net/instances/400x/23128327.jpg" medium="image" />
	</item>
		<item>
		<title>Implementing String.Contains</title>
		<link>http://ihadthisideaonce.com/2012/07/05/implementing-string-contains/</link>
		<comments>http://ihadthisideaonce.com/2012/07/05/implementing-string-contains/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 02:00:00 +0000</pubDate>
		<dc:creator>Jim Counts</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Coding4Fun]]></category>
		<category><![CDATA[CoffeeScript]]></category>
		<category><![CDATA[finite state machines]]></category>

		<guid isPermaLink="false">https://ihadthisideaonce.wordpress.com/?p=510</guid>
		<description><![CDATA[After writing up the Finite State Machine from SoCalCodeCamp, I had CoffeeScript on the brain and decided to go back and look at my first CoffeeScript experiment to see if there was any room for improvement.  Actually, I knew there was room for improvement.  One of the times when I was stuck in my presentation [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=510&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><img style="margin:10px 10px 0 0;display:inline;float:left;" src="https://lh3.googleusercontent.com/-KCrad3h3oKw/T_ZJgLB4p0I/AAAAAAAACdE/_0K4mDNgvQI/s800/P6100083.JPG" alt="" align="left" />After writing up the Finite State Machine from SoCalCodeCamp, I had CoffeeScript on the brain and decided to go back and look at my first CoffeeScript experiment to see if there was any room for improvement.  Actually, I knew there was room for improvement.  One of the times when I was stuck in my presentation I flipped over to this machine and I’m pretty sure I blanched visibly and the counted loop in the “read” function.</p>
<p>So lets revisit my first CoffeeScript state machine.  This machine determines if a specified substring exists within a string. In other words, it implements <em>bool String.Contains(String)</em>.  Besides all the room for improvement, I think there is an opportunity for some meaningful use of CoffeeScript classes.</p>
<p>First we&#8217;ll warm up by adding a shim for alert.</p>
<pre><code>alert = (value) -&gt; console.log value </code></pre>
<p>Now we can get started with our conversion, we&#8217;ll start from the bottom up this time.</p>
<h2>Remove Test Duplication</h2>
<p>Here is our current test code.</p>
<pre class="csharpcode">test1 = <span class="str">"Windows is an operating system installed on many machines."</span>
test2 = <span class="str">"Welcome to the operating room, the Doctor is just finishing his martini."</span>

getMachineResult = (b) -&gt; 
  result = <span class="str">""</span>
  <span class="kwrd">if</span> b == <span class="kwrd">true</span> 
   result = <span class="str">" Accepted. "</span>
  <span class="kwrd">else</span>
   result = <span class="str">" Not Accepted. "</span>
  result

machine = createMachine(rules, 0, finalStates)
machine.readAll test1
alert getMachineResult(machine.acceptedInput()) + test1

machine2 = createMachine(rules, 0, finalStates)
machine2.readAll test2
alert getMachineResult(machine2.acceptedInput()) + test2</pre>
<p>Lets remove the duplication and the weirdo <code>getMachineResult</code> method.</p>
<pre class="csharpcode">testMachine = (input) -&gt;
  machine = createMachine(rules, 0, finalStates)
  machine.readAll input  
  alert [machine.acceptedInput(), input].join <span class="str">'--'</span>

testMachine <span class="str">"Windows is an operating system installed on many machines."</span>
testMachine <span class="str">"Welcome to the operating room, the Doctor is just finishing his martini."</span></pre>
<h2>Encapsulate Machine Creation</h2>
<p>Our <code>testMachine</code> function currently closes over <code>rules</code> and <code>finalStates</code> from the CoffeeScript &#8220;module&#8221; scope. We also have these five lines which represent the logic necessary for getting ready to create our machine.</p>
<pre class="csharpcode">source = <span class="str">"operating system"</span>.split <span class="str">''</span> 
rules = (createRule x, source <span class="kwrd">for</span> x <span class="kwrd">in</span> [0..source.length])
altRules = (createAltRule x, source <span class="kwrd">for</span> x <span class="kwrd">in</span> [0..source.length])
rules.concat altRules
finalStates = [ source.length ]</pre>
<p>And the machine is actually created in <code>testMachine</code></p>
<pre class="csharpcode">machine = createMachine(rules, 0, finalStates)</pre>
<p>Lets encapsulate all this logic into one function, get it out of the module scope, and generalize it so that it can work with any search string.</p>
<pre class="csharpcode">createSearchMachine = (searchString) -&gt;
  source = searchString.split <span class="str">''</span> 
  states = [0..source.length]
  rules = (createRule x, source <span class="kwrd">for</span> x <span class="kwrd">in</span> states)
    .concat (createAltRule x, source <span class="kwrd">for</span> x <span class="kwrd">in</span> states)
  createMachine rules, 0, [ source.length ]

testMachine = (input, searchString) -&gt;
  machine = createSearchMachine searchString
  # ...</pre>
<p>I did a little experimenting with this one and I&#8217;m pretty pleased with the results.  Because the character array indexes actually represent the states the search machine can take, we cant just iterate over the characters.  I think the new version makes it clear that the use of the index range is not a mistake.  I also decided to see if I could chain the call to <code>concat</code> right off of the list comprehension and that worked. Then the line was really long, so i decided to see if significant whitespace would prevent me from continuing the statement on the next line, but it worked just fine. Note that the <code>()</code> around the list comprehension are necessary both times. The parenthesis aren&#8217;t part of calling <code>concat</code>, they are part of the list comprehension.</p>
<p>I saved another line by moving <code>finalStates</code> inline, then updated the signature and call site in <code>testMachine</code>.</p>
<h2>Creating Machines</h2>
<p>Here is our current <code>createMachine</code> implementation. I don&#8217;t see any advantage to making it into a class, so I&#8217;ll just clean it up.</p>
<pre class="csharpcode">createMachine = (rules, initialState, finalStates) -&gt;
 {
   currentState: initialState
   transitionRules: rules
   acceptanceStates: finalStates
   read: (c) -&gt;
    <span class="kwrd">for</span> i <span class="kwrd">in</span> [0..<span class="kwrd">this</span>.transitionRules.length - 1]
      <span class="kwrd">if</span> <span class="kwrd">this</span>.transitionRules[i].match <span class="kwrd">this</span>.currentState, c
        <span class="kwrd">return</span> <span class="kwrd">this</span>.currentState = <span class="kwrd">this</span>.transitionRules[i].resultState
   readAll: (s) -&gt; <span class="kwrd">this</span>.read x <span class="kwrd">for</span> x <span class="kwrd">in</span> s.split <span class="str">''</span>
   acceptedInput: () -&gt; <span class="kwrd">this</span>.currentState <span class="kwrd">in</span> <span class="kwrd">this</span>.acceptanceStates
 }</pre>
<p>I got rid of the object properties and captured with closure instead. I also converted the counted loop into a cleaner <code>for..in</code> loop. Finally, I picked some better variable names.</p>
<pre class="csharpcode">createMachine = (transitionRules, currentState, acceptanceStates) -&gt;
  readAll: (input) -&gt; <span class="kwrd">this</span>.read inputChar <span class="kwrd">for</span> inputChar <span class="kwrd">in</span> input.split <span class="str">''</span>
  read: (inputChar) -&gt;
    <span class="kwrd">for</span> rule <span class="kwrd">in</span> transitionRules
      <span class="kwrd">if</span> rule.match currentState, inputChar
        <span class="kwrd">return</span> currentState = rule.resultState  
  acceptedInput: -&gt; currentState <span class="kwrd">in</span> acceptanceStates</pre>
<p>After testing I see that this still works as expected.</p>
<h2>Creating Rules</h2>
<p>Our rule creation is really spread out and contains a bit of duplication:</p>
<pre class="csharpcode">createRule = (index, source) -&gt; {
 initialState: index
 inputChar: source[index]
 resultState: index + 1
 match: (q, c) -&gt; <span class="kwrd">true</span> <span class="kwrd">if</span> (<span class="kwrd">this</span>.initialState == q &amp;&amp; <span class="kwrd">this</span>.inputChar == c)
 }

createAltRule = (index, source) -&gt; 
 <span class="kwrd">if</span> index == source.length
  {
    # trap <span class="kwrd">in</span> acceptance state
    initialState: index
    inputChar: <span class="kwrd">null</span>
    resultState: index
    match: (q, c) -&gt; <span class="kwrd">true</span> <span class="kwrd">if</span> (<span class="kwrd">this</span>.initialState == q) 
  }
 <span class="kwrd">else</span>
  {
    # <span class="kwrd">return</span> to start state
    initialState: index
    inputChar: source[index]
    resultState: 0
    match: (q, c) -&gt; <span class="kwrd">true</span> <span class="kwrd">if</span> (<span class="kwrd">this</span>.initialState == q &amp;&amp; <span class="kwrd">this</span>.inputChar != c)
  }</pre>
<p>Primarily these rules only vary by their method for evaluating <code>match</code>. Our POR (plain old rule) takes an index (which in this case represents a state) and a source string (of which we are only interested in one character) then computes the next state. The match function is true if the passed in state and input character match the stored values. This method can definitely be cleaned up.</p>
<pre class="csharpcode">createRule = (CurrentState, InputChar, NextState) -&gt;
  getNextState: -&gt; NextState
  match: (machineState, inputChar) -&gt;
    machineState <span class="kwrd">is</span> CurrentState and inputChar <span class="kwrd">is</span> InputChar</pre>
<p>With <code>createRule</code> defined this way, we need to make some changes to <code>createSearchMachine</code> so that it passes the needed data, and to <code>createMachine</code> so that it calls <code>getNextState</code>. If the machine is going to query <code>getNextState</code> instead of accessing a property, then the alternate rules will need functions with the same name and semantics.</p>
<pre class="csharpcode">createAltRule = (index, source) -&gt; 
 <span class="kwrd">if</span> index == source.length
  {
    # trap <span class="kwrd">in</span> acceptance state
    initialState: index
    inputChar: <span class="kwrd">null</span>
    resultState: index
    getNextState: -&gt; <span class="preproc">@resultState</span>
    match: (q, c) -&gt; <span class="kwrd">true</span> <span class="kwrd">if</span> (<span class="kwrd">this</span>.initialState == q) 
  }
 <span class="kwrd">else</span>
  {
    # <span class="kwrd">return</span> to start state
    initialState: index
    inputChar: source[index]
    resultState: 0
    getNextState: -&gt; <span class="preproc">@resultState</span>
    match: (q, c) -&gt; <span class="kwrd">true</span> <span class="kwrd">if</span> (<span class="kwrd">this</span>.initialState == q &amp;&amp; <span class="kwrd">this</span>.inputChar != c)
  }</pre>
<p>So I&#8217;m beginning to sense a relationship between the POR and the alternate rules. First, I test the new code and once again find out that it works.  Lets convert <code>createRule</code> into a class, then use the <code>createRule</code> method as a shim to call the constructor.</p>
<pre class="csharpcode"><span class="kwrd">class</span> Rule
  constructor: (@CurrentState, @InputChar, @NextState) -&gt;
  getNextState: =&gt; <span class="preproc">@NextState</span>
  match: (machineState, inputChar) =&gt;
    machineState <span class="kwrd">is</span> <span class="preproc">@CurrentState</span> and inputChar <span class="kwrd">is</span> <span class="preproc">@InputChar</span>

createRule = (CurrentState, InputChar, NextState) -&gt;
  <span class="kwrd">new</span> Rule CurrentState, InputChar, NextState</pre>
<p>The purpose of the shim is just to ensure that we don&#8217;t need to update all the call sites while we are refactoring the rules. With this new code in place, I test and everything still works. Now we can look at extending <code>Rule</code> to take over parts of <code>createAltRule</code>. Lets look at the top half of <code>createAltRule</code> first.</p>
<pre class="csharpcode">createAltRule = (index, source) -&gt; 
 <span class="kwrd">if</span> index == source.length
  {
    # trap <span class="kwrd">in</span> acceptance state
    initialState: index
    inputChar: <span class="kwrd">null</span>
    resultState: index
    getNextState: -&gt; <span class="preproc">@resultState</span>
    match: (q, c) -&gt; <span class="kwrd">true</span> <span class="kwrd">if</span> (<span class="kwrd">this</span>.initialState == q) 
  }</pre>
<p>The purpose of this branch is to define a rule that traps the machine in a certain state. In this case, it will be the acceptance state. If we count the number of characters in the search string, we find a number that represents the machine’s acceptance state.  If we manage to reach that acceptance state, we want to stay in it.  Once we have determined that the source string contains the search string, the machine should accept the input, no matter what the rest of the string says.  The trap state implementation just compares the machine state to the acceptance state, and returns the acceptance state when the machine calls getNextState.</p>
<p>Here is how we can extend <code>Rule</code> to support this.</p>
<pre class="csharpcode"><span class="kwrd">class</span> TrapRule extends Rule
  constructor: (@CurrentState) -&gt;  
    super @CurrentState, <span class="kwrd">null</span>, <span class="preproc">@CurrentState</span>  
  match: (machineState, inputChar) =&gt;
    machineState <span class="kwrd">is</span> <span class="preproc">@CurrentState</span></pre>
<p>The <code>TrapRule</code> class extends <code>Rule</code> by replacing the <code>match</code> implementation with the same logic comparison implemented in the old code. I use <code>super</code> to call the <code>Rule</code> constructor with the <code>@CurrentState</code> value as both the current and next state. I pass <code>null</code> as the character to make it explicit that the input character is not used.</p>
<p>Now we can update the <code>createAltRule</code> function.</p>
<pre class="csharpcode">createAltRule = (index, source) -&gt; 
 <span class="kwrd">if</span> index == source.length
    <span class="kwrd">new</span> TrapRule index
 <span class="kwrd">else</span>
  {
    # <span class="kwrd">return</span> to start state
    initialState: index
    inputChar: source[index]
    resultState: 0
    getNextState: -&gt; <span class="preproc">@resultState</span>
    match: (q, c) -&gt; <span class="kwrd">true</span> <span class="kwrd">if</span> (<span class="kwrd">this</span>.initialState == q &amp;&amp; <span class="kwrd">this</span>.inputChar != c)
  }</pre>
<p>The bottom half of <code>createAltRule</code> describes a &#8220;return rule&#8221;. This rule handles any scenario where the machine reads a character that is not in the search string, and also any scenario where the character <em>is</em> in the search string, but not in the correct position. For example, both of our test strings start with the character <em>W</em>. The return rule would apply because <em>W</em> does not appear in <em>operating system</em>. As the machine reads along it will encounter <em>o</em> at position 5. Finding this character, it will advance from state 0 to state 1. The next character it wants to read is <em>p</em>. But in either test string, <em>p</em> is not the character at position 6. So, the return rule will apply and return the machine to state 0. Without the return rules, the machine could only accept strings that <em>start with</em> the search string, but we want a machine that accept strings which <em>contain</em> the search string. So, the <code>match</code> function looks at the input character passed in by the machine, and matches when the character does <em>not</em> match the stored character, and <code>getNextState</code> always returns <code>0</code>.</p>
<p>Here is a <code>ReturnRule</code> class that implements the same logic.</p>
<pre class="csharpcode"><span class="kwrd">class</span> ReturnRule extends Rule
  constructor: (@CurrentState, @InputChar) -&gt;
    super @CurrentState, @InputChar, 0
  match: (machineState, inputChar) =&gt;
    machineState <span class="kwrd">is</span> <span class="preproc">@CurrentState</span> and inputChar isnt <span class="preproc">@InputChar</span></pre>
<p>And we can reduce our <code>createAltRule</code> method to this:</p>
<pre class="csharpcode">createAltRule = (index, source) -&gt; 
 <span class="kwrd">if</span> index <span class="kwrd">is</span> source.length
    <span class="kwrd">new</span> TrapRule index
 <span class="kwrd">else</span>
    <span class="kwrd">new</span> ReturnRule index, source[index]</pre>
<p>And this works too. Now that we have cleaned up our rules we can see that our shim is only called in one place, and does very little, so we can inline the <code>Rule</code> constructor and delete <code>createRule</code>.</p>
<pre class="csharpcode">createSearchMachine = (searchString) -&gt;
  source = searchString.split <span class="str">''</span> 
  states = [0..source.length]
  rules = (<span class="kwrd">new</span> Rule x, source[x], x + 1 <span class="kwrd">for</span> x <span class="kwrd">in</span> states)
    .concat (createAltRule x, source <span class="kwrd">for</span> x <span class="kwrd">in</span> states)
  createMachine rules, 0, [ source.length ]</pre>
<p>Lets try to get rid of the call to <code>createAltRule</code> with better list comprehension.</p>
<pre class="csharpcode">createSearchMachine = (searchString) -&gt;
  source = searchString.split <span class="str">''</span> 
  states = [0..source.length]
  rules = (<span class="kwrd">new</span> Rule x, source[x], x + 1 <span class="kwrd">for</span> x <span class="kwrd">in</span> states)
    .concat (<span class="kwrd">new</span> ReturnRule x, source[x] <span class="kwrd">for</span> x <span class="kwrd">in</span> states when x isnt source.length)
  createMachine rules, 0, [ source.length ]</pre>
<p>As an intermediate step, I simply filtered out the state that would have led to creating the trap rule and replaced the call to <code>createAltRule</code> with a direct instantiation of <code>ReturnRule</code>. I expect this to fail, but it doesn&#8217;t! Turns our our machine has a bug in it, since I designed it “knowing” that every possible state/character combination would have a rule, I did not handle the case in <code>read</code> where no rules matched. Just to be on the safe side, I&#8217;ll update read by moving the current state to <code>-1</code> when no rules match.  Although it’s conventional to use non-negative integer states when simulating state machines, the truth is that you can use any symbol, positive, negative, or Celtic runes, it’s up to you.  Here is the updated Read implementation:</p>
<pre class="csharpcode">  read: (inputChar) -&gt;
    <span class="kwrd">for</span> rule <span class="kwrd">in</span> transitionRules
      <span class="kwrd">if</span> rule.match currentState, inputChar
        <span class="kwrd">return</span> currentState = rule.getNextState()  
    currentState = -1</pre>
<p>Now, the machine fails as expected. We can repair it by creating the <code>TrapRule</code> and pushing it into the rules collection.</p>
<pre class="csharpcode">createSearchMachine = (searchString) -&gt;
  source = searchString.split <span class="str">''</span> 
  states = [0..source.length]
  rules = (<span class="kwrd">new</span> Rule x, source[x], x + 1 <span class="kwrd">for</span> x <span class="kwrd">in</span> states)
    .concat (<span class="kwrd">new</span> ReturnRule x, source[x] <span class="kwrd">for</span> x <span class="kwrd">in</span> states when x isnt source.length)
  rules.push <span class="kwrd">new</span> TrapRule source.length
  createMachine rules, 0, [ source.length ]</pre>
<p>This works so we can get rid of the <code>createAltRule</code> function.  I made all these changes to the existing <a href="https://gist.github.com/2430336#file_fsm.coffee" target="_blank">gist</a> and I committed a few intermediate steps along the way.  Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ihadthisideaonce.wordpress.com/510/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ihadthisideaonce.wordpress.com/510/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ihadthisideaonce.com&#038;blog=25258562&#038;post=510&#038;subd=ihadthisideaonce&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ihadthisideaonce.com/2012/07/05/implementing-string-contains/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/78c791f5288628576aaba9b64af6ce00?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">magnifico18</media:title>
		</media:content>

		<media:content url="https://lh3.googleusercontent.com/-KCrad3h3oKw/T_ZJgLB4p0I/AAAAAAAACdE/_0K4mDNgvQI/s800/P6100083.JPG" medium="image" />
	</item>
	</channel>
</rss>
