﻿<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:blogChannel="http://backend.userland.com/blogChannelModule" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
  <channel>
    <title>Sean Blakemore's Blog</title>
    <description>Like trying to fit a square peg in a round hole</description>
    <link>http://sblakemore.com/blog/</link>
    <docs>http://www.rssboard.org/rss-specification</docs>
    <generator>BlogEngine.NET 2.9.1.0</generator>
    <language>en-GB</language>
    <blogChannel:blogRoll>http://sblakemore.com/blog/opml.axd</blogChannel:blogRoll>
    <blogChannel:blink>http://sblakemore.com/blog/syndication.axd</blogChannel:blink>
    <dc:creator>Sean Blakemore</dc:creator>
    <dc:title>Sean Blakemore's Blog</dc:title>
    <geo:lat>-27.539940</geo:lat>
    <geo:long>153.077400</geo:long>
    <item>
      <title>Silencing a 3D Printer - Stepper Dampers</title>
      <description>&lt;p&gt;I recently built a new 3D printer, my second after the &lt;a href="http://reprap.org/wiki/MendelMax"&gt;MendelMax&lt;/a&gt; I’ve been running for a few years now. I went with a &lt;a href="http://reprap.org/wiki/Kossel"&gt;Kossel Mini&lt;/a&gt;, it’s an amazing little machine and since it’s designed to print only in PLA it can sit right next to me on the desk without filling the room with nasty ABS fumes.&lt;/p&gt;  &lt;p&gt;That’s all well and good but if you’ve ever sat next to a 3D printer you know that they can be pretty noisy. Especially one as fast as the Kossel Mini, it can be really distractingly loud. After searching around for solutions I came across some whispers of a product on a 3D printing forum about stepper dampers and just how much of an amazing difference they made. It seems there is still very little awareness of these little gems in the community but the few that have tried them are adamant that it’s the best upgrade they’ve ever done!&lt;/p&gt;  &lt;p&gt;&lt;a href="http://sblakemore.com/blog/image.axd?picture=DSC01957.jpg"&gt;&lt;img title="DSC01957" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="DSC01957" src="http://sblakemore.com/blog/image.axd?picture=DSC01957_thumb.jpg" width="487" height="324"&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;As you can see they are made from two metal elements joined by a rubber gasket between them. One side bolts to the motor and the other to your printer as normal, this leads to the motor to be fully isolated from the printer. The rubber is formulated to dampen the specific frequencies the motors produce and is very stiff, with the amount a printers belts are tightened there is no danger of problems caused by the rubber flexing and moving.&lt;/p&gt;  &lt;p&gt;So… do they work? Well as with the few others than have tried them I can say with certainty that they are simply jaw-droppingly amazing! I can now sit right next to the printer and completely forget it is even running. Check out this video I made to show the difference.&lt;/p&gt;  &lt;div id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:23f81c95-0efb-4941-b9c6-21471ff5bf82" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;div&gt;&lt;object width="478" height="268"&gt;&lt;param name="movie" value="http://www.youtube.com/v/MEWux_inEvM?hl=en&amp;amp;hd=1"&gt;&lt;embed src="http://www.youtube.com/v/MEWux_inEvM?hl=en&amp;amp;hd=1" type="application/x-shockwave-flash" width="478" height="268"&gt;&lt;/object&gt;&lt;/div&gt;&lt;div style="width:478px;clear:both;font-size:.8em"&gt;I now couldn’t live without these!&lt;/div&gt;&lt;/div&gt;  &lt;p&gt;&amp;nbsp;&lt;/p&gt;  &lt;p&gt;As you can see the difference is around 17dB! Nothing more to be said, they really are that good!&lt;/p&gt;</description>
      <link>http://sblakemore.com/blog/post/Silencing-a-3D-Printer-Stepper-Dampers.aspx</link>
      <comments>http://sblakemore.com/blog/post/Silencing-a-3D-Printer-Stepper-Dampers.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=7b1567a9-0bcc-461e-acab-efdb5836570a</guid>
      <pubDate>Thu, 26 Jun 2014 10:26:00 +1800</pubDate>
      <category>3D Printing</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=7b1567a9-0bcc-461e-acab-efdb5836570a</pingback:target>
      <slash:comments>29</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=7b1567a9-0bcc-461e-acab-efdb5836570a</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/Silencing-a-3D-Printer-Stepper-Dampers.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=7b1567a9-0bcc-461e-acab-efdb5836570a</wfw:commentRss>
    </item>
    <item>
      <title>What JavaScript taught me about C# – Understanding ‘Access to modified closure’</title>
      <description>&lt;h3&gt;Background&lt;/h3&gt;
&lt;p&gt;If you&amp;rsquo;ve spent any time writing C# using a copy of ReSharper you will have come across the phrase &amp;lsquo;Access to modified closure&amp;rsquo;. It&amp;rsquo;s a well known warning and there are &lt;a href="http://stackoverflow.com/questions/4675252/access-to-modified-closure-question"&gt;plenty&lt;/a&gt; &lt;a href="http://stackoverflow.com/questions/235455/access-to-modified-closure"&gt;of&lt;/a&gt; &lt;a href="http://stackoverflow.com/questions/304258/access-to-modified-closure-2"&gt;StackOverflow&lt;/a&gt; &lt;a href="http://stackoverflow.com/questions/1688465/resharper-warning-access-to-modified-closure"&gt;questions&lt;/a&gt; and &lt;a href="http://weblogs.asp.net/fbouma/archive/2009/06/25/linq-beware-of-the-access-to-modified-closure-demon.aspx"&gt;blog&lt;/a&gt; &lt;a href="http://www.ticklishtechs.net/2009/04/10/access-to-modified-closure/"&gt;posts&lt;/a&gt; about it.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;ve personally run up against this many times, and although I know what to do when it bites me, I&amp;rsquo;ve never really understood why it was happening. It just never really clicked for me.&lt;/p&gt;
&lt;p&gt;Not until recently that is, when I decided it was time for me to become a JavaScript programmer instead of a jQuery programmer and actually learn the language properly!&lt;/p&gt;
&lt;h3&gt;The Warning&lt;/h3&gt;
&lt;p&gt;Here is some code, as simple as I could make it, that produces the warning and illustrates the behaviour:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:51dddc32-af99-41d1-9d68-715e53bd0c2f" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;var actions = new Action[5];

for (int i = 0; i &amp;lt; actions.Length; i++)
    actions[i] = () =&amp;gt; Console.WriteLine(i);

foreach (var action in actions)
    action();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;The &amp;lsquo;Access to modified closure&amp;rsquo; is referring to the use of &amp;lsquo;i&amp;rsquo;, the loop variable, inside the lambda and being passed to &amp;lsquo;Console.WriteLine&amp;rsquo;. If you haven&amp;rsquo;t run into this before you&amp;rsquo;ll be surprised to find that this code will produce the following output:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:3b285a19-0fed-41e3-9d2a-46e597db34b5" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: text;"&gt;5
5
5
5
5&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;The way to produce the behaviour you would have been expecting is to make a copy of the loop variable inside the loop and use that instead:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:2443cbf0-cc97-456c-b2fc-665fbbbfde32" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;var actions = new Action[5];

for (int i = 0; i &amp;lt; actions.Length; i++)
{
    var local = i;
    actions[i] = () =&amp;gt; Console.WriteLine(local);
}

foreach (var action in actions)
    action();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;This will now produce:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:45bc0185-d2fc-41d3-9820-c62227df7198" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: text;"&gt;0
1
2
3
4&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Ok, that&amp;rsquo;s all well and good, we can now easily enough fix this problem if we run into it. Doesn&amp;rsquo;t it just feel a bit weird though? Why would making a copy of the variable and then passing that to &amp;lsquo;Console.WriteLine&amp;rsquo; actually change the output?&lt;/p&gt;
&lt;h3&gt;Epiphany&lt;/h3&gt;
&lt;p&gt;Everywhere else I&amp;rsquo;ve read about this talks about &amp;lsquo;capturing variables&amp;rsquo; or &amp;lsquo;closing over variables&amp;rsquo;. Sometimes all it takes is a particular combination of words, just the right phrasing, to make you feel that you really understand something.&lt;/p&gt;
&lt;p&gt;It wasn&amp;rsquo;t quite correct to say that JavaScript taught me anything about C#, it was actually Douglas Crockford, it was in his book &amp;ldquo;The Good Parts&amp;rdquo; that I found just the right way of explaining closures. Here is the magic sentence:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&amp;ldquo;It is important to understand that the inner function has access to the actual variables of the outer functions and not copies&amp;rdquo;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So the lambdas have access to the actual variable &amp;lsquo;i&amp;rsquo; and not a copy with the value at the time the lambda was created. Because the loop has finished and &amp;lsquo;i&amp;rsquo; has been incremented to 5 by the time we execute the lambdas, that is what we see. On The other hand if we create a variable which is local to the loop then the lambda has access to the value at the time because the local variable is created for each iteration!&lt;/p&gt;
&lt;p&gt;Now consider this code:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:ca5988da-035f-4302-84f5-df8382bf82a6" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;var i = 1;

Action action = () =&amp;gt; Console.WriteLine(i);

i++;

action();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Which will output:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:5c36d497-cad3-4606-bfbe-dd7a1d5d8c1b" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: text;"&gt;2&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;And this code:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:c44abce8-a034-4cc6-b2b1-58d42ed3e122" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;var i = 1;

var j = i;
Action action = () =&amp;gt; Console.WriteLine(j);

i++;

action();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Which will output:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:49ba1857-09ac-4dea-ba00-42b9ce677122" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: text;"&gt;1&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Brilliant! How did I not fully grasp this before?&lt;/p&gt;
&lt;h3&gt;Breaking change in C# 5&lt;/h3&gt;
&lt;p&gt;Using Visual Studio 2010 and .Net 4, if we change the problem code to use a &amp;lsquo;foreach&amp;rsquo; loop instead we have the same problem because the loop variable is reassigned for each iteration instead of being recreated:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:10059012-f321-4cab-bdbf-6fa65c910d60" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;var values = new[] { 0, 1, 2, 3, 4 };
var actions = new List&amp;lt;Action&amp;gt;();

foreach (var v in values)
{
    actions.Add(() =&amp;gt; Console.WriteLine(v));
}

foreach (var action in actions)
    action();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;And this will output:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:a4842807-7aa7-42c9-8ff1-8b3911428cc0" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: text;"&gt;4
