<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-4072716272532023483</atom:id><lastBuildDate>Wed, 07 Mar 2012 14:16:37 +0000</lastBuildDate><category>Visual Studio</category><category>Weaving</category><category>Performance</category><category>MVVM</category><category>Data Structures</category><category>Unit Test</category><category>dynamic</category><category>Easy Wins Optimizations</category><category>.Net</category><category>Code Contracts</category><category>Interception</category><category>F#</category><category>Dynamic Method</category><category>C++</category><category>C#</category><category>Sorted List</category><category>Productivity</category><category>IL</category><category>Agile</category><category>WCF</category><category>Cecil</category><category>Expression</category><category>HashSet</category><category>LINQ-To-SQL</category><category>Mono</category><category>Event</category><title>Theory to Practice to Theory</title><description /><link>http://www.elishalom.com/</link><managingEditor>noreply@blogger.com (Elisha)</managingEditor><generator>Blogger</generator><openSearch:totalResults>17</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/TheoryToPracticeToTheory" /><feedburner:info uri="theorytopracticetotheory" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-4498207737749883684</guid><pubDate>Wed, 22 Feb 2012 19:23:00 +0000</pubDate><atom:updated>2012-02-22T21:23:56.536+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Event</category><category domain="http://www.blogger.com/atom/ns#">IL</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Behind the scenes of events</title><description>&lt;p&gt;Events are a classic implementation of the &lt;a href="http://en.wikipedia.org/wiki/Observer_pattern"&gt;observer pattern&lt;/a&gt;. Support for events syntax exists in many languages, such as C#. In this post we’ll try to understand the internals of events.&lt;/p&gt;  &lt;h2&gt;Delegates background&lt;/h2&gt;  &lt;p&gt;The most abstract way to describe a delegate is a “pointer to a method”. A very relevant feature of delegates is that they can “point” at multiple methods. In order to do so we use the &lt;em&gt;=+&lt;/em&gt; operator and combine to other delegates, for example:&lt;/p&gt;  &lt;pre style="background: black" class="code"&gt;&lt;span style="color: white"&gt;[&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Test&lt;/span&gt;&lt;span style="color: white"&gt;]&lt;br /&gt;&lt;/span&gt;&lt;span style="color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="color: white"&gt;Invoke_TwoDelegatesCombined_BothCalled()&lt;br /&gt;{&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;bool &lt;/span&gt;&lt;span style="color: white"&gt;wasACalled = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;false&lt;/span&gt;&lt;span style="color: white"&gt;;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;bool &lt;/span&gt;&lt;span style="color: white"&gt;wasBCalled = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;false&lt;/span&gt;&lt;span style="color: white"&gt;;&lt;br /&gt;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #6897bb"&gt;Action &lt;/span&gt;&lt;span style="color: white"&gt;delA = () =&amp;gt; wasACalled = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;true&lt;/span&gt;&lt;span style="color: white"&gt;;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #6897bb"&gt;Action &lt;/span&gt;&lt;span style="color: white"&gt;delB = () =&amp;gt; wasBCalled = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;true&lt;/span&gt;&lt;span style="color: white"&gt;;&lt;br /&gt;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #6897bb"&gt;Action &lt;/span&gt;&lt;span style="color: white"&gt;combine = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;null&lt;/span&gt;&lt;span style="color: white"&gt;;&lt;br /&gt;    combine += delA;&lt;br /&gt;    combine += delB;&lt;br /&gt;&lt;br /&gt;    combine.Invoke();&lt;br /&gt;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Assert&lt;/span&gt;&lt;span style="color: white"&gt;.That(wasACalled);&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Assert&lt;/span&gt;&lt;span style="color: white"&gt;.That(wasBCalled);&lt;br /&gt;}&lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;But, what actually happens here? Let’s take a look at this code:&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;&lt;span style="color: white"&gt;combine += delA;&lt;/span&gt;&lt;/pre&gt;This code compiles to the following IL:&lt;pre style="background: black" class="code"&gt;IL_0031: ldloc.2&lt;br /&gt;IL_0032: ldloc.0&lt;br /&gt;IL_0033: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)&lt;br /&gt;IL_0038: castclass [mscorlib]System.Action&lt;br /&gt;IL_003d: stloc.2&lt;/pre&gt;&lt;p&gt;Which is equivalent to:&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;&lt;span style="color: white"&gt;combine = &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Delegate&lt;/span&gt;&lt;span style="color: white"&gt;.Combine(combine, delA);&lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;The result of the compiled code is direct call to &lt;a href="http://msdn.microsoft.com/en-us/library/b1eh4771.aspx"&gt;&lt;em&gt;Delegate.Combine&lt;/em&gt;&lt;/a&gt;, which makes any future call to the combined result forwarded to both delegates.&lt;/p&gt;&lt;h2&gt;Default event&lt;/h2&gt;&lt;p&gt;If we use default event implementation, the compiler generates two methods and a backing field. The backing field is a delegate storing the subscribers, the methods are add and remove the subscribers from the delegate. This implementations allows us to add and remove subscribers for whom the event is visible and raise the event from the type itself. For example:&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;&lt;span style="color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Publisher&lt;br /&gt;&lt;/span&gt;&lt;span style="color: white"&gt;{&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public event &lt;/span&gt;&lt;span style="color: #6897bb"&gt;EventHandler &lt;/span&gt;&lt;span style="color: white"&gt;MyEvent;&lt;br /&gt;&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="color: white"&gt;Publish()&lt;br /&gt;    {&lt;br /&gt;        MyEvent(&lt;/span&gt;&lt;span style="color: #cc7832"&gt;this&lt;/span&gt;&lt;span style="color: white"&gt;, &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;EventArgs&lt;/span&gt;&lt;span style="color: white"&gt;.Empty);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;The event compiles into a field, which is a delegate of the event type:&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;&lt;span style="color: white"&gt;.field private class [mscorlib]System.EventHandler MyEvent&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;And into two methods for adding and removing subscribers:&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;.event [mscorlib]System.EventHandler MyEvent&lt;br /&gt;{&lt;br /&gt;    .addon instance void Events.Publisher::add_MyEvent(class [mscorlib]System.EventHandler)&lt;br /&gt;    .removeon instance void Events.Publisher::remove_MyEvent(class [mscorlib]System.EventHandler)&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;With the signatures:&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;.method public hidebysig specialname &lt;br /&gt; instance void add_MyEvent (&lt;br /&gt;  class [mscorlib]System.EventHandler 'value'&lt;br /&gt; ) cil managed&lt;br /&gt;&lt;br /&gt;.method public hidebysig specialname &lt;br /&gt; instance void remove_MyEvent (&lt;br /&gt;  class [mscorlib]System.EventHandler 'value'&lt;br /&gt; ) cil managed&lt;/pre&gt;&lt;p&gt;The bodies of the events, not surprisingly, manipulates the backing field, we can ignore the bodies for now.&lt;/p&gt;&lt;p&gt;So up to here we see what the declaration of event compiles into – an event declaration, a backing field which is a delegate of the event type and two methods for adding and removing subscribers. All this magic for single C# line of code.&lt;/p&gt;&lt;p&gt;The other side of the event is what happens as we raise it. The event can be raised only from within the type that declares it. For example:&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;&lt;span style="color: white"&gt;MyEvent(&lt;/span&gt;&lt;span style="color: #cc7832"&gt;this&lt;/span&gt;&lt;span style="color: white"&gt;, &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;EventArgs&lt;/span&gt;&lt;span style="color: white"&gt;.Empty);&lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;Compiles into:&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;IL_0000: nop&lt;br /&gt;IL_0001: ldarg.0&lt;br /&gt;IL_0002: ldfld class [mscorlib]System.EventHandler Events.Publisher::MyEvent&lt;br /&gt;IL_0007: ldarg.0&lt;br /&gt;IL_0008: ldsfld class [mscorlib]System.EventArgs [mscorlib]System.EventArgs::Empty&lt;br /&gt;IL_000d: callvirt instance void [mscorlib]System.EventHandler::Invoke(object, class [mscorlib]System.EventArgs)&lt;/pre&gt;&lt;p&gt;All this code does is accessing the delegate backing field and invoking it.&lt;/p&gt;&lt;h2&gt;Custom event&lt;/h2&gt;&lt;p&gt;In fact, the event is not custom but the add/remove methods are. Custom add/remove for events is a feature in C# which I think is not very commonly used (in contrast to properties). It allows the developer provide an alternative implementation to the event subscription.&lt;/p&gt;&lt;pre style="background: black" class="code"&gt;&lt;span style="color: #cc7832"&gt;public event &lt;/span&gt;&lt;span style="color: #6897bb"&gt;EventHandler &lt;/span&gt;&lt;span style="color: white"&gt;MyCustomEvent&lt;br /&gt;{&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;add &lt;/span&gt;&lt;span style="color: white"&gt;{}&lt;br /&gt;    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;remove &lt;/span&gt;&lt;span style="color: white"&gt;{ }&lt;br /&gt;}&lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;The compiled class in this case does not contain a backing field. It contains the declaration of the event and the two methods with the custom provided body.&lt;/p&gt;&lt;p&gt;A difference which derived from the compiled code difference is that there’s no way to raise the event directly. This makes sense since the custom code can do many things (or nothing) with the subscribers and not store them in a common place for later invocation. If we’d try to raise &lt;em&gt;MyCystomEvent&lt;/em&gt; in the same way we tried to raise &lt;em&gt;MyEvent&lt;/em&gt; we’ll get a compilation error.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-4498207737749883684?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=7Nc8eTpQam0:-PKI-oZCGyo:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=7Nc8eTpQam0:-PKI-oZCGyo:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/7Nc8eTpQam0" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/7Nc8eTpQam0/behind-scenes-of-events.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>2</thr:total><feedburner:origLink>http://www.elishalom.com/2012/02/behind-scenes-of-events.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-6412729671228319761</guid><pubDate>Sun, 19 Feb 2012 21:08:00 +0000</pubDate><atom:updated>2012-02-19T23:08:01.540+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">dynamic</category><category domain="http://www.blogger.com/atom/ns#">IL</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">Dynamic Method</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">Performance</category><title>Retrieving property value by name using dynamic method</title><description>In the &lt;a href="http://eli-shalom.blogspot.com/2012/02/performance-of-dynamic-keyword.html"&gt;previous post&lt;/a&gt; we compared some alternatives of the dynamic keyword. One important alternative which is very interesting is based on &lt;a href="http://msdn.microsoft.com/en-us/library/3y322t50.aspx"&gt;reflection emit&lt;/a&gt;. Reflection emit enables us to generate code using IL at runtime, compile it and execute it right away.&lt;br /&gt;
In this post we’ll see how to extract from an unknown type a string property named &lt;em&gt;‘Name’&lt;/em&gt; using a &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx"&gt;dynamic method&lt;/a&gt;.&lt;br /&gt;
&lt;h2&gt;
The code&lt;/h2&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public static string &lt;/span&gt;&lt;span style="color: white;"&gt;GetNameByDynamicMethod(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object &lt;/span&gt;&lt;span style="color: white;"&gt;arg)
{
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Type &lt;/span&gt;&lt;span style="color: white;"&gt;type = arg.GetType();

    &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Func&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; getterDelegate;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(!typeToEmitDelegateMap.TryGetValue(type, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;out &lt;/span&gt;&lt;span style="color: white;"&gt;getterDelegate))
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;typeName = type.Name;

        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;PropertyInfo &lt;/span&gt;&lt;span style="color: white;"&gt;nameProperty = type.GetProperty(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"Name"&lt;/span&gt;&lt;span style="color: white;"&gt;);
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Type &lt;/span&gt;&lt;span style="color: white;"&gt;returnType = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;);
                
        &lt;/span&gt;&lt;span style="color: grey;"&gt;// Define a new dynamic method
        // The method returns a string type
        // The method expects single parameter
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;method = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;DynamicMethod&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"GetNameFrom" &lt;/span&gt;&lt;span style="color: white;"&gt;+ typeName, 
                                       returnType, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new&lt;/span&gt;&lt;span style="color: white;"&gt;[] {&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object&lt;/span&gt;&lt;span style="color: white;"&gt;)});
                
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;ILGenerator &lt;/span&gt;&lt;span style="color: white;"&gt;ilGenerator = method.GetILGenerator();

        &lt;/span&gt;&lt;span style="color: grey;"&gt;// Load to the stack the first method argument.
        //In our case, this is an object whose type we already know
        &lt;/span&gt;&lt;span style="color: white;"&gt;ilGenerator.Emit(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Ldarg_0);
        
        &lt;/span&gt;&lt;span style="color: grey;"&gt;// Cast the object to the type we already know
        &lt;/span&gt;&lt;span style="color: white;"&gt;ilGenerator.Emit(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Castclass, type);

        &lt;/span&gt;&lt;span style="color: grey;"&gt;// Call the getter method on the casted instance
        &lt;/span&gt;&lt;span style="color: white;"&gt;ilGenerator.EmitCall(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Call, nameProperty.GetGetMethod(), &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;);

        &lt;/span&gt;&lt;span style="color: grey;"&gt;// Return the value from Name property
        &lt;/span&gt;&lt;span style="color: white;"&gt;ilGenerator.Emit(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Ret);

        &lt;/span&gt;&lt;span style="color: grey;"&gt;// Compile the method and create a delegate to the new method
        &lt;/span&gt;&lt;span style="color: white;"&gt;getterDelegate = (&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Func&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt;)method.CreateDelegate(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Func&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt;));

        typeToEmitDelegateMap.Add(type, getterDelegate);
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;getterDelegate(arg);
}&lt;/span&gt;&lt;/pre&gt;
What we did here was to define a new method, generate its code with IL, compile it and execute it. This new method is equivalent in many ways to a method we’d generate in the original program. This new method will be hosted in a dynamic module in the memory.&lt;br /&gt;
&lt;br /&gt;
The advantage of this kind of method over reflection is that compiles the code once and doesn’t need to explore the type again any time we need to get the property value.&lt;br /&gt;
&lt;h2&gt;Performance&lt;/h2&gt;
A quick comparison for calling these alternatives 10,000,000 times each:&lt;br /&gt;
&lt;table border="1" cellpadding="2" cellspacing="0" style="width: 400px;"&gt;&lt;tbody&gt;
&lt;tr&gt;      &lt;td valign="top" width="134"&gt;&lt;/td&gt;      &lt;td valign="top" width="132"&gt;&lt;strong&gt;Seconds&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="132"&gt;&lt;strong&gt;Ratio to directly&lt;/strong&gt;&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="134"&gt;&lt;strong&gt;Directly&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="132"&gt;0.0131&lt;/td&gt;      &lt;td valign="top" width="132"&gt;1&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="134"&gt;&lt;strong&gt;Dynamic&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="132"&gt;0.4609&lt;/td&gt;      &lt;td valign="top" width="132"&gt;35&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="134"&gt;&lt;strong&gt;Expression&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="132"&gt;0.9154&lt;/td&gt;      &lt;td valign="top" width="132"&gt;70&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="134"&gt;&lt;strong&gt;Reflection emit&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="132"&gt;0.9832&lt;/td&gt;      &lt;td valign="top" width="132"&gt;75&lt;/td&gt;    &lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
As can be seen, using the dynamic keyword works much faster than compiling an expression or a dynamic method at runtime.&lt;br /&gt;
&lt;br /&gt;
Another interesting data is the time that each alternative takes to set up (The time to perform the first call):&lt;br /&gt;
&lt;table border="1" cellpadding="2" cellspacing="0" style="width: 362px;"&gt;&lt;tbody&gt;
&lt;tr&gt;      &lt;td valign="top" width="200"&gt;&lt;/td&gt;      &lt;td valign="top" width="160"&gt;&lt;strong&gt;Seconds&lt;/strong&gt;&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="220"&gt;&lt;strong&gt;Directly&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="169"&gt;0.00003&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="224"&gt;&lt;strong&gt;Dynamic&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="172"&gt;0.08047&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="224"&gt;&lt;strong&gt;Expression&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="174"&gt;0.00114&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="223"&gt;&lt;strong&gt;Reflection emit&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="175"&gt;0.02169&lt;/td&gt;    &lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-6412729671228319761?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=QfAtj3a4_10:DMSMEJHQACI:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=QfAtj3a4_10:DMSMEJHQACI:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/QfAtj3a4_10" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/QfAtj3a4_10/retrieving-property-value-by-name-using.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2012/02/retrieving-property-value-by-name-using.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-8565199585237089091</guid><pubDate>Fri, 17 Feb 2012 11:33:00 +0000</pubDate><atom:updated>2012-02-18T08:50:40.431+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">dynamic</category><category domain="http://www.blogger.com/atom/ns#">Expression</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">Performance</category><title>Performance of the dynamic keyword</title><description>In .NET 4.0 a new keyword was introduced, the &lt;em&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd264741.aspx"&gt;dynamic&lt;/a&gt;&lt;/em&gt; keyword. One of the things it enables is calling methods on an instance and bypassing the compile time type checks. It can be useful in many scenarios such as duck typing.&lt;br /&gt;
In this post, we’ll see that in some cases the keyword might have an unnecessary performance hit. Another thing we’ll see is how to save some of that time.
&lt;br /&gt;
&lt;h2&gt;Simple performance measure&lt;/h2&gt;
Let’s compare the performance of 3 versions for getting a property value - directly, using dynamic and using reflection:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public static string &lt;/span&gt;&lt;span style="color: white;"&gt;GetName(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Student &lt;/span&gt;&lt;span style="color: white;"&gt;arg)
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;arg.Name;
}
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static string &lt;/span&gt;&lt;span style="color: white;"&gt;GetNameByDynamic(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;dynamic &lt;/span&gt;&lt;span style="color: white;"&gt;arg)
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;arg.Name;
}
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static string &lt;/span&gt;&lt;span style="color: white;"&gt;GetNameByReflection(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object &lt;/span&gt;&lt;span style="color: white;"&gt;arg)
{
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Type &lt;/span&gt;&lt;span style="color: white;"&gt;type = arg.GetType();

    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodInfo &lt;/span&gt;&lt;span style="color: white;"&gt;getter;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(!typeToMethodMap.TryGetValue(type, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;out &lt;/span&gt;&lt;span style="color: white;"&gt;getter))
    {
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;PropertyInfo &lt;/span&gt;&lt;span style="color: white;"&gt;property = type.GetProperty(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"Name"&lt;/span&gt;&lt;span style="color: white;"&gt;);
        getter = property.GetGetMethod();
        typeToMethodMap.Add(type, getter);
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;) getter.Invoke(arg, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;);
}&lt;/span&gt;&lt;/pre&gt;
Calling each method 10,000,000 times sums to: &lt;em&gt;GetName=0.02 seconds, GetNameByDynamic=0.47 seconds, GetNameByReflection=15.41. &lt;/em&gt;Meaning, dynamic compared to strong type call is ~20 times slower.
&lt;br /&gt;
&lt;h2&gt;Improving performance using interface&lt;/h2&gt;
One way to deal with this performance hit is to extract an interface from all possible objects, using it, we can get back working with strong type:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public interface &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;INameProvider&lt;/span&gt;&lt;span style="color: white;"&gt;{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;Name { &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;get&lt;/span&gt;&lt;span style="color: white;"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;set&lt;/span&gt;&lt;span style="color: white;"&gt;; }
}&lt;/span&gt;&lt;/pre&gt;
And change our method to:
&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public static string &lt;/span&gt;&lt;span style="color: white;"&gt;GetNameByInterface(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;INameProvider &lt;/span&gt;&lt;span style="color: white;"&gt;arg)
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;arg.Name;
}&lt;/span&gt;&lt;/pre&gt;
Luckily this code run at 0.07 seconds, which is ~7 times faster than the dynamic version. The conclusion from this is that if our code is in critical performance area, we better extract an interface (as long as it makes sense – don’t abuse the interface if the types has no logical commonality!).
&lt;br /&gt;
&lt;h2&gt;Improving reflection version using expressions&lt;/h2&gt;
What should we do if our code is written in pre-.NET 4.0 version and our solution based on reflection? In this case, our code runs ~750 times slower than the strong type version. Since we can’t use &lt;em&gt;dynamic,&lt;/em&gt; which was introduced first at .NET 4.0, we should find some other solution. A simple one is generating a method using &lt;a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx"&gt;expressions&lt;/a&gt;. The main advantage of expressions here is that they can be compiled into a new method which we can reuse.
&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public static string &lt;/span&gt;&lt;span style="color: white;"&gt;GetNameByExpression(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object &lt;/span&gt;&lt;span style="color: white;"&gt;arg)
{
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Type &lt;/span&gt;&lt;span style="color: white;"&gt;type = arg.GetType();

    &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Func&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; getterDelegate;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(!typeToDelegateMap.TryGetValue(type, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;out &lt;/span&gt;&lt;span style="color: white;"&gt;getterDelegate))
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;parameterExpression = &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Expression&lt;/span&gt;&lt;span style="color: white;"&gt;.Parameter(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object&lt;/span&gt;&lt;span style="color: white;"&gt;), &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"arg"&lt;/span&gt;&lt;span style="color: white;"&gt;);
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;castExpression = &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Expression&lt;/span&gt;&lt;span style="color: white;"&gt;.TypeAs(parameterExpression, type);
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MemberExpression &lt;/span&gt;&lt;span style="color: white;"&gt;memberExpression = &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Expression&lt;/span&gt;&lt;span style="color: white;"&gt;.Property(castExpression, &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"Name"&lt;/span&gt;&lt;span style="color: white;"&gt;);
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;lambda = &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Expression&lt;/span&gt;&lt;span style="color: white;"&gt;.Lambda&amp;lt;&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Func&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt;&amp;gt;(memberExpression, parameterExpression);

        getterDelegate = lambda.Compile();
        typeToDelegateMap.Add(type, getterDelegate);
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;getterDelegate(arg);
}&lt;/span&gt;&lt;/pre&gt;
This code here is basically equivalent to generating a lambda which looks like:
&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;object &lt;/span&gt;&lt;span style="color: white;"&gt;arg) =&amp;gt; ((&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Student&lt;/span&gt;&lt;span style="color: white;"&gt;)arg).Name;&lt;/span&gt;&lt;/pre&gt;
Since we compile the code once we can skip the reflection invocation each time and end with much faster code. Running this method times 10,000,000 takes 0.86 seconds, which is ~18 times faster than the reflection solution.
&lt;br /&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
If you writing code which must run as fast as possible, this is the performance summary:&lt;br /&gt;
&lt;br /&gt;
&lt;table border="1" cellpadding="2" cellspacing="0" style="width: 400px;"&gt;&lt;tbody&gt;
&lt;tr&gt;      &lt;td valign="top" width="144"&gt;&lt;/td&gt;      &lt;td valign="top" width="122"&gt;&lt;strong&gt;Seconds&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="132"&gt;&lt;strong&gt;Ratio to directly&lt;/strong&gt;&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="144"&gt;&lt;strong&gt;Directly&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="122"&gt;0.02&lt;/td&gt;      &lt;td valign="top" width="132"&gt;1&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="144"&gt;&lt;strong&gt;Through interface&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="122"&gt;0.07&lt;/td&gt;      &lt;td valign="top" width="132"&gt;3.5&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="144"&gt;&lt;strong&gt;Using dynamic&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="122"&gt;0.47&lt;/td&gt;      &lt;td valign="top" width="132"&gt;23.5&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="144"&gt;&lt;strong&gt;Using expression&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="122"&gt;0.86&lt;/td&gt;      &lt;td valign="top" width="132"&gt;43&lt;/td&gt;    &lt;/tr&gt;
&lt;tr&gt;      &lt;td valign="top" width="144"&gt;&lt;strong&gt;Reflection&lt;/strong&gt;&lt;/td&gt;      &lt;td valign="top" width="122"&gt;15.41&lt;/td&gt;      &lt;td valign="top" width="132"&gt;770&lt;/td&gt;    &lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-8565199585237089091?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=6JnG1Gr4YHU:P5IHv92t6fA:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=6JnG1Gr4YHU:P5IHv92t6fA:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/6JnG1Gr4YHU" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/6JnG1Gr4YHU/performance-of-dynamic-keyword.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>2</thr:total><feedburner:origLink>http://www.elishalom.com/2012/02/performance-of-dynamic-keyword.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-3081590894130258526</guid><pubDate>Sat, 04 Feb 2012 20:58:00 +0000</pubDate><atom:updated>2012-02-18T08:56:40.927+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Weaving</category><category domain="http://www.blogger.com/atom/ns#">IL</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">Mono</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">Cecil</category><title>Monitoring execution using Mono Cecil</title><description>This post will demonstrate how to monitor the execution of .Net code using Mono Cecil. This can be useful for logging, for performance analysis and mainly for fun. The concept is obviously IL weaving. We’ll look for entry points and existing IL instructions to weave around the new IL. In this post we’ll show only four types of monitoring, in reality we have some more. The four types are: Enter method, Exit method, Jump from method and Jump back to method. Jump in this context means call other method and return from other method.&lt;br /&gt;
In our example we’ll assume we have some simple ‘notifier’ which the weaved code will call:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public class &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Notifier&lt;/span&gt;
&lt;span style="color: white;"&gt;{&lt;/span&gt;
&lt;span style="color: white;"&gt;    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Action&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; Enter;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Action&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; Exit;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Action&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; JumpOut;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;Action&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; JumpBack;

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static void &lt;/span&gt;&lt;span style="color: white;"&gt;NotifyEnter(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;methodName)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(Enter != &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;)
        {
            Enter(methodName);
        }
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static void &lt;/span&gt;&lt;span style="color: white;"&gt;NotifyExit(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;methodName)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(Exit != &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;)
        {
            Exit(methodName);
        }
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static void &lt;/span&gt;&lt;span style="color: white;"&gt;NotifyJumpOut(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;methodName)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(JumpOut != &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;)
        {
            JumpOut(methodName);
        }
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static void &lt;/span&gt;&lt;span style="color: white;"&gt;NotifyJumpBack(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;methodName)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(JumpBack != &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;)
        {
            JumpBack(methodName);
        }
    }
}&lt;/span&gt;&lt;/pre&gt;
&lt;h2&gt;Monitoring enter&lt;/h2&gt;
This is the most trivial weave, this one inserts before the first instruction in the method body a call to &lt;em&gt;Enter&lt;/em&gt; callback. In order to do so, we need first to load the assembly and find all the methods into which we can weave:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public void &lt;/span&gt;&lt;span style="color: white;"&gt;Weave()
{
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;AssemblyDefinition &lt;/span&gt;&lt;span style="color: white;"&gt;assembly = &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;AssemblyDefinition&lt;/span&gt;&lt;span style="color: white;"&gt;.ReadAssembly(assemblyPath);

    &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IEnumerable&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodDefinition&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; methodDefinitions = assembly.MainModule.GetTypes()
        .SelectMany(type =&amp;gt; type.Methods).Where(method =&amp;gt; method.HasBody);
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;foreach &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;method &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;in &lt;/span&gt;&lt;span style="color: white;"&gt;methodDefinitions)
    {
        WeaveMethod(assembly, method);
    }

    assembly.Write(assemblyPath);
}&lt;/span&gt;&lt;/pre&gt;
Now we add reference into the weaved assembly to the callbacks. This is not yet the weaving, this is required definition for the assembly to use in the weaved assembly. We’ll get the called methods using reflection:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #ffc66d;"&gt;Type &lt;/span&gt;&lt;span style="color: white;"&gt;notifierType = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Notifier&lt;/span&gt;&lt;span style="color: white;"&gt;);
enterMethod = notifierType.GetMethod(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"NotifyEnter"&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;BindingFlags&lt;/span&gt;&lt;span style="color: white;"&gt;.Public | &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;BindingFlags&lt;/span&gt;&lt;span style="color: white;"&gt;.Static, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new&lt;/span&gt;&lt;span style="color: white;"&gt;[] {&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;)}, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;);
exitMethod = notifierType.GetMethod(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"NotifyExit"&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;BindingFlags&lt;/span&gt;&lt;span style="color: white;"&gt;.Public | &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;BindingFlags&lt;/span&gt;&lt;span style="color: white;"&gt;.Static, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new&lt;/span&gt;&lt;span style="color: white;"&gt;[] {&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;)}, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;);
jumpFromMethod = notifierType.GetMethod(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"NotifyJumpOut"&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;BindingFlags&lt;/span&gt;&lt;span style="color: white;"&gt;.Public | &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;BindingFlags&lt;/span&gt;&lt;span style="color: white;"&gt;.Static, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new&lt;/span&gt;&lt;span style="color: white;"&gt;[] {&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;)}, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;);
jumpBackMethod = notifierType.GetMethod(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"NotifyJumpBack"&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;BindingFlags&lt;/span&gt;&lt;span style="color: white;"&gt;.Public | &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;BindingFlags&lt;/span&gt;&lt;span style="color: white;"&gt;.Static, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new&lt;/span&gt;&lt;span style="color: white;"&gt;[] {&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;)}, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;);&lt;/span&gt;&lt;/pre&gt;
Afterwards, we’ll add the references to the weaved assembly:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;enterReference = assembly.MainModule.Import(enterMethod);&lt;/span&gt;
&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;exitReference = assembly.MainModule.Import(exitMethod);&lt;/span&gt;
&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;jumpFromReference = assembly.MainModule.Import(jumpFromMethod);&lt;/span&gt;
&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;jumpBackReference = assembly.MainModule.Import(jumpBackMethod);&lt;/span&gt;&lt;/pre&gt;
So our weave method looks like:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;private static void &lt;/span&gt;&lt;span style="color: white;"&gt;WeaveMethod(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;AssemblyDefinition &lt;/span&gt;&lt;span style="color: white;"&gt;assembly, &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodDefinition &lt;/span&gt;&lt;span style="color: white;"&gt;method)
{
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;enterReference = assembly.MainModule.Import(enterMethod);
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;exitReference = assembly.MainModule.Import(exitMethod);
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;jumpFromReference = assembly.MainModule.Import(jumpFromMethod);
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;jumpBackReference = assembly.MainModule.Import(jumpBackMethod);

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;name = method.DeclaringType.FullName + &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"." &lt;/span&gt;&lt;span style="color: white;"&gt;+ method.Name;
            
    WeaveEnter(method, enterReference, name);
    WeaveJump(method, jumpFromReference, jumpBackReference, name);
    WeaveExit(method, exitReference, name);
}&lt;/span&gt;&lt;/pre&gt;
Now, we have everything ready to weave the enter monitoring code:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;private static void &lt;/span&gt;&lt;span style="color: white;"&gt;WeaveEnter(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodDefinition &lt;/span&gt;&lt;span style="color: white;"&gt;method, &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;methodReference, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;name)
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;ilProcessor = method.Body.GetILProcessor();

    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction &lt;/span&gt;&lt;span style="color: white;"&gt;loadNameInstruction = ilProcessor.Create(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Ldstr, name);
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction &lt;/span&gt;&lt;span style="color: white;"&gt;callEnterInstruction = ilProcessor.Create(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Call, methodReference);

    ilProcessor.InsertBefore(method.Body.Instructions.First(), loadNameInstruction);
    ilProcessor.InsertAfter(loadNameInstruction, callEnterInstruction);
}&lt;/span&gt;&lt;/pre&gt;
The &lt;em&gt;ILProcessor&lt;/em&gt; is a helper utility which &lt;em&gt;Cecil&lt;/em&gt; provides to make the weaving simpler. The first instruction we weave is loading of a string which is the name of the method being entered. The second instruction we weave is a call instruction which uses as argument the loaded string. We insert the instructions in the beginning of the method and from now on every time the method is entered the callback will be invoked.&lt;br /&gt;
&lt;h2&gt;Monitoring exit&lt;/h2&gt;
Monitoring exit is a little more interesting. In contrast to enter where we have single weaving point, exit may have multiple exit points – multiple return statements, thrown exceptions, etc…&lt;br /&gt;
Here we’ll monitor for simplicity return statements only:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;private static void &lt;/span&gt;&lt;span style="color: white;"&gt;WeaveExit(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodDefinition &lt;/span&gt;&lt;span style="color: white;"&gt;method, &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;exitReference, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;name)
{
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;ILProcessor &lt;/span&gt;&lt;span style="color: white;"&gt;ilProcessor = method.Body.GetILProcessor();

    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;List&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; returnInstructions = method.Body.Instructions.Where(instruction =&amp;gt; instruction.OpCode == &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Ret).ToList();
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;foreach &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;returnInstruction &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;in &lt;/span&gt;&lt;span style="color: white;"&gt;returnInstructions)
    {
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction &lt;/span&gt;&lt;span style="color: white;"&gt;loadNameInstruction = ilProcessor.Create(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Ldstr, name);
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction &lt;/span&gt;&lt;span style="color: white;"&gt;callExitReference = ilProcessor.Create(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Call, exitReference);

        ilProcessor.InsertBefore(returnInstruction, loadNameInstruction);
        ilProcessor.InsertAfter(loadNameInstruction, callExitReference);
    }
}&lt;/span&gt;&lt;/pre&gt;
As can be seen, we first find all the return instructions. Afterwards, we insert before them call to our callback in a similar way to the enter callback.&lt;br /&gt;
&lt;h2&gt;Monitoring method jumps&lt;/h2&gt;
This monitoring type will enable us knowing when we jump to another method. If we are doing performance measuring, in “ideal” world (where we have single thread and no context switches) this would be the place where we stop and resume measuring the time for the executed method. Here for simplicity we’ll weave around simple &lt;em&gt;call&lt;/em&gt; instructions, ignoring other types of call (like &lt;em&gt;callvirt&lt;/em&gt;).
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;private static void &lt;/span&gt;&lt;span style="color: white;"&gt;WeaveJump(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodDefinition &lt;/span&gt;&lt;span style="color: white;"&gt;method, &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;jumpFromReference, &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodReference &lt;/span&gt;&lt;span style="color: white;"&gt;jumpBackReference, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;name)
{
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;ILProcessor &lt;/span&gt;&lt;span style="color: white;"&gt;ilProcessor = method.Body.GetILProcessor();

    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;List&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt; callInstructions = method.Body.Instructions.Where(instruction =&amp;gt; instruction.OpCode == &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Call).ToList();
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;foreach &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;callInstruction &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;in &lt;/span&gt;&lt;span style="color: white;"&gt;callInstructions)
    {
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction &lt;/span&gt;&lt;span style="color: white;"&gt;loadNameForFromInstruction = ilProcessor.Create(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Ldstr, name);
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction &lt;/span&gt;&lt;span style="color: white;"&gt;callJumpFromInstruction = ilProcessor.Create(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Call, jumpFromReference);

        ilProcessor.InsertBefore(callInstruction, loadNameForFromInstruction);
        ilProcessor.InsertAfter(loadNameForFromInstruction, callJumpFromInstruction);

        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction &lt;/span&gt;&lt;span style="color: white;"&gt;loadNameForBackInstruction = ilProcessor.Create(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Ldstr, name);
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Instruction &lt;/span&gt;&lt;span style="color: white;"&gt;callJumpBackInstruction = ilProcessor.Create(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;OpCodes&lt;/span&gt;&lt;span style="color: white;"&gt;.Call, jumpBackReference);

        ilProcessor.InsertAfter(callInstruction, loadNameForBackInstruction);
        ilProcessor.InsertAfter(loadNameForBackInstruction, callJumpBackInstruction);
    }
}&lt;/span&gt;&lt;/pre&gt;
Here, we find all the &lt;em&gt;call&lt;/em&gt; instructions and insert before them a call to &lt;em&gt;JumpFrom&lt;/em&gt; and after them call to &lt;em&gt;JumpBack&lt;/em&gt;. This way we get a call before leaving and returning to the method.&lt;br /&gt;
&lt;h2&gt;Example&lt;/h2&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public void &lt;/span&gt;&lt;span style="color: white;"&gt;MethodA()
{
    MethodB();
}&lt;/span&gt;&lt;/pre&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private void &lt;/span&gt;&lt;span style="color: white;"&gt;MethodB()
{
}&lt;/span&gt;&lt;/pre&gt;
If we execute &lt;em&gt;MethodA&lt;/em&gt; we’re about the receive these calls:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Enter MethodA&lt;/li&gt;
&lt;li&gt;JumpFrom MethodA&lt;/li&gt;
&lt;li&gt;Enter MethodB&lt;/li&gt;
&lt;li&gt;Exit MethodB&lt;/li&gt;
&lt;li&gt;JumpBack MethodA&lt;/li&gt;
&lt;li&gt;ExitMethod A&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
Mono Cecil can be used for low level AOP where the aspects targets are IL instructions. There are already some great tools out there for AOP like &lt;a href="http://www.sharpcrafters.com/"&gt;PostSharp&lt;/a&gt;, but it is cool to know how simply a solution can be implemented using Cecil.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-3081590894130258526?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=mN-RBfC787k:_g-1yjEVHZI:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=mN-RBfC787k:_g-1yjEVHZI:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/mN-RBfC787k" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/mN-RBfC787k/monitoring-execution-using-mono-cecil.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>4</thr:total><feedburner:origLink>http://www.elishalom.com/2012/02/monitoring-execution-using-mono-cecil.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-4795793038685378755</guid><pubDate>Fri, 18 Nov 2011 16:05:00 +0000</pubDate><atom:updated>2012-02-18T09:03:38.750+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">IL</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>The synchronized keyword</title><description>&lt;h2&gt;What is does&lt;/h2&gt;
A not very known feature of .NET is the &lt;em&gt;synchronized &lt;/em&gt;keyword. The keyword can be used on methods and it ensures:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Instance method – can be executed in single thread on the instance (different instances are not synchronized). Equivalent to &lt;em&gt;lock(this).&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;Static method – can be executed in single thread. Equivalent to &lt;em&gt;lock(typeof(TypeName))&lt;/em&gt;. &lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Usage in C#&lt;/h2&gt;
If you’ll look at the C# specification you’ll see that there’s no mention to this keyword. The reason is that the keyword is an IL keyword and not a C# one. In order to instruct the compiler to mark the method as synchronized we can use the &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimplattribute.aspx"&gt;&lt;em&gt;MethodImplAttibute&lt;/em&gt;&lt;/a&gt;&lt;em&gt;&amp;nbsp;&lt;/em&gt;with &lt;em&gt;Synchronized &lt;/em&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx"&gt;&lt;em&gt;MethodImplOptions&lt;/em&gt;&lt;/a&gt;. For example:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;[&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MethodImpl&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;MethodImplOptions&lt;/span&gt;&lt;span style="color: white;"&gt;.Synchronized)]
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public void &lt;/span&gt;&lt;span style="color: white;"&gt;MethodWithSyncAttribute()
{
}
&lt;/span&gt;&lt;/pre&gt;
&lt;h2&gt;The IL result&lt;/h2&gt;
&lt;h3&gt;Using &lt;em&gt;synchronized&lt;/em&gt; keyword&lt;/h3&gt;
The &lt;em&gt;MethodWithSyncAttribute()&lt;/em&gt; looks in IL:&lt;br /&gt;
&lt;blockquote&gt;
&lt;span style="font-family: 'Courier New';"&gt;.method public hidebysig instance void&amp;nbsp; MethodWithSyncAttribute() cil managed synchronized 
      &lt;br /&gt;{ 

      &lt;br /&gt;&amp;nbsp; // Code size&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 2 (0x2) 

      &lt;br /&gt;&amp;nbsp; .maxstack&amp;nbsp; 8 

      &lt;br /&gt;&amp;nbsp; IL_0000:&amp;nbsp; nop 

      &lt;br /&gt;&amp;nbsp; IL_0001:&amp;nbsp; ret 

      &lt;br /&gt;}&lt;/span&gt;&lt;/blockquote&gt;
