<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" 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:copyright="http://blogs.law.harvard.edu/tech/rss" xmlns:image="http://purl.org/rss/1.0/modules/image/">
    <channel>
        <title>Steve Wilkes</title>
        <link>http://geekswithblogs.net/mrsteve/Default.aspx</link>
        <description>.NET, Agile, TDD, design patterns and all that jazz</description>
        <language>en-GB</language>
        <copyright>Steve Wilkes</copyright>
        <managingEditor>steve@agileobjects.co.uk</managingEditor>
        <generator>Subtext Version 0.0.0.0</generator>
        <image>
            <title>Steve Wilkes</title>
            <url>http://geekswithblogs.net/images/RSS2Image.gif</url>
            <link>http://geekswithblogs.net/mrsteve/Default.aspx</link>
            <width>77</width>
            <height>60</height>
        </image>
        <item>
            <title>Why Automated Tests Are So Great</title>
            <category>Patterns</category>
            <category>Patterns</category>
            <category>Programming Practices</category>
            <category>Unit testing</category>
            <category>Unit testing</category>
            <category>Programming Practices</category>
            <category>UI Testing</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2013/03/02/automated-integration-unit-testing-advantages.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2013/03/02/automated-integration-unit-testing-advantages.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2013/03/02/automated-integration-unit-testing-advantages.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;I've recently done work at a company where there are no automated tests, and tests aren't part of the culture. I've been writing tests for so long now that it's jarring to consider working without them, so I've gone ahead and written tests for my part of the work. As I've done so it's really brought home the advantages of writing tests, and I wanted to list them out.&lt;/p&gt;  &lt;h3&gt;Tests Make Your Code Work&lt;/h3&gt;  &lt;p&gt;The earlier you write a test for a piece of code, the sooner you'll find yourself stepping through it, double-checking that and how it works. Working with code through tests is a unique experience, and things occur to you when you're stepping through a class that won't when you're reading through it. What if that variable turned out to have that value? What if that resource turned out to be unavailable? Watching your code go through its paces brings home the fact that it's going to be part of a functioning system with real users one day, and makes you consider if it does its job properly.&lt;/p&gt; &lt;h3&gt;Tests Give You Easy Entry Points To Diagnose Problems&lt;/h3&gt;  &lt;p&gt;If something goes wrong in a particular part of your system, tests give you a way to access that part without going through the various layers that usually sit between it and the outside world. Without tests you have to crank up the entire system and work your way from the user interface to the situation that caused the error. That could include getting a user into a particular state or entering a particular combination of data - do any of that even a little bit wrong and you can easily find yourself no closer to a solution, proclaiming that "&lt;a title="It Works On My Machine: read more (opens in a new window)" href="http://www.codinghorror.com/blog/2007/03/the-works-on-my-machine-certification-program.html" target="_blank"&gt;it works on my machine&lt;/a&gt;". Worse still is if the error was caused by something transient, or a quirk in a third party system only triggered by certain circumstances - with tests you can easily stub out components and reliably simulate that behaviour so you can check how your system deals with it. Without tests... well... good luck with that.&lt;/p&gt;  &lt;h3&gt;Tests Guard Against Other People's Changes&lt;/h3&gt;  &lt;p&gt;A colleague working without tests reported the other day that he'd spent most of a day trying to figure out why part of the system he'd written had stopped working. He'd been sending the same data to a third-party service all along, and up until that morning it'd always worked; he now wasn't sure if something had changed with his setup or what he was doing, or something had changed with the third party. Tests would have stopped this problem before it got started - he would have had a failing test to go to telling him what had changed.&lt;/p&gt;  &lt;h3&gt;Tests Are Specification&lt;/h3&gt;  &lt;p&gt;You have a specification which says in circumstance ABC the system should perform action XYZ - does it? Sure, you stepped through it those times and saw it do XYZ, but a lot has happened since then - does it do XYZ now? Tests are an &lt;em&gt;executable&lt;/em&gt; specification of what your system does. Not what it's &lt;em&gt;supposed&lt;/em&gt; to do, but what it &lt;em&gt;does&lt;/em&gt;. Tests are the only specification you have which the code &lt;em&gt;definitely&lt;/em&gt; fulfils. You probably have a Word document which says how your system is supposed to behave, but your tests tell you how it &lt;em&gt;actually&lt;/em&gt; behaves. In every area of life, you only know what you can demonstrate - tests are a great way of demonstrating what your system does.&lt;/p&gt;  &lt;h3&gt;Tests Are Documentation&lt;/h3&gt;  &lt;p&gt;How are the classes and subsystems in your system used? What inputs do they expect? What outputs do they give? Do they have any quirky behaviour? Do they throw exceptions or returns nulls or empty collections? That third-party library you're using to validate bank account details - does it say account number 111111 with a valid sort code is valid, or invalid? You can write comments, &lt;a title="Read more about Sandcastle (opens in a new window)" href="http://blogs.msdn.com/b/sandcastle" target="_blank"&gt;Sandcastle&lt;/a&gt; comments, Word documents and make UML diagrams all you want, but your tests are the only documentation you can &lt;em&gt;rely on&lt;/em&gt; to be accurate. If code changes, passing tests &lt;em&gt;have&lt;/em&gt; to change with it - comments, documents and diagrams don't.&lt;/p&gt;  &lt;h3&gt;Tests Are Insurance&lt;/h3&gt;  &lt;p&gt;You put an application live and move on. A few months later you revisit it to add a new feature - without tests, how easy is it to tell if your new feature breaks any of your old features? This is a few months down the road and your familiarity with the existing system has faded, so your intuition isn't going to help you as much as it once did. This is another area where tests pay huge dividends - if your new feature breaks an existing one, your tests will let you know. I've added to and refactored code on a well-tested project where I've genuinely had no idea (and put next to no effort into figuring out) if it would break something - safely insured that if it does, my tests will tell me. Without tests you're stepping on eggshells whenever you need to change existing code.&lt;/p&gt;  &lt;p&gt;...and &lt;em&gt;that's&lt;/em&gt; why tests are so great. I've been working with them for so long now that it baffles me how anyone writes anything non-trivial without them. Getting used to writing tests takes some discipline and effort, but it's repaid many times over - if you don't write tests, you owe it to yourself and your team to start.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/152285.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2013/03/02/automated-integration-unit-testing-advantages.aspx</guid>
            <pubDate>Sat, 02 Mar 2013 09:52:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/152285.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2013/03/02/automated-integration-unit-testing-advantages.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/152285.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/152285.aspx</trackback:ping>
        </item>
        <item>
            <title>A Generic, IDisposable, Unit-Testable, Error-Handling WCF Service Client</title>
            <category>Programming Practices</category>
            <category>WCF</category>
            <category>Programming Practices</category>
            <category>ASP.NET</category>
            <category>C#</category>
            <category>Dependency Injection (DI)</category>
            <category>ASP.NET MVC</category>
            <category>C#</category>
            <category>ASP.NET MVC </category>
            <category>Dependency Injection (DI) </category>
            <category>CodeProject</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2013/02/17/generic-idisposable-unit-testable-error-handling-wcf-service-client.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2013/02/17/generic-idisposable-unit-testable-error-handling-wcf-service-client.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2013/02/17/generic-idisposable-unit-testable-error-handling-wcf-service-client.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;I recently reused my &lt;a title="My original generic, disposable WCF service client" href="http://geekswithblogs.net/mrsteve/archive/2011/06/30/generic-disposable-wcf-service-client.aspx" target="_blank"&gt;generic, disposable WCF service client&lt;/a&gt;, and made some changes to make it simpler to use and easier to unit test. The original client was used like this:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;serviceClientWrapper = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ServiceClientWrapper&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ManagementServiceClient&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IManagementService&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;(config))
{
    serviceClientWrapper.CreateServiceClient().CallService();
}&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;...where &lt;font size="2" face="Consolas"&gt;config&lt;/font&gt; is a &lt;span style="background: white; color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;WebServiceConfig&lt;/font&gt;&lt;/span&gt; - a simple Data Bag which contains details of the service to call:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System.Security.Cryptography.X509Certificates;

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;Binding
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;get&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;set&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;Endpoint
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;get&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;set&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public bool &lt;/span&gt;&lt;span style="background: white; color: black"&gt;IgnoreSslErrors
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;get&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;set&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;X509Certificate2 &lt;/span&gt;&lt;span style="background: white; color: black"&gt;ClientCertificate
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;get&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;set&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
    }
}&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;Having worked with the client on previous projects I'd noticed some problems with it; every time you use it you have to write a &lt;span style="background: white; color: blue"&gt;&lt;font size="2" face="Consolas"&gt;using&lt;/font&gt;&lt;/span&gt; statement and call &lt;font size="2" face="Consolas"&gt;CreateServiceClient()&lt;/font&gt;. That's a minor inconvenience, but a bigger problem comes with unit testing code that uses it - newing up the &lt;span style="background: white; color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;ServiceClientWrapper&lt;/font&gt;&lt;/span&gt; makes it impossible to &lt;a title="Read more about mocking (opens in a new window)" href="http://en.wikipedia.org/wiki/Mock_object" target="_blank"&gt;mock&lt;/a&gt;, but the class being &lt;font size="2" face="Consolas"&gt;IDisposable&lt;/font&gt; means it's intended for one-shot uses and isn't an appropriate candidate to be &lt;a title="Read more about Dependency Injection (opens in a new window)" href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank"&gt;injected&lt;/a&gt; as a dependency. I worked around this by injecting in a &lt;span style="background: white; color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;ServiceClientWrapperFactory&lt;/font&gt;&lt;/span&gt; class which I &lt;em&gt;could&lt;/em&gt; mock, but at some point I read &lt;a title="Visit Jimmy Bogard's blog (opens in a new window)" href="http://lostechies.com/jimmybogard" target="_blank"&gt;Jimmy Bogard&lt;/a&gt; advise that your design may be flawed if you're making objects which do nothing but create other objects, and while I generally have no problem changing a design to make it more testable, I knew this was one of those occasions. &lt;/p&gt;