4
4
4
4&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;It&amp;rsquo;s &amp;lsquo;4&amp;rsquo; and not &amp;lsquo;5&amp;rsquo; this time because in the &amp;lsquo;for&amp;rsquo; the loop variable will be incremented to the point that the test in the second statement of the declaration fails and the loop exits.&lt;/p&gt;
&lt;p&gt;This is as we would expect given the explanation above, however there is a twist! If you take this code and compile it Visual Studio 2011 using .Net 4.5 then you will get this following output:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:dfd0b76d-7c20-4a9d-b3c6-5a8eb60912e1" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: text;"&gt;0
1
2
3
4&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Well what do you know, they &amp;ldquo;fixed&amp;rdquo; it. Not that it was really broken in the first place, just unexpected unless you properly understand closures. This was achieved by making it such that the variable is now logically declared inside the loop. Be aware however, they didn&amp;rsquo;t change the &amp;lsquo;for&amp;rsquo; loop and that still works as before.&lt;/p&gt;</description>
      <link>http://sblakemore.com/blog/post/What-JavaScript-taught-me-about-C-Understanding-Access-to-modified-closure.aspx</link>
      <comments>http://sblakemore.com/blog/post/What-JavaScript-taught-me-about-C-Understanding-Access-to-modified-closure.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=6c590ce3-467d-467a-9f42-b9ec1c653f48</guid>
      <pubDate>Wed, 09 May 2012 14:04:00 +1800</pubDate>
      <category>Development</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=6c590ce3-467d-467a-9f42-b9ec1c653f48</pingback:target>
      <slash:comments>7</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=6c590ce3-467d-467a-9f42-b9ec1c653f48</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/What-JavaScript-taught-me-about-C-Understanding-Access-to-modified-closure.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=6c590ce3-467d-467a-9f42-b9ec1c653f48</wfw:commentRss>
    </item>
    <item>
      <title>Doing indecent things with Mono.Cecil - An alternative to ILMerge for WPF</title>
      <description>&lt;h3&gt;Background&lt;/h3&gt;