It is very clear that this method has no explicit lock instructions like &lt;em&gt;Monitor.Enter&lt;/em&gt; for example. Yet, it’ll still behave the same as if we used a lock block around the method body.&lt;br /&gt;
&lt;h3&gt;Using lock block&lt;/h3&gt;
The previous method is equivalent to the next:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public void &lt;/span&gt;&lt;span style="color: white;"&gt;MethodWithExplicitLock()
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;lock&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;this&lt;/span&gt;&lt;span style="color: white;"&gt;)
    {
    }
}
&lt;/span&gt;&lt;/pre&gt;
This method translates into:&lt;br /&gt;
&lt;blockquote&gt;
&lt;span style="font-family: 'Courier New';"&gt;.method public hidebysig instance void&amp;nbsp; MethodWithExplicitLock() cil managed 
      &lt;br /&gt;{ 

      &lt;br /&gt;&amp;nbsp; // Code size&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 36 (0x24) 

      &lt;br /&gt;&amp;nbsp; .maxstack&amp;nbsp; 2 

      &lt;br /&gt;&amp;nbsp; .locals init ([0] bool '&amp;lt;&amp;gt;s__LockTaken0', 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; [1] class Sync.Logger CS$2$0000, 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; [2] bool CS$4$0001) 

      &lt;br /&gt;&amp;nbsp; IL_0000:&amp;nbsp; nop 

      &lt;br /&gt;&amp;nbsp; IL_0001:&amp;nbsp; ldc.i4.0 

      &lt;br /&gt;&amp;nbsp; IL_0002:&amp;nbsp; stloc.0 

      &lt;br /&gt;&amp;nbsp; .try 

      &lt;br /&gt;&amp;nbsp; { 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0003:&amp;nbsp; ldarg.0 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0004:&amp;nbsp; dup 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0005:&amp;nbsp; stloc.1 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0006:&amp;nbsp; ldloca.s&amp;nbsp;&amp;nbsp; '&amp;lt;&amp;gt;s__LockTaken0' 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0008:&amp;nbsp; call&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; void [mscorlib]System.Threading.Monitor::Enter(object, 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; bool&amp;amp;) 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_000d:&amp;nbsp; nop 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_000e:&amp;nbsp; nop 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_000f:&amp;nbsp; nop 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0010:&amp;nbsp; leave.s&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0022 

      &lt;br /&gt;&amp;nbsp; }&amp;nbsp; // end .try 

      &lt;br /&gt;&amp;nbsp; finally 

      &lt;br /&gt;&amp;nbsp; { 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0012:&amp;nbsp; ldloc.0 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0013:&amp;nbsp; ldc.i4.0 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0014:&amp;nbsp; ceq 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0016:&amp;nbsp; stloc.2 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0017:&amp;nbsp; ldloc.2 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0018:&amp;nbsp; brtrue.s&amp;nbsp;&amp;nbsp; IL_0021 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_001a:&amp;nbsp; ldloc.1 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_001b:&amp;nbsp; call&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; void [mscorlib]System.Threading.Monitor::Exit(object) 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0020:&amp;nbsp; nop 

      &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IL_0021:&amp;nbsp; endfinally 

      &lt;br /&gt;&amp;nbsp; }&amp;nbsp; // end handler 

      &lt;br /&gt;&amp;nbsp; IL_0022:&amp;nbsp; nop 

      &lt;br /&gt;&amp;nbsp; IL_0023:&amp;nbsp; ret 

      &lt;br /&gt;}&lt;/span&gt;&lt;/blockquote&gt;