&lt;p&gt;So I had these problems to solve:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Stop the user having to write &lt;span style="background: white; color: blue"&gt;&lt;font size="2" face="Consolas"&gt;using&lt;/font&gt;&lt;/span&gt; statements &lt;/li&gt;

  &lt;li&gt;Make the client injectable &lt;/li&gt;

  &lt;li&gt;Make the client mockable or stubbable &lt;/li&gt;

  &lt;li&gt;Get rid of the factory class which did nothing but make clients for unit tests&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I'd also noticed a lot of boilerplate code to handle exceptions and retry service calls, and I wanted to get rid of that, too.&lt;/p&gt;

&lt;p&gt;Thanks to these requirements, the class I wrote ended up being quite different to the previous client. It's still &lt;font size="2" face="Consolas"&gt;IDisposable&lt;/font&gt; (more on why later) but it hides the process of creating and &lt;span style="background: white; color: blue"&gt;&lt;font size="2" face="Consolas"&gt;using&lt;/font&gt;&lt;/span&gt; a service client inside two &lt;font size="2" face="Consolas"&gt;Execute()&lt;/font&gt; methods. The previous client being constructed with a &lt;font size="2" face="Consolas"&gt;config&lt;/font&gt; limited its use to the service and setup defined therein - the new client is passed a &lt;font size="2" face="Consolas"&gt;config&lt;/font&gt; through its &lt;font size="2" face="Consolas"&gt;Execute()&lt;/font&gt; methods, which means the same instance can be used to call different services with different settings.&lt;/p&gt;

&lt;p&gt;This is the new class I wrote:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System;
&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System.Net;
&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System.Net.Security;
&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System.ServiceModel;

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ServiceClientWrapper&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;TClient, TService&amp;gt; : &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IDisposable
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;where &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TClient : &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ClientBase&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;TService&amp;gt;, TService
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;where &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TService : &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;class
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TClient _serviceClient;

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;Execute(
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config,
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Action&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;TService&amp;gt; serviceCall,
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Action&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CommunicationException&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; commsExceptionHandler = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;,
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;int &lt;/span&gt;&lt;span style="background: white; color: black"&gt;numberOfTimesToRetry = 1)
    {
        Execute&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;object&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;(
            config,
            service =&amp;gt; { serviceCall.Invoke(service); &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;; },
            commsExceptionHandler,
            numberOfTimesToRetry);
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TResult Execute&amp;lt;TResult&amp;gt;(
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config,
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Func&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;TService, TResult&amp;gt; serviceCall,
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Action&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CommunicationException&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; commsExceptionHandler = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;,
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;int &lt;/span&gt;&lt;span style="background: white; color: black"&gt;numberOfTimesToRetry = 1)
    {
        SetupSecurity(config);

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;i = 0;
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CommunicationException &lt;/span&gt;&lt;span style="background: white; color: black"&gt;thrownException = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;while &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(i &amp;lt; numberOfTimesToRetry)
        {&lt;br /&gt;&lt;span style="background: white; color: blue"&gt;            this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.&lt;/span&gt;DisposeExistingServiceClientIfRequired(); &lt;br /&gt;
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;try
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return &lt;/span&gt;&lt;span style="background: white; color: black"&gt;serviceCall.Invoke(CreateServiceClient(config));
            }
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;catch &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CommunicationException &lt;/span&gt;&lt;span style="background: white; color: black"&gt;faultEx)
            {
                thrownException = faultEx;

                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(commsExceptionHandler != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
                {
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;try
                    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
                        commsExceptionHandler.Invoke(thrownException);
                    }
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;catch &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CommunicationException &lt;/span&gt;&lt;span style="background: white; color: black"&gt;rethrownEx)
                    {
                        thrownException = rethrownEx;
                    }
                }

                ++i;
            }
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;finally
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.DisposeExistingServiceClientIfRequired();
            }
        }

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;throw &lt;/span&gt;&lt;span style="background: white; color: black"&gt;thrownException;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private static void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;SetupSecurity(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(config.IgnoreSslErrors)
        {
            &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ServicePointManager&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.ServerCertificateValidationCallback =
                (obj, certificate, chain, errors) =&amp;gt; &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;true&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        }
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;else
        &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
            &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ServicePointManager&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.ServerCertificateValidationCallback =
                (obj, certificate, chain, errors) =&amp;gt; errors == &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;SslPolicyErrors&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.None;
        }
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;&lt;span style="background: white; color: blue"&gt;protected&lt;/span&gt; virtual &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TService CreateServiceClient(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config)
    {
        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// Or you can use:
        // this._serviceClient = (TClient)typeof(TClient).&lt;a title="A fast extension method to create an instance from a Type (opens in a new window)" href="http://geekswithblogs.net/mrsteve/archive/2012/02/19/a-fast-c-sharp-extension-method-using-expression-trees-create-instance-from-type-again.aspx" style="color: green" target="_blank"&gt;GetInstance&lt;/a&gt;(
        //     config.Binding,
        //     new EndpointAddress(config.Endpoint));
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClient = (TClient)&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Activator&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.CreateInstance(
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;typeof&lt;/span&gt;&lt;span style="background: white; color: black"&gt;(TClient),
            config.Binding,
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;EndpointAddress&lt;/span&gt;&lt;span style="background: white; color: black"&gt;(config.Endpoint));

        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_serviceClient;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;Dispose()
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.DisposeExistingServiceClientIfRequired();
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;DisposeExistingServiceClientIfRequired()
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClient != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;try
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClient.State == &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;CommunicationState&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Faulted)
                {
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClient.Abort();
                }
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;else
                &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClient.Close();
                }
            }
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;catch
            &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClient.Abort();
            }

            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClient = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        }
    }
}&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;At its simplest you use it like this - note that this time it's a member of the class using it - it's been injected in through the constructor, for instance:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClientWrapper.Execute(
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config,&lt;br /&gt;    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;service =&amp;gt; service.DoSomething());&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;If you have a service which returns a value, you can call it like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;response = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClientWrapper.Execute(&lt;br /&gt;    &lt;span style="background: white; color: black"&gt;&lt;/span&gt;&lt;span style="background: white; color: black"&gt;config,&lt;br /&gt;  &lt;/span&gt;&lt;/span&gt;&lt;span style="background: white; color: black"&gt;  service =&amp;gt; service.GetResponse());&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;If you want to handle &lt;span style="background: white; color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;CommunicationException&lt;/font&gt;&lt;/span&gt;s yourself, you can pass in a handler:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;response = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClientWrapper.Execute(
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config,&lt;br /&gt;&lt;/span&gt;&lt;span style="background: white; color: black"&gt;    service =&amp;gt; service.GetResponseWhichMightError(),
    commsException =&amp;gt; SendMeAnEmailAboutThis(commsException));&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;...and if you want to retry a service call when &lt;span style="background: white; color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;CommunicationException&lt;/font&gt;&lt;/span&gt;s are thrown, you can pass in the number of times to retry:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;response = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClientWrapper.Execute(
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config,&lt;br /&gt;&lt;/span&gt;&lt;span style="background: white; color: black"&gt;    service =&amp;gt; service.GetUnreliableResponse(),
    commsException =&amp;gt; SendMeAnEmailAboutThis(commsException),
    numberOfTimesToRetry: 3);&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;And so to the testability! Moving the WCF client creation code into a dedicated virtual &lt;font size="2" face="Consolas"&gt;CreateServiceClient&lt;/font&gt; method makes the client wrapper stubbable:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System.ServiceModel;&lt;/span&gt;&lt;span style="background: white; color: black"&gt;

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;StubServiceClientWrapper&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;TClient, TService&amp;gt; : &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ServiceClientWrapper&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;TClient, TService&amp;gt;
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;where &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TClient : &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ClientBase&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;TService&amp;gt;, TService
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;where &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TService : &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;class
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TService _serviceClientToReturn;

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public &lt;/span&gt;&lt;span style="background: white; color: black"&gt;StubServiceClientWrapper(TService serviceClientToReturn)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClientToReturn = serviceClientToReturn;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;protected override &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TService CreateServiceClient(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClientToReturn;
    }
}&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;...where the stub is created with a &lt;font size="2" face="Consolas"&gt;TService&lt;/font&gt; instance to return from the overridden &lt;font size="2" face="Consolas"&gt;CreateServiceClient&lt;/font&gt; method. Then - as an example - a &lt;span style="background: white; color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;Service&lt;/font&gt;&lt;/span&gt; class like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;public class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Service
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_config;
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ServiceClientWrapper&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ManagementServiceClient&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IManagementService&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; _serviceClientWrapper;

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public &lt;/span&gt;&lt;span style="background: white; color: black"&gt;Service(
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config,
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ServiceClientWrapper&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ManagementServiceClient&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IManagementService&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; serviceClientWrapper)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._config = config;
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClientWrapper = serviceClientWrapper;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;GetResponse()
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._serviceClientWrapper.Execute(
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._config,
            serviceClient =&amp;gt; serviceClient.GetResponse());
    }
}&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;...can be tested using a combination of the stub and a mock (using &lt;a title="Visit Moq's website (opens in a new window)" href="http://code.google.com/p/moq" target="_blank"&gt;Moq&lt;/a&gt; in this case) like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;config = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WebServiceConfig
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    Binding = &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"MyBinding"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;,
    Endpoint = &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"http://service.com/Service.svc"
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;};

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;wcfClient = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Mock&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IManagementService&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;();
wcfClient.Setup(wcf =&amp;gt; wcf.GetResponse()).Returns(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"Hello!"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;stubClientWrapper = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;StubServiceClientWrapper&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ManagementServiceClient&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IManagementService&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;(
    wcfClient.Object);

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;service = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Service&lt;/span&gt;&lt;span style="background: white; color: black"&gt;(config, stubClientWrapper);

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;serviceResponse = service.GetResponse();

&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Assert&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.AreEqual(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"Hello!"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, serviceResponse);&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;And there we have it - a unit-testable WCF service client wrapper. Because the stub only overrides the &lt;font size="2" face="Consolas"&gt;CreateServiceClient&lt;/font&gt; method everything else can be unit tested, including the retry and error-handling behaviour. &lt;/p&gt;

&lt;p&gt;As mentioned, the new client wrapper is still &lt;font size="2" face="Consolas"&gt;IDisposable&lt;/font&gt;, even though you should never end up with an undisposed WCF client within it; I chose to leave it as &lt;font size="2" face="Consolas"&gt;IDisposable&lt;/font&gt; because classes with disposable members &lt;a title="Read the Microsoft guideline on disposable members (opens in a new window)" href="http://msdn.microsoft.com/en-us/ms182172.aspx" target="_blank"&gt;should themselves be disposable&lt;/a&gt;.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/152148.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2013/02/17/generic-idisposable-unit-testable-error-handling-wcf-service-client.aspx</guid>
            <pubDate>Sun, 17 Feb 2013 12:23:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/152148.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2013/02/17/generic-idisposable-unit-testable-error-handling-wcf-service-client.aspx#feedback</comments>
            <slash:comments>2</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/152148.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/152148.aspx</trackback:ping>
        </item>
        <item>
            <title>GetValueOrDefault() For An Expression of Arbitrary Length Using Expression Trees</title>
            <category>ASP.NET MVC </category>
            <category>ASP.NET MVC</category>
            <category>C#</category>
            <category>C#</category>
            <category>ASP.NET</category>
            <category>Programming Practices</category>
            <category>Expression Trees</category>
            <category>Programming Practices</category>
            <category>CodeProject</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2013/01/10/getvalueordefault-expression-object-graph-arbitrary-length-depth-expression-tree.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2013/01/10/getvalueordefault-expression-object-graph-arbitrary-length-depth-expression-tree.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2013/01/10/getvalueordefault-expression-object-graph-arbitrary-length-depth-expression-tree.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;In my most recent project we had to support classes with fairly deep object graphs where any of the nodes could validly be null. We didn't want to have lots of 'if not null' checks everywhere, so I wrote an extension method which takes an expression of any length and returns the expression value or a default value if any of the nodes are null. It enabled us to do this - for this example let's say we've got a &lt;font size="2" face="Consolas"&gt;&lt;font size="2" face="Consolas"&gt;&lt;span style="background: white; color: #2b91af"&gt;Person&lt;/span&gt;&lt;/font&gt;&lt;/font&gt; class which has an &lt;font size="2" face="Consolas"&gt;Address&lt;/font&gt; property of type &lt;font size="2" face="Consolas"&gt;&lt;span style="background: white; color: #2b91af"&gt;Address&lt;/span&gt;&lt;/font&gt;, which in turn has a &lt;font size="2" face="Consolas"&gt;Postcode&lt;/font&gt; property of type &lt;font size="2" face="Consolas"&gt;&lt;font size="2" face="Consolas"&gt;&lt;span style="background: white; color: #2b91af"&gt;Postcode&lt;/span&gt;&lt;/font&gt;&lt;/font&gt;, which itself has a &lt;font size="2" face="Consolas"&gt;Value&lt;/font&gt; property of type &lt;span style="background: white; color: blue"&gt;&lt;font size="2" face="Consolas"&gt;string&lt;/font&gt;&lt;/span&gt;:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;person.GetValueOrDefault(p =&amp;gt; p.Address.Postcode.Value);&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;You can also optionally pass in a default value to return, like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: black"&gt;person.GetValueOrDefault(p =&amp;gt; p.Address.Postcode.Value, &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"No postcode"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;If &lt;font size="2" face="Consolas"&gt;person&lt;/font&gt;, &lt;font size="2" face="Consolas"&gt;person.Address&lt;/font&gt; or &lt;font size="2" face="Consolas"&gt;person.Address.Postcode&lt;/font&gt; are null the default value is returned. Here's the code for the extension method, followed by an overview of how it works:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System;
&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System.Linq;
&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System.Linq.Expressions;
&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;using &lt;/span&gt;&lt;span style="background: white; color: black"&gt;System.Collections.Concurrent;

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public static class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ObjectExtensions
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public static &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TResponse GetValueOrDefault&amp;lt;T, TResponse&amp;gt;(
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this &lt;/span&gt;&lt;span style="background: white; color: black"&gt;T root,
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Expression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Func&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;T, TResponse&amp;gt;&amp;gt; property,
        TResponse defaultValue = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;default&lt;/span&gt;&lt;span style="background: white; color: black"&gt;(TResponse))
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;where &lt;/span&gt;&lt;span style="background: white; color: black"&gt;T : &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;class
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(root == &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return &lt;/span&gt;&lt;span style="background: white; color: black"&gt;defaultValue;
 
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ValueOrDefaultCache&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;T, TResponse&amp;gt;.Cache
            .GetOrAdd(property.Body.ToString(), key =&amp;gt; CreateValueOrDefaultLambda(property))
            .Invoke(root, defaultValue);
    }
 
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private static &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Func&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;T, TResponse, TResponse&amp;gt; CreateValueOrDefaultLambda&amp;lt;T, TResponse&amp;gt;(
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Expression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Func&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;T, TResponse&amp;gt;&amp;gt; property)
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;where &lt;/span&gt;&lt;span style="background: white; color: black"&gt;T : &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;class
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;rootParameter = property.Parameters.First();
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;defaultValueParameter = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Expression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Parameter(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;typeof&lt;/span&gt;&lt;span style="background: white; color: black"&gt;(TResponse), &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"default"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);
 
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;memberExpression = (&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;MemberExpression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)property.Body;
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Expression &lt;/span&gt;&lt;span style="background: white; color: black"&gt;valueOrDefaultExpression = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
 
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;while &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(memberExpression != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;memberDefaultValue = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Expression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Default(memberExpression.Type);
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;memberIsNotDefault = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Expression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.NotEqual(memberExpression, memberDefaultValue);
 
            valueOrDefaultExpression = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Expression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Condition(
                memberIsNotDefault,
                (valueOrDefaultExpression ?? memberExpression),
                defaultValueParameter);
 
            memberExpression = memberExpression.Expression &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;as &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;MemberExpression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        }
 
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;lambda = &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Expression&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Lambda&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Func&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;T, TResponse, TResponse&amp;gt;&amp;gt;(
            valueOrDefaultExpression, 
            rootParameter,
            defaultValueParameter);
 
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return &lt;/span&gt;&lt;span style="background: white; color: black"&gt;lambda.Compile();
    }
 
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private static class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ValueOrDefaultCache&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;T, TResponse&amp;gt;
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public static readonly &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ConcurrentDictionary&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Func&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;T, TResponse, TResponse&amp;gt;&amp;gt; Cache =
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ConcurrentDictionary&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Func&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;T, TResponse, TResponse&amp;gt;&amp;gt;();
    }
}&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;font size="2" face="Consolas"&gt;&lt;span style="background: white; color: #2b91af"&gt;ValueOrDefaultCache&lt;/span&gt;&lt;/font&gt; class contains a &lt;font size="2" face="Consolas"&gt;&lt;span style="background: white; color: #2b91af"&gt;ConcurrentDictionary&lt;/span&gt;&lt;/font&gt; which caches functions which return a value or default for a given expression against the 'signature' of the expression itself. Because &lt;font size="2" face="Consolas"&gt;&lt;span style="background: white; color: #2b91af"&gt;ValueOrDefaultCache&lt;/span&gt;&lt;/font&gt; is static and generic, one dictionary and set of functions is cached per root and leaf object type, ensuring the functions are unique. To illustrate, the cache entry for our &lt;font size="2" face="Consolas"&gt;person.GetValueOrDefault()&lt;/font&gt; example above looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/7d2ad0142e02_92B4/Cache_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="Cache" border="0" alt="Cache" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/7d2ad0142e02_92B4/Cache_thumb.png" width="1060" height="123" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The cached method is built using Expression Trees; starting at the leaf the while loop walks back up to the expression root, creating a nested &lt;a title="Read about the ternary operator (opens in a new window)" href="http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx" target="_blank"&gt;ternary condition&lt;/a&gt; for each node. The condition's true branch returns the expression value for the leaf node, or the set of ternary conditions so far for the other nodes. The false branch returns the default value - either that supplied by the caller or the default value of the leaf node's Type. Once a set of ternary operators has been built which checks the entire expression, a Lambda Expression is created and compiled into the function to be cached and executed.&lt;/p&gt;