&lt;p&gt;ILMerge is a great tool for merging .NET assemblies, when we want to deploy an application as a single executable file we can merge in the dependencies and we&amp;rsquo;re good to go.&lt;/p&gt;
&lt;p&gt;Unfortunately ILMerge doesn&amp;rsquo;t work on WPF applications because according to the &lt;a href="http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx"&gt;ILMerge page&lt;/a&gt; on Microsoft Research:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;They contain resources with encoded assembly identities. ILMerge is unable to deserialize the resources, modify the assembly identities, and then re-serialize them.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h3&gt;The Fix&lt;/h3&gt;
&lt;p&gt;There has been an alternative floating around for some time which can be seen &lt;a href="http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx"&gt;here&lt;/a&gt;, but in short you can add the DLLs your application depends upon as an embedded resource and then load them in the AssemblyResolve event for the AppDomain. Here is the code reproduced, it&amp;rsquo;s pretty short and to the point:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:1c73d6fa-fffe-4b8e-bab9-5f99967780ac" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =&amp;gt; 
{
   String resourceName = "AssemblyLoadingAndReflection." +
      new AssemblyName(args.Name).Name + ".dll";

   using (var stream = Assembly.GetExecutingAssembly()
                          .GetManifestResourceStream(resourceName)) 
   {
      Byte[] assemblyData = new Byte[stream.Length];
      stream.Read(assemblyData, 0, assemblyData.Length);
      return Assembly.Load(assemblyData);
   }
};&lt;/pre&gt;
&lt;/div&gt;
&lt;h3&gt;The End?&lt;/h3&gt;
&lt;p&gt;Great, so why am I writing another blog post about this? Well there are a couple of problems with this solution on it&amp;rsquo;s own.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Adding these assemblies to your Visual Studio solution and setting them to Embedded Resource feels pretty messy and on a large project you can easily build up quite a few referenced DLLs. This is even worse when trying to embed libraries which are a project in the same solution.&lt;/li&gt;
&lt;li&gt;You can&amp;rsquo;t easily add the AssemblyResolve hook in your WPF application early enough, before it tries to load your referenced libraries. You have to shim the WPF App class with another class that has a Main method, make this the program startup object, then from there you can add the hook and run the WPF App.Main method. Obviously not ideal.&lt;/li&gt;
&lt;li&gt;If you&amp;rsquo;re distributing a library rather than an application, and have other libraries merged in as resources, there isn&amp;rsquo;t anywhere you can properly attach the hook and have everything work as expected.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;The Redux&lt;/h3&gt;
&lt;p&gt;There is a little-known feature of the CLR called a Module Initializer which is simply a global function which runs when a managed module first loads and is guaranteed to run before any other code. This looks like the perfect place to hook the AssemblyResolve method, it would allow us to use this technique in libraries and it would also remove the need to shim the WPF App class.&lt;/p&gt;
&lt;p&gt;Wait a second, that sounds really neat, how come I&amp;rsquo;ve never heard of this before? Simple, although they&amp;rsquo;re a feature of the CLR they are not exposed in C#. There is no way to create them! We can still use them though, by injecting the IL for the implementation using Mono.Cecli. There is a great post about how to do that &lt;a href="http://einaregilsson.com/module-initializers-in-csharp/"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Things get slightly hairy when you start talking about rewriting assemblies and injecting IL but it really isn&amp;rsquo;t too bad and Mono.Cecil makes things easy.&lt;/p&gt;
&lt;p&gt;But just hang on one second, if we&amp;rsquo;re doing this post-build and modifying the assembly, why can&amp;rsquo;t we also inject the implementation for the AssemblyResolve event, not just the hook, and for that matter why don&amp;rsquo;t we embed the assemblies at this point also. If we could do all this, surely we could take a pre-built application which has no special code to enable any of this, like when using ILMerge, and then inject the required code, embed the assemblies and everything should just work!&lt;/p&gt;
&lt;h3&gt;The Code&lt;/h3&gt;
&lt;p&gt;At this point I think I&amp;rsquo;m just going to dump the code on you, there isn&amp;rsquo;t too much of it but it does deal with some complex things so if you want to dig into it you can. All up there is about 150 lines of code in total, which is pretty nuts if you think about what it&amp;rsquo;s actually doing&amp;hellip;&lt;/p&gt;
&lt;p&gt;First up we have a console application with the following Main method:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:ce5187dd-41f8-4d0a-89e8-b2763bc3e7f8" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;static void Main(string[] args)
{
    var path = args[0];
    var dlls = Directory.GetFiles(Path.GetDirectoryName(path), "*.dll");
    var targetAssembly = AssemblyDefinition.ReadAssembly(path);

    var packer = new Packer(targetAssembly);
    packer.Embed(dlls);
    packer.Inject();

    targetAssembly.Write(path);
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;So we expect to be passed the path to an executable and we assume that we should merge all of the DLL files in the same directory as the executable. Then we use the nifty Packer class to embed the DLLs and inject the required IL.&lt;/p&gt;
&lt;p&gt;Take a deep breath because here is the Packer class in full:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:32d3b5c9-d58c-4364-b156-759890bad937" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;internal class Packer
{
    private readonly AssemblyDefinition assembly;

    public Packer(AssemblyDefinition assembly)
    {
        this.assembly = assembly;
    }

    public void Embed(IEnumerable&amp;lt;string&amp;gt; files)
    {
        foreach (var file in files)
        {
            var data = File.ReadAllBytes(file);
            var resourceName = string.Format("{0}.{1}", assembly.Name.Name, Path.GetFileName(file));
            var resource = new EmbeddedResource(resourceName, ManifestResourceAttributes.Private, data);
            assembly.MainModule.Resources.Add(resource);
        }
    }

    public void Inject()
    {
        var assemblyResolve = DefineOnAssemblyResolveMethod();
        var ctor = DefineModuleCtor(assemblyResolve);

        var moduleType = assembly.MainModule.Types.Single(x =&amp;gt; x.Name == "&amp;lt;Module&amp;gt;");
        moduleType.Methods.Add(assemblyResolve);
        moduleType.Methods.Add(ctor);
    }

    private MethodDefinition DefineOnAssemblyResolveMethod()
    {
        var method = new MethodDefinition("OnAssemblyResolve",
            MethodAttributes.Private |
            MethodAttributes.HideBySig |
            MethodAttributes.Static,
            ImportType&amp;lt;Assembly&amp;gt;());
        method.Parameters.Add(new ParameterDefinition(ImportType&amp;lt;object&amp;gt;()));
        method.Parameters.Add(new ParameterDefinition(ImportType&amp;lt;ResolveEventArgs&amp;gt;()));

        method.Body.Variables.Add(new VariableDefinition(ImportType&amp;lt;Assembly&amp;gt;()));
        method.Body.Variables.Add(new VariableDefinition(ImportType&amp;lt;string&amp;gt;()));
        method.Body.Variables.Add(new VariableDefinition(ImportType&amp;lt;Stream&amp;gt;()));
        method.Body.Variables.Add(new VariableDefinition(ImportType&amp;lt;byte[]&amp;gt;()));
        method.Body.InitLocals = true;

        var il = method.Body.GetILProcessor();
        il.Emit(OpCodes.Call, ImportMethod&amp;lt;Assembly&amp;gt;("GetEntryAssembly"));
        il.Emit(OpCodes.Stloc_0);
        il.Emit(OpCodes.Ldstr, "{0}.{1}.dll");
        il.Emit(OpCodes.Ldloc_0);
        il.Emit(OpCodes.Callvirt, ImportMethod&amp;lt;Assembly&amp;gt;("GetName", new Type[0]));
        il.Emit(OpCodes.Callvirt, ImportMethod&amp;lt;AssemblyName&amp;gt;("get_Name"));
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Callvirt, ImportMethod&amp;lt;ResolveEventArgs&amp;gt;("get_Name"));
        il.Emit(OpCodes.Newobj, ImportCtor&amp;lt;AssemblyName&amp;gt;(typeof(string)));
        il.Emit(OpCodes.Call, ImportMethod&amp;lt;AssemblyName&amp;gt;("get_Name"));
        il.Emit(OpCodes.Call, ImportMethod&amp;lt;string&amp;gt;("Format", typeof(string), typeof(object), typeof(object)));
        il.Emit(OpCodes.Stloc_1);
        il.Emit(OpCodes.Ldloc_0);
        il.Emit(OpCodes.Ldloc_1);
        il.Emit(OpCodes.Callvirt, ImportMethod&amp;lt;Assembly&amp;gt;("GetManifestResourceStream", typeof(string)));
        il.Emit(OpCodes.Stloc_2);
        il.Emit(OpCodes.Ldloc_2);
        il.Emit(OpCodes.Brfalse_S, il.Create(OpCodes.Ldnull));
        il.Emit(OpCodes.Ldloc_2);
        il.Emit(OpCodes.Callvirt, ImportMethod&amp;lt;Stream&amp;gt;("get_Length"));
        il.Emit(OpCodes.Conv_Ovf_I);
        il.Emit(OpCodes.Newarr, ImportType&amp;lt;byte&amp;gt;());
        il.Emit(OpCodes.Stloc_3);
        il.Emit(OpCodes.Ldloc_2);
        il.Emit(OpCodes.Ldloc_3);
        il.Emit(OpCodes.Ldc_I4_0);
        il.Emit(OpCodes.Ldloc_3);
        il.Emit(OpCodes.Ldlen);
        il.Emit(OpCodes.Conv_I4);
        il.Emit(OpCodes.Callvirt, ImportMethod&amp;lt;Stream&amp;gt;("Read", typeof(byte[]), typeof(int), typeof(int)));
        il.Emit(OpCodes.Pop);
        il.Emit(OpCodes.Ldloc_2);
        il.Emit(OpCodes.Callvirt, ImportMethod&amp;lt;Stream&amp;gt;("Dispose"));
        il.Emit(OpCodes.Ldloc_3);
        il.Emit(OpCodes.Call, ImportMethod&amp;lt;Assembly&amp;gt;("Load", typeof(byte[])));
        il.Emit(OpCodes.Ret);
        il.Append(il.Create(OpCodes.Ldnull));
        il.Emit(OpCodes.Ret);

        return method;
    }

    private MethodDefinition DefineModuleCtor(MethodDefinition assemblyResolveMethod)
    {
        var ctor = new MethodDefinition(".cctor",
            MethodAttributes.Static |
            MethodAttributes.SpecialName |
            MethodAttributes.RTSpecialName,
            assembly.MainModule.Import(typeof (void)));

        var il = ctor.Body.GetILProcessor();
        il.Emit(OpCodes.Call, ImportMethod&amp;lt;AppDomain&amp;gt;("get_CurrentDomain"));
        il.Emit(OpCodes.Ldnull);
        il.Emit(OpCodes.Ldftn, assemblyResolveMethod);
        il.Emit(OpCodes.Newobj, ImportCtor&amp;lt;ResolveEventHandler&amp;gt;(typeof(object), typeof(IntPtr)));
        il.Emit(OpCodes.Callvirt, ImportMethod&amp;lt;AppDomain&amp;gt;("add_AssemblyResolve"));
        il.Emit(OpCodes.Ret);

        return ctor;
    }

    private TypeReference ImportType&amp;lt;T&amp;gt;()
    {
        return assembly.MainModule.Import(typeof(T));
    }
    private MethodReference ImportMethod&amp;lt;T&amp;gt;(string methodName)
    {
        return assembly.MainModule.Import(typeof(T).GetMethod(methodName));
    }
    private MethodReference ImportMethod&amp;lt;T&amp;gt;(string methodName, params Type[] types)
    {
        return assembly.MainModule.Import(typeof(T).GetMethod(methodName, types));
    }
    private MethodReference ImportCtor&amp;lt;T&amp;gt;(params Type[] types)
    {
        return assembly.MainModule.Import(typeof(T).GetConstructor(types));
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;If you just let your eyes glaze over the il.Emit calls, this is pretty easy to follow. You can just assume that all the IL is the implementation of the AssemblyResolve event and the hook for it in the Module Initializer. We just add the definition of these methods and add the DLLs as resources and Mono.Cecil does the rest.&lt;/p&gt;
&lt;h3&gt;The proof is in the pudding&lt;/h3&gt;
&lt;p&gt;I was able to run the above code against a moderately large WPF application which has been under development for quite some time, and in production for over 6 months, without any thought of merging dependencies. The EXE file got considerably larger. I then deleted all the DLLs from the directory and somewhat to my surprise the application ran without any issues!&lt;/p&gt;
&lt;p&gt;The ultimate test of something like this is whether it can merge itself. Obviously the Packer class makes heavy use of Mono.Cecil to get the job done so my console application has a reference to that DLL. Happily I can report that running this 150 lines of code application on itself successfully produces a single EXE file with Mono.Cecil packed inside and everything works as it should.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;I was actually playing around with this almost exactly a year ago, when I ran across the code I thought it might be a bit of fun and I should write it up for a blog post. It has no real error handling and has not been thoroughly tested or used in production. As such please consider it a sample and proof of concept only. Don&amp;rsquo;t blame me if it kills your pet or anything.&lt;/p&gt;
&lt;p&gt;Here is the sample:&lt;/p&gt;
&lt;div id="scid:F60BB8FA-6F02-4999-8F5E-9DD4E92C4DA7:c47d25a7-2dda-46dd-9453-cc0494436de8" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;div&gt;&lt;a onclick="javascript: pageTracker._trackPageview('Packager.zip');" href="http://sblakemore.com/blog/file.axd?file=Packager.zip" target="_self"&gt;Packager.zip&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;</description>
      <link>http://sblakemore.com/blog/post/An-alternative-to-ILMerge-for-WPF.aspx</link>
      <comments>http://sblakemore.com/blog/post/An-alternative-to-ILMerge-for-WPF.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=6800623d-d6b7-41ac-9370-b29ae1a5ee52</guid>
      <pubDate>Thu, 05 Apr 2012 16:20:00 +1800</pubDate>
      <category>Development</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=6800623d-d6b7-41ac-9370-b29ae1a5ee52</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=6800623d-d6b7-41ac-9370-b29ae1a5ee52</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/An-alternative-to-ILMerge-for-WPF.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=6800623d-d6b7-41ac-9370-b29ae1a5ee52</wfw:commentRss>
    </item>
    <item>
      <title>Multiple login pages with ASP.NET MVC</title>
      <description>&lt;p&gt;I’m working on a multi-tenant web application where I need to have several different login forms for different types of users. For example for Admins, Affiliates, Customers etc.&lt;/p&gt;  &lt;h3&gt;The problem&lt;/h3&gt;  &lt;p&gt;This causes a problem because the Forms Authentication bits assume there will be a single login page for the whole application and it’s only possible to set a single loginUrl in the web.config to redirect users requesting pages which require authentication.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h3&gt;The solution&lt;/h3&gt;  &lt;p&gt;There are a couple of &lt;a href="http://forums.asp.net/post/2754379.aspx"&gt;solutions&lt;/a&gt; floating around but most of them feel really dirty. You also can’t get away with putting another authentication element in a web.config file in a subfolder of your site because:&lt;/p&gt;  &lt;p&gt;&lt;em&gt;It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;In my case things are slightly more complicated because I will be composing my application from modules which are loaded in at runtime. These modules can also add their own login pages so I need something extensible.&lt;/p&gt;  &lt;h3&gt;No, really - the solution&lt;/h3&gt;  &lt;p&gt;We can’t fight that ASP.NET will only support redirecting to a single location, so let us instead redirect to a location whose ‘single responsibility’ is to forward the user to the login page they actually need. Enter the LoginRedirectController!&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:6025b84b-714a-427e-828e-b6a3a85f7592" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: c#;"&gt;public class LoginRedirectController : Controller
{
    public ActionResult Index(string returnUrl)
    {
        //TODO: Redirect!
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And then we need to register this in the web.config as our loginUrl.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:01ce6171-395c-490b-9107-0d6bf88e9acc" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: xml;"&gt;&amp;lt;authentication mode="Forms"&amp;gt;
  &amp;lt;forms loginUrl="~/LoginRedirect" requireSSL="true" cookieless="UseCookies" /&amp;gt;
&amp;lt;/authentication&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;We’re going to be looking at the returnUrl parameter which ASP.NET populates for us to figure out where to send people from here. I’m breaking up these different sections of the application into MVC Areas and the default behaviour is to have a prefix to the URL for every page in a given area. For example the Admin area has a route which looks like this: Admin/{controller}/{action}/{id}. Fleshing out our LoginRedirectController we arrive at:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:8d8dd6a2-5831-455f-b187-e505de09cf45" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: c#;"&gt;private readonly IReturnUrlHandler returnUrlHandler;

public LoginRedirectController(IReturnUrlHandler returnUrlHandler)
{
    this.returnUrlHandler = returnUrlHandler;
}

public ActionResult Index(string returnUrl)
{
    var route = returnUrlHandler.GetRoute(returnUrl);
    return RedirectToRoute(route, new { returnUrl });
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Nice and simple! We have a (badly named) interface called IReturnUrlHandler and a GetRoute method to which we can pass the returnUrl. The job of the IReturnUrlHandler is simply to map between a returnUrl and a named route. We make sure to pass the returnUrl on to whatever route we’re forwarding to so the user will eventually arrive at whatever page they originally requested after being logged in.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:ca8740d1-04dd-4dcb-a4a2-feeab8b62646" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: c#;"&gt;public interface IReturnUrlHandler
{
    void Register(string returnUrlPrefix, string loginRoute);
    string GetRoute(string returnUrl);
}

public class ReturnUrlHandler : IReturnUrlHandler
{
    private const string DefaultRoute = "Home";
    private readonly Dictionary&amp;lt;string, string&amp;gt; redirectRules = new Dictionary&amp;lt;string, string&amp;gt;();

    public void Register(string returnUrlPrefix, string loginRoute)
    {
        redirectRules.Add(returnUrlPrefix, loginRoute);
    }

    public string GetRoute(string returnUrl)
    {
        var key = redirectRules.Keys.FirstOrDefault(x =&amp;gt;
            returnUrl.StartsWith(x, StringComparison.OrdinalIgnoreCase));
        return !string.IsNullOrEmpty(key) ? redirectRules[key] : DefaultRoute;
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;No magic in here at all. We have a register method which allows us to add prefix and route combinations to a dictionary which is then used to resolve the name of a suitable route in our LoginRedirectController. Note that if we don’t find a matching route we send them to one named “Home” which just dumps them back on the root of the site. To use this final piece we just need to add named routes to our different login pages and register them.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:e94581a0-c58f-4e0b-acff-0ce79299e53c" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: c#;"&gt;context.MapRoute("Admin_Login", "Admin/Login", 
                new { controller = "Auth", action = "Login" });

returnUrlHandler.Register("/Admin", "Admin_Login");&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And finally just to complete the picture we have our AuthController in the Admin area.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:830cd43a-b973-4bab-86d4-ccabc0cca7d0" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: c#;"&gt;[HttpGet]
public ActionResult Login()
{
    if (Request.IsAuthenticated)
        return RedirectToAction("Index", "Dashboard");

    return View(new AdminLoginModel());
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(AdminLoginModel input, string returnUrl)
{
    //TODO: Validate username and password against something

    if (ModelState.IsValid)
    {
        formsAuth.SetAuthCookie(input.Username, false);

        //Important! Check IsLocalUrl to prevent open redirection attack!
        if (Url.IsLocalUrl(returnUrl))
            return Redirect(returnUrl);
        return RedirectToAction("Index", "Dashboard");
    }

    return View(new AdminLoginModel { Username = input.Username });
}&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;Summary&lt;/h3&gt;

&lt;p&gt;It certainly does the job and is very clean. Perfect for me because my modules can be loaded in at runtime and register their own login pages, it’s up to you whether your situation is something where the benefits of this outweigh the ceremony involved.&lt;/p&gt;</description>
      <link>http://sblakemore.com/blog/post/Multiple-login-pages-with-ASPNET-MVC.aspx</link>
      <comments>http://sblakemore.com/blog/post/Multiple-login-pages-with-ASPNET-MVC.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=7041ac2a-8180-4051-81e4-657d123a014c</guid>
      <pubDate>Tue, 20 Mar 2012 11:44:00 +1800</pubDate>
      <category>Development</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=7041ac2a-8180-4051-81e4-657d123a014c</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=7041ac2a-8180-4051-81e4-657d123a014c</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/Multiple-login-pages-with-ASPNET-MVC.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=7041ac2a-8180-4051-81e4-657d123a014c</wfw:commentRss>
    </item>
    <item>
      <title>DIY PCB Drill Press for $15 (sort of)</title>
      <description>&lt;p&gt;I’ve recently been working on producing my own PCBs at home and ran into the problem of how to reliably and accurately drill the holes I needed.&lt;/p&gt;  &lt;p&gt;I had a quick search to see how other people were attacking the problem and managed to find &lt;a href="http://www.instructables.com/id/PCB-Drill-Press-Using-Salvaged-Door-Hinges/"&gt;a design&lt;/a&gt; for a home made drill press on Instructables which was genius in it’s simplicity. Four hinges and some lengths of timber combine to make an almost perfect plunge action with great accuracy. Here is my take on the idea with photos of the mechanism and a quick video showing it in action.&lt;/p&gt; &lt;iframe height="281" src="http://player.vimeo.com/video/35739713" frameborder="0" width="500" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" webkitallowfullscreen="webkitallowfullscreen"&gt;&lt;/iframe&gt;   &lt;p&gt;&lt;a title="IMG_2762" href="http://www.flickr.com/photos/21273834@N04/6769321321/"&gt;&lt;img border="0" alt="IMG_2762" src="http://static.flickr.com/7171/6769321321_e7d6c8e891.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;300 x 300mm working area for about $15 in timber and hardware (no, that’s not including the rotary tool!).&lt;/p&gt;  &lt;p&gt;&lt;a title="IMG_2765" href="http://www.flickr.com/photos/21273834@N04/6769322275/"&gt;&lt;img border="0" alt="IMG_2765" src="http://static.flickr.com/7033/6769322275_a6b203702e.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Because PCBs are woven fibreglass and epoxy they're tough as anything and we're making tiny holes, usually a millimeter or less. The drill must spin at high RPM to make the outside edge of the tiny diameter bit travel fast enough. This rotary tool will do 35,000 RPM which drives through PCBs like butter.&lt;/p&gt;  &lt;p&gt;&lt;a title="IMG_2767" href="http://www.flickr.com/photos/21273834@N04/6769324159/"&gt;&lt;img border="0" alt="IMG_2767" src="http://static.flickr.com/7175/6769324159_19bb7a08c5.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Hinged rectangle fixed to the back piece means the drill will move vertically with very little arc.&lt;/p&gt;  &lt;p&gt;&lt;a title="IMG_2772" href="http://www.flickr.com/photos/21273834@N04/6769328135/"&gt;&lt;img border="0" alt="IMG_2772" src="http://static.flickr.com/7159/6769328135_ca9a1daedc.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Brackets on either side of the gantry to minimise lateral movement due to slop in the hinges.&lt;/p&gt;  &lt;p&gt;&lt;a title="IMG_2768" href="http://www.flickr.com/photos/21273834@N04/6769325061/"&gt;&lt;img border="0" alt="IMG_2768" src="http://static.flickr.com/7001/6769325061_15e7cbb28e.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Two springs held down by a screw and washer to provide an automatic return. They kept popping out to the sides under load, crossing them over each other seems to keep them in line. &lt;/p&gt;  &lt;p&gt;&lt;a title="IMG_2766" href="http://www.flickr.com/photos/21273834@N04/6769323239/"&gt;&lt;img border="0" alt="IMG_2766" src="http://static.flickr.com/7158/6769323239_aac00c52c1.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;I used to brackets on the solid frame to make sure it wasn't going anywhere.&lt;/p&gt;  &lt;p&gt;&lt;a title="IMG_2769" href="http://www.flickr.com/photos/21273834@N04/6769325917/"&gt;&lt;img border="0" alt="IMG_2769" src="http://static.flickr.com/7010/6769325917_2588a5f387.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Small hole drilled all the way through the platform, we don't want the bit hitting the wood.&lt;/p&gt;  &lt;p&gt;&lt;a title="IMG_2771" href="http://www.flickr.com/photos/21273834@N04/6769327073/"&gt;&lt;img border="0" alt="IMG_2771" src="http://static.flickr.com/7166/6769327073_671d0608d5.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;U-bolts holding the drill in position. I'm using the flexible shaft attachment on a cheapo dremel knock-off.&lt;/p&gt;  &lt;p&gt;&lt;a title="IMG_2773" href="http://www.flickr.com/photos/21273834@N04/6769329163/"&gt;&lt;img border="0" alt="IMG_2773" src="http://static.flickr.com/7165/6769329163_3d3c765f5c.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Tiny 1.05mm tungsten carbide drill bit, these things break very easily.&lt;/p&gt;</description>
      <link>http://sblakemore.com/blog/post/DIY-PCB-Drill-Press-for-$15-(sort-of).aspx</link>
      <comments>http://sblakemore.com/blog/post/DIY-PCB-Drill-Press-for-$15-(sort-of).aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=0613f5fe-e899-45e7-8201-5e317857918f</guid>
      <pubDate>Mon, 20 Feb 2012 16:43:52 +1800</pubDate>
      <category>Electronics</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=0613f5fe-e899-45e7-8201-5e317857918f</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=0613f5fe-e899-45e7-8201-5e317857918f</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/DIY-PCB-Drill-Press-for-$15-(sort-of).aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=0613f5fe-e899-45e7-8201-5e317857918f</wfw:commentRss>
    </item>
    <item>
      <title>Power Management in C# – Stop the system or display from sleeping</title>
      <description>&lt;p&gt;In a desktop application I’m working on there are a number of long running batch processes that can be run by the user. This caused problems when the user kicked off a batch process and then walked away from the computer, returning a few hours later to find that the system had gone to sleep and the batch had failed!&lt;/p&gt;  &lt;h3&gt;SetThreadExecutionState&lt;/h3&gt;  &lt;p&gt;A little searching led me to the unmanaged &lt;a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa373208%28v=vs.85%29.aspx"&gt;SetThreadExecutionState&lt;/a&gt; function which can be used to tell Windows that the calling thread is doing something important which requires the system to be awake. The function can be used in two ways, it can be called repeatedly to reset the system’s idle timer or it can be used in “continuous” mode where the system should not enter sleep mode until told otherwise. Check the MSDN link above for full details.&lt;/p&gt;    &lt;h3&gt;How to use it?&lt;/h3&gt;  &lt;p&gt;I took a trip to &lt;a href="http://pinvoke.net"&gt;pinvoke.net&lt;/a&gt; and wrapped the function into a C# class. I implemented IDisposable on the class so that it can be used to scope the work being performed if required.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:75baa80e-fac8-4c00-96f4-bb34769d966b" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: c#;"&gt;using (new PowerManager(ExecutionState.SystemRequired, isContinuous: true))
{
    //Do some long running work here
    DoSomeWork();
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Alternatively, passing isContinuous as false will let you reset the system idle timer as you process work items.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:794faf87-62b7-45b9-8f39-4ac6f063ef6f" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: c#;"&gt;using (var powerManager = new PowerManager(ExecutionState.SystemRequired, isContinuous: false))
{
    for (int i = 0; i &amp;lt; 1000; i++)
    {
        //Do work here
        DoSomeWork();
        //Reset the system idle timer to prevent sleep
        //before processing the next bit of work
        powerManager.ResetTimer();
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;h3&gt;How does it work?&lt;/h3&gt;

&lt;p&gt;For your copy and pasting pleasure, here is the entire class. Please do thoroughly read the MSDN docs to understand the implications of using these different modes!&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:79b00bbd-aba1-4d23-91ba-68c3a8cf64c9" class="wlWriterEditableSmartContent"&gt;&lt;pre class="brush: c#;"&gt;[Flags]
public enum ExecutionState : uint
{
    DisplayRequired = 0x00000002,
    SystemRequired = 0x00000001,
    AwaymodeRequired = 0x00000040
}

public class PowerManager : IDisposable
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    static extern ExecutionState SetThreadExecutionState(ExecutionState flags);

    private const uint ContinuousFlag = 0x80000000;

    public bool IsContinuous { get; private set; }
    public ExecutionState State { get; private set; }

    public PowerManager(ExecutionState state, bool isContinuous)
    {
        State = state;
        IsContinuous = isContinuous;

        if ((state &amp;amp; ExecutionState.AwaymodeRequired) != 0 &amp;amp;&amp;amp; !isContinuous)
            throw new InvalidOperationException("Awaymode is only valid when the state is continuous");

        SetThreadExecutionState(isContinuous ? state | (ExecutionState)ContinuousFlag : state);
    }

    public void ResetTimer()
    {
        if (IsContinuous)
            throw new InvalidOperationException("The execution state is continuous");

        SetThreadExecutionState(State);
    }

    ~PowerManager()
    {
        ClearContinuousState();
    }

    public void Dispose()
    {
        ClearContinuousState();
        GC.SuppressFinalize(this);
    }

    private bool disposed;
    private void ClearContinuousState()
    {
        if (!disposed)
        {
            if (IsContinuous)
                SetThreadExecutionState((ExecutionState)ContinuousFlag);

            disposed = true;
        }
    }
}&lt;/pre&gt;&lt;/div&gt;</description>
      <link>http://sblakemore.com/blog/post/Power-Management-in-C-Stop-the-system-or-display-from-sleeping.aspx</link>
      <comments>http://sblakemore.com/blog/post/Power-Management-in-C-Stop-the-system-or-display-from-sleeping.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=d25f254c-9b23-4296-8231-33791a05464c</guid>
      <pubDate>Sat, 18 Feb 2012 13:23:00 +1800</pubDate>
      <category>Development</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=d25f254c-9b23-4296-8231-33791a05464c</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=d25f254c-9b23-4296-8231-33791a05464c</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/Power-Management-in-C-Stop-the-system-or-display-from-sleeping.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=d25f254c-9b23-4296-8231-33791a05464c</wfw:commentRss>
    </item>
    <item>
      <title>Dirty Checking your Silverlight and WPF data entry forms</title>
      <description>&lt;p&gt;Let’s just dive right in and have a demo to see what we’re trying to accomplish. Below is a Silverlight application with some interesting behaviour, if you start changing any data the application will notice and the save button becomes enabled, the state of the form is ‘dirty’. That isn’t very interesting on it’s own, what is interesting is that if you then put the data back to the way it was when you started, the save button becomes disabled again and the form returns to the ‘clean’ state. Here, have a play…&lt;/p&gt;  &lt;p&gt;&lt;object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="640" height="210"&gt;&lt;param name="source" value="http://sblakemore.com/blog/silverlight/sblakemore.dirtychecking.xap" /&gt;&lt;param name="minRuntimeVersion" value="4.0.50401.0" /&gt;&lt;param name="background" value="White" /&gt;&lt;param name="autoUpgrade" value="true" /&gt;&lt;a style="text-decoration: none;" href="http://go.microsoft.com/fwlink/?LinkID=149156&amp;amp;v=4.0.50401.0"&gt; &lt;img style="border-style: none;" src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" /&gt; &lt;/a&gt; &lt;/object&gt;&lt;/p&gt;    &lt;h3&gt;How is it done&lt;/h3&gt;  &lt;p&gt;Ok, pretty cool. Let’s have a look at the code behind file and you will see that there is nothing much going on.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:78531b9a-4200-4a48-a931-5b430e8daa79" class="wlWriterSmartContent"&gt;   &lt;pre class="brush: c#;"&gt;namespace SBlakemore.DirtyChecking
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;And here is the XAML markup for the data entry form, now we’re starting to get some clues about how this is implemented. &lt;em&gt;Note: I’ve removed the UserControl declaration and the styles which are in it’s resource dictionary for clarity, however the StackPanel below is the root of the UserControl.&lt;/em&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:9e2eda48-2b99-4762-83f1-779e8d86cb09" class="wlWriterSmartContent"&gt;
  &lt;pre class="brush: xml;"&gt;    &amp;lt;StackPanel&amp;gt;
        &amp;lt;local:Tracker x:Name=&amp;quot;tracker&amp;quot; HorizontalContentAlignment=&amp;quot;Stretch&amp;quot;&amp;gt;
            &amp;lt;Grid Margin=&amp;quot;20 20 20 0&amp;quot;&amp;gt;
                &amp;lt;Grid.ColumnDefinitions&amp;gt;
                    &amp;lt;ColumnDefinition Width=&amp;quot;3*&amp;quot; /&amp;gt;
                    &amp;lt;ColumnDefinition Width=&amp;quot;7*&amp;quot; /&amp;gt;
                &amp;lt;/Grid.ColumnDefinitions&amp;gt;
                &amp;lt;Grid.RowDefinitions&amp;gt;
                    &amp;lt;RowDefinition Height=&amp;quot;35&amp;quot; /&amp;gt;
                    &amp;lt;RowDefinition Height=&amp;quot;35&amp;quot; /&amp;gt;
                    &amp;lt;RowDefinition Height=&amp;quot;35&amp;quot; /&amp;gt;
                    &amp;lt;RowDefinition Height=&amp;quot;35&amp;quot; /&amp;gt;
                &amp;lt;/Grid.RowDefinitions&amp;gt;
                
                &amp;lt;TextBlock Text=&amp;quot;Artist:&amp;quot; /&amp;gt;
                &amp;lt;TextBox local:Tracker.Property=&amp;quot;Text&amp;quot; Text=&amp;quot;Michael Jackson&amp;quot; /&amp;gt;

                &amp;lt;TextBlock Grid.Row=&amp;quot;1&amp;quot; Text=&amp;quot;Title:&amp;quot; /&amp;gt;
                &amp;lt;TextBox Grid.Row=&amp;quot;1&amp;quot; local:Tracker.Property=&amp;quot;Text&amp;quot; Text=&amp;quot;Thriller&amp;quot; /&amp;gt;

                &amp;lt;TextBlock Grid.Row=&amp;quot;2&amp;quot; Text=&amp;quot;Explicit Lyrics:&amp;quot; /&amp;gt;
                &amp;lt;CheckBox Grid.Row=&amp;quot;2&amp;quot; local:Tracker.Property=&amp;quot;IsChecked&amp;quot;/&amp;gt;

                &amp;lt;TextBlock Grid.Row=&amp;quot;3&amp;quot; Text=&amp;quot;Genre:&amp;quot; /&amp;gt;
                &amp;lt;ComboBox Grid.Row=&amp;quot;3&amp;quot; local:Tracker.Property=&amp;quot;SelectedItem&amp;quot; SelectedIndex=&amp;quot;3&amp;quot;&amp;gt;
                    &amp;lt;sys:String&amp;gt;Blues&amp;lt;/sys:String&amp;gt;
                    &amp;lt;sys:String&amp;gt;Country&amp;lt;/sys:String&amp;gt;
                    &amp;lt;sys:String&amp;gt;Jazz&amp;lt;/sys:String&amp;gt;
                    &amp;lt;sys:String&amp;gt;Pop&amp;lt;/sys:String&amp;gt;
                    &amp;lt;sys:String&amp;gt;Soul&amp;lt;/sys:String&amp;gt;
                    &amp;lt;sys:String&amp;gt;Hip Hop&amp;lt;/sys:String&amp;gt;
                &amp;lt;/ComboBox&amp;gt;
            &amp;lt;/Grid&amp;gt;
        &amp;lt;/local:Tracker&amp;gt;
        
        &amp;lt;Button Content=&amp;quot;Save&amp;quot; Width=&amp;quot;80&amp;quot; Height=&amp;quot;30&amp;quot; Margin=&amp;quot;10&amp;quot;
                IsEnabled=&amp;quot;{Binding IsChanged, ElementName=tracker}&amp;quot; /&amp;gt;
    &amp;lt;/StackPanel&amp;gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h3&gt;Looking Closer&lt;/h3&gt;

&lt;p&gt;There are three things to note here.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I’ve wrapped the data entry controls in something called Tracker. &lt;/li&gt;

  &lt;li&gt;All of the data entry controls have a value set for an attached property which is defined by Tracker, and that value is the name of the property which holds the data for that particular data entry control. For example for a TextBox the attached property is set to “Text”, and for a Checkbox the attached property is set to “IsChecked”. &lt;/li&gt;

  &lt;li&gt;The save button is being enabled and disabled by being bound to the IsChanged property on our tracker. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You will probably by now have figured out in principle how this works. When the Tracker control is loaded it recurses through all of it’s children looking for anything which declares a value for Tracker.Property. When it finds one it looks at the value set for Tracker.Property and then finds the DependencyProperty of that name on the declaring control, it will then take a snapshot of the value and subscribe to change notifications from the DependencyProperty. Whenever a change notification is received it will read the new value and compare it to the snapshot to see if the value is ‘dirty’ and has been changed. The IsChanged property on Tracker returns true if one of more of it’s children have changed.&lt;/p&gt;

&lt;p&gt;This is pretty cool because implementing this feature in the model quickly becomes a nasty mess of INotifyPropertyChanged madness and as soon as the model and data entry form become anything more than trivial you will run up against complications and edge cases. In addition you end up with event subscriptions everywhere trying to track your properties and because of this could easily cause memory leaks.&lt;/p&gt;

&lt;p&gt;Much better to pull this complexity out of your ViewModels and implement it instead as a cross cutting concern which is applied to your data entry forms declaratively.&lt;/p&gt;

&lt;h3&gt;Show me the Code!&lt;/h3&gt;

&lt;p&gt;Here is the code for the Tracker class.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:c1b2ecc6-a4f4-48ce-9ed0-7f40218a83df" class="wlWriterSmartContent"&gt;
  &lt;pre class="brush: c#;"&gt;public class Tracker : ContentControl
{
    public bool IsChanged
    {
        get { return (bool)GetValue(IsChangedProperty); }
        set { SetValue(IsChangedProperty, value); }
    }
    public static readonly DependencyProperty IsChangedProperty =
        DependencyProperty.Register(&amp;quot;IsChanged&amp;quot;, typeof(bool), typeof(Tracker), new PropertyMetadata(false));

    public static string GetProperty(DependencyObject obj)
    {
        return (string)obj.GetValue(PropertyProperty);
    }
    public static void SetProperty(DependencyObject obj, string value)
    {
        obj.SetValue(PropertyProperty, value);
    }
    public static readonly DependencyProperty PropertyProperty =
        DependencyProperty.RegisterAttached(&amp;quot;Property&amp;quot;, typeof(string), typeof(Tracker), new PropertyMetadata(null));

    private readonly Dictionary&amp;lt;PropertyWatcher, object&amp;gt; trackedPropertySnapshot = new Dictionary&amp;lt;PropertyWatcher, object&amp;gt;();
    private readonly List&amp;lt;PropertyWatcher&amp;gt; changedProperties = new List&amp;lt;PropertyWatcher&amp;gt;();
    private readonly object nullProperty = new object();

    public Tracker()
    {
        Loaded += (s, e) =&amp;gt;
        {
            var content = Content as DependencyObject;
            if (content != null)
                WalkDownVisualTree(content);
        };
    }

    public void AcceptChanges()
    {
        changedProperties.Clear();

        IsChanged = false;
    }

    private void WalkDownVisualTree(DependencyObject current)
    {
        var property = current.ReadLocalValue(PropertyProperty);
        if (property != DependencyProperty.UnsetValue)
            RegisterTrackedProperty(current, (string)property);

        var count = VisualTreeHelper.GetChildrenCount(current);
        for (int i = 0; i &amp;lt; count; i++)
        {
            WalkDownVisualTree(VisualTreeHelper.GetChild(current, i));
        }
    }

    private void RegisterTrackedProperty(DependencyObject item, string propertyName)
    {
        var notifier = new PropertyWatcher(item, propertyName);
        notifier.ValueChanged += TrackedPropertyChanged;

        trackedPropertySnapshot.Add(notifier, notifier.Value);
    }

    private void TrackedPropertyChanged(object sender, EventArgs e)
    {
        var notifier = ((PropertyWatcher)sender);
        var original = trackedPropertySnapshot[notifier] jQuery15209391723657026887_1327589005650 nullProperty;
        var current = notifier.Value ?? nullProperty;

        if (!original.Equals(current))
        {
            if (!changedProperties.Contains(notifier))
                changedProperties.Add(notifier);
        }
        else
            changedProperties.Remove(notifier);

        IsChanged = changedProperties.Count != 0;
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;It took me a bit of playing around to figure out how to subscribe to change notifications for the relevant property, something which is not too big of a deal in WPF, and in the end I came up with a very handy little class I called PropertyWatcher. The constructor takes a source object and a string with the name of a property on the source object.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:bab3f67b-8fe8-4c85-aaea-f1d5269398b3" class="wlWriterSmartContent"&gt;
  &lt;pre class="brush: c#;"&gt;public class PropertyWatcher : DependencyObject
{
    public DependencyObject Source { get; protected set; }

    public PropertyWatcher(DependencyObject source, string propertyName)
    {
        Source = source;

        var path = new PropertyPath(propertyName);
        var binding = new Binding { Path = path, Mode = BindingMode.OneWay, Source = source };
        BindingOperations.SetBinding(this, ValueProperty, binding);
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register(&amp;quot;Value&amp;quot;, typeof(object), typeof(PropertyWatcher), new PropertyMetadata(null, OnPropertyChanged));

    private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var notifier = (PropertyWatcher)sender;
        notifier.ValueChanged(notifier, EventArgs.Empty);
    }

    public object Value
    {
        get { return GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public event EventHandler ValueChanged = delegate { };
}&lt;/pre&gt;
&lt;/div&gt;

&lt;h3&gt;Final Thoughts&lt;/h3&gt;

&lt;p&gt;It’s a pretty nice feature to be able to not have to prompt a user to save an entity which, in their mind, they haven’t actually changed. I’ve used a specialised and enhanced version of the code above in a pretty complex WPF data entry form and am pleased with how it’s working.&lt;/p&gt;

&lt;p&gt;One possible nice enhancement would be to try to encapsulate this into a Behaviour to make the whole thing Blendable.&lt;/p&gt;

&lt;p&gt;How do you feel about tracking changes in this way? Code download below.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F60BB8FA-6F02-4999-8F5E-9DD4E92C4DA7:b7526674-0e02-4adc-a0d5-441cee5108ba" class="wlWriterSmartContent"&gt;
  &lt;div&gt;&lt;a href="http://sblakemore.com/blog/file.axd?file=SBlakemore.DirtyChecking.zip" target="_self"&gt;SBlakemore.DirtyChecking.zip&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;</description>
      <link>http://sblakemore.com/blog/post/Dirty-Checking-your-Silverlight-or-WPF-data-entry-forms.aspx</link>
      <comments>http://sblakemore.com/blog/post/Dirty-Checking-your-Silverlight-or-WPF-data-entry-forms.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=07273a0a-2624-4e7a-8790-0bfcdc4c93d2</guid>
      <pubDate>Sun, 11 Jul 2010 19:36:00 +1800</pubDate>
      <category>Development</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=07273a0a-2624-4e7a-8790-0bfcdc4c93d2</pingback:target>
      <slash:comments>5</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=07273a0a-2624-4e7a-8790-0bfcdc4c93d2</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/Dirty-Checking-your-Silverlight-or-WPF-data-entry-forms.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=07273a0a-2624-4e7a-8790-0bfcdc4c93d2</wfw:commentRss>
    </item>
    <item>
      <title>Bidirectional Integrity: IEnumerable and read only Entity properties</title>
      <description>&lt;p&gt;&lt;a href="http://www.lostechies.com/members/bogardj/default.aspx"&gt;Jimmy Bogard&lt;/a&gt; over at &lt;a href="http://www.lostechies.com/"&gt;LosTechies&lt;/a&gt; has a great little series of posts going ahead at the moment on &amp;ldquo;strengthening your domain&amp;rdquo;. For the time constrained amongst us, I&amp;rsquo;ll quickly summarise his points so you can understand what I say here without going back to the source, however please do go ahead and check them out if your haven&amp;rsquo;t, there is some great advice there:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2010/02/03/strengthening-your-domain-a-primer.aspx"&gt;Strengthening your domain: a primer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2010/02/23/strengthening-your-domain-aggregate-construction.aspx"&gt;Strengthening your domain: Aggregate Construction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2010/03/10/strengthening-your-domain-encapsulated-collections.aspx"&gt;Strengthening your domain: Encapsulated collections&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It&amp;rsquo;s his most recent post in the series on encapsulated collections which I&amp;rsquo;d like to talk more about.&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h3&gt;Entity relationships and invariants&lt;/h3&gt;
&lt;p&gt;To quickly summarise Jimmy&amp;rsquo;s post so we can continue the discussion where he left off, let&amp;rsquo;s look at some poor code&amp;hellip;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:1072e196-0454-4d44-a571-950690fa06d2" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Province { get; set; }
    public List&amp;lt;Order&amp;gt; Orders { get; set; }

    public string GetFullName()
    {
        return LastName + ", " + FirstName;
    }
}

public class Order
{
    public Order(Customer customer)
    {
        Customer = customer;
        customer.Orders.Add(this);
    }

    public Customer Customer { get; set; }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;What&amp;rsquo;s wrong with this?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;First of all we&amp;rsquo;re exposing a setter on the Orders property of Customer, exposing a setter on a collection property is bad because it allows calling code to completely replace our collection from under our nose without us knowing.&lt;/li&gt;
&lt;li&gt;We&amp;rsquo;re exposing our concrete List directly, this should be at the very least an IList so we can change our implementation without changing our interface.&lt;/li&gt;
&lt;li&gt;It&amp;rsquo;s clear from the Order constructor that we have a bidirectional relationship here, the invariant is then that when the Customer property of the Order class is set, that Order should be in the Orders collection on the Customer class. Exposing the setter on the Customer property of the Order class and exposing in the Orders property of the Customer class a collection which can be modified allows people to mess with our invariant.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;How can we fix it? Here&amp;rsquo;s Jimmy&amp;rsquo;s code&amp;hellip;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:fecfada2-4101-4158-a2a1-9a0e5c984396" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;public class Customer
{
    private readonly IList&amp;lt;Order&amp;gt; _orders = new List&amp;lt;Order&amp;gt;();

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Province { get; set; }
    public IEnumerable&amp;lt;Order&amp;gt; Orders { get { return _orders; } }

    public string GetFullName()
    {
        return LastName + ", " + FirstName;
    }

    internal void AddOrder(Order order)
    {
        _orders.Add(order);
    }
}

public class Order
{
    public Customer Customer { get; protected set; }

    public Order(Customer customer)
    {
        Customer = customer;
        customer.AddOrder(this);
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Great, so we&amp;rsquo;ve removed the setters and now we&amp;rsquo;re only exposing an IEnumerable collection, no one can mess with our invariant and break our behaviour by not understanding our intention!&lt;/p&gt;
&lt;h3&gt;Looking a little closer&lt;/h3&gt;
&lt;p&gt;There is another interesting invariant at play in Jimmy&amp;rsquo;s code above, one of the invariants of the Order class is that it does not make sense to have an Order that is not associated with a Customer. To force the point, Jimmy has made it such that the only way to create an Order is by passing it a Customer as required by the constructor. The Order constructor then in turn calls an internal method on the Customer class to enforce the integrity of our bidirectional relationship. The method is left internal because we don&amp;rsquo;t want it to be seen everywhere, Orders and Customers should only become related in any way through the Order constructor.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s make things slightly more complex. We&amp;rsquo;ve had a chat with our domain experts and they&amp;rsquo;ve told us that our Order which cannot exist without a Customer should also not exist without OrderLines. Ok that&amp;rsquo;s no problem, we know how to handle that, just more constructor parameters and internal methods!&lt;/p&gt;
&lt;p&gt;This is where I start to have a problem, because although our external API is nice and clean, internally our code starts getting harder to understand and bigger in size as we add internal methods here and there.&lt;/p&gt;
&lt;h3&gt;Extension methods, generics, lambdas and reflection, what else is there in life?&lt;/h3&gt;
&lt;p&gt;Wouldn&amp;rsquo;t it be nice if we could add an item to an IEnumerable from another related entity without needing internal methods? Wouldn&amp;rsquo;t it be nice to be able to set protected properties? Well let&amp;rsquo;s be gratuitous and slightly immature and find a way to answer these questions using all the cool language features of the day!&lt;/p&gt;
&lt;p&gt;Because we don&amp;rsquo;t want to expose dangerous functionality like this all throughout our application, really its just to help us make a clean API which is implemented cleanly on the inside too, we&amp;rsquo;re going to stuff everything in our &lt;a href="http://martinfowler.com/eaaCatalog/layerSupertype.html"&gt;Layer Supertype&lt;/a&gt;, you very likely have one for your domain anyway&amp;hellip;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:ffa64d63-dbd1-44cc-9ca9-af126bdf4f98" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;protected void SetInaccessibleProperty&amp;lt;TObj, TValue&amp;gt;(TObj target, TValue value,
    Expression&amp;lt;Func&amp;lt;TObj, TValue&amp;gt;&amp;gt; propertyExpression)
{
    propertyExpression.ToPropertyInfo().SetValue(target, value, null);
}

protected TValue GetInaccessibleProperty&amp;lt;TObj, TValue&amp;gt;(TObj target,
    Expression&amp;lt;Func&amp;lt;TObj, TValue&amp;gt;&amp;gt; propertyExpression)
{
    return (TValue)propertyExpression.ToPropertyInfo().GetValue(target, null);
}

protected void AddToIEnumerable&amp;lt;TEntity, TValue&amp;gt;(TEntity target, TValue value,
    Expression&amp;lt;Func&amp;lt;TEntity, IEnumerable&amp;lt;TValue&amp;gt;&amp;gt;&amp;gt; propertyExpression)
{
    IEnumerable&amp;lt;TValue&amp;gt; enumerable = GetInaccessibleProperty(target, propertyExpression);

    if (enumerable is ICollection&amp;lt;TValue&amp;gt;)
        ((ICollection&amp;lt;TValue&amp;gt;)enumerable).Add(value);
    else
        throw new ArgumentException(
            string.Format("Property must be assignable to ICollection&amp;lt;{0}&amp;gt;", typeof(TValue).Name));
}

protected void RemoveFromIEnumerable&amp;lt;TEntity, TValue&amp;gt;(TEntity target, TValue value,
    Expression&amp;lt;Func&amp;lt;TEntity, IEnumerable&amp;lt;TValue&amp;gt;&amp;gt;&amp;gt; propertyExpression)
{
    IEnumerable&amp;lt;TValue&amp;gt; enumerable = GetInaccessibleProperty(target, propertyExpression);

    if (enumerable is ICollection&amp;lt;TValue&amp;gt;)
        ((ICollection&amp;lt;TValue&amp;gt;)enumerable).Remove(value);
    else
        throw new ArgumentException(string.Format("Property must be assignable to ICollection&amp;lt;{0}&amp;gt;",
            typeof(TValue).Name));
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Yikes, try saying that piece of generic soup five times really quickly after a few beers! But lets go a little further now and use these four methods to create something even more useful&amp;hellip;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:967efe95-5a6b-450b-a726-512f7c6b2d14" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;protected void AddManyToOne&amp;lt;TOne, TMany&amp;gt;(
    TOne one, Expression&amp;lt;Func&amp;lt;TOne, IEnumerable&amp;lt;TMany&amp;gt;&amp;gt;&amp;gt; collectionExpression,
    TMany many, Expression&amp;lt;Func&amp;lt;TMany, TOne&amp;gt;&amp;gt; propertyExpression)
{
    AddToIEnumerable(one, many, collectionExpression);
    SetInaccessibleProperty(many, one, propertyExpression);
}

protected void RemoveManyToOne&amp;lt;TOne, TMany&amp;gt;(
    TOne one, Expression&amp;lt;Func&amp;lt;TOne, IEnumerable&amp;lt;TMany&amp;gt;&amp;gt;&amp;gt; collectionExpression,
    TMany many, Expression&amp;lt;Func&amp;lt;TMany, TOne&amp;gt;&amp;gt; propertyExpression)
    where TOne : class
{
    RemoveFromIEnumerable(one, many, collectionExpression);
    SetInaccessibleProperty(many, null, propertyExpression);
}

protected void RemoveManyToMany&amp;lt;T1, T2&amp;gt;(
    T1 entity1, Expression&amp;lt;Func&amp;lt;T1, IEnumerable&amp;lt;T2&amp;gt;&amp;gt;&amp;gt; expression1,
    T2 entity2, Expression&amp;lt;Func&amp;lt;T2, IEnumerable&amp;lt;T1&amp;gt;&amp;gt;&amp;gt; expression2)
{
    RemoveFromIEnumerable(entity1, entity2, expression1);
    RemoveFromIEnumerable(entity2, entity1, expression2);
}

protected void AddManyToMany&amp;lt;T1, T2&amp;gt;(
    T1 entity1, Expression&amp;lt;Func&amp;lt;T1, IEnumerable&amp;lt;T2&amp;gt;&amp;gt;&amp;gt; expression1,
    T2 entity2, Expression&amp;lt;Func&amp;lt;T2, IEnumerable&amp;lt;T1&amp;gt;&amp;gt;&amp;gt; expression2)
{
    AddToIEnumerable(entity1, entity2, expression1);
    AddToIEnumerable(entity2, entity1, expression2);
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Note that these are all protected so that they can only be accessed by derived types. The obvious exception being other idiots reflecting on your code! There is one other piece that&amp;rsquo;s missing, you may have spotted it already, I pulled it out into an extension method because I find it so useful elsewhere&amp;hellip;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:68127ce8-38f5-49a8-ad98-c052e88da273" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;public static class ExpressionExtensions
{
    public static PropertyInfo ToPropertyInfo(this LambdaExpression expression)
    {
        var prop = expression.Body as MemberExpression;

        if (prop != null)
        {
            var info = prop.Member as PropertyInfo;
            if (info != null)
                return info;
        }

        throw new ArgumentException("The expression target is not a Property");
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Now we can take a look at how this would leave our Order and Customer class looking&amp;hellip;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:ed2cb710-8c32-4416-8b84-79e2a814eac7" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;public class Customer : DomainBase
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Province { get; set; }
    public IEnumerable&amp;lt;Order&amp;gt; Orders { get; protected set; }

    public string GetFullName()
    {
        return LastName + ", " + FirstName;
    }
}

public class Order : DomainBase
{
    public Customer Customer { get; protected set; }

    public Order(Customer customer)
    {
        AddManyToOne(customer, x =&amp;gt; x.Orders, this, x =&amp;gt; x.Customer);
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;This looks much cleaner and easier to read, and the effect on a larger domain would be dramatic. Comments or criticisms please?&lt;/p&gt;
&lt;h3&gt;Performance considerations&lt;/h3&gt;
&lt;p&gt;Yes it&amp;rsquo;s slower and your application may associate Orders and Customers several orders of magnitude more slowly. What you need to figure out is whether that matters in any way. If associating an Order with a Customer truly is a bottleneck in your application then the only thing I can do is offer my congratulations on how amazing the rest of your code must be and also how many orders per second you must be processing!&lt;/p&gt;
&lt;p&gt;Hope this helps!&lt;/p&gt;</description>
      <link>http://sblakemore.com/blog/post/Bidirectional-Integrity-IEnumerable-and-read-only-Entity-properties.aspx</link>
      <comments>http://sblakemore.com/blog/post/Bidirectional-Integrity-IEnumerable-and-read-only-Entity-properties.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=513ee702-3406-4165-8379-26fcc5c790a2</guid>
      <pubDate>Fri, 12 Mar 2010 13:18:00 +1800</pubDate>
      <category>Development</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=513ee702-3406-4165-8379-26fcc5c790a2</pingback:target>
      <slash:comments>6</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=513ee702-3406-4165-8379-26fcc5c790a2</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/Bidirectional-Integrity-IEnumerable-and-read-only-Entity-properties.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=513ee702-3406-4165-8379-26fcc5c790a2</wfw:commentRss>
    </item>
    <item>
      <title>Silverlight 4 COM Automation – Taking photos with a DSLR using Windows Image Acquisition</title>
      <description>&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: This code was written using the PDC09 Beta and may not work without modification on future builds!&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Silverlight 4 brings a lot to the table and in my opinion is the most exciting looking release so far. There is a whole slew of new possibilities which have opened up because of a number of important new features, the feature I&amp;rsquo;m going to be looking at is &lt;a href="http://www.microsoft.com/com/default.mspx"&gt;COM&lt;/a&gt; automation.&lt;/p&gt;
&lt;p&gt;Huge amounts of functionality built into Windows and installed by third party software is now at your fingertips. So how do we get access to it?&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h3&gt;ComAutomationFactory and the &amp;lsquo;dynamic&amp;rsquo; keyword&lt;/h3&gt;
&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.interop.comautomationfactory(VS.96).aspx"&gt;ComAutomationFactory&lt;/a&gt; is a new static class in the System.Windows.Interop namespace which exposes three methods and a single property. &amp;lsquo;&lt;a href="http://msdn.microsoft.com/en-us/library/dd264736(VS.100).aspx"&gt;dynamic&lt;/a&gt;&amp;rsquo; is a new language keyword available in C# 4.&lt;/p&gt;
&lt;h4&gt;ComAutomationFactory methods and property&lt;/h4&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:62c8954e-22dc-4fc8-90bb-ad21428d8ac4" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;ComAutomationFactory.CreateObject("ProgId");
ComAutomationFactory.GetObject("ProgId");&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;CreateObject and GetObject allow us to either activate and spin up a new instance, or get a reference to a currently activated and running instance of a given COM server. So for example, you are able to spawn a new copy of Outlook to add a calendar entry or alternatively you can attach to the copy the user is already running.&lt;/p&gt;
&lt;p&gt;These methods require the ProgId for the COM server you want to talk to. Each COM object on a computer is uniquely identified by a CLSID (essentially a Guid) which is stored in the registry. A ProgId is a string which maps to a CLSID in the registry, making COM servers much easier to work with, this is much the same as how a domain name maps to an IP address. For example, Outlook can be addressed as &amp;ldquo;&lt;em&gt;Outlook.Application&lt;/em&gt;&amp;rdquo; instead of &lt;em&gt;{D5CDD1EA-BB6A-4AAF-A3B0-98E5A3B120F4}&lt;/em&gt;!&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:80f34d96-70fc-4bf7-8c95-1dad60d71c8c" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;ComAutomationFactory.GetEvent(comObject, "eventName");&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;GetEvent returns an instance of &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.interop.comautomationevent(VS.96).aspx"&gt;ComAutomationEvent&lt;/a&gt; and is interesting in that it allows us to subscribe to events raised by the COM server, we will be using this later!&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:5999dbe0-d1b5-449c-a070-d9805a0712ae" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;ComAutomationFactory.IsAvailable;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;The IsAvailable property returns a boolean as you might expect which lets us know if it is possible to use COM automation in the current context. COM automation in Silverlight requires that the application is running &lt;a href="http://msdn.microsoft.com/en-us/library/dd550721(VS.96).aspx"&gt;Out-Of-Browser&lt;/a&gt; and has been given &lt;a href="http://msdn.microsoft.com/en-us/library/ee721083(VS.96).aspx"&gt;elevated permissions&lt;/a&gt;, it is also available only on Windows systems!&lt;/p&gt;
&lt;h4&gt;The &amp;lsquo;dynamic&amp;rsquo; keyword&lt;/h4&gt;
&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd264736(VS.100).aspx"&gt;dynamic&lt;/a&gt; is a new type which bypasses static type checking. Sounds confusing but it comes in really handy for working with objects the compiler doesn&amp;rsquo;t know the exact shape of at design time, so for example objects retrieved via reflection, from a dynamic language like IronPython or IronRuby or indeed COM objects we&amp;rsquo;ve grabbed by ProgId!&lt;/p&gt;
&lt;p&gt;What all this means is that we can declare a variable to be of type dynamic and the compiler will let us call any method or property without complaining about it not being there. These calls are then resolved at run time.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:f1990134-753b-4768-acf2-d79ae8a3e1d9" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;dynamic dyn = "This is actually a string";
//This code builds without complaint from the compiler.
dyn.ThisMethodObviouslyDoesntExistOnAString();
dyn.NorDoesThisProperty = true;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;And as you can see below, Visual Studio allows me to do this.&lt;/p&gt;
&lt;p&gt;&lt;img style="display: inline; border-width: 0px;" title="dynamic expression" src="http://sblakemore.com/blog/image.axd?picture=dynamic.jpg" alt="dynamic expression" width="359" height="69" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Windows Image Acquisition&lt;/h3&gt;
&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/ms630368(VS.85).aspx"&gt;Windows Image Acquisition&lt;/a&gt; is an API provided by Windows and has been around in the OS since Windows ME in one form or another. WIA allows us to program in a uniform way against any scanner or camera device which has a compatible driver. Windows ME introduced WIA 1.0 which was replaced with WIA 2.0 in Windows Vista, this application was written and tested on Windows 7 and WIA 2.0 so this comes under a &amp;ldquo;works on my machine&amp;rdquo; disclaimer!&lt;/p&gt;
&lt;p&gt;It is possible to &lt;a href="http://www.microsoft.com/downloads/details.aspx?familyid=a332a77a-01b8-4de6-91c2-b7ea32537e29&amp;amp;displaylang=en"&gt;download the WIA 2.0 binaries&lt;/a&gt; from Microsoft and register them under Windows XP SP1+, I&amp;rsquo;ve had this working in the past and is fairly painless so I won&amp;rsquo;t go into it here.&lt;/p&gt;
&lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/ms630491(VS.85).aspx"&gt;reference documentation on MSDN&lt;/a&gt; is comprehensive and also handily gives the ProgId for all the different objects making use from Silverlight really easy.&lt;/p&gt;
&lt;h3&gt;The sample code&lt;/h3&gt;
&lt;p&gt;To have a little play around with these new features in Silverlight and C# I put together a little application which allows my to take pictures with my WIA enabled Nikon DSLR. Taking photos from a Nikon using a browser plug-in, crazy!?!&lt;/p&gt;
&lt;p&gt;First of all we need to let the user choose a device to take pictures with:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:48ed6dbb-0d41-4f00-84c2-9dfde0c5fede" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;using (dynamic dialog = ComAutomationFactory.CreateObject("WIA.CommonDialog"))
{
    var device = dialog.ShowSelectDevice(
        (int)WiaDeviceType.CameraDeviceType, true, false);
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Notice that CreateObject returns IDisposable, so we try to make sure we call Dispose for any reference obtained this way to ensure we release all resources cleanly.&lt;/p&gt;
&lt;p&gt;This will pop open a modal dialog which allows us to pick our device.&lt;/p&gt;
&lt;p&gt;&lt;img style="display: inline; border-width: 0px;" title="D40X" src="http://sblakemore.com/blog/image.axd?picture=tmpF3E2.png" alt="D40X" width="463" height="302" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Now since we&amp;rsquo;re able to subscribe to events raised by the COM object, lets see if we can get a notification when a picture is taken. This will allow us to respond to both our application requesting a picture be taken but also let us know when someone presses the shutter release on the camera itself!&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:5e652478-2749-445e-ab41-8600450a27e0" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;ComAutomationEvent evt = ComAutomationFactory.GetEvent(manager, "OnEvent");
evt.EventRaised += OnEvent;

private void OnEvent(object sender, ComAutomationEventArgs e)
{
    if (e.Arguments[0].ToString() != EventId.ItemCreated)
        return;

    //Grab the raw image bytes
    var item = device.Items[device.Items.Count];
    var imagefile = item.Transfer(FormatId.Jpeg);
    var imageData = (byte[]) imagefile.FileData.BinaryData;

    PictureTaken(this, new PictureTakenEventArgs(imageData));
}

public event EventHandler&amp;lt;PictureTakenEventArgs&amp;gt; PictureTaken = delegate { };&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Here we get a ComAutomationEvent from the ComAutomationFactory.GetEvent method and subscribe to it&amp;rsquo;s EventRaised event. In the handler we extract the raw image bytes using the WIA API and then notify any interested parties a picture was taken.&lt;/p&gt;
&lt;p&gt;Taking a picture programmatically is even more trivial.&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:26570648-ebe7-4327-aeec-def87672bb15" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;device.ExecuteCommand(CommandId.TakePicture);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;The sample application in the download below has a simple UI which allows you, when running Out-Of-Browser on Windows, to take pictures and displays them on screen.&lt;/p&gt;
&lt;p&gt;&lt;img style="display: inline; border-width: 0px;" title="Mmmm Coffee" src="http://sblakemore.com/blog/image.axd?picture=tmp4DD5.png" alt="Mmmm Coffee" width="499" height="392" border="0" /&gt;&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;All in all I&amp;rsquo;m very excited about Silverlight 4 and Silverlight in general, a lot of missing pieces are falling into place with this new release and we should be able to create some really compelling stuff.&lt;/p&gt;
&lt;p&gt;My concern is that since none of this COM business will work on OSX, nor is there any alternative scheme on that platform, we are heading down the wrong track. Yes, we can now create applications that &amp;ldquo;Light Up&amp;rdquo; on Windows, but really I&amp;rsquo;d like to offer the same powerful functionality to all my users. Some are of the opinion that the real exciting thing with Silverlight and Moonlight is the future of a true cross platform development model based on C#, XAML and web based deployment, and for me not having feature parity across even officially supported operating systems is a worry.&lt;/p&gt;
&lt;p&gt;Never the less, I&amp;rsquo;m loving it!&lt;/p&gt;
&lt;h4&gt;Code Download&lt;/h4&gt;
&lt;div id="scid:F60BB8FA-6F02-4999-8F5E-9DD4E92C4DA7:3344e3ce-1438-453e-83f3-3185116bcffc" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;div&gt;&lt;a onclick="javascript: pageTracker._trackPageview('SBlakemore.SilverlightWia.zip');" href="http://sblakemore.com/blog/file.axd?file=SBlakemore.SilverlightWia.zip" target="_self"&gt;SBlakemore.SilverlightWia.zip&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;</description>
      <link>http://sblakemore.com/blog/post/Silverlight-4-COM-Automation-e28093-Taking-photos-with-a-DSLR-using-Windows-Image-Acquisition.aspx</link>
      <comments>http://sblakemore.com/blog/post/Silverlight-4-COM-Automation-e28093-Taking-photos-with-a-DSLR-using-Windows-Image-Acquisition.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=d8675128-2082-41fc-aafc-ba41acc57269</guid>
      <pubDate>Tue, 22 Dec 2009 22:01:00 +1800</pubDate>
      <category>Development</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=d8675128-2082-41fc-aafc-ba41acc57269</pingback:target>
      <slash:comments>15</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=d8675128-2082-41fc-aafc-ba41acc57269</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/Silverlight-4-COM-Automation-e28093-Taking-photos-with-a-DSLR-using-Windows-Image-Acquisition.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=d8675128-2082-41fc-aafc-ba41acc57269</wfw:commentRss>
    </item>
    <item>
      <title>A Frosty First Post</title>
      <description>&lt;p&gt;So to christen my new home I though I would post a few photos of what I woke up to this morning in deepest Buckinghamshire in the south of England!&lt;/p&gt;  &lt;p&gt;&lt;a href="http://sblakemore.com/blog/image.axd?picture=P1010460.jpg"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Out the upstairs window" border="0" alt="Out the upstairs window" src="http://sblakemore.com/blog/image.axd?picture=P1010460_thumb.jpg" width="184" height="244" /&gt;&lt;/a&gt; &lt;a href="http://sblakemore.com/blog/image.axd?picture=P1010472.jpg"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="An &amp;#39;interesting&amp;#39; drive to work" border="0" alt="An &amp;#39;interesting&amp;#39; drive to work" src="http://sblakemore.com/blog/image.axd?picture=P1010472_thumb.jpg" width="244" height="184" /&gt;&lt;/a&gt; &lt;a href="http://sblakemore.com/blog/image.axd?picture=P1010487.jpg"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Bemused bystanders" border="0" alt="Bemused bystanders" src="http://sblakemore.com/blog/image.axd?picture=P1010487_thumb.jpg" width="244" height="184" /&gt;&lt;/a&gt;&lt;/p&gt;</description>
      <link>http://sblakemore.com/blog/post/A-Frosty-First-Post.aspx</link>
      <comments>http://sblakemore.com/blog/post/A-Frosty-First-Post.aspx#comment</comments>
      <guid>http://sblakemore.com/blog/post.aspx?id=c75e2cec-de62-43b6-a352-c87b38fefc7f</guid>
      <pubDate>Sat, 19 Dec 2009 02:23:48 +1800</pubDate>
      <category>Photography</category>
      <category>Personal</category>
      <dc:publisher>Sean</dc:publisher>
      <pingback:server>http://sblakemore.com/blog/pingback.axd</pingback:server>
      <pingback:target>http://sblakemore.com/blog/post.aspx?id=c75e2cec-de62-43b6-a352-c87b38fefc7f</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://sblakemore.com/blog/trackback.axd?id=c75e2cec-de62-43b6-a352-c87b38fefc7f</trackback:ping>
      <wfw:comment>http://sblakemore.com/blog/post/A-Frosty-First-Post.aspx#comment</wfw:comment>
      <wfw:commentRss>http://sblakemore.com/blog/syndication.axd?post=c75e2cec-de62-43b6-a352-c87b38fefc7f</wfw:commentRss>
    </item>
  </channel>
</rss>