As can be seen, the lock block translates naturally into a try/finally block with calls to &lt;em&gt;Montior.Enter&lt;/em&gt; and &lt;em&gt;Monitor.Leave&lt;/em&gt;.&lt;br /&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
The&lt;em&gt; synchronized &lt;/em&gt;keyword is an IL keyword that synchronizes the marked method calls. It causes the method to behave in equivalent way to the one where the whole body is surrounded with lock block. It is interesting to note that locking instructions are generated only during JIT when using the keyword.&lt;br /&gt;
The bottom line is that for C# developers it mostly provides another syntactic sugar for defining trivial lock.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-4795793038685378755?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=5PV74gYtcOo:F_20-6XhsD0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=5PV74gYtcOo:F_20-6XhsD0:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/5PV74gYtcOo" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/5PV74gYtcOo/synchronized-keyword.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2011/11/synchronized-keyword.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-866442351724288478</guid><pubDate>Sat, 02 Jul 2011 17:16:00 +0000</pubDate><atom:updated>2011-07-02T20:16:55.117+03:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">Visual Studio</category><title>Visual Studio 2010 code complexity extension</title><description>An Alpha version of code complexity addin for Visual Studio 2010 is available. The extension can be found at project page at &lt;a href="http://netcodemetrics.codeplex.com/" target="_blank"&gt;CodePlex&lt;/a&gt;.&lt;br /&gt;
The extension shows the complexity of the methods in the IDE near the method and measures the method “health”.&lt;br /&gt;
For example, view of healthy methods (low complexity):&lt;br /&gt;
&lt;a href="http://lh4.ggpht.com/-eHltnPJ3ynY/Tg9RqB-MAHI/AAAAAAAAASE/_jS8C0Eyv7U/s1600-h/GoodMethods%25255B5%25255D.png"&gt;&lt;img alt="GoodMethods" border="0" height="391" src="http://lh3.ggpht.com/-ulepzFlXdCk/Tg9RrBLjcbI/AAAAAAAAASI/qivVAy4HpYg/GoodMethods_thumb%25255B3%25255D.png?imgmax=800" style="background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="GoodMethods" width="558" /&gt;&lt;/a&gt;&lt;br /&gt;
And example of too complex method:&lt;br /&gt;
&lt;a href="http://lh5.ggpht.com/-txJhIn-uigg/Tg9RsD9JIRI/AAAAAAAAASM/zYDT5Phq9yE/s1600-h/BadMethod%25255B7%25255D.png"&gt;&lt;img alt="BadMethod" border="0" height="395" src="http://lh3.ggpht.com/-jX3PdY4biHE/Tg9RtGb7X8I/AAAAAAAAASQ/E7zPv2_23Y4/BadMethod_thumb%25255B5%25255D.png?imgmax=800" style="background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="BadMethod" width="710" /&gt;&lt;/a&gt;&lt;br /&gt;
Currently, the complexity metric shown is simple complexity (defined by Code Complete). This metric counts the number of possible paths in the method. A health method is one with low complexity, and method with 10 paths is not so good and&amp;nbsp;worth&amp;nbsp;simplifying.&lt;br /&gt;
&lt;br /&gt;
Keep it green!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-866442351724288478?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=zqkrY10Kdx4:o4-rgY22rM0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=zqkrY10Kdx4:o4-rgY22rM0:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/zqkrY10Kdx4" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/zqkrY10Kdx4/visual-studio-2010-code-complexity.html</link><author>noreply@blogger.com (Elisha)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh3.ggpht.com/-ulepzFlXdCk/Tg9RrBLjcbI/AAAAAAAAASI/qivVAy4HpYg/s72-c/GoodMethods_thumb%25255B3%25255D.png?imgmax=800" height="72" width="72" /><thr:total>1</thr:total><feedburner:origLink>http://www.elishalom.com/2011/07/visual-studio-2010-code-complexity.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-7707276543568518862</guid><pubDate>Sat, 02 Jul 2011 17:01:00 +0000</pubDate><atom:updated>2012-02-18T09:06:34.842+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Interception</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">C++</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Intercepting unmanaged call in managed code</title><description>This post will demonstrate how to intercept unmanaged calls in the executing process. There are many reasons for intercepting unmanaged calls, among them monitoring, debugging and some other hacks.&lt;br /&gt;
In this post it’ll be demonstrated how to intercept calls to &lt;a href="http://msdn.microsoft.com/en-us/library/aa363858(v=vs.85).aspx" target="_blank"&gt;CreateFile&lt;/a&gt; from Kernel32 library. The &lt;em&gt;CreateFile&lt;/em&gt; method is called for opening an existing file and creating new one. For example, calls to &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx" target="_blank"&gt;File.OpenText&lt;/a&gt; will initiate a call to &lt;em&gt;CreateFile&lt;/em&gt;.&lt;br /&gt;
&lt;h2&gt;Hooking &lt;em&gt;CreateFile&lt;/em&gt; in unmanaged code&lt;/h2&gt;We’ll define a function pointer type for &lt;em&gt;CreateFile&lt;/em&gt;:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;typedef &lt;/span&gt;&lt;span style="color: white;"&gt;HANDLE (WINAPI *FileCreateFunction)(
    LPCWSTR lpFileName,
    DWORD dwDesiredAccess,
    DWORD dwShareMode,
    LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    DWORD dwCreationDisposition,
    DWORD dwFlagsAndAttributes,
    HANDLE hTemplateFile);