&lt;p&gt;For example, on the first pass over the loop for our &lt;font size="2" face="Consolas"&gt;person.GetValueOrDefault()&lt;/font&gt; example:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/7d2ad0142e02_92B4/Expression1_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="Expression1" border="0" alt="Expression1" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/7d2ad0142e02_92B4/Expression1_thumb.png" width="792" height="71" /&gt;&lt;/a&gt;&lt;/p&gt;





&lt;p&gt;...the &lt;font size="2" face="Consolas"&gt;valueOrDefaultExpression&lt;/font&gt; goes as far as checking if &lt;font size="2" face="Consolas"&gt;p.Address.Postcode.Value&lt;/font&gt; is different to the default value for &lt;span style="background: white; color: blue"&gt;&lt;font size="2" face="Consolas"&gt;string&lt;/font&gt;&lt;/span&gt;; if it is it returns it, otherwise it returns the value of the &lt;font size="2" face="Consolas"&gt;default&lt;/font&gt; parameter passed to the function. The second time around the loop looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/7d2ad0142e02_92B4/Expression2_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="Expression2" border="0" alt="Expression2" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/7d2ad0142e02_92B4/Expression2_thumb.png" width="971" height="74" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;...now the conditional checks if &lt;font size="2" face="Consolas"&gt;p.Address.Postcode&lt;/font&gt; is different to the default value for &lt;font size="2" face="Consolas"&gt;&lt;font size="2" face="Consolas"&gt;&lt;span style="background: white; color: #2b91af"&gt;Postcode&lt;/span&gt;&lt;/font&gt;&lt;/font&gt;; if it is it returns the result of the first conditional, otherwise as before it returns the value of the &lt;font size="2" face="Consolas"&gt;default&lt;/font&gt; parameter passed to the function.&lt;/p&gt;