&lt;/span&gt;&lt;/pre&gt;Afterwards, we’ll store the original &lt;em&gt;CreateFile&lt;/em&gt; method and create a hook to which will redirect calls:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;FileCreateFunction OriginalCreateFile = (FileCreateFunction)GetProcAddress(GetModuleHandle(L&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"kernel32"&lt;/span&gt;&lt;span style="color: white;"&gt;), &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"CreateFileW"&lt;/span&gt;&lt;span style="color: white;"&gt;);
&lt;/span&gt;&lt;/pre&gt;&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;HANDLE WINAPI CreateFileHook(
    LPCWSTR lpFileName,
    DWORD dwDesiredAccess,
    DWORD dwShareMode,
    LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    DWORD dwCreationDisposition,
    DWORD dwFlagsAndAttributes,
    HANDLE hTemplateFile)
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;bool &lt;/span&gt;&lt;span style="color: white;"&gt;hasListener = createFileCallback != NULL;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if&lt;/span&gt;&lt;span style="color: white;"&gt;(hasListener)
    {
        createFileCallback(lpFileName);
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;OriginalCreateFile(
        lpFileName,
        dwDesiredAccess,
        dwShareMode,
        lpSecurityAttributes,
        dwCreationDisposition,
        dwFlagsAndAttributes,
        hTemplateFile);
}
&lt;/span&gt;&lt;/pre&gt;For now, ignore the code about the callback, this code we’ll be used later for notifying the managed when a file is created.&lt;br /&gt;
&lt;br /&gt;
As we can see, the hook function has the same signature as the original one. This is obvious since the function caller will not be changed, just the target method. The hook observes the function arguments and forwards the call to the original call.&lt;br /&gt;
&lt;br /&gt;
Now, we’ll forward the calls from &lt;em&gt;CreateFile&lt;/em&gt; to the new hook using &lt;a href="http://codefromthe70s.org/mhook22.aspx" target="_blank"&gt;mhook&lt;/a&gt; library:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;BOOL APIENTRY DllMain( HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved)
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;switch &lt;/span&gt;&lt;span style="color: white;"&gt;(ul_reason_for_call)
    {
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;case &lt;/span&gt;&lt;span style="color: white;"&gt;DLL_PROCESS_ATTACH:
        Mhook_SetHook((PVOID*)&amp;amp;OriginalCreateFile, CreateFileHook);
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;break&lt;/span&gt;&lt;span style="color: white;"&gt;;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;case &lt;/span&gt;&lt;span style="color: white;"&gt;DLL_PROCESS_DETACH:
        createFileCallback = NULL;
        Mhook_Unhook((PVOID*)&amp;amp;OriginalCreateFile);
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;break&lt;/span&gt;&lt;span style="color: white;"&gt;;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;case &lt;/span&gt;&lt;span style="color: white;"&gt;DLL_THREAD_ATTACH:
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;case &lt;/span&gt;&lt;span style="color: white;"&gt;DLL_THREAD_DETACH:
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;break&lt;/span&gt;&lt;span style="color: white;"&gt;;    
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;TRUE;
}
&lt;/span&gt;&lt;/pre&gt;This code will hook the &lt;em&gt;CreateFile&lt;/em&gt; method (&lt;em&gt;OriginalCreateFile&lt;/em&gt;) to our new defined hook when the library is loaded into the process.&lt;br /&gt;
&lt;h2&gt;Using the library in managed code&lt;/h2&gt;In order to load the unmanaged library we’ll use P/invoke calls:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;[&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;DllImport&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"kernel32"&lt;/span&gt;&lt;span style="color: white;"&gt;, SetLastError = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;true&lt;/span&gt;&lt;span style="color: white;"&gt;)]
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;static extern &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IntPtr &lt;/span&gt;&lt;span style="color: white;"&gt;LoadLibrary(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;lpFileName);

[&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;DllImport&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"kernel32.dll"&lt;/span&gt;&lt;span style="color: white;"&gt;, SetLastError = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;true&lt;/span&gt;&lt;span style="color: white;"&gt;)]
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;static extern bool &lt;/span&gt;&lt;span style="color: white;"&gt;FreeLibrary(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IntPtr &lt;/span&gt;&lt;span style="color: white;"&gt;hModule);
&lt;/span&gt;&lt;/pre&gt;Loading the library:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;static void &lt;/span&gt;&lt;span style="color: white;"&gt;Main(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;[] args)
{
    &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IntPtr &lt;/span&gt;&lt;span style="color: white;"&gt;library = LoadLibrary(&lt;/span&gt;&lt;span style="color: #a31515;"&gt;@"..\..\..\Debug\InterceptionLibrary.dll"&lt;/span&gt;&lt;span style="color: white;"&gt;);
    FreeLibrary(library);
}
&lt;/span&gt;&lt;/pre&gt;Right now, all the calls will behave the same, but all will be routed through our new hook (a user of the software will experience no difference).&lt;br /&gt;
&lt;h2&gt;Preparing a callback in unmanaged code&lt;/h2&gt;We would like to know what file is being created, so we’ll define a callback function pointer that matches it:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;typedef void &lt;/span&gt;&lt;span style="color: white;"&gt;(*NotifyCallbackFunction)(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;const &lt;/span&gt;&lt;span style="color: white;"&gt;TCHAR* fileName);
&lt;/span&gt;&lt;/pre&gt;The managed code will register a callback using the method:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;extern &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"C" &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;__declspec&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #da4832;"&gt;dllexport&lt;/span&gt;&lt;span style="color: white;"&gt;) &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;void &lt;/span&gt;&lt;span style="color: white;"&gt;RegisterFileCreateListener(
    NotifyCallbackFunction callback )
{
    createFileCallback = callback;
}
&lt;/span&gt;&lt;/pre&gt;This method is exposed so it can be used by the managed code using:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;extern &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"C" &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;__declspec&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #da4832;"&gt;dllexport&lt;/span&gt;&lt;span style="color: white;"&gt;)
&lt;/span&gt;&lt;/pre&gt;&lt;h2&gt;Registering the callback through managed code&lt;/h2&gt;First, in order to call the register method, we’ll need to define a delegate into the register method will be loaded (ignore the callback delegate for now):&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;[&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;UnmanagedFunctionPointer&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;CallingConvention&lt;/span&gt;&lt;span style="color: white;"&gt;.Cdecl)]
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private delegate void &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;RegisterFileListenerDel&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;OnFileCreatedDel &lt;/span&gt;&lt;span style="color: white;"&gt;callback);
&lt;/span&gt;&lt;/pre&gt;In order to load the register method into the managed assembly, we’ll need to use:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;[&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;DllImport&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"kernel32"&lt;/span&gt;&lt;span style="color: white;"&gt;, SetLastError = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;true&lt;/span&gt;&lt;span style="color: white;"&gt;)]
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;static extern &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IntPtr &lt;/span&gt;&lt;span style="color: white;"&gt;GetProcAddress(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IntPtr &lt;/span&gt;&lt;span style="color: white;"&gt;hModule, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;procName);
&lt;/span&gt;&lt;/pre&gt;Loading the method is done by:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #6897bb;"&gt;IntPtr &lt;/span&gt;&lt;span style="color: white;"&gt;pAddressOfFunctionToCall = GetProcAddress(library, &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"RegisterFileCreateListener"&lt;/span&gt;&lt;span style="color: white;"&gt;);
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;registerListener = (&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;RegisterFileListenerDel&lt;/span&gt;&lt;span style="color: white;"&gt;)
                       &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Marshal&lt;/span&gt;&lt;span style="color: white;"&gt;.GetDelegateForFunctionPointer(
                           pAddressOfFunctionToCall,
                           &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;RegisterFileListenerDel&lt;/span&gt;&lt;span style="color: white;"&gt;));