&lt;p&gt;The Expression continues to built in this way to an arbitrary depth. Eventually the expression from our example looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/7d2ad0142e02_92B4/Expression3_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="Expression3" border="0" alt="Expression3" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/7d2ad0142e02_92B4/Expression3_thumb.png" width="1190" height="74" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And we've got a way of checking each node in an object graph of arbitrary depth to make sure it has a value. The expression is compiled and the resulting function cached, so the next time we execute &lt;span style="background: white; color: black"&gt;&lt;font size="2" face="Consolas"&gt;person.GetValueOrDefault(p =&amp;gt; p.Address.Postcode.Value)&lt;/font&gt;&lt;/span&gt;, it runs at almost native speed.&lt;/p&gt;



&lt;p&gt;This version of the function only deals with &lt;font face="Consolas" size="2"&gt;&lt;span style="background: white; color: #2b91af"&gt;MemberAccessExpression&lt;/span&gt;&lt;/font&gt;s, which means it doesn't deal with &lt;font face="Consolas" size="2"&gt;&lt;span style="background: white; color: #2b91af"&gt;CallExpression&lt;/span&gt;&lt;/font&gt;s; calls to instance or extension methods. Maybe I'll update it to do so at some point, otherwise I'll leave it as an exercise for the reader :)&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/151781.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2013/01/10/getvalueordefault-expression-object-graph-arbitrary-length-depth-expression-tree.aspx</guid>
            <pubDate>Thu, 10 Jan 2013 11:26:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/151781.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2013/01/10/getvalueordefault-expression-object-graph-arbitrary-length-depth-expression-tree.aspx#feedback</comments>
            <slash:comments>2</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/151781.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/151781.aspx</trackback:ping>
        </item>
        <item>
            <title>Extending WatiN 3: Detecting if a PDF Has Opened In a New Window</title>
            <category>UI Testing</category>
            <category>Programming Practices</category>
            <category>ASP.NET</category>
            <category>C#</category>
            <category>Patterns</category>
            <category>ASP.NET MVC </category>
            <link>http://geekswithblogs.net/mrsteve/archive/2013/01/04/watin-detect-if-pdf-opened-in-new-window.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2013/01/04/watin-detect-if-pdf-opened-in-new-window.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2013/01/04/watin-detect-if-pdf-opened-in-new-window.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;a title="WatiN (opens in a new window)" href="http://watin.org" target="_blank"&gt;WatiN&lt;/a&gt; lets you attach to browser windows so you can verify their contents and close them as part of your tests, but the standard API doesn't detect windows with PDF documents in them. Adapted from &lt;a title="The WatiN question on StackOverflow (opens in a new window)" href="http://stackoverflow.com/questions/1191897/how-to-check-if-pdf-was-successfully-opened-in-the-browser-using-watin" target="_blank"&gt;this answer&lt;/a&gt; on StackOverflow, here's an extension method which does.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;private static readonly &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ConstraintContext &lt;/span&gt;&lt;span style="background: white; color: black"&gt;_emptyConstraintContext = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ConstraintContext&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();

&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public static &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TPage ShouldOpenANewWindow&amp;lt;TPage&amp;gt;(
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TPage page,
    &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Action&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;TPage&amp;gt; windowOpeningAction,
    &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Constraint &lt;/span&gt;&lt;span style="background: white; color: black"&gt;windowFindMethod,
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;bool &lt;/span&gt;&lt;span style="background: white; color: black"&gt;closeBrowserIfExists = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;true&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;where &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TPage : &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;BasePage
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Assert&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.IsFalse(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Browser&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Exists&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IE&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;(windowFindMethod));
 
    windowOpeningAction.Invoke(page);
 
    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// Make sure the opening window hasn't been replaced by checking a window 
    // still exists with the Title of the Document of the given page:
    &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Assert&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.IsTrue(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Browser&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Exists&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IE&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Find&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.ByTitle(page.Document.Title)));
 
    &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;InternetExplorer &lt;/span&gt;&lt;span style="background: white; color: black"&gt;matchingWindow = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
            
    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// Try 10 times to find a matching window:
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;for &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;int &lt;/span&gt;&lt;span style="background: white; color: black"&gt;i = 0; i &amp;lt; 10; i++)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;foreach &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;InternetExplorer &lt;/span&gt;&lt;span style="background: white; color: black"&gt;internetExplorer &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;in new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;ShellWindowsClass&lt;/span&gt;&lt;span style="background: white; color: black"&gt;())
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(internetExplorer.FullName.Contains(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"iexplore.exe"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;))
            {
                &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(windowFindMethod.Matches(
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;TitleAndUrlAttributeBag&lt;/span&gt;&lt;span style="background: white; color: black"&gt;(internetExplorer.LocationName, internetExplorer.LocationURL),
                    _emptyConstraintContext))
                {
                    matchingWindow = internetExplorer;
                    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;break&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
                }
            }
        }
 
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(matchingWindow != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;break&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        }
 
        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// None of the currently-open IE windows matches the given title or URL; 
        // wait for 1 second then try again:
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Thread&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Sleep(1000);
    }
 
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(matchingWindow == &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
    {
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Assert&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Fail(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"The expected new browser window was not found."&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);
    }
 
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(closeBrowserIfExists)
    {
        matchingWindow.Quit();
    }
 
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return &lt;/span&gt;&lt;span style="background: white; color: black"&gt;page;
}&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;The method extends a base &lt;span style="color: rgb(43, 145, 175); font-family: Consolas; font-size: small;"&gt;Page&lt;/span&gt; class, assuming that you're using &lt;a title="Read more about WatiN's page pattern (opens in a new window)" href="http://watinandmore.blogspot.co.uk/2009/06/introducing-page-class.html" target="_blank"&gt;WatiN's Page pattern&lt;/a&gt;. You invoke it on an instance of a page, passing in an action which is expected to cause the new window to open, and a WatiN &lt;span style="color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;Constraint&lt;/font&gt; &lt;/span&gt;detailing how to identify the window if it exists. The &lt;span style="color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;Constraint&lt;/font&gt; &lt;/span&gt;is passed a &lt;span style="color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;TitleAndUrlAttributeBag&lt;/font&gt;&lt;/span&gt;, a simple implementation of WatiN's &lt;span style="color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;&lt;a title="View the IAttributeBag source code (opens in a new window)" href="http://sourceforge.net/p/watin/code/1217/tree/trunk/src/Core/Interfaces/IAttributeBag.cs" target="_blank"&gt;IAttributeBag&lt;/a&gt;&lt;/font&gt; &lt;/span&gt;interface which provides title and URL values only. This means you can only use &lt;span style="color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;Constraint&lt;/font&gt;&lt;/span&gt;s which check window titles or URLs, but this should be sufficient for most cases. Here's the &lt;span style="color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;TitleAndUrlAttributeBag&lt;/font&gt;&lt;/span&gt; source:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;internal class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;TitleAndUrlAttributeBag &lt;/span&gt;&lt;span style="background: white; color: black"&gt;: &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;IAttributeBag
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;private readonly &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Dictionary&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt; _attributes;

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public &lt;/span&gt;&lt;span style="background: white; color: black"&gt;TitleAndUrlAttributeBag(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;windowTitle, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;browserUrl)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._attributes = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Dictionary&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;lt;&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string&lt;/span&gt;&lt;span style="background: white; color: black"&gt;&amp;gt;
        {
            { &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"title"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, windowTitle },
            { &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"href"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;, browserUrl}
        };
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public &lt;/span&gt;&lt;span style="background: white; color: black"&gt;T GetAdapter&amp;lt;T&amp;gt;() &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;where &lt;/span&gt;&lt;span style="background: white; color: black"&gt;T : &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;class
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return default&lt;/span&gt;&lt;span style="background: white; color: black"&gt;(T);
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;GetAttributeValue(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;attributeName)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return this&lt;/span&gt;&lt;span style="background: white; color: black"&gt;._attributes[attributeName];
    }
}&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;Note the hard-coded strings &lt;span style="color: #a31515"&gt;&lt;font size="2" face="Consolas"&gt;"title"&lt;/font&gt;&lt;/span&gt; and &lt;span style="color: #a31515"&gt;&lt;font size="2" face="Consolas"&gt;"href"&lt;/font&gt;&lt;/span&gt;; &lt;a title="View WatiN's list of AttributeConstraint constants (opens in a new window)" href="http://sourceforge.net/p/watin/code/1217/tree/trunk/src/Core/Find.cs#l31" target="_blank"&gt;these are the values&lt;/a&gt; WatiN will request when processing an &lt;span style="color: #2b91af"&gt;&lt;font size="2" face="Consolas"&gt;AttributeConstraint&lt;/font&gt; &lt;/span&gt;for a title or URL respectively.&lt;/p&gt;

  &lt;p&gt;So, given this Page class:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;internal class &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;MyPage &lt;/span&gt;&lt;span style="background: white; color: black"&gt;: &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;BasePage
&lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;public void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;ViewTermsAndConditions()
    {
        &lt;span style="background: white; color: blue"&gt;this&lt;/span&gt;.Document.Link(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Find&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.ById(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"terms-and-conditions"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)).Click();
    }
}&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;...you can use the extension method to check a Terms and Conditions PDF opens in a new window like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;myPage = &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;new &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;MyPage&lt;/span&gt;&lt;span style="background: white; color: black"&gt;();