&lt;/span&gt;&lt;/pre&gt;Now, we’ll have to define a callback delegate and method:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;[&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;UnmanagedFunctionPointer&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;CallingConvention&lt;/span&gt;&lt;span style="color: white;"&gt;.Cdecl, CharSet = &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;CharSet&lt;/span&gt;&lt;span style="color: white;"&gt;.Unicode)]
&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private delegate void &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;OnFileCreatedDel&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;fileName);
&lt;/span&gt;&lt;/pre&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;private static void &lt;/span&gt;&lt;span style="color: white;"&gt;OnFileCreated(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;fileName)
{
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Console&lt;/span&gt;&lt;span style="color: white;"&gt;.WriteLine(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"File opened: &lt;/span&gt;&lt;span style="color: mediumseagreen;"&gt;{0}&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"&lt;/span&gt;&lt;span style="color: white;"&gt;, fileName);
}
&lt;/span&gt;&lt;/pre&gt;Now, all needed is to register the callback using the method loaded in the previous step:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: white;"&gt;registerListener(OnFileCreated);
&lt;/span&gt;&lt;/pre&gt;That’s all, as long as the library is loaded our callback we’ll be notified on every &lt;em&gt;CreateFile&lt;/em&gt; call.&lt;br /&gt;
&lt;h2&gt;Example&lt;/h2&gt;This is our final version of the main method in the managed code:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;static void &lt;/span&gt;&lt;span style="color: white;"&gt;Main(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;[] args)
{
    &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IntPtr &lt;/span&gt;&lt;span style="color: white;"&gt;library = LoadLibrary(&lt;/span&gt;&lt;span style="color: #a31515;"&gt;@"..\..\..\Debug\InterceptionLibrary.dll"&lt;/span&gt;&lt;span style="color: white;"&gt;);
    
    &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IntPtr &lt;/span&gt;&lt;span style="color: white;"&gt;pAddressOfFunctionToCall = GetProcAddress(library, &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"RegisterFileCreateListener"&lt;/span&gt;&lt;span style="color: white;"&gt;);
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;registerListener = (&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;RegisterFileListenerDel&lt;/span&gt;&lt;span style="color: white;"&gt;)
                           &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Marshal&lt;/span&gt;&lt;span style="color: white;"&gt;.GetDelegateForFunctionPointer(
                               pAddressOfFunctionToCall,
                               &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #6897bb;"&gt;RegisterFileListenerDel&lt;/span&gt;&lt;span style="color: white;"&gt;));
    registerListener(OnFileCreated);

    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;File&lt;/span&gt;&lt;span style="color: white;"&gt;.OpenText(&lt;/span&gt;&lt;span style="color: #a31515;"&gt;@"C:\Development\wow.txt"&lt;/span&gt;&lt;span style="color: white;"&gt;).Dispose();
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;File&lt;/span&gt;&lt;span style="color: white;"&gt;.CreateText(&lt;/span&gt;&lt;span style="color: #a31515;"&gt;@"C:\Development\wow2.txt"&lt;/span&gt;&lt;span style="color: white;"&gt;).Dispose();

    FreeLibrary(library);
}
&lt;/span&gt;&lt;/pre&gt;Running this code will notify these files created:&lt;br /&gt;
&lt;a href="http://lh3.ggpht.com/-YG_sZy2IAXw/Tg9HGmnhJLI/AAAAAAAAAR8/G0lwh8NmJ4Y/s1600-h/image%25255B3%25255D.png"&gt;&lt;img alt="image" border="0" height="172" src="http://lh4.ggpht.com/-KIGP6H4BEd8/Tg9HHfMHCvI/AAAAAAAAASA/3Ap5dbaeJTE/image_thumb%25255B1%25255D.png?imgmax=800" style="background-image: none; border-bottom: 0px; border-left: 0px; border-right: 0px; border-top: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="image" width="749" /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;h2&gt;Summary&lt;/h2&gt;In order to be notified about a native call in managed code:&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;Create an unmanaged library&lt;/li&gt;
&lt;li&gt;Hook the requested method using &lt;em&gt;mhook&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;Create and expose a callback registration method&lt;/li&gt;
&lt;li&gt;In managed code load the library&lt;/li&gt;
&lt;li&gt;Register a callback&lt;/li&gt;
&lt;/ol&gt;You can download the source code example &lt;a href="https://sites.google.com/site/theorytopracticetotheory/intercepting-unmanaged-call-in-managed-code/InterceptionExample.zip?attredirects=0&amp;amp;d=1"&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;h2&gt;Alternatives&lt;/h2&gt;There several other ways, another possible way to intercept calls in unmanaged calls is &lt;a href="http://research.microsoft.com/en-us/projects/detours/" target="_blank"&gt;Detours&lt;/a&gt;, a library developed by Microsoft. Another possible solution is &lt;a href="http://easyhook.codeplex.com/" target="_blank"&gt;EasyHook&lt;/a&gt;, a library that allows intercepting unmanaged calls directly from managed code.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-7707276543568518862?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=9yuYmI8QSYM:qYxoDooMEHA:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=9yuYmI8QSYM:qYxoDooMEHA:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/9yuYmI8QSYM" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/9yuYmI8QSYM/intercepting-unmanaged-call-in-managed.html</link><author>noreply@blogger.com (Elisha)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/-KIGP6H4BEd8/Tg9HHfMHCvI/AAAAAAAAASA/3Ap5dbaeJTE/s72-c/image_thumb%25255B1%25255D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2011/07/intercepting-unmanaged-call-in-managed.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-719216088506799950</guid><pubDate>Sat, 18 Dec 2010 21:22:00 +0000</pubDate><atom:updated>2012-02-18T09:11:58.362+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Agile</category><title>Agile means a release is ready today</title><description>The trigger for this post is an interesting experience I had this week our weekly demo. I lead the demo and made the client worried. This demo had a positive side – only a few crashes, our system had stability problems during the previous phases. Being able to work with almost no exception is great progress. So far, so good. The downside was that we had to set the environment in some points during the demo, like:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Run a script to fix the registry&lt;/li&gt;
&lt;li&gt;Watch the task manager to ensure it’s done processing before sending new request&lt;/li&gt;
&lt;li&gt;Delete local DB between sessions&lt;/li&gt;
&lt;li&gt;…&lt;/li&gt;
&lt;/ul&gt;It repeated itself during the last few demos, it annoyed us – the developers and it&amp;nbsp;definitely&amp;nbsp;&lt;a href="http://www.elilopian.com/2010/12/16/agile-demos-smells/" target="_blank"&gt;annoyed the client&lt;/a&gt;. The result was a request from the client to change the architecture. This is rarely a legitimate request, the client asks for features, for a “demoable” value. Architecture and design should not be the client concerns. This helped learning important basics about the demo: how did a demo with such progress made a client so worried?&lt;br /&gt;
&lt;h2&gt;The purpose of demo&lt;/h2&gt;The demo has two parallel purposes, they can live side by side, but it’s crucial to know which one each dome serves:&lt;br /&gt;
&lt;h3&gt;Feedback for new concepts&lt;/h3&gt;This is clear characteristic of demos of a new products. The client has hard time telling what are the exact features that solves the problem the product is aimed for. In this phase, the developers are in charge of demonstrating how the initial ideas “feels” in real life – a POC the client can interact with. This phase is important in the product lifetime. In this phase the features must be perceptible, but not perfect. The ideal result of this demo is a client decision whether the feature is good or not, should it be thrown or should it go into the product.&lt;br /&gt;
&lt;h3&gt;Show the value the product provides&lt;/h3&gt;Hopefully, this is the characteristic of most demos. These demos give the client a close view of the development progress – the client knows what value the product provides. In this point decisions can be made – use the new value (like selling the new version) and choose what is the next important value the product should provide.&lt;br /&gt;
&lt;h23&gt;Choose wisely – which purpose this demo serves?&lt;/h23&gt;Defining before the demo what it’s supposed to achieve is crucial.&lt;br /&gt;
&lt;h3&gt;When should we choose?&lt;/h3&gt;The answer is easy – before the iteration plan. The reasons are clear: For a POC the least possible should be done, the feature may not be part of the product, no need to put effort there at this moment. For a progress demo a feature will be planned differently – coding will take longer (this is not a throw away code – refactoring, unit-testing…), satellite tasks will be required (like installer, licensing, etc.). In this iteration the feature will require more tickets, so it must be planned accordingly.&lt;br /&gt;
&lt;h3&gt;How to choose?&lt;/h3&gt;If there’s confidence the feature is what the client wants in the product – plan an iteration in such way the feature is in the product and it’s “productized”. If there’s a doubt, plan in such a way the feature will be demoable but with the least effort as possible.&lt;br /&gt;
&lt;h2&gt;What is done&lt;/h2&gt;“What is done” is important in a demo that show the current value of the product. Then what is done? The answer is very simple: The product can be released right after the demo. In these demos there’s a simple but important guideline – perform the demo on a neutral machine from an installed version. Meaning – running the product from the development IDE on a development machine is not good enough.&lt;br /&gt;
If the demo purpose is to show what the client can use, show the client what can be used. The client can use only what is already “productized”, so if the feature is not part of the installer, it doesn’t help. If the the feature is not linked to the license, it doesn’t help. If the feature crashes and&amp;nbsp;constantly&amp;nbsp;requires workarounds, it doesn’t help.&lt;br /&gt;
&lt;h2&gt;Bottom line&lt;/h2&gt;All developers know how to achieve a successful demo. The problem is identifying what is the next demo purpose. Before planning the next iteration be clear about the iteration “What is done”. One of the things which could cause a failure is acknowledging the product passed the POC phase and it’s a real product (This is where me and my team failed this week). A good parameter for moving between the phases concluded from the question “when users will use it?”.&lt;br /&gt;
After identifying the demo purpose, plan the iteration accordingly and make sure the demo fits it’s purpose.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-719216088506799950?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=hZtEUITx2wk:KL7YvVXkJTk:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=hZtEUITx2wk:KL7YvVXkJTk:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/hZtEUITx2wk" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/hZtEUITx2wk/agile-means-release-is-ready-today.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2010/12/agile-means-release-is-ready-today.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-8445538210720133653</guid><pubDate>Thu, 26 Aug 2010 19:06:00 +0000</pubDate><atom:updated>2012-02-18T09:13:25.586+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MVVM</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Automatic generation of View-Model - test drive</title><description>In the &lt;a href="http://eli-shalom.blogspot.com/2010/08/automatic-generation-of-view-model.html" target="_blank"&gt;previous post&lt;/a&gt; I tried to present an approach for automatic View-Model generation. When trying to use it in real life project, as simple as registration form, many missing features were revealed.&lt;br /&gt;
&lt;br /&gt;
Here’s a list of issues which were noticed on simple implementation:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;There’s no way to access the model from the abstract View-Model &lt;/li&gt;
&lt;li&gt;There’s no way no pass arguments to the constructor &lt;/li&gt;
&lt;li&gt;No built in way to define the order of validations &lt;/li&gt;
&lt;li&gt;No way to raise event of &lt;em&gt;PropertyChanged&lt;/em&gt; other than the property being set &lt;/li&gt;
&lt;li&gt;No way to declare additional errors on properties which are not mapped to the model &lt;/li&gt;
&lt;/ul&gt;&lt;h2&gt;Actual attempt to use the framework in registration form&lt;/h2&gt;&lt;a href="http://lh5.ggpht.com/_Zs5PrU6IvpQ/THa6KpLEPbI/AAAAAAAAAQI/Zwb2t6nSvuI/s1600-h/image%5B3%5D.png"&gt;&lt;img alt="image" border="0" height="241" src="http://lh4.ggpht.com/_Zs5PrU6IvpQ/THa6LbcQHXI/AAAAAAAAAQM/EKqGa69sgig/image_thumb%5B1%5D.png?imgmax=800" style="border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline;" title="image" width="543" /&gt;&lt;/a&gt;&lt;br /&gt;
This is the simple registration – all fields are mandatory, email must match some regular expression and password verification must be same as password. The model has 3 properties – Email, Name and Password. These properties are mapped to the View-Model. Let’s see how this code looks like in the View-Model using the new framework:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public abstract class &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;UserRegistrationViewModel &lt;/span&gt;&lt;span style="color: white;"&gt;: 
                                        &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;INotifyPropertyChanged&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IDataErrorInfo&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IUserViewModel
&lt;/span&gt;&lt;span style="color: white;"&gt;{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private static readonly &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;ViewModelGenerator &lt;/span&gt;&lt;span style="color: white;"&gt;viewModelsGenerator = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;ViewModelGenerator&lt;/span&gt;&lt;span style="color: white;"&gt;();

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public static &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;UserRegistrationViewModel &lt;/span&gt;&lt;span style="color: white;"&gt;CreateUserRegistrationViewModel(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;User &lt;/span&gt;&lt;span style="color: white;"&gt;user)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;viewModelsGenerator.Generate&amp;lt;&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;UserRegistrationViewModel&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;gt;(user);
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;protected &lt;/span&gt;&lt;span style="color: white;"&gt;UserRegistrationViewModel() { }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private const string &lt;/span&gt;&lt;span style="color: white;"&gt;MANDATORY_FIELD_ERROR_MESSAGE = &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"This field is mandatory"&lt;/span&gt;&lt;span style="color: white;"&gt;;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private const string &lt;/span&gt;&lt;span style="color: white;"&gt;PASSWORD_VERIFICATION_PROPERTY_NAME = &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"PasswordVerification"&lt;/span&gt;&lt;span style="color: white;"&gt;;

    [&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Model&lt;/span&gt;&lt;span style="color: white;"&gt;]
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private readonly &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;User &lt;/span&gt;&lt;span style="color: white;"&gt;user;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;ICommand &lt;/span&gt;&lt;span style="color: white;"&gt;save;

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public event &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;PropertyChangedEventHandler &lt;/span&gt;&lt;span style="color: white;"&gt;PropertyChanged = (sender, args) =&amp;gt; { };

    [&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Validation&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MandatoryValidator&lt;/span&gt;&lt;span style="color: white;"&gt;))]
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public abstract string &lt;/span&gt;&lt;span style="color: white;"&gt;Name { &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;get&lt;/span&gt;&lt;span style="color: white;"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;set&lt;/span&gt;&lt;span style="color: white;"&gt;; }

    [&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Validation&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;EmailValidator&lt;/span&gt;&lt;span style="color: white;"&gt;))]
    [&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Validation&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MandatoryValidator&lt;/span&gt;&lt;span style="color: white;"&gt;))]
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public abstract string &lt;/span&gt;&lt;span style="color: white;"&gt;Email { &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;get&lt;/span&gt;&lt;span style="color: white;"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;set&lt;/span&gt;&lt;span style="color: white;"&gt;; }

    [&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Validation&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;typeof&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;MandatoryValidator&lt;/span&gt;&lt;span style="color: white;"&gt;))]
    [&lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;RelatedProperty&lt;/span&gt;&lt;span style="color: white;"&gt;(PASSWORD_VERIFICATION_PROPERTY_NAME)]
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public abstract string &lt;/span&gt;&lt;span style="color: white;"&gt;Password { &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;get&lt;/span&gt;&lt;span style="color: white;"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;set&lt;/span&gt;&lt;span style="color: white;"&gt;; }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private string &lt;/span&gt;&lt;span style="color: white;"&gt;passwordVerification;
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public string &lt;/span&gt;&lt;span style="color: white;"&gt;PasswordVerification
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;get &lt;/span&gt;&lt;span style="color: white;"&gt;{ &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;passwordVerification; }
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;set
        &lt;/span&gt;&lt;span style="color: white;"&gt;{
            passwordVerification = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;value&lt;/span&gt;&lt;span style="color: white;"&gt;;
        }
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;private string &lt;/span&gt;&lt;span style="color: white;"&gt;GetPasswordVerificationValidation()
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if&lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;.IsNullOrEmpty(passwordVerification))
        {
            &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;MANDATORY_FIELD_ERROR_MESSAGE;
        }
        
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(user.Password != passwordVerification)
        {
            &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"Password and Verification must be same"&lt;/span&gt;&lt;span style="color: white;"&gt;;
        }

        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return null&lt;/span&gt;&lt;span style="color: white;"&gt;;
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public virtual string this&lt;/span&gt;&lt;span style="color: white;"&gt;[&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;columnName]
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;get
        &lt;/span&gt;&lt;span style="color: white;"&gt;{
            &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(columnName == PASSWORD_VERIFICATION_PROPERTY_NAME)
            {
                &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;GetPasswordVerificationValidation();
            }

            &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return null&lt;/span&gt;&lt;span style="color: white;"&gt;;
        }
    }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public string &lt;/span&gt;&lt;span style="color: white;"&gt;Error { &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;get &lt;/span&gt;&lt;span style="color: white;"&gt;{ &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;&lt;span style="color: #cc7832;"&gt;return null&lt;/span&gt;&lt;span style="color: white;"&gt;; &lt;/span&gt;&lt;/span&gt;&lt;span style="color: white;"&gt;} }

    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;ICommand &lt;/span&gt;&lt;span style="color: white;"&gt;Save
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;get
        &lt;/span&gt;&lt;span style="color: white;"&gt;{
            &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;if &lt;/span&gt;&lt;span style="color: white;"&gt;(save == &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;null&lt;/span&gt;&lt;span style="color: white;"&gt;)
            {
                save = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;SaveCommand&lt;/span&gt;&lt;span style="color: white;"&gt;(user);
            }

            &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;save;
        }
    }
}
&lt;/span&gt;&lt;/pre&gt;
Let’s see how this code demonstrates the solutions to some of the missing features.&lt;br /&gt;
&lt;br /&gt;
Accessing the model – in order to to get an instance of the model, a new attribute is presented &lt;em&gt;[Model]&lt;/em&gt;. Decorating a field with it will make sure that field is initialized with the model instance.&lt;br /&gt;
&lt;br /&gt;
Raising &lt;em&gt;PropertyChaned&lt;/em&gt; event on other property than the one being set – in order to deal with it a new attribute is presented &lt;em&gt;[RelatedProperty]. &lt;/em&gt;When the property is being set, the &lt;em&gt;PropertyChanged&lt;/em&gt; event will be raised for all properties – the one being set and the related properties.&lt;br /&gt;
&lt;br /&gt;
Defining additional errors for non-mapped properties – the generated View-Model tries to resolve errors for mapped properties, if it find none it forwards the call the base View-Model (the abstract class) and checks for additional errors.&lt;br /&gt;
&lt;h2&gt;Download&lt;/h2&gt;The framework source can be found in &lt;a href="http://dynamiccontrollers.codeplex.com/SourceControl/list/changesets" target="_blank"&gt;CodePlex&lt;/a&gt;. It is still very partial and contains many bugs but it already works on the basic scenarios :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-8445538210720133653?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=ySGvpB3b9ng:wYMpyl3TFM8:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=ySGvpB3b9ng:wYMpyl3TFM8:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/ySGvpB3b9ng" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/ySGvpB3b9ng/automatic-generation-of-view-model-test.html</link><author>noreply@blogger.com (Elisha)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/_Zs5PrU6IvpQ/THa6LbcQHXI/AAAAAAAAAQM/EKqGa69sgig/s72-c/image_thumb%5B1%5D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2010/08/automatic-generation-of-view-model-test.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-8691484075295767458</guid><pubDate>Thu, 19 Aug 2010 21:23:00 +0000</pubDate><atom:updated>2012-02-18T09:15:36.841+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MVVM</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Automatic generation of View-Model - first attempt</title><description>&lt;p&gt;I recently found myself writing the same code again and again. As can be guessed, I’m writing a WPF application based on &lt;a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" target="_blank"&gt;MVVM&lt;/a&gt; architecture. In order to avoid writing the same code again I am trying to generate the View-Model automatically using &lt;a href="http://www.castleproject.org/dynamicproxy/" target="_blank"&gt;Castle Dynamic Proxy&lt;/a&gt;.&lt;/p&gt;&lt;h2&gt;Simplest scenario – forwarding calls to model&lt;/h2&gt;&lt;p&gt;This is probably the simplest case we encounter. This is so simple we are tempted to bind the view directly to the model.&lt;/p&gt;&lt;h3&gt;Naive implementation&lt;/h3&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Model
&lt;/span&gt;&lt;span style="color: white"&gt;{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public object &lt;/span&gt;&lt;span style="color: white"&gt;Prop { &lt;/span&gt;&lt;span style="color: #cc7832"&gt;get&lt;/span&gt;&lt;span style="color: white"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832"&gt;set&lt;/span&gt;&lt;span style="color: white"&gt;; }
}

&lt;/span&gt;&lt;span style="color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel
&lt;/span&gt;&lt;span style="color: white"&gt;{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;private readonly &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Model &lt;/span&gt;&lt;span style="color: white"&gt;model;

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="color: white"&gt;ViewModel(&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Model &lt;/span&gt;&lt;span style="color: white"&gt;model)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832"&gt;this&lt;/span&gt;&lt;span style="color: white"&gt;.model = model;
    }

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public object &lt;/span&gt;&lt;span style="color: white"&gt;Prop
    {
        &lt;/span&gt;&lt;span style="color: #cc7832"&gt;get &lt;/span&gt;&lt;span style="color: white"&gt;{ &lt;/span&gt;&lt;span style="color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="color: white"&gt;model.Prop; }
        &lt;/span&gt;&lt;span style="color: #cc7832"&gt;set &lt;/span&gt;&lt;span style="color: white"&gt;{ model.Prop = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;value&lt;/span&gt;&lt;span style="color: white"&gt;; }
    }
}
&lt;/span&gt;&lt;/pre&gt;&lt;h3&gt;The generated alternative&lt;/h3&gt;&lt;p&gt;So, what we’d like to achieve is skipping the forwarding implementation. The View-Model can look like:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="color: #cc7832"&gt;public abstract class &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel
&lt;/span&gt;&lt;span style="color: white"&gt;{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public abstract object &lt;/span&gt;&lt;span style="color: white"&gt;Prop { &lt;/span&gt;&lt;span style="color: #cc7832"&gt;get&lt;/span&gt;&lt;span style="color: white"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832"&gt;set&lt;/span&gt;&lt;span style="color: white"&gt;; }
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;So far, it’s very simple :) Let’s see how it’s being used with the Model:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="color: white"&gt;[&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Test&lt;/span&gt;&lt;span style="color: white"&gt;]
&lt;/span&gt;&lt;span style="color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="color: white"&gt;Generate_SetPropertyValue_ModelPropertyUpdated()
{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;viewModelGenerator = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModelGenerator&lt;/span&gt;&lt;span style="color: white"&gt;();
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;model = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Model&lt;/span&gt;&lt;span style="color: white"&gt;();
    
    &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel &lt;/span&gt;&lt;span style="color: white"&gt;generatedViewModel = viewModelGenerator.Generate&amp;lt;&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel&lt;/span&gt;&lt;span style="color: white"&gt;&amp;gt;(model);

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;object &lt;/span&gt;&lt;span style="color: white"&gt;valueToAssign = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new object&lt;/span&gt;&lt;span style="color: white"&gt;();
    generatedViewModel.Prop = valueToAssign;

    &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Assert&lt;/span&gt;&lt;span style="color: white"&gt;.That(model.Prop, &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Is&lt;/span&gt;&lt;span style="color: white"&gt;.SameAs(valueToAssign));
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;This example shows that we’ve created a View-Model based on a Model instance, simulated a call to a property setter and the new value automatically reflected the Model. That was simple, wasn’t it?&lt;/p&gt;&lt;h2&gt;Next scenario – Implementing &lt;em&gt;INotifyPropertyChanged&lt;/em&gt;&lt;/h2&gt;&lt;p&gt;This is a very common scenario, which has very common implementation. It’s so common I’ll skip the naive implementation and jump to the generated version directly:&lt;/p&gt;&lt;h3&gt;The generated alternative&lt;/h3&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="color: #cc7832"&gt;public abstract class &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel &lt;/span&gt;&lt;span style="color: white"&gt;: &lt;/span&gt;&lt;span style="color: #6897bb"&gt;INotifyPropertyChanged
&lt;/span&gt;&lt;span style="color: white"&gt;{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public abstract object &lt;/span&gt;&lt;span style="color: white"&gt;Prop { &lt;/span&gt;&lt;span style="color: #cc7832"&gt;get&lt;/span&gt;&lt;span style="color: white"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832"&gt;set&lt;/span&gt;&lt;span style="color: white"&gt;; }
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public event &lt;/span&gt;&lt;span style="color: #6897bb"&gt;PropertyChangedEventHandler &lt;/span&gt;&lt;span style="color: white"&gt;PropertyChanged;
}

[&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Test&lt;/span&gt;&lt;span style="color: white"&gt;]
&lt;/span&gt;&lt;span style="color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="color: white"&gt;Generate_SetPropertyValue_PropertyChangedRaised()
{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;viewModelGenerator = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModelGenerator&lt;/span&gt;&lt;span style="color: white"&gt;();
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;model = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Model&lt;/span&gt;&lt;span style="color: white"&gt;();
    &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel &lt;/span&gt;&lt;span style="color: white"&gt;generatedViewModel = viewModelGenerator.Generate&amp;lt;&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel&lt;/span&gt;&lt;span style="color: white"&gt;&amp;gt;(model);

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;bool &lt;/span&gt;&lt;span style="color: white"&gt;wasRaised = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;false&lt;/span&gt;&lt;span style="color: white"&gt;;
    generatedViewModel.PropertyChanged += (sender, args) =&amp;gt; wasRaised = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;true&lt;/span&gt;&lt;span style="color: white"&gt;;

    generatedViewModel.Prop = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new object&lt;/span&gt;&lt;span style="color: white"&gt;();

    &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Assert&lt;/span&gt;&lt;span style="color: white"&gt;.That(wasRaised, &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Is&lt;/span&gt;&lt;span style="color: white"&gt;.True);
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;In this case we’ve generated a View-Model that implements &lt;em&gt;INotifyPropertyChanged. &lt;/em&gt;We had to do nothing but declaring the View-Model implements &lt;em&gt;INotifyPropertyChanged. &lt;/em&gt;Whenever a property value is changed the event will be raised with the property name.&lt;/p&gt;&lt;h2&gt;Last scenario – Implementing &lt;em&gt;IDataErrorInfo&lt;/em&gt;&lt;/h2&gt;&lt;p&gt;This case is trivial too so I’ll skip again the naive solution.&lt;/p&gt;&lt;h3&gt;The generated alternative&lt;/h3&gt;&lt;p&gt;First we’ll take a look at the format of the abstract View-Model and the validation declaration:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="color: #cc7832"&gt;public abstract class &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel &lt;/span&gt;&lt;span style="color: white"&gt;: &lt;/span&gt;&lt;span style="color: #6897bb"&gt;IDataErrorInfo
&lt;/span&gt;&lt;span style="color: white"&gt;{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public abstract string this&lt;/span&gt;&lt;span style="color: white"&gt;[&lt;/span&gt;&lt;span style="color: #cc7832"&gt;string &lt;/span&gt;&lt;span style="color: white"&gt;columnName] { &lt;/span&gt;&lt;span style="color: #cc7832"&gt;get&lt;/span&gt;&lt;span style="color: white"&gt;; }
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public abstract string &lt;/span&gt;&lt;span style="color: white"&gt;Error { &lt;/span&gt;&lt;span style="color: #cc7832"&gt;get&lt;/span&gt;&lt;span style="color: white"&gt;; }

    [&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Validation&lt;/span&gt;&lt;span style="color: white"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832"&gt;typeof&lt;/span&gt;&lt;span style="color: white"&gt;(&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;DummyValidator&lt;/span&gt;&lt;span style="color: white"&gt;))]
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public abstract object &lt;/span&gt;&lt;span style="color: white"&gt;Prop { &lt;/span&gt;&lt;span style="color: #cc7832"&gt;get&lt;/span&gt;&lt;span style="color: white"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832"&gt;set&lt;/span&gt;&lt;span style="color: white"&gt;; }
}

&lt;/span&gt;&lt;span style="color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;DummyValidator &lt;/span&gt;&lt;span style="color: white"&gt;: &lt;/span&gt;&lt;span style="color: #6897bb"&gt;IValidator
&lt;/span&gt;&lt;span style="color: white"&gt;{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public string &lt;/span&gt;&lt;span style="color: white"&gt;Validate(&lt;/span&gt;&lt;span style="color: #cc7832"&gt;object &lt;/span&gt;&lt;span style="color: white"&gt;value)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="color: #a5c25c"&gt;&amp;quot;error&amp;quot;&lt;/span&gt;&lt;span style="color: white"&gt;;
    }
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;The view model is implementing now the &lt;em&gt;IDataErrorInfo&lt;/em&gt; interface. The interfaces require implementation of indexer that maps from property to error message. The automatic View-Model generation should take care of it. In order to declare the required validations we’ll use the Validation attribute. The attribute defines which validator to use on the property. The validation result will be mapped to the property name.&lt;/p&gt;&lt;p&gt;For example:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="color: white"&gt;[&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Test&lt;/span&gt;&lt;span style="color: white"&gt;]
&lt;/span&gt;&lt;span style="color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="color: white"&gt;Generate_SetInvalidPropertyValue_PropertyErrorIsCorrect()
{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;viewModelGenerator = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModelGenerator&lt;/span&gt;&lt;span style="color: white"&gt;();
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;model = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Model&lt;/span&gt;&lt;span style="color: white"&gt;();

    &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel &lt;/span&gt;&lt;span style="color: white"&gt;generatedViewModel = viewModelGenerator.Generate&amp;lt;&lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ViewModel&lt;/span&gt;&lt;span style="color: white"&gt;&amp;gt;(model);

    generatedViewModel.Prop = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new object&lt;/span&gt;&lt;span style="color: white"&gt;();

    &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Assert&lt;/span&gt;&lt;span style="color: white"&gt;.That(generatedViewModel[&lt;/span&gt;&lt;span style="color: #a5c25c"&gt;&amp;quot;Prop&amp;quot;&lt;/span&gt;&lt;span style="color: white"&gt;], &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Is&lt;/span&gt;&lt;span style="color: white"&gt;.EqualTo(&lt;/span&gt;&lt;span style="color: #a5c25c"&gt;&amp;quot;error&amp;quot;&lt;/span&gt;&lt;span style="color: white"&gt;));
}
&lt;/span&gt;&lt;/pre&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;p&gt;MVVM is used many times in common and similar scenarios. The code is usually a template which we can generate dynamically. This way the code duplication will be drastically reduced and allow uniform implementation.&lt;/p&gt;&lt;p&gt;The examples here were simplified but the concept should be clear. There’s much more work on the framework in order to cover more real life scenarios, soon to come :) I’ll upload framework the source code to &lt;a href="http://www.codeplex.com/" target="_blank"&gt;CodePlex&lt;/a&gt; before the next post.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-8691484075295767458?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=s576WTzroTk:XVAxDOcE4aM:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=s576WTzroTk:XVAxDOcE4aM:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/s576WTzroTk" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/s576WTzroTk/automatic-generation-of-view-model.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2010/08/automatic-generation-of-view-model.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-6609146057819181911</guid><pubDate>Sat, 24 Jul 2010 14:53:00 +0000</pubDate><atom:updated>2012-02-18T09:16:34.168+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Productivity</category><title>Balancing working hours toward better productivity</title><description>I'll start by saying - &lt;strong&gt;I don't know what's the best balance&lt;/strong&gt;. Then, what can I tell?&lt;br /&gt;
&lt;h2&gt;The obvious&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;The ratio between our working hours and productivity is not linear. We all know that, nothing new here. If we work 12 hours a day instead of 10 we won’t produce 20% more features. &lt;/li&gt;
&lt;li&gt;When we need to get more work done, we work more hours. &lt;/li&gt;
&lt;/ol&gt;&lt;h2&gt;The almost obvious&lt;/h2&gt;How’s our productivity looks like during the day?&lt;br /&gt;
&lt;a href="http://lh3.ggpht.com/_Zs5PrU6IvpQ/TEr-d7_dMYI/AAAAAAAAAPw/PWJvSQHlYTs/s1600-h/image%5B6%5D.png"&gt;&lt;img alt="image" border="0" height="339" src="http://lh3.ggpht.com/_Zs5PrU6IvpQ/TEr-ey2h_MI/AAAAAAAAAP0/JYfSPkBEs3o/image_thumb%5B4%5D.png?imgmax=800" style="border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline;" title="image" width="540" /&gt;&lt;/a&gt; &lt;br /&gt;
Everybody agrees about this graph until the productivity gets closer to zero. But, is possible to have &lt;strong&gt;negative productivity &lt;/strong&gt;?&lt;br /&gt;
&lt;h2&gt;Negative productivity&lt;/h2&gt;This is the unintuitive part, we encountered it so many times but it’s still hard to accept it. From some part of the day, we do more harm than good – we cause more bugs, produce fragile design and less readable code. Even though our feature might work just fine, we did more harm than good – next week, when we have to extended the feature, we’ll have to understand code in inferior standard. We’ll fight the design and most likely, we’ll fight the bugs we missed before.&lt;br /&gt;
From my personal experience, during the last year I found myself fighting with features for very long hours, in most of the times where I gave up and left office the next morning was extremely effective. I could throw away all the mess I did during the previous evening and write nice code within an hour.&lt;br /&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;The conclusion is very straight forward – when you’re getting to the zone of overwork, &lt;strong&gt;Go Home!&lt;/strong&gt; You’re wasting your time, you’re wasting your boss’s money and you’re planting seeds in code that’ll annoy your teammates in the near future. We all know this is counter intuitive, but working less, closer to balanced hours, makes us more productive.&lt;br /&gt;
&lt;h2&gt;More thoughts&lt;/h2&gt;We have concentrated on the productivity of a single day. A bit more interesting can be to analyze a whole week, is it possible that working one day less a week will improve our productivity? If we’d find it to be true, will we act and shorten our work week? If we’d reduce shorten our work week, should we get paid less or more? On one hand we’re more productive, so we should be paid more, but on the other hand, we work less, so we should be paid less. This lead to an interesting question - are we paid for our time or for our results?&lt;br /&gt;
There’s a lot to think about here, but we must find first the optimal balance of working hours and days.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-6609146057819181911?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=Dg6Jhm76HJk:0kssoeYjxxc:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=Dg6Jhm76HJk:0kssoeYjxxc:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/Dg6Jhm76HJk" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/Dg6Jhm76HJk/whats-best-tradeoff-between-working.html</link><author>noreply@blogger.com (Elisha)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh3.ggpht.com/_Zs5PrU6IvpQ/TEr-ey2h_MI/AAAAAAAAAP0/JYfSPkBEs3o/s72-c/image_thumb%5B4%5D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2010/07/whats-best-tradeoff-between-working.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-6427155774537295636</guid><pubDate>Thu, 22 Jul 2010 05:04:00 +0000</pubDate><atom:updated>2012-02-18T09:17:37.085+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Worker thread using parallel tasks</title><description>Worker thread is a known pattern – there’s work to do, it needs to be done asynchronously and we want to get all the work results when it’s ready. What we’re going to see is an implementation of it as an alternative to the common implemenatations. This implemenation will take advantage of the new &lt;a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx" target="_blank"&gt;parallel tasks library&lt;/a&gt;.&lt;br /&gt;
To formalize the requirements:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;The worker queues items to process &lt;/li&gt;
&lt;li&gt;The items are processed asynchronously &lt;/li&gt;
&lt;li&gt;Only one item can be proceesed at a time &lt;/li&gt;
&lt;li&gt;The items are proceesed in the order they were queued &lt;/li&gt;
&lt;li&gt;The worker will store the processed results in the order they were processed &lt;/li&gt;
&lt;/ul&gt;&lt;h2&gt;The &lt;em&gt;worker&lt;/em&gt; class&lt;/h2&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Worker&lt;/span&gt;&lt;span style="color: white"&gt;&amp;lt;TItem, TResult&amp;gt;
{
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;private readonly &lt;/span&gt;&lt;span style="color: #6897bb"&gt;IItemsProcessor&lt;/span&gt;&lt;span style="color: white"&gt;&amp;lt;TItem, TResult&amp;gt; itemsProcessor;
    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;private &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Task &lt;/span&gt;&lt;span style="color: white"&gt;lastTask;

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="color: #6897bb"&gt;IList&lt;/span&gt;&lt;span style="color: white"&gt;&amp;lt;TResult&amp;gt; ProcessedItems { &lt;/span&gt;&lt;span style="color: #cc7832"&gt;get&lt;/span&gt;&lt;span style="color: white"&gt;; &lt;/span&gt;&lt;span style="color: #cc7832"&gt;private set&lt;/span&gt;&lt;span style="color: white"&gt;; }

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="color: white"&gt;Worker(&lt;/span&gt;&lt;span style="color: #6897bb"&gt;IItemsProcessor&lt;/span&gt;&lt;span style="color: white"&gt;&amp;lt;TItem,TResult&amp;gt; itemsProcessor)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832"&gt;this&lt;/span&gt;&lt;span style="color: white"&gt;.itemsProcessor = itemsProcessor;
        ProcessedItems = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;List&lt;/span&gt;&lt;span style="color: white"&gt;&amp;lt;TResult&amp;gt;();
        InitializeNullTask();
    }

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;private void &lt;/span&gt;&lt;span style="color: white"&gt;InitializeNullTask()
    {
        lastTask = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;Task&lt;/span&gt;&lt;span style="color: white"&gt;&amp;lt;TResult&amp;gt;(() =&amp;gt; &lt;/span&gt;&lt;span style="color: #cc7832"&gt;default&lt;/span&gt;&lt;span style="color: white"&gt;(TResult));
        lastTask.Start();
    }

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="color: white"&gt;ProcessItem(TItem item)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;nextTask = lastTask
            .ContinueWith(task =&amp;gt;
                              {
                                  &lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;processItem = itemsProcessor.ProcessItem(item);
                                  ProcessedItems.Add(processItem);
                              });
        lastTask = nextTask;
    }

    &lt;/span&gt;&lt;span style="color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="color: white"&gt;WaitForPendingItems()
    {
        &lt;/span&gt;&lt;span style="color: #cc7832"&gt;using &lt;/span&gt;&lt;span style="color: white"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="color: white"&gt;sync = &lt;/span&gt;&lt;span style="color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d"&gt;ManualResetEvent&lt;/span&gt;&lt;span style="color: white"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832"&gt;false&lt;/span&gt;&lt;span style="color: white"&gt;))
        {
            lastTask.ContinueWith(task =&amp;gt; sync.Set());
            sync.WaitOne();
        }
    }
}
&lt;/span&gt;&lt;/pre&gt;The &lt;em&gt;worker&lt;/em&gt; creates a a task for each item needs to be processed. Each &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank"&gt;&lt;em&gt;task&lt;/em&gt;&lt;/a&gt; is executed in the thread pool, the point where we ensure that the tasks are ran in the correct order is the &lt;a href="http://msdn.microsoft.com/en-us/library/dd321405.aspx" target="_blank"&gt;&lt;em&gt;ContinueWith&lt;/em&gt;&lt;/a&gt; call. &lt;em&gt;ContinueWith&lt;/em&gt; takes care for the order of the tasks execution.&lt;br /&gt;
&lt;br /&gt;
The &lt;em&gt;InitializeNullTask&lt;/em&gt; creates a task that, suprisingly, does nothing but to set a head to the tasks queue. This task helps us avoid in &lt;em&gt;ProcessItem&lt;/em&gt; to check if this is the first item to process. The first task starts with call to &lt;em&gt;Start&lt;/em&gt; while all the other starts with &lt;a href="http://msdn.microsoft.com/en-us/library/dd321405.aspx" target="_blank"&gt;&lt;em&gt;ContinueWith&lt;/em&gt;&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;em&gt;WaitForPendingItems&lt;/em&gt; also enques a task. This time, the task is only waiting to be executed, which means all other items were already processed. When the task starts it releases the enquing thread.&lt;br /&gt;
&lt;h2&gt;Usage example&lt;/h2&gt;In this example we’ll download a list of web pages and check print their sizes. The downloader impelments the &lt;em&gt;IItemsProcessor&lt;/em&gt; we’ve seen the &lt;em&gt;worker&lt;/em&gt; expects.
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public class &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;WebUrlsDownloader &lt;/span&gt;&lt;span style="color: white;"&gt;: &lt;/span&gt;&lt;span style="color: #6897bb;"&gt;IItemsProcessor&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;byte&lt;/span&gt;&lt;span style="color: white;"&gt;[]&amp;gt;
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;public byte&lt;/span&gt;&lt;span style="color: white;"&gt;[] ProcessItem(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string &lt;/span&gt;&lt;span style="color: white;"&gt;url)
    {
        &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;using &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;webClient = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;WebClient&lt;/span&gt;&lt;span style="color: white;"&gt;())
        {
            &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;return &lt;/span&gt;&lt;span style="color: white;"&gt;webClient.DownloadData(url);
        }
    }
}
&lt;/span&gt;&lt;/pre&gt;And the actual usage:&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="color: #cc7832;"&gt;public void &lt;/span&gt;&lt;span style="color: white;"&gt;DownloadFiles()
{
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;worker = &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Worker&lt;/span&gt;&lt;span style="color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;string&lt;/span&gt;&lt;span style="color: white;"&gt;, &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;byte&lt;/span&gt;&lt;span style="color: white;"&gt;[]&amp;gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;WebUrlsDownloader&lt;/span&gt;&lt;span style="color: white;"&gt;());
    worker.ProcessItem(&lt;/span&gt;&lt;span style="color: #a31515;"&gt;@"http://msdn.microsoft.com/en-us/library/dd537608.aspx"&lt;/span&gt;&lt;span style="color: white;"&gt;);
    worker.ProcessItem(&lt;/span&gt;&lt;span style="color: #a31515;"&gt;@"http://msdn.microsoft.com/en-us/library/dd537609.aspx"&lt;/span&gt;&lt;span style="color: white;"&gt;);
    worker.ProcessItem(&lt;/span&gt;&lt;span style="color: #a31515;"&gt;@"http://msdn.microsoft.com/en-us/library/dd997405.aspx"&lt;/span&gt;&lt;span style="color: white;"&gt;);
    worker.WaitForPendingItems();
    &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Console&lt;/span&gt;&lt;span style="color: white;"&gt;.WriteLine(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"Finished downloading files:"&lt;/span&gt;&lt;span style="color: white;"&gt;);
    &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;foreach &lt;/span&gt;&lt;span style="color: white;"&gt;(&lt;/span&gt;&lt;span style="color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="color: white;"&gt;processedItem &lt;/span&gt;&lt;span style="color: #cc7832;"&gt;in &lt;/span&gt;&lt;span style="color: white;"&gt;worker.ProcessedItems)
    {
        &lt;/span&gt;&lt;span style="color: #ffc66d;"&gt;Console&lt;/span&gt;&lt;span style="color: white;"&gt;.WriteLine(&lt;/span&gt;&lt;span style="color: #a5c25c;"&gt;"Downloaded file with size: {0}"&lt;/span&gt;&lt;span style="color: white;"&gt;, processedItem.Length);
    }
}&lt;/span&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-6427155774537295636?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=anpga2u4Evo:60b7QPPmml8:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=anpga2u4Evo:60b7QPPmml8:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/anpga2u4Evo" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/anpga2u4Evo/worker-thread-using-parallel-tasks.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2010/07/worker-thread-using-parallel-tasks.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-8035681672109996406</guid><pubDate>Mon, 12 Jul 2010 21:19:00 +0000</pubDate><atom:updated>2012-02-18T09:18:12.515+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">F#</category><category domain="http://www.blogger.com/atom/ns#">Unit Test</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Unit testing F#</title><description>&lt;a href="http://www.fsharp.net/" target="_blank"&gt;F#&lt;/a&gt; is a cool and exiting language. It’s much more than an academic language, it can solve many real life (coding) problems in its functional manner. As to production code, it must be covered with unit tests. I’ll show a simple example of unit test written in C# with moq against F# code.&lt;br /&gt;
The code under test is a simple lottery calculator, it takes a list of participants and tells how much every participant won - 5 times the number of hits. Simple, isn’t it?&lt;br /&gt;
Let’s take a look at the code under test, it could probably be written better, but ignore it for now :)&lt;br /&gt;
&lt;pre class="code" style="background: black;"&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;type &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;LotteryCalculator(winningNumbers:System.Collections.Generic.IList&amp;lt;System.Int32&amp;gt;) = 
    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;let &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;calculatePrize(participatingNumbers) =
        &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;let &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;numOfHits = participatingNumbers |&amp;gt; 
                        Seq.filter (&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;fun &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;participatingNumber &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;-&amp;gt; &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;winningNumbers.Contains participatingNumber) |&amp;gt;
                        Set.ofSeq |&amp;gt; 
                        Set.count
        numOfHits * &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;5
    
    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;member &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;this.CalculatePrizes(participants:System.Collections.Generic.IEnumerable&amp;lt;IParticipant&amp;gt;) =
        participants
        |&amp;gt; Seq.map (&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;fun &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;participant &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;-&amp;gt; &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;(participant, calculatePrize(participant.GetTicket())))
&lt;/span&gt;&lt;/pre&gt;So, we have an API method, &lt;em&gt;CalculatePrizes()&lt;/em&gt;, which take a collection of participants, look at their tickets and returns a tuples list of participant and prize. So we have something like this: &lt;em&gt;CalculatePrizes: System.Collections.Generic.IEnumerable&amp;lt;IParticipant&amp;gt; –&amp;gt; seq&amp;lt;IParticipant * int&amp;gt;&lt;/em&gt;&lt;br /&gt;
&lt;br /&gt;
After dealing with some issues, on which I’ll tell in a future post, I wrote this test:
&lt;pre class="code" style="background: black;"&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;[&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;Test&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;]
&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;public void &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;CalculatePrizes_RecievesTwoParticipant_MatchCorrectPrizes()
{
    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;firstParticipantMock = &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;Moq.&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;Mock&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;IParticipant&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;gt;();
    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;IParticipant &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;firstParticipant = firstParticipantMock.Object;
    firstParticipantMock.Setup(fake =&amp;gt; fake.GetTicket()).Returns(&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;List&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;int&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;gt; {&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;1&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;, &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;4&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;, &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;5&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;});
    
    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;secondParticipantMock = &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;Moq.&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;Mock&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;IParticipant&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;gt;();
    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;IParticipant &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;secondParticipant = secondParticipantMock.Object;
    secondParticipantMock.Setup(fake =&amp;gt; fake.GetTicket()).Returns(&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;List&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;int&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;gt; { &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;1&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;, &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;2&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;, &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;4 &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;});

    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;lotteryCalculator = &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;LotteryCalculator&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;(&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;new &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;List&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;int&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;&amp;gt; {&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;1&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;, &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;2&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;, &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;3&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;});
    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;participantPrizes = lotteryCalculator.CalculatePrizes(&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;new&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;[] { firstParticipant, secondParticipant });

    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #cc7832;"&gt;var &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;prizes = participantPrizes.ToDictionary(tuple =&amp;gt; tuple.Item1, tuple =&amp;gt; tuple.Item2);

    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;Assert&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;.That(prizes[firstParticipant], &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;Is&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;.EqualTo(&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;5&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;));
    &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;Assert&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;.That(prizes[secondParticipant], &lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #ffc66d;"&gt;Is&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;.EqualTo(&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: #6897bb;"&gt;10&lt;/span&gt;&lt;span style="background-attachment: initial; background-clip: initial; background-color: black; background-image: initial; background-origin: initial; color: white;"&gt;));
}
&lt;/span&gt;&lt;/pre&gt;It’s nice that we can keep our unit tests written in C#, it’s also important in cases where the users of the code (most likely us in other module) will use it in C# as well.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-8035681672109996406?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=WcB5sezshDA:WDJpypP--Wc:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=WcB5sezshDA:WDJpypP--Wc:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/WcB5sezshDA" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/WcB5sezshDA/unit-testing-f.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2010/07/unit-testing-f.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-8708746113794821974</guid><pubDate>Sat, 09 Jan 2010 14:23:00 +0000</pubDate><atom:updated>2010-01-09T16:25:07.380+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">Code Contracts</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Code contracts – Where invariant method called?</title><description>&lt;p&gt;I assume you’re already know code contracts and heard about &lt;em&gt;invariant methods&lt;/em&gt;. This post will demonstrate how simple code compiles with invariant method.&lt;/p&gt;&lt;p&gt;This simple class declares a method as invariant method:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;InvariantExample
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="background: black; color: white"&gt;Method()
    {
        &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Console&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.WriteLine(&lt;/span&gt;&lt;span style="background: black; color: #a5c25c"&gt;&amp;quot;In Method&amp;quot;&lt;/span&gt;&lt;span style="background: black; color: white"&gt;);
    }

    [&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;ContractInvariantMethod&lt;/span&gt;&lt;span style="background: black; color: white"&gt;]
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;protected void &lt;/span&gt;&lt;span style="background: black; color: white"&gt;InvariantMethod()
    {
        &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Contract&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Invariant(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;2 &lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt; &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;1&lt;/span&gt;&lt;span style="background: black; color: white"&gt;);
    }
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;Using &lt;a href="http://www.red-gate.com/products/reflector/" target="_blank"&gt;reflector&lt;/a&gt; we can see that &lt;em&gt;Method&lt;/em&gt; compiles to:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="background: black; color: white"&gt;Method()
{
    &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Console&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.WriteLine(&lt;/span&gt;&lt;span style="background: black; color: #a5c25c"&gt;&amp;quot;In Method&amp;quot;&lt;/span&gt;&lt;span style="background: black; color: white"&gt;);
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;this&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.$InvariantMethod$();
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;As we can see the compiled method ends with a call to our invariant method. Assuming we had more methods in our class we would have seen similar call in each one of them. The &lt;em&gt;invariants&lt;/em&gt; is less explicit than most contracts features but it's a powerful part of it, use wisely!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-8708746113794821974?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=I2d5ET6gVYI:-nv6j1C0O4A:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=I2d5ET6gVYI:-nv6j1C0O4A:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/I2d5ET6gVYI" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/I2d5ET6gVYI/code-contracts-where-invariant-method.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2010/01/code-contracts-where-invariant-method.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-1396102712986404297</guid><pubDate>Mon, 07 Dec 2009 07:16:00 +0000</pubDate><atom:updated>2012-02-18T09:19:51.073+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Easy Wins Optimizations</category><category domain="http://www.blogger.com/atom/ns#">HashSet</category><category domain="http://www.blogger.com/atom/ns#">Data Structures</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Easy Wins Optimizations – HashSet</title><description>HashSet is a data structure introduced in .Net 3.5 framework. The main advantage of HashSet is that it adds and fetches items in very low complexity (constant amortized time). We’ll try to see how faster can it be over List. In the example we’ll go over code that stores all historical lottery results and checks if some results appear among the historical ones.&lt;h2&gt;Registering results&lt;/h2&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public abstract class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;ResultsRegistrarBase
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;protected &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;ICollection&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt; codes;

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="background: black; color: white"&gt;AddResult(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num1, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num2, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num3, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num4, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num5, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num6)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long &lt;/span&gt;&lt;span style="background: black; color: white"&gt;code = ConvertToCode(num1, num2, num3, num4, num5, num6);

        codes.Add(code);
    }

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public bool &lt;/span&gt;&lt;span style="background: black; color: white"&gt;ContainsResult(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num1, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num2, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num3, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num4, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num5, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num6)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long &lt;/span&gt;&lt;span style="background: black; color: white"&gt;code = ConvertToCode(num1, num2, num3, num4, num5, num6);

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="background: black; color: white"&gt;codes.Contains(code);
    }

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;private static long &lt;/span&gt;&lt;span style="background: black; color: white"&gt;ConvertToCode(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num1, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num2, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num3, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num4, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num5, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num6)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="background: black; color: white"&gt;num1 + (&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Math&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Pow(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;10&lt;/span&gt;&lt;span style="background: black; color: white"&gt;, &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;0&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) + num2 * (&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Math&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Pow(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;10&lt;/span&gt;&lt;span style="background: black; color: white"&gt;, &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;2&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) +
               num3 * (&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Math&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Pow(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;10&lt;/span&gt;&lt;span style="background: black; color: white"&gt;, &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;4&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) + num4 * (&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Math&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Pow(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;10&lt;/span&gt;&lt;span style="background: black; color: white"&gt;, &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;6&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) +
               num5 * (&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Math&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Pow(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;10&lt;/span&gt;&lt;span style="background: black; color: white"&gt;, &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;8&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) + num6 * (&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;) &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Math&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Pow(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;10&lt;/span&gt;&lt;span style="background: black; color: white"&gt;, &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;10&lt;/span&gt;&lt;span style="background: black; color: white"&gt;);
    }
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;This class is in charge of storing and finding the results. It assumes it gets the numbers sorted and the &lt;em&gt;ConvertToCode&lt;/em&gt; method maps all the numbers to one “big&amp;quot; number”. For example: 1,5,20,30,45,49 will be mapped to &lt;u&gt;49&lt;/u&gt;45&lt;u&gt;30&lt;/u&gt;20&lt;u&gt;05&lt;/u&gt;01. The &lt;em&gt;codes&lt;/em&gt; collection will be initialized in a base class:&lt;/p&gt;&lt;p&gt;The naive code:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;NaiveResultsRegistrar &lt;/span&gt;&lt;span style="background: black; color: white"&gt;: &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;ResultsRegistrarBase
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="background: black; color: white"&gt;NaiveResultsRegistrar()
    {
        codes = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;List&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt;();
    }
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;The code based on HashSet:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;HashSetResultsRegistrar &lt;/span&gt;&lt;span style="background: black; color: white"&gt;: &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;ResultsRegistrarBase
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="background: black; color: white"&gt;HashSetResultsRegistrar()
    {
        codes = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;HashSet&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;long&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt;();
    }
}
&lt;/span&gt;&lt;/pre&gt;&lt;h2&gt;How faster is it over the the naive code?&lt;/h2&gt;&lt;p&gt;The difference is huge, on a simple case where we have 250,000 historical results and we’re querying the collection 50,000 times the average running time of the naive code is 1:28 minutes and the code based on HashSet takes only 0.2 seconds. The HashSet code run ~360 times faster than the naive code. The reason for this major change is that List has to iterate over all the items in order to determine if it contains the requested item. HashSet uses a hash method, without getting to implementation details, it lets enables the contains look in very few entries in order to determine if an item is contained or not in the collection.&lt;/p&gt;&lt;p&gt;This is a major improvement was received using minimal change in the code. So in cases where we query a large collection whether some items are in it, usage of HashSet can give us major running time&amp;#160; improvement with minimal change.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-1396102712986404297?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=8zCXJ4vn2oY:-eeu5sN0jTU:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=8zCXJ4vn2oY:-eeu5sN0jTU:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/8zCXJ4vn2oY" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/8zCXJ4vn2oY/easy-wins-optimizations-hashset.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2009/12/easy-wins-optimizations-hashset.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-1786152090242732662</guid><pubDate>Thu, 03 Dec 2009 09:24:00 +0000</pubDate><atom:updated>2012-02-18T09:20:53.123+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">LINQ-To-SQL</category><category domain="http://www.blogger.com/atom/ns#">WCF</category><title>How to pass LINQ-To-SQL data objects with associations through WCF service?</title><description>Sometimes we need to pass a simple data object through WCF service. It has few simple steps for performing it.&lt;h2&gt;Make data objects declare columns as Data Members&lt;/h2&gt;&lt;p&gt;This step is very simple, all needed is to define in the DBML editor that the &lt;a href="http://msdn.microsoft.com/en-us/library/bb546184.aspx" target="_blank"&gt;serialization mode&lt;/a&gt; is Unidirectional.&lt;/p&gt;&lt;p&gt;&lt;a href="http://lh3.ggpht.com/_Zs5PrU6IvpQ/SxeDz1JknFI/AAAAAAAAAOQ/v5CO9mdVcDo/s1600-h/image%5B8%5D.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="365" alt="image" src="http://lh5.ggpht.com/_Zs5PrU6IvpQ/SxeD1Z3QsxI/AAAAAAAAAOU/ngj2DkQ_wio/image_thumb%5B4%5D.png?imgmax=800" width="554" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;By defining this serialization mode the generated code will be decorated with &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank"&gt;DataContract&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx" target="_blank"&gt;DataMember&lt;/a&gt; attributes on classes and columns. By doing so the objects are compatible with WCF service and declared as part of the contract.&lt;/p&gt;&lt;h2&gt;Visit the objects associations properties before returning them from the service&lt;/h2&gt;&lt;p&gt;For example, if we’re dealing with this simple schema and our service returns a customer with requested ID.&lt;/p&gt;&lt;p&gt;&lt;a href="http://lh3.ggpht.com/_Zs5PrU6IvpQ/SxeD2ba6uiI/AAAAAAAAAOY/aH7uFzqUo3A/s1600-h/image%5B37%5D.png"&gt;&lt;img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="396" alt="image" src="http://lh4.ggpht.com/_Zs5PrU6IvpQ/SxeD3LiYU7I/AAAAAAAAAOc/1vQ1Udh_0Cs/image_thumb%5B31%5D.png?imgmax=800" width="390" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;p&gt;Assuming we’re having this naive code:&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;StoreService &lt;/span&gt;&lt;span style="background: black; color: white"&gt;: &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;IStoreService
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Customer &lt;/span&gt;&lt;span style="background: black; color: white"&gt;GetCustomer(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;id)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;using &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;store = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;StoreDataContext&lt;/span&gt;&lt;span style="background: black; color: white"&gt;())
        {
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="background: black; color: white"&gt;store.Customers.First(dbCustomer =&amp;gt; dbCustomer.ID == id);
        }
    }
}&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;The client will get the correct customer, but it won’t have the Orders property filled, even if the customer has orders the property value will be null. The reason for this behavior is that the generated code doesn’t execute the query against the database when it’s serializing. The solution is to access all data members before it serializes.&lt;/p&gt;&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;StoreService &lt;/span&gt;&lt;span style="background: black; color: white"&gt;: &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;IStoreService
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Customer &lt;/span&gt;&lt;span style="background: black; color: white"&gt;GetCustomerWithRelations(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;id)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;using &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;store = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;StoreDataContext&lt;/span&gt;&lt;span style="background: black; color: white"&gt;())
        {
            &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Customer &lt;/span&gt;&lt;span style="background: black; color: white"&gt;customer = store.Customers.First(dbCustomer =&amp;gt; dbCustomer.ID == id);
            VisitDataMembers(customer);            
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="background: black; color: white"&gt;customer;
        }
    }

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public static void &lt;/span&gt;&lt;span style="background: black; color: white"&gt;VisitDataMembers(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;object &lt;/span&gt;&lt;span style="background: black; color: white"&gt;dataMember)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;if &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(dataMember == &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;null&lt;/span&gt;&lt;span style="background: black; color: white"&gt;)
        {
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return&lt;/span&gt;&lt;span style="background: black; color: white"&gt;;
        }

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;bool &lt;/span&gt;&lt;span style="background: black; color: white"&gt;isEnumerable = dataMember &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;is &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;IEnumerable&lt;/span&gt;&lt;span style="background: black; color: white"&gt;;
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;if &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(isEnumerable)
        {
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;foreach &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;item &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;in &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;IEnumerable&lt;/span&gt;&lt;span style="background: black; color: white"&gt;)dataMember)
            {
                VisitDataMembers(item);
            }
        }

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;properties = dataMember.GetType().GetProperties();
        &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;IEnumerable&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;PropertyInfo&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt; dataMemberProperties = 
            properties.Where(property =&amp;gt; property.IsDefined(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;typeof&lt;/span&gt;&lt;span style="background: black; color: white"&gt;(&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;DataMemberAttribute&lt;/span&gt;&lt;span style="background: black; color: white"&gt;), &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;true&lt;/span&gt;&lt;span style="background: black; color: white"&gt;));
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;foreach &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;PropertyInfo &lt;/span&gt;&lt;span style="background: black; color: white"&gt;dataMemberProperty &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;in &lt;/span&gt;&lt;span style="background: black; color: white"&gt;dataMemberProperties)
        {
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;dataMemberValue = dataMemberProperty.GetValue(dataMember, &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;null&lt;/span&gt;&lt;span style="background: black; color: white"&gt;);
            VisitDataMembers(dataMemberValue);            
        }
    }
}
&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;This &lt;em&gt;VisitDataMembers &lt;/em&gt;method ensures all data members properties are accessed at least once before serialization and the client will be able to use all the data which is accessible for the data object tree. For example in the sample schema, the client will be able to get from customer to orders to products to materials.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-1786152090242732662?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=LAygkq5FkDQ:FXR1Da3rgXI:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=LAygkq5FkDQ:FXR1Da3rgXI:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/LAygkq5FkDQ" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/LAygkq5FkDQ/how-to-pass-linq-to-sql-data-objects.html</link><author>noreply@blogger.com (Elisha)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh5.ggpht.com/_Zs5PrU6IvpQ/SxeD1Z3QsxI/AAAAAAAAAOU/ngj2DkQ_wio/s72-c/image_thumb%5B4%5D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2009/12/how-to-pass-linq-to-sql-data-objects.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-4072716272532023483.post-6427771313230957287</guid><pubDate>Wed, 25 Nov 2009 20:05:00 +0000</pubDate><atom:updated>2012-02-18T09:23:10.512+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Easy Wins Optimizations</category><category domain="http://www.blogger.com/atom/ns#">Sorted List</category><category domain="http://www.blogger.com/atom/ns#">Data Structures</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">.Net</category><title>Easy Wins Optimizations – Sorted List</title><description>This is the first post of easy wins optimizations posts. The need for these posts comes from the fact the most of us hardly ever need it :) Sounds wired? It should. What it means is that we don’t need in most of the time, the most naive code does the best work for us. When we encounter the case that requires optimization we hardly remember the simplest ways of doing it.&lt;br /&gt;
In this post on sorted list we’ll go over an example of optimizing simple case.&lt;br /&gt;
&lt;h3&gt;How to find a person in a collection whose age is closest mine?&lt;/h3&gt;Assume we have a person class with age defined on it:&lt;br /&gt;
&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public double &lt;/span&gt;&lt;span style="background: black; color: white"&gt;Age { &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;get&lt;/span&gt;&lt;span style="background: black; color: white"&gt;; &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;private set&lt;/span&gt;&lt;span style="background: black; color: white"&gt;; }

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="background: black; color: white"&gt;Person(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double &lt;/span&gt;&lt;span style="background: black; color: white"&gt;age)
    {
        Age = age;
    }
}
&lt;/span&gt;&lt;/pre&gt;What we want is to collect many people into a list, and any time we asked about an age, we find the closest person to this age. We can think of it as an application for dating service that match people by age.&lt;br /&gt;
&lt;h2&gt;The naive solution&lt;/h2&gt;So what can be simpler than collecting all persons to a list? Probably nothing, this is how we do it:&lt;br /&gt;
&lt;pre class="code" style="background: black"&gt;&lt;span style="background: black; color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;NaivePersonFinder &lt;/span&gt;&lt;span style="background: black; color: white"&gt;: &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;IPersonFinder
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;private readonly &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;List&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt; persons = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;List&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt;();

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="background: black; color: white"&gt;Add(&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person &lt;/span&gt;&lt;span style="background: black; color: white"&gt;person)
    {
        persons.Add(person);
    }

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person &lt;/span&gt;&lt;span style="background: black; color: white"&gt;FindPeopleInRange(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double &lt;/span&gt;&lt;span style="background: black; color: white"&gt;requiredAge)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person &lt;/span&gt;&lt;span style="background: black; color: white"&gt;closestPerson = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;null&lt;/span&gt;&lt;span style="background: black; color: white"&gt;;
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double &lt;/span&gt;&lt;span style="background: black; color: white"&gt;smallestDiffrence = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.MaxValue;
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;foreach &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;person &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;in &lt;/span&gt;&lt;span style="background: black; color: white"&gt;persons)
        {
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double &lt;/span&gt;&lt;span style="background: black; color: white"&gt;difference = &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Math&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Abs(person.Age - requiredAge);
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;if &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(difference &amp;lt; smallestDiffrence)
            {
                smallestDiffrence = difference;
                closestPerson = person;
            }
        }

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="background: black; color: white"&gt;closestPerson;
    }
}
&lt;/span&gt;&lt;/pre&gt;The code iterates over the collection in the most straight forward way there is and updates the closest person whenever it encounter closer person. Simple! Isn’t it?&lt;br /&gt;
&lt;h3&gt;But I need faster results!&lt;/h3&gt;&lt;span style="font-weight: bold;"&gt;The sorted list solution&lt;/span&gt;&lt;br /&gt;
How does sorted list helps us here? Sorted list allow us to search items using &lt;a href="http://en.wikipedia.org/wiki/Binary_search_algorithm" target="_blank"&gt;Binary Search&lt;/a&gt;. Binary search saves a lot of time since it has to query very few items in the collection in order to find the closest one. For example, to find the closest item in a collection of 1,000 items it’ll have to query ~10 and saves iteration over the hole 1,000.&lt;br /&gt;
&lt;h2&gt;Some code&lt;/h2&gt;&lt;pre class="code" style="background: black;"&gt;&lt;span style="background: black; color: #cc7832"&gt;public class &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;SortedPersonFinder &lt;/span&gt;&lt;span style="background: black; color: white"&gt;: &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;IPersonFinder
&lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;private readonly &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;SortedList&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double&lt;/span&gt;&lt;span style="background: black; color: white"&gt;, &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt; persons = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;SortedList&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double&lt;/span&gt;&lt;span style="background: black; color: white"&gt;, &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt;();

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public void &lt;/span&gt;&lt;span style="background: black; color: white"&gt;Add(&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person &lt;/span&gt;&lt;span style="background: black; color: white"&gt;person)
    {
        persons.Add(person.Age, person);
    }

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;public &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person &lt;/span&gt;&lt;span style="background: black; color: white"&gt;FindPeopleInRange(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double &lt;/span&gt;&lt;span style="background: black; color: white"&gt;requiredAge)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;if &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(persons.ContainsKey(requiredAge))
        {
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="background: black; color: white"&gt;persons[requiredAge];
        }

        &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;IList&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt; sortedAges = persons.Keys;

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;index = BinarySearchIndex(requiredAge);

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;closestPersons = &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;new &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;List&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Person&lt;/span&gt;&lt;span style="background: black; color: white"&gt;&amp;gt;(&lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;3&lt;/span&gt;&lt;span style="background: black; color: white"&gt;);

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;if &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(index &amp;gt; &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;0&lt;/span&gt;&lt;span style="background: black; color: white"&gt;)
        {
            closestPersons.Add(persons[sortedAges[index - &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;1&lt;/span&gt;&lt;span style="background: black; color: white"&gt;]]);
        }

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;if &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(index &amp;lt; sortedAges.Count - &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;1&lt;/span&gt;&lt;span style="background: black; color: white"&gt;)
        {
            closestPersons.Add(persons[sortedAges[index + &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;1&lt;/span&gt;&lt;span style="background: black; color: white"&gt;]]);
        }

        closestPersons.Add(persons[sortedAges[index]]);

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="background: black; color: white"&gt;closestPersons.OrderBy(person =&amp;gt; &lt;/span&gt;&lt;span style="background: black; color: #ffc66d"&gt;Math&lt;/span&gt;&lt;span style="background: black; color: white"&gt;.Abs(person.Age - requiredAge)).First();
    }

    &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;private int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;BinarySearchIndex(&lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double &lt;/span&gt;&lt;span style="background: black; color: white"&gt;requiredAge)
    {
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;sortedAges = persons.Keys;

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;scopeStart = &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;0&lt;/span&gt;&lt;span style="background: black; color: white"&gt;;
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;var &lt;/span&gt;&lt;span style="background: black; color: white"&gt;scopeEnd = sortedAges.Count - &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;1&lt;/span&gt;&lt;span style="background: black; color: white"&gt;;

        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;int &lt;/span&gt;&lt;span style="background: black; color: white"&gt;index = &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;0&lt;/span&gt;&lt;span style="background: black; color: white"&gt;;
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;while &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(scopeEnd &amp;gt; scopeStart )
        {
            index = (scopeStart + scopeEnd) / &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;2&lt;/span&gt;&lt;span style="background: black; color: white"&gt;;
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;double &lt;/span&gt;&lt;span style="background: black; color: white"&gt;ageAtIndex = sortedAges[index];
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;if &lt;/span&gt;&lt;span style="background: black; color: white"&gt;(requiredAge &amp;gt; ageAtIndex)
            {
                scopeStart = index + &lt;/span&gt;&lt;span style="background: black; color: #6897bb"&gt;1&lt;/span&gt;&lt;span style="background: black; color: white"&gt;;
            }
            &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;else
            &lt;/span&gt;&lt;span style="background: black; color: white"&gt;{
                scopeEnd = index;
            }
        }
        &lt;/span&gt;&lt;span style="background: black; color: #cc7832"&gt;return &lt;/span&gt;&lt;span style="background: black; color: white"&gt;index;
    }
}&lt;/span&gt;&lt;/pre&gt;The code is more complex than the naive version, but it finds the results much faster. It uses .Net &lt;a href="http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.aspx" target="_blank"&gt;Sorted List&lt;/a&gt; collection. This is a collection that updates a collection of&amp;nbsp; keys whenever the collection changes. The keys kept ordered and we can easily access them and binary search them.&lt;br /&gt;
&lt;h3&gt;How much faster is it?&lt;/h3&gt;On 100,000 persons collection and 50,000 queries the running time of the sorted list is much more faster than the naive:&lt;br /&gt;
The naive solution did it in average time of ~100 seconds&lt;br /&gt;
The sorted list solution had average time of ~6 seconds. This is a major improvement, it means that it ran more the 15 times faster than the naive solution.&lt;br /&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;If we have a collection on which order can be applied &lt;strong&gt;AND&lt;/strong&gt; we also need quick results for queries based on the order sorted list can easily improve running time. We must always remember that the running time is usually negligible even in the most naive code. If no optimization required – don’t optimize, more gain we’ll be earned from simple and maintainable code.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4072716272532023483-6427771313230957287?l=www.elishalom.com' alt='' /&gt;&lt;/div&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=RoZ4okEJzGk:rw18tplPCzg:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?a=RoZ4okEJzGk:rw18tplPCzg:63t7Ie-LG7Y"&gt;&lt;img src="http://feeds.feedburner.com/~ff/TheoryToPracticeToTheory?d=63t7Ie-LG7Y" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/TheoryToPracticeToTheory/~4/RoZ4okEJzGk" height="1" width="1"/&gt;</description><link>http://feedproxy.google.com/~r/TheoryToPracticeToTheory/~3/RoZ4okEJzGk/easy-wins-optimizations-sorted-list.html</link><author>noreply@blogger.com (Elisha)</author><thr:total>0</thr:total><feedburner:origLink>http://www.elishalom.com/2009/11/easy-wins-optimizations-sorted-list.html</feedburner:origLink></item></channel></rss>