myPage.ShouldOpenANewWindow(
    page =&amp;gt; page.ViewTermsAndConditions(), 
    &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Find&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.ByUrl(url =&amp;gt; url.EndsWith(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"terms.pdf"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)));&lt;/span&gt;&lt;/pre&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/151738.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2013/01/04/watin-detect-if-pdf-opened-in-new-window.aspx</guid>
            <pubDate>Fri, 04 Jan 2013 15:28:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/151738.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2013/01/04/watin-detect-if-pdf-opened-in-new-window.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/151738.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/151738.aspx</trackback:ping>
        </item>
        <item>
            <title>Extending WatiN 2: Wait for JQuery document.ready() Functions to Complete</title>
            <category>ASP.NET MVC </category>
            <category>C#</category>
            <category>C#</category>
            <category>ASP.NET MVC</category>
            <category>ASP.NET</category>
            <category>Programming Practices</category>
            <category>UI Testing</category>
            <category>JQuery</category>
            <category>Programming Practices</category>
            <category>CodeProject</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2012/11/29/making-watin-wait-for-jquery-document-ready-functions-to-complete.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2012/11/29/making-watin-wait-for-jquery-document-ready-functions-to-complete.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2012/11/29/making-watin-wait-for-jquery-document-ready-functions-to-complete.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;a title="Read more about WatiN (opens in a new window)" href="http://watin.org" target="_blank"&gt;WatiN&lt;/a&gt;'s &lt;font size="2" face="Consolas"&gt;DomContainer.&lt;/font&gt;&lt;font size="2" face="Consolas"&gt;&lt;a title="View the WaitForComplete() source code (opens in a new window)" href="http://sourceforge.net/p/watin/code/1217/tree/trunk/src/Core/DomContainer.cs#l139" target="_blank"&gt;WaitForComplete()&lt;/a&gt;&lt;/font&gt; method pauses test execution until the DOM has finished loading, but if your page has functions registered with JQuery's &lt;font size="2" face="Consolas"&gt;&lt;a title="JQuery's ready() function (opens in a new window)" href="http://api.jquery.com/ready" target="_blank"&gt;ready()&lt;/a&gt;&lt;/font&gt; function, you'll probably want to wait for those to finish executing before testing it. Here's a WatiN extension method which pauses test execution until that happens.&lt;/p&gt;  &lt;p&gt;JQuery (as far as I can see) doesn't provide an event or other way of being notified of when it's finished running your &lt;font size="2" face="Consolas"&gt;ready()&lt;/font&gt; functions, so you have to get around it another way. Luckily, because &lt;font size="2" face="Consolas"&gt;ready()&lt;/font&gt; executes the functions it's given in the order they're registered, you can simply register another one to add a 'marker' div to the page, and tell WatiN to wait for that div to exist. Here's the code; I added the extension method to &lt;a title="View the Browser source code (opens in a new window)" href="http://sourceforge.net/p/watin/code/1217/tree/trunk/src/Core/Browser.cs" target="_blank"&gt;&lt;font size="2" face="Consolas"&gt;Browser&lt;/font&gt;&lt;/a&gt; rather than &lt;a title="View the DomContainer source code (opens in a new window)" href="http://sourceforge.net/p/watin/code/1217/tree/trunk/src/Core/DomContainer.cs" target="_blank"&gt;&lt;font size="2" face="Consolas"&gt;DomContainer&lt;/font&gt;&lt;/a&gt; (&lt;font size="2" face="Consolas"&gt;Browser&lt;/font&gt; derives from &lt;font size="2" face="Consolas"&gt;DomContainer&lt;/font&gt;) because it's the sort of thing you only execute once for each of the pages your test loads, so &lt;font size="2" face="Consolas"&gt;Browser&lt;/font&gt; seemed like a good place to put it.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;public static void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;WaitForJQueryDocumentReadyFunctionsToComplete(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Browser &lt;/span&gt;&lt;span style="background: white; color: black"&gt;browser)
{
    &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// Don't try this if JQuery isn't defined on the page:
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;bool&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Parse(browser.Eval(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"typeof $ == 'function'"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)))
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;const string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;jqueryCompleteId = &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"jquery-document-ready-functions-complete"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
 
        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// Register a ready() function which adds a marker div to the body:
        &lt;/span&gt;&lt;span style="background: white; color: black"&gt;browser.Eval(
&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;           @"$(document).ready(function() { " &lt;span style="color: rgb(0, 0, 0);"&gt;+&lt;/span&gt; &lt;br /&gt;                "$('body').append('&amp;lt;div id=""" &lt;/span&gt;&lt;span style="background: white; color: black"&gt;+ jqueryCompleteId + &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;@""" /&amp;gt;'); " &lt;span style="color: rgb(0, 0, 0);"&gt;+&lt;/span&gt; &lt;br /&gt;            "});"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);

        &lt;/span&gt;&lt;span style="background: white; color: green"&gt;// Wait for the marker div to exist or make the test fail:
        &lt;/span&gt;&lt;span style="background: white; color: black"&gt;browser.Div(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Find&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.ById(jqueryCompleteId))
               .WaitUntilExistsOrFail(&lt;/span&gt;&lt;span style="background-color: white;"&gt;10, &lt;/span&gt;&lt;span style="background-color: white; color: rgb(163, 21, 21); background-position: initial initial; background-repeat: initial initial;"&gt;"JQuery document ready functions did not complete."&lt;/span&gt;&lt;span style="background-color: white;"&gt;);
&lt;/span&gt;&lt;span style="background-color: white;"&gt;    }
&lt;/span&gt;&lt;span style="background-color: white;"&gt;}&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;The code uses the &lt;font size="2" face="Consolas"&gt;Eval()&lt;/font&gt; method to send JavaScript to the browser to be executed; first to check that JQuery actually exists on the page, then to add the new &lt;font size="2" face="Consolas"&gt;ready()&lt;/font&gt; method. WaitUntilExistsOrFail() is another WatiN extension method I've written (I've ended up writing really &lt;a title="More WatiN extension methods (opens in a new window)" href="http://geekswithblogs.net/mrsteve/archive/2012/10/26/watin-set-text-is-element-visible-is-field-hidden-extension-methods.aspx" target="_blank"&gt;quite a lot of them&lt;/a&gt;) which waits for the element on which it is invoked to exist, and uses &lt;font size="2" face="Consolas"&gt;&lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.Fail()&lt;/font&gt; to fail the test with the given message if it doesn't exist within the specified number of seconds. Here it is:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;public static void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;WaitUntilExistsOrFail(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Element &lt;/span&gt;&lt;span style="background: white; color: black"&gt;element, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;int &lt;/span&gt;&lt;span style="background: white; color: black"&gt;timeoutInSeconds, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;failureMessage)
{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;try
    &lt;/span&gt;&lt;span style="background: white; color: black"&gt;{
        element.WaitUntilExists(timeoutInSeconds);
    }
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;catch &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(&lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;WatiNTimeoutException&lt;/span&gt;&lt;span style="background: white; color: black"&gt;)
    {
        &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;Assert&lt;/span&gt;&lt;span style="background: white; color: black"&gt;.Fail(failureMessage);
    }
}&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;&lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;WatiNTimeoutException&lt;/span&gt;&lt;/font&gt; is a using alias for &lt;font size="2" face="Consolas"&gt;WatiN.Core.Exceptions.&lt;span style="color: rgb(43, 145, 175);"&gt;TimeoutException&lt;/span&gt;&lt;/font&gt;:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;using &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;WatiNTimeoutException&lt;/span&gt; = WatiN.Core.Exceptions.&lt;span style="color: rgb(43, 145, 175);"&gt;TimeoutException&lt;/span&gt;;&lt;/pre&gt;&lt;p&gt;...I use an alias to avoid a conflict with the base class libraries' &lt;font size="2" face="Consolas"&gt;System.&lt;span style="color: rgb(43, 145, 175);"&gt;TimeoutException&lt;/span&gt;&lt;/font&gt;.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/151397.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2012/11/29/making-watin-wait-for-jquery-document-ready-functions-to-complete.aspx</guid>
            <pubDate>Thu, 29 Nov 2012 19:22:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/151397.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2012/11/29/making-watin-wait-for-jquery-document-ready-functions-to-complete.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/151397.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/151397.aspx</trackback:ping>
        </item>
        <item>
            <title>No More NCrunch For Me</title>
            <category>Programming Practices</category>
            <category>Unit testing</category>
            <category>ASP.NET</category>
            <category>ASP.NET MVC </category>
            <category>C#</category>
            <category>Patterns</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2012/10/28/ncrunch-review-issues-problems-pros-cons.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2012/10/28/ncrunch-review-issues-problems-pros-cons.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2012/10/28/ncrunch-review-issues-problems-pros-cons.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;When I opened up Visual Studio this morning, I was greeted with this little popup:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/Expiring_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="Expiring" border="0" alt="Expiring" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/Expiring_thumb.png" width="183" height="116" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a title="Visit NCrunch's website (opens in a new window)" href="http://www.ncrunch.net" target="_blank"&gt;NCrunch&lt;/a&gt; is a Visual Studio add-in which runs your tests while you work so you know if and when you've broken anything, as well as providing coverage indicators in the IDE and coverage metrics on demand. It recently &lt;a title="Read the blog about NCrunch going commercial (opens in a new window)" href="http://blog.ncrunch.net/post/First-Official-Non-beta-Release!-NCrunch-Goes-Commercial.aspx" target="_blank"&gt;went commercial&lt;/a&gt; (which I thought was fair enough), and time is running out for the free version I've been using for the last couple of months. From my experiences using NCrunch I'm going to let it expire, and go about my business without it. Here's why.&lt;/p&gt;  &lt;p&gt;Before I start, let me say that I think NCrunch is a good product, which is to say it's had a positive impact on my programming. I've used it to help test-drive a library I'm making right from the start of the project, and especially at the beginning it was very useful to have it run all my tests whenever I made a change. The first problem is that while that was cool to start with, it’s recently become a bit of a chore.&lt;/p&gt;  &lt;h3&gt;Problems Running Tests&lt;/h3&gt;  &lt;p&gt;NCrunch has two 'engine modes' in which it can run tests for you - it can run all your tests when you make a change, or it can figure out which tests were impacted and only run those. Unfortunately, it became clear pretty early on that that second option (which &lt;em&gt;is&lt;/em&gt; marked as 'experimental') wasn't really working for me, so I had to have it run everything. With a smallish number of tests and while I was adding new features that was great, but I've now got 445 tests (still not exactly loads) and am more in a 'clean and tidy' mode where I know that a change I'm making will probably only affect a particular subset of the tests. With that in mind it's a bit of a drag sitting there after I make a change and having to wait for NCrunch to run everything. I &lt;em&gt;could&lt;/em&gt; disable it and manually run the tests I know are impacted, but then what's the point of having NCrunch? If the 'impacted only' engine mode worked well this problem would go away, but that's not what I found.&lt;/p&gt;  &lt;p&gt;Secondly, what's wrong with this picture?&lt;/p&gt;  &lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/DuplicateTestRunning_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="DuplicateTestRunning" border="0" alt="DuplicateTestRunning" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/DuplicateTestRunning_thumb.png" width="313" height="85" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;I've got 445 tests, and NCrunch has queued 4&lt;em&gt;55&lt;/em&gt; tests to run. So it's queued duplicate tests - in this quickly-screenshotted case 10, but I've seen the total queue get up over 600. If I'm already itchy waiting for it to run all my tests against a change I know only affects a few, I'm even itchier waiting for it to run a lot of them &lt;em&gt;twice&lt;/em&gt;.&lt;/p&gt;  &lt;h3&gt;Problems With Code Coverage&lt;/h3&gt;  &lt;p&gt;NCrunch marks each line of code with a dot to say if it's covered by tests - a black dot says the line isn't covered, a red dot says it's covered but at least one of the covering tests is failing, and a green dot means all the covering tests pass. It also calculates coverage statistics for you. Unfortunately, there's a couple of flaws in the coverage.&lt;/p&gt;  &lt;p&gt;Firstly, it doesn't support &lt;font size="2" face="Consolas"&gt;ExcludeFromCodeCoverage&lt;/font&gt; attributes. This feature has been requested and I expect will be included in a later release, but right now it doesn't. So this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/ExcludeFromCodeCoverage_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="ExcludeFromCodeCoverage" border="0" alt="ExcludeFromCodeCoverage" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/ExcludeFromCodeCoverage_thumb.png" width="337" height="99" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;...is counted as a non-covered line, and drags your coverage statistics down. Hmph. As well as that, coverage of certain types of code is missed. This:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/CoverageError_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="CoverageError" border="0" alt="CoverageError" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/CoverageError_thumb.png" width="674" height="95" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;...is &lt;em&gt;definitely&lt;/em&gt; covered. I am 100% absolutely certain it is, by several tests. NCrunch doesn't pick it up, down go my coverage statistics. I've had NCrunch find genuinely uncovered code which I've been able to remove, and that's great, but what's the coverage percentage on this project? Umm... I don't know.&lt;/p&gt;      &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;None of these are major, tool-crippling problems, and I expect NCrunch to get much better in future releases. The current version has some great features, like this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/BreakIntoCoveringTests_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="BreakIntoCoveringTests" border="0" alt="BreakIntoCoveringTests" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/No-More-NCrunch-For-Me_793C/BreakIntoCoveringTests_thumb.png" width="363" height="177" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;...that's a line of code with a failing test covering it, and NCrunch can run that failing test and take me to that line exquisitely easily. That's awesome! I'd happily pay for a tool that can do that. But here's the thing: NCrunch (&lt;a title="Visit NCrunch's pricing page (opens in a new window)" href="http://www.ncrunch.net/buy" target="_blank"&gt;currently&lt;/a&gt;) costs $159 (about £100) for a personal licence and $289 (about £180) for a commercial one. I'm not sure which one I'd need as my project is a personal one which I'm intending to open-source, but I'm a professional, self-employed developer, but in any case - that seems like a lot of money for an imperfect tool. If it did everything it's advertised to do more or less perfectly I'd consider it, but it doesn't. So no more NCrunch for me.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/151090.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2012/10/28/ncrunch-review-issues-problems-pros-cons.aspx</guid>
            <pubDate>Sun, 28 Oct 2012 10:20:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/151090.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2012/10/28/ncrunch-review-issues-problems-pros-cons.aspx#feedback</comments>
            <slash:comments>2</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/151090.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/151090.aspx</trackback:ping>
        </item>
        <item>
            <title>Extending WatiN: Useful Extension Methods</title>
            <category>UI Testing</category>
            <category>ASP.NET MVC </category>
            <category>C#</category>
            <category>ASP.NET</category>
            <category>Programming Practices</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2012/10/26/watin-set-text-is-element-visible-is-field-hidden-extension-methods.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2012/10/26/watin-set-text-is-element-visible-is-field-hidden-extension-methods.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2012/10/26/watin-set-text-is-element-visible-is-field-hidden-extension-methods.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;I've been doing a fair amount of UI testing using &lt;a title="Visit WatiN's website" href="http://watin.org" target="_blank"&gt;WatiN&lt;/a&gt; recently – here’s some extension methods I've found useful.&lt;/p&gt;  &lt;p&gt;This checks if a WatiN &lt;font color="#2b91af" size="2" face="Consolas"&gt;TextField&lt;/font&gt; is actually a hidden field. WatiN makes no distinction between text and hidden inputs, so this can come in handy if you render an input sometimes as hidden and sometimes as a visible text field. Note that this doesn't check if an input is &lt;em&gt;visible&lt;/em&gt; (I've got another extension method for that in a moment), it checks if it’s &lt;em&gt;hidden&lt;/em&gt;.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;public static bool &lt;/span&gt;&lt;span style="background: white; color: black"&gt;IsHiddenField(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;TextField &lt;/span&gt;&lt;span style="background: white; color: black"&gt;textField)
{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(textField == &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null &lt;/span&gt;&lt;span style="background: white; color: black"&gt;|| !textField.Exists)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return false&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;var &lt;/span&gt;&lt;span style="background: white; color: black"&gt;textFieldType = textField.GetAttributeValue(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"type"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;);

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(textFieldType != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;) &amp;amp;&amp;amp; textFieldType.ToLowerInvariant() == &lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"hidden"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
}&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The next method quickly sets the value of a text field to a given string. By default WatiN types the text you give it into a text field one character at a time which can be necessary if you have behaviour you want to test which is triggered by individual key presses, but which most of time is just painfully slow; this method dumps the text in in one go. Note that if it's not a hidden field then it gives it focus first; this helps trigger validation once the value has been set and focus moves elsewhere.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;public static void &lt;/span&gt;&lt;span style="background: white; color: black"&gt;SetText(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;TextField &lt;/span&gt;&lt;span style="background: white; color: black"&gt;textField, &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;string &lt;/span&gt;&lt;span style="background: white; color: black"&gt;value)
{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;((textField == &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;) || !textField.Exists)
    {
         &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(!textField.IsHiddenField())
    {
        textField.Focus();
    }

    textField.Value = value;
}&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Finally, here's a method which checks if an &lt;font color="#2b91af" size="2" face="Consolas"&gt;Element&lt;/font&gt; is currently visible. It does so by walking up the DOM and checking for a &lt;font size="2" face="Consolas"&gt;Style.Display&lt;/font&gt; of '&lt;font face="Consolas"&gt;none&lt;/font&gt;' on any element between the one on which the method is invoked, and any of its ancestors.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="background: white; color: blue"&gt;public static bool &lt;/span&gt;&lt;span style="background: white; color: black"&gt;IsElementVisible(&lt;/span&gt;&lt;span style="background: white; color: blue"&gt;this &lt;/span&gt;&lt;span style="background: white; color: #2b91af"&gt;&lt;font color="#2b91af"&gt;Element&lt;/font&gt; &lt;/span&gt;&lt;span style="background: white; color: black"&gt;element)
{
    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;((element == &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;) || !element.Exists)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return false&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;while &lt;/span&gt;&lt;span style="background: white; color: black"&gt;((element != &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;null&lt;/span&gt;&lt;span style="background: white; color: black"&gt;) &amp;amp;&amp;amp; element.Exists)
    {
        &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;if &lt;/span&gt;&lt;span style="background: white; color: black"&gt;(element.Style.Display.ToLowerInvariant().Contains(&lt;/span&gt;&lt;span style="background: white; color: #a31515"&gt;"none"&lt;/span&gt;&lt;span style="background: white; color: black"&gt;))
        {
            &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return false&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
        }

        element = element.Parent;
    }

    &lt;/span&gt;&lt;span style="background: white; color: blue"&gt;return true&lt;/span&gt;&lt;span style="background: white; color: black"&gt;;
}&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;Hope they come in handy &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/Useful-WatiN-Extensions_F702/wlEmoticon-smile_2.png" /&gt;&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/151081.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2012/10/26/watin-set-text-is-element-visible-is-field-hidden-extension-methods.aspx</guid>
            <pubDate>Fri, 26 Oct 2012 15:53:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/151081.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2012/10/26/watin-set-text-is-element-visible-is-field-hidden-extension-methods.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/151081.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/151081.aspx</trackback:ping>
        </item>
        <item>
            <title>Unobtrusive Maximum Input Lengths with JQuery and FluentValidation</title>
            <category>ASP.NET</category>
            <category>ASP.NET MVC </category>
            <category>JQuery</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2012/10/03/unobtrusive-jquery-validation-input-maxlengths-with-fluentvalidation.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2012/10/03/unobtrusive-jquery-validation-input-maxlengths-with-fluentvalidation.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2012/10/03/unobtrusive-jquery-validation-input-maxlengths-with-fluentvalidation.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;If you use &lt;a title="FluentValidation on Codeplex" href="http://fluentvalidation.codeplex.com" target="_blank"&gt;FluentValidation&lt;/a&gt; and set a maximum length for a string or a maximum  value for a numeric property, JQuery validation is used to show an error message when the user inputs too many characters or a numeric value which is too big. On a recent project we wanted to use &lt;font face="Consolas" size="2"&gt;input&lt;/font&gt;’s maxlength attribute to prevent a user from entering too many characters rather than cure the problem with an error message, and I added this JQuery to add maxlength attributes based on JQuery validation’s &lt;font face="Consolas" size="2"&gt;data-&lt;/font&gt; attributes.&lt;/p&gt;  &lt;pre class="code"&gt;$(&lt;span style="color: blue"&gt;function &lt;/span&gt;() {
    $(&lt;span style="color: maroon"&gt;"input[data-val-range-max],input[data-val-length-max]"&lt;/span&gt;).each(&lt;span style="color: blue"&gt;function &lt;/span&gt;(i, e) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;input = $(e);
        &lt;span style="color: blue"&gt;var &lt;/span&gt;maxlength = input.is(&lt;span style="color: maroon"&gt;"[data-val-range-max]"&lt;/span&gt;)
            ? input.data(&lt;span style="color: maroon"&gt;"valRangeMax"&lt;/span&gt;).toString().length
            : input.data(&lt;span style="color: maroon"&gt;"valLengthMax"&lt;/span&gt;);
        input.attr(&lt;span style="color: maroon"&gt;"maxlength"&lt;/span&gt;, maxlength);
    });
});&lt;/pre&gt;

&lt;p&gt;Presto!&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/150888.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2012/10/03/unobtrusive-jquery-validation-input-maxlengths-with-fluentvalidation.aspx</guid>
            <pubDate>Wed, 03 Oct 2012 16:58:34 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/150888.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2012/10/03/unobtrusive-jquery-validation-input-maxlengths-with-fluentvalidation.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/150888.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/150888.aspx</trackback:ping>
        </item>
        <item>
            <title>Fixing Chrome&amp;rsquo;s AJAX Request Caching Bug</title>
            <category>JQuery</category>
            <category>C#</category>
            <category>ASP.NET MVC </category>
            <category>ASP.NET</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2012/08/30/fixing-chromes-ajax-post-request-caching-bug.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2012/08/30/fixing-chromes-ajax-post-request-caching-bug.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2012/08/30/fixing-chromes-ajax-post-request-caching-bug.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;I recently had to make a set of web pages restore their state when the user arrived on them after clicking the browser’s back button. The pages in question had various content loaded in response to user actions, which meant I had to manually get them back into a valid state after the page loaded.&lt;/p&gt;  &lt;p&gt;I got hold of the page’s data in a JavaScript ViewModel using a &lt;a title="Read more about JQuery's ajax function" href="http://api.jquery.com/jQuery.ajax" target="_blank"&gt;JQuery ajax&lt;/a&gt; call, then iterated over the properties, filling in the fields as I went. I built in the ability to describe dependencies between inputs to make sure fields were filled in in the correct order and at the correct time, and that all worked nicely. To make sure the browser didn’t cache the AJAX call results I used the JQuery’s &lt;font face="Consolas" size="2"&gt;cache: false&lt;/font&gt; option, and ASP.NET MVC’s &lt;a title="Read more about ASP.NET MVC's OutputCache attribute" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute%28v=vs.108%29.aspx" target="_blank"&gt;OutputCache&lt;/a&gt; attribute for good measure. That all worked perfectly… except in Chrome.&lt;/p&gt;  &lt;p&gt;Chrome insisted on retrieving the data from its cache. &lt;font face="Consolas" size="2"&gt;cache: false&lt;/font&gt; adds a random query string parameter to make the browser think it’s a unique request – it made no difference. I made the AJAX call a POST – it made no difference.&lt;/p&gt;  &lt;p&gt;Eventually what I had to do was add a random token to the URL (not the query string) and use MVC routing to deliver the request to the correct action. The project had a single Controller for all AJAX requests, so this route:&lt;/p&gt;  &lt;pre class="code"&gt;routes.MapRoute(
    name: &lt;span style="color: #a31515"&gt;"NonCachedAjaxActions"&lt;/span&gt;,
    url: &lt;span style="color: #a31515"&gt;"AjaxCalls/{cacheDisablingToken}/{action}"&lt;/span&gt;,
    defaults: &lt;span style="color: blue"&gt;new &lt;/span&gt;{ controller = &lt;span style="color: #a31515"&gt;"AjaxCalls" &lt;/span&gt;},
    constraints: &lt;span style="color: blue"&gt;new &lt;/span&gt;{ cacheDisablingToken = &lt;span style="color: #a31515"&gt;"[0-9]+" &lt;/span&gt;});&lt;/pre&gt;


&lt;p&gt;…and this amendment to the ajax call:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;function &lt;/span&gt;loadPageData(url) {
    &lt;span style="color: #006400"&gt;// Insert a timestamp before the URL's action segment:
    &lt;/span&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;indexOfFinalUrlSeparator = url.lastIndexOf(&lt;span style="color: maroon"&gt;"/"&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;uniqueUrl =
        url.substring(0, (indexOfFinalUrlSeparator + 1)) +
        &lt;span style="color: blue"&gt;new &lt;/span&gt;Date().getTime() + 
        url.substring(indexOfFinalUrlSeparator);
    &lt;span style="color: #006400"&gt;// Call the now-unique action URL:
    &lt;/span&gt;$.ajax(uniqueUrl, { cache: &lt;span style="color: blue"&gt;false&lt;/span&gt;, success: completePageDataLoad });
}&lt;/pre&gt;


&lt;p&gt;…did the trick.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/150580.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2012/08/30/fixing-chromes-ajax-post-request-caching-bug.aspx</guid>
            <pubDate>Thu, 30 Aug 2012 17:58:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/150580.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2012/08/30/fixing-chromes-ajax-post-request-caching-bug.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/150580.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/150580.aspx</trackback:ping>
        </item>
        <item>
            <title>A Super-Fast C# Extension Method using Expression Trees to Create an instance from a Type</title>
            <category>Programming Practices</category>
            <category>C#</category>
            <category>C#</category>
            <category>Programming Practices</category>
            <category>Expression Trees</category>
            <category>CodeProject</category>
            <link>http://geekswithblogs.net/mrsteve/archive/2012/02/19/a-fast-c-sharp-extension-method-using-expression-trees-create-instance-from-type-again.aspx</link>
            <description>&lt;p&gt;Originally posted on: &lt;a href='http://geekswithblogs.net/mrsteve/archive/2012/02/19/a-fast-c-sharp-extension-method-using-expression-trees-create-instance-from-type-again.aspx'&gt;http://geekswithblogs.net/mrsteve/archive/2012/02/19/a-fast-c-sharp-extension-method-using-expression-trees-create-instance-from-type-again.aspx&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Having written &lt;a target="_blank" title="My original Type.GetInstance() extension method (opens in a new window)" href="http://geekswithblogs.net/mrsteve/archive/2012/01/11/csharp-expression-trees-create-instance-from-type-extension-method.aspx"&gt;an extension method&lt;/a&gt; to create an instance from a &lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175)"&gt;Type&lt;/span&gt;&lt;/font&gt; and been &lt;a target="_blank" title="Performance testing of my previous extension method (opens in a new window)" href="http://geekswithblogs.net/mrsteve/archive/2012/02/11/c-sharp-performance-new-vs-expression-tree-func-vs-activator.createinstance.aspx"&gt;a bit underwhelmed&lt;/a&gt; by its performance, I looked into exactly what was happening and have now got it working much, &lt;i&gt;much&lt;/i&gt; faster.&lt;/p&gt;&lt;p&gt;To recap, the problem with the first version of this method is that it cached the &lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175)"&gt;Func&lt;/span&gt;&lt;/font&gt;s it created with all their argument types as &lt;font size="2" face="Consolas"&gt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&lt;/font&gt;, which meant they had to be cast every time the &lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175)"&gt;Func&lt;/span&gt;&lt;/font&gt; was invoked. This can be seen in all the &lt;b&gt;Convert&lt;/b&gt; calls in Visual Studio's expression visualiser:&lt;/p&gt;&lt;p&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="Expression Visualiser" alt="Expression Visualiser" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/tdgrsfe_89A3/ExpressionVisualiser_thumb.gif" width="742" border="0" height="86" /&gt;&lt;/p&gt;
&lt;p&gt;It turned out that this way of doing things was 10 times slower than using &lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175)"&gt;Activator&lt;/span&gt;.CreateInstance()&lt;/font&gt; with no constructor parameters, and took 70% of the time when one or more parameters was used. I was sure I could improve on that :)&lt;/p&gt;&lt;p&gt;With the source of the performance problem being the type of the cache forcing casting of the arguments, what I needed was a type-safe cache. The types in question are the types of the constructor parameters used when &lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175)"&gt;Type&lt;/span&gt;.GetInstance()&lt;/font&gt; is called, so what I needed was some sort of dynamic cache which would retain those types. I read &lt;a target="_blank" title="C# in Depth (opens in a new window)" href="http://www.manning.com/skeet2/"&gt;C# in Depth&lt;/a&gt; recently, and picked up a handy bit of trivia to do with static, generic types.&lt;/p&gt;&lt;p&gt;When you use a static generic type, the C# compiler creates a singleton instance of that type &lt;i&gt;for each unique combination of type parameters you use&lt;/i&gt;. That means with a static, generic helper class, the compiler would create a type-safe cache for me, which I can key by the &lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175)"&gt;Type&lt;/span&gt;&lt;/font&gt; being constructed. So that was what I did:&lt;/p&gt;&lt;pre class="code-block" style="font-family:Consolas;font-size:13;color:black;background:white;"&gt;&lt;span style="color:blue;"&gt;using&lt;/span&gt; System;
&lt;span style="color:blue;"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;span style="color:blue;"&gt;using&lt;/span&gt; System.Linq;
&lt;span style="color:blue;"&gt;using&lt;/span&gt; System.Linq.Expressions;
&lt;span style="color:blue;"&gt;using&lt;/span&gt; System.Reflection;
 
&lt;span style="color:blue;"&gt;public&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;class&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;TypeExtensions&lt;/span&gt;
{
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;summary&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; Returns an instance of the &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;/&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt; on which the method is invoked.&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type on which the method was invoked.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;An instance of the &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;/&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;&lt;/span&gt;
    &lt;span style="color:blue;"&gt;public&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;object&lt;/span&gt; GetInstance(&lt;span style="color:blue;"&gt;this&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt; type)
    {
        &lt;span style="color:blue;"&gt;return&lt;/span&gt; GetInstance&amp;lt;&lt;span style="color:#2b91af;"&gt;TypeToIgnore&lt;/span&gt;&amp;gt;(type, &lt;span style="color:blue;"&gt;null&lt;/span&gt;);
    }
 
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;summary&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; Returns an instance of the &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;/&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt; on which the method is invoked.&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;typeparam name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"TArg"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type of the argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type on which the method was invoked.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"argument"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;An instance of the given &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;/&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;&lt;/span&gt;
    &lt;span style="color:blue;"&gt;public&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;object&lt;/span&gt; GetInstance&amp;lt;TArg&amp;gt;(&lt;span style="color:blue;"&gt;this&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt; type, TArg argument)
    {
        &lt;span style="color:blue;"&gt;return&lt;/span&gt; GetInstance&amp;lt;TArg, &lt;span style="color:#2b91af;"&gt;TypeToIgnore&lt;/span&gt;&amp;gt;(type, argument, &lt;span style="color:blue;"&gt;null&lt;/span&gt;);
    }
 
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;summary&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; Returns an instance of the &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;/&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt; on which the method is invoked.&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;typeparam name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"TArg1"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type of the first argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;typeparam name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"TArg2"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type of the second argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type on which the method was invoked.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"argument1"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The first argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"argument2"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The second argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;An instance of the given &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;/&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;&lt;/span&gt;
    &lt;span style="color:blue;"&gt;public&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;object&lt;/span&gt; GetInstance&amp;lt;TArg1, TArg2&amp;gt;(&lt;span style="color:blue;"&gt;this&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt; type, TArg1 argument1, TArg2 argument2)
    {
        &lt;span style="color:blue;"&gt;return&lt;/span&gt; GetInstance&amp;lt;TArg1, TArg2, &lt;span style="color:#2b91af;"&gt;TypeToIgnore&lt;/span&gt;&amp;gt;(type, argument1, argument2, &lt;span style="color:blue;"&gt;null&lt;/span&gt;);
    }
 
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;summary&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; Returns an instance of the &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;/&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt; on which the method is invoked.&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;typeparam name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"TArg1"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type of the first argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;typeparam name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"TArg2"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type of the second argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;typeparam name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"TArg3"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type of the third argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The type on which the method was invoked.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"argument1"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The first argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"argument2"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The second argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;param name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"argument3"&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The third argument to pass to the constructor.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;
    &lt;span style="color:gray;"&gt;///&lt;/span&gt;&lt;span style="color:green;"&gt; &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;An instance of the given &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&lt;/span&gt;&lt;span style="color:gray;"&gt;"type"&lt;/span&gt;&lt;span style="color:gray;"&gt;/&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;&lt;/span&gt;
    &lt;span style="color:blue;"&gt;public&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;object&lt;/span&gt; GetInstance&amp;lt;TArg1, TArg2, TArg3&amp;gt;(
        &lt;span style="color:blue;"&gt;this&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt; type,
        TArg1 argument1,
        TArg2 argument2,
        TArg3 argument3)
    {
        &lt;span style="color:blue;"&gt;return&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;InstanceCreationFactory&lt;/span&gt;&amp;lt;TArg1, TArg2, TArg3&amp;gt;&lt;br /&gt;            .CreateInstanceOf(type, argument1, argument2, argument3);
    }
 
    &lt;span style="color:green;"&gt;// To allow for overloads with differing numbers of arguments, we flag arguments which should be &lt;/span&gt;
    &lt;span style="color:green;"&gt;// ignored by using this Type:&lt;/span&gt;
    &lt;span style="color:blue;"&gt;private&lt;/span&gt; &lt;span style="color:blue;"&gt;class&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;TypeToIgnore&lt;/span&gt;
    {
    }
 
    &lt;span style="color:blue;"&gt;private&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;class&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;InstanceCreationFactory&lt;/span&gt;&amp;lt;TArg1, TArg2, TArg3&amp;gt;
    {
        &lt;span style="color:green;"&gt;// This dictionary will hold a cache of object-creation functions, keyed by the Type to create:&lt;/span&gt;
        &lt;span style="color:blue;"&gt;private&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;readonly&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TArg1, TArg2, TArg3, &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt;&amp;gt; _instanceCreationMethods = 
            &lt;span style="color:blue;"&gt;new&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TArg1, TArg2, TArg3, &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();
 
        &lt;span style="color:blue;"&gt;public&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;object&lt;/span&gt; CreateInstanceOf(&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt; type, TArg1 arg1, TArg2 arg2, TArg3 arg3)
        {
            CacheInstanceCreationMethodIfRequired(type);
 
            &lt;span style="color:blue;"&gt;return&lt;/span&gt; _instanceCreationMethods[type].Invoke(arg1, arg2, arg3);
        }
 
        &lt;span style="color:blue;"&gt;private&lt;/span&gt; &lt;span style="color:blue;"&gt;static&lt;/span&gt; &lt;span style="color:blue;"&gt;void&lt;/span&gt; CacheInstanceCreationMethodIfRequired(&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt; type)
        {
            &lt;span style="color:green;"&gt;// Bail out if we've already cached the instance creation method:&lt;/span&gt;
            &lt;span style="color:blue;"&gt;if&lt;/span&gt; (_instanceCreationMethods.ContainsKey(type))
            {
                &lt;span style="color:blue;"&gt;return&lt;/span&gt;;
            }
 
            &lt;span style="color:blue;"&gt;var&lt;/span&gt; argumentTypes = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(TArg1), &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(TArg2), &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(TArg3) };
 
            &lt;span style="color:green;"&gt;// Get a collection of the constructor argument Types we've been given; ignore any &lt;/span&gt;
            &lt;span style="color:green;"&gt;// arguments which are of the 'ignore this' Type:&lt;/span&gt;
            &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] constructorArgumentTypes = argumentTypes.Where(t =&amp;gt; t != &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;TypeToIgnore&lt;/span&gt;)).ToArray();
 
            &lt;span style="color:green;"&gt;// Get the Constructor which matches the given argument Types:&lt;/span&gt;
            &lt;span style="color:blue;"&gt;var&lt;/span&gt; constructor = type.GetConstructor(
                &lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.Instance | &lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.Public,
                &lt;span style="color:blue;"&gt;null&lt;/span&gt;,
                &lt;span style="color:#2b91af;"&gt;CallingConventions&lt;/span&gt;.HasThis,
                constructorArgumentTypes,
                &lt;span style="color:blue;"&gt;new&lt;/span&gt; &lt;span style="color:#2b91af;"&gt;ParameterModifier&lt;/span&gt;[0]);
 
            &lt;span style="color:green;"&gt;// Get a set of Expressions representing the parameters which will be passed to the Func:&lt;/span&gt;
            &lt;span style="color:blue;"&gt;var&lt;/span&gt; lamdaParameterExpressions = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[]
            {
                &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Parameter(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(TArg1), &lt;span style="color:#a31515;"&gt;"param1"&lt;/span&gt;),
                &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Parameter(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(TArg2), &lt;span style="color:#a31515;"&gt;"param2"&lt;/span&gt;),
                &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Parameter(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(TArg3), &lt;span style="color:#a31515;"&gt;"param3"&lt;/span&gt;)
            };
 
            &lt;span style="color:green;"&gt;// Get a set of Expressions representing the parameters which will be passed to the constructor:&lt;/span&gt;
            &lt;span style="color:blue;"&gt;var&lt;/span&gt; constructorParameterExpressions = lamdaParameterExpressions
                .Take(&lt;span style="background-color: white; "&gt;constructorArgumentTypes.Length&lt;/span&gt;&lt;span style="background-color: white; "&gt;)
&lt;/span&gt;&lt;span style="background-color: white; "&gt;                .ToArray();&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;            &lt;span style="color:green;"&gt;// Get an Expression representing the constructor call, passing in the constructor parameters:&lt;/span&gt;
            &lt;span style="color:blue;"&gt;var&lt;/span&gt; constructorCallExpression = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.New(constructor, constructorParameterExpressions);
 
            &lt;span style="color:green;"&gt;// Compile the Expression into a Func which takes three arguments and returns the constructed object:&lt;/span&gt;
            &lt;span style="color:blue;"&gt;var&lt;/span&gt; constructorCallingLambda = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;
                .Lambda&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TArg1, TArg2, TArg3, &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;(constructorCallExpression, lamdaParameterExpressions)
                .Compile();
 
            _instanceCreationMethods[type] = constructorCallingLambda;
        }
    }
}&lt;/pre&gt;&lt;p&gt;The &lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175)"&gt;Func&lt;/span&gt;&lt;/font&gt;s created by this version of the method now look like this in the Expression Visualiser:&lt;/p&gt;&lt;p&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="ExpressionVisualiser_2" alt="ExpressionVisualiser_2" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/ytfe_11B24/ExpressionVisualiser_2_thumb.gif" width="626" border="0" height="80" /&gt;&lt;/p&gt;&lt;p&gt;That's more like it - no casting! So how does it perform compared to the previous set of methods? Well, here's the output of &lt;a target="_blank" title="The previous method's performance (opens in a new window)" href="http://geekswithblogs.net/mrsteve/archive/2012/02/11/c-sharp-performance-new-vs-expression-tree-func-vs-activator.createinstance.aspx"&gt;the same performance measurement I ran before&lt;/a&gt;; the third column shows the total number of 
ticks taken to create 100,000 objects, the fourth the number of ticks taken per object:&lt;/p&gt;&lt;p&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="GetInstancePerformance_2" alt="GetInstancePerformance_2" src="http://gwb.blob.core.windows.net/mrsteve/Windows-Live-Writer/ukty_11C4A/GetInstancePerformance_2_thumb.gif" width="485" border="0" height="163" /&gt;&lt;/p&gt;&lt;p&gt;To sum up the improvement:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;An instance is now created in 5 ticks - between 10% and 7% of the time taken by &lt;font size="2" face="Consolas"&gt;&lt;span style="color: rgb(43, 145, 175)"&gt;Activator&lt;/span&gt;.CreateInstance()&lt;/font&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;Because the arguments aren't cast, performance doesn't degrade when constuctors are used with extra parameters&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;That's more like it! I was especially pleased to be able to apply a bit of trivia I read from a C# book to a problem like this and see a genuine improvement. The more I use and get used to Expression Trees, the more I like them and find uses for them :)&lt;/p&gt; &lt;img src="http://geekswithblogs.net/mrsteve/aggbug/148756.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Wilkes</dc:creator>
            <guid>http://geekswithblogs.net/mrsteve/archive/2012/02/19/a-fast-c-sharp-extension-method-using-expression-trees-create-instance-from-type-again.aspx</guid>
            <pubDate>Sun, 19 Feb 2012 19:42:18 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/mrsteve/comments/148756.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/mrsteve/archive/2012/02/19/a-fast-c-sharp-extension-method-using-expression-trees-create-instance-from-type-again.aspx#feedback</comments>
            <slash:comments>10</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/mrsteve/comments/commentRss/148756.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/mrsteve/services/trackbacks/148756.aspx</trackback:ping>
        </item>
    </channel>
</rss>