<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:blogChannel="http://backend.userland.com/blogChannelModule" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>Rich on Software</title>
    <description />
    <link>http://www.richonsoftware.com/</link>
    <docs>http://www.rssboard.org/rss-specification</docs>
    <generator>BlogEngine.NET 2.6.0.5</generator>
    <language>en-GB</language>
    <blogChannel:blogRoll>http://www.richonsoftware.com/opml.axd</blogChannel:blogRoll>
    <blogChannel:blink>http://www.dotnetblogengine.net/syndication.axd</blogChannel:blink>
    <dc:creator>Rich Czyzewski</dc:creator>
    <dc:title>Rich on Software</dc:title>
    <geo:lat>0.000000</geo:lat>
    <geo:long>0.000000</geo:long>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/RichOnSoftware" /><feedburner:info uri="richonsoftware" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
      <title>Using Windows Azure Web Sites – Hosting a blog with BlogEngine.NET</title>
      <description>&lt;p&gt;&lt;font color="#ff0000"&gt;** Update: BlogEngine.NET is now included as part of Windows Azure’s Website App Gallery ** &lt;/font&gt;&lt;/p&gt;  &lt;p&gt;&lt;font color="#ff0000"&gt;Currently the Gallery only includes version 2.5.0.6 of BlogEngine.NET, which is a couple of versions behind now. If you want to install the latest version then the steps below should still be applicable.&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;&lt;font color="#ff0000"&gt;&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;Windows Azure Web Sites is one of the new features in Windows Azure announced by Scott Guthrie on his blog post &lt;a href="http://weblogs.asp.net/scottgu/archive/2012/06/07/meet-the-new-windows-azure.aspx"&gt;Meet the New Windows Azure&lt;/a&gt;. Azure Web Sites are akin to the shared hosting model, where many sites are hosted under one installation of IIS inside of a single VM. Azure puts a bit of a spin on this concept by allowing scale out of the Web Site to multiple VMs and the ability to reserve entire VMs just for its usage. &lt;/p&gt;  &lt;p&gt;&lt;a href="https://www.windowsazure.com/en-us/home/scenarios/web-sites/"&gt;WindowsAzure.com&lt;/a&gt; describes Azure Web Sites as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Build highly scalable web sites on Windows Azure&lt;/p&gt;    &lt;p&gt;Quickly and easily deploy sites to a highly scalable cloud environment that allows you to start small and scale as traffic grows.&lt;/p&gt;    &lt;p&gt;Use the languages and open source apps of your choice then deploy with FTP, Git and TFS. Easily integrate Windows Azure services like SQL Database, Caching, CDN and Storage.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This functionality is currently free for up to 10 websites during the technical preview. However, I can’t imagine it being all that expensive once it comes out of preview. &lt;/p&gt;  &lt;p&gt;The biggest feature that really stands out IMO is the ability to just use Web Deploy in Visual Studio for deployments. Aside from the new publish profile it’s not necessary to change anything else about the project/solution. All of this drastically reduces the barrier to entry for anyone wanting to get started with Windows Azure.&lt;/p&gt;  &lt;p&gt;With that said, we’re going to go through the process of deploying BlogEngine.NET to Windows Azure using the new Web Sites features and see that things are demonstrably easier than what was required in the past. Additionally, this should give us a quick run through of the new management portal for Azure (more on this below).&lt;/p&gt;  &lt;p&gt;Here’s an overview of what we’ll need:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Windows Azure Account (you can sign up for a 90 day free trial) &lt;/li&gt;    &lt;li&gt;Visual Studio 2010 SP1 or higher (SP1 is required for the Azure SDK) &lt;/li&gt;    &lt;li&gt;BlogEngine.NET WAP Project source (detailed below) &lt;/li&gt;    &lt;li&gt;Windows Azure SDK 1.7 or higher, if using VS 2010 SP1 (links provided below) &lt;/li&gt; &lt;/ul&gt;  &lt;h2&gt;Azure Setup&lt;/h2&gt;  &lt;p&gt;If you don’t already have an Azure account, you’ll need to sign up for one before you can continue. Again they have a 90 day free trial, so there’s no hassle. Once you have your account set up, we’ll need to enable the Web Sites preview, which also enables the preview of the new management portal. This happens to be relatively painless.&lt;/p&gt;  &lt;p&gt;&lt;img title="AccountA" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="AccountA" src="http://www.richonsoftware.com/image.axd?picture=AccountA.png" width="618" height="108" /&gt;&lt;/p&gt;  &lt;p&gt;&lt;img title="PreviewFeaturesA" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="PreviewFeaturesA" src="http://www.richonsoftware.com/image.axd?picture=PreviewFeaturesA.png" width="618" height="121" /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=PreviewFeatures2B_2.png"&gt;&lt;img title="PreviewFeatures2B" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="PreviewFeatures2B" src="http://www.richonsoftware.com/image.axd?picture=PreviewFeatures2B_thumb_2.png" width="644" height="593" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=PreviewPortalIntroA.png"&gt;&lt;img title="PreviewPortalIntroA" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="PreviewPortalIntroA" src="http://www.richonsoftware.com/image.axd?picture=PreviewPortalIntroA_thumb.png" width="644" height="429" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;After electing to use the preview portal you’ll get a quick guided tour detailing its new features. With the new portal and the Web Sites option enabled, we can finally create an Azure Web Site.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=Portal01A.png"&gt;&lt;img title="Portal01A" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Portal01A" src="http://www.richonsoftware.com/image.axd?picture=Portal01A_thumb.png" width="644" height="267" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=Portal02A.png"&gt;&lt;img title="Portal02A" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Portal02A" src="http://www.richonsoftware.com/image.axd?picture=Portal02A_thumb.png" width="644" height="267" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;There are several other blog engines in the gallery, unfortunately BlogEngine.NET isn’t one of them. Select &lt;em&gt;Quick Create&lt;/em&gt; since we’re going to do a basic/default installation of BlogEngine.NET. If we were backing our BlogEngine.NET install with a Sql Server we’d select &lt;em&gt;Create with Database&lt;/em&gt; instead of &lt;em&gt;Quick Create&lt;/em&gt;. Note the URL field can be entered as whatever you want it to be.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=Portal03.png"&gt;&lt;img title="Portal03" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Portal03" src="http://www.richonsoftware.com/image.axd?picture=Portal03_thumb.png" width="644" height="446" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Once finished we should now have a running web site, just with nothing deployed to it yet &lt;img class="wlEmoticon wlEmoticon-winkingsmile" style="border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none" alt="Winking smile" src="http://www.richonsoftware.com/image.axd?picture=wlEmoticon-winkingsmile.png" /&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=Portal04.png"&gt;&lt;img title="Portal04" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Portal04" src="http://www.richonsoftware.com/image.axd?picture=Portal04_thumb.png" width="644" height="357" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Next up we need to go to the management screen and pull down the publish profile. This tells Visual Studio how to publish to our Azure Web Site.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=Portal05.png"&gt;&lt;img title="Portal05" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Portal05" src="http://www.richonsoftware.com/image.axd?picture=Portal05_thumb.png" width="644" height="448" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;h2&gt;Azure SDK Install&lt;/h2&gt;  &lt;p&gt;If you’re using Visual Studio 2012 RC, you can skip this step. For those running VS 2010 SP1, you’re going to need to install the Azure SDK 1.7 or greater in order for VS 2010 to use the publish profile. Ultimately this just updates the publish options in VS 2010 to be like that of VS 2012’s.&lt;/p&gt;  &lt;p&gt;You can download the SDK from here: &lt;a href="https://www.windowsazure.com/en-us/develop/downloads/"&gt;https://www.windowsazure.com/en-us/develop/downloads/&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;I installed the .NET Full version, but Windows SDK only should work fine.&lt;/p&gt;  &lt;h2&gt;BlogEngine.NET Web Application Project&lt;/h2&gt;  &lt;p&gt;The default download/install of BlogEngine.NET is an “old school” web site project, which isn’t exactly compatible with Windows Azure (there’s a way, it’s just not easy). Web application projects are compatible with Windows Azure out of the box. Earlier this year the only option for BlogEngine.NET was to manually do the conversion, which wasn’t exactly straight forward. See my blog post: &lt;a href="http://www.richonsoftware.com/post/2012/02/26/Converting-BlogEngineNET-25-to-a-Web-Application.aspx"&gt;Converting BlogEngine.NET 2.5 to a Web Application&lt;/a&gt; for more info.&lt;/p&gt;  &lt;p&gt;Luckily enough, when the BlogEngine.NET developers released 2.6 they also released a branch that is already converted to a web application. You can find more information on &lt;a href="http://rtur.net/blog/post/2012/03/25/BlogEngineWeb-Web-Application-Project.aspx"&gt;this post&lt;/a&gt; on rtur’s website (listed as coordinator for BlogEngine.NET) :&lt;/p&gt;  &lt;p&gt;The WAP version is under a different codeplex repository located here: &lt;a href="http://blogengineweb.codeplex.com/"&gt;http://blogengineweb.codeplex.com/&lt;/a&gt;. As opposed to downloading the precompiled version we’re going to pull down the source since using the publish profile in Visual Studio requires a functioning build.&lt;/p&gt;  &lt;p&gt;Download the &lt;a href="http://blogengineweb.codeplex.com/SourceControl/changeset/changes/a8ffc0a445c0#"&gt;source changeset for BlogEngine.NET 2.6 as a WAP from codeplex&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Make sure to extract this to a directory hierarchy that does not have spaces in it. The XCopy post build steps in BlogEngine.NET weren’t set up to work with a directory structure containing spaces.&lt;/p&gt;  &lt;p&gt;Open it up in Visual Studio and make sure everything builds. Before we’re able to publish we’ll need to do a little project house cleaning. BlogEngine.NET ‘s WAP project has a handful of files that are missing yet still part of the project. We just have to remove the references to these files, otherwise the publish process will halt on them.&lt;/p&gt;  &lt;p&gt;Delete the files from the following locations (should be easy spot with the exclamation marks) as seen below.&lt;/p&gt;  &lt;p&gt;&lt;img title="BlogEngineCleanup01" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="BlogEngineCleanup01" src="http://www.richonsoftware.com/image.axd?picture=BlogEngineCleanup01.png" width="334" height="908" /&gt;&lt;/p&gt;  &lt;p&gt;Now we’re ready to publish. Right click on BlogEngine.Web and select Publish.&lt;/p&gt;  &lt;p&gt;&lt;img title="BlogEnginePublish01" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="BlogEnginePublish01" src="http://www.richonsoftware.com/image.axd?picture=BlogEnginePublish01.png" width="516" height="464" /&gt;&lt;/p&gt;  &lt;p&gt;This should bring up the publish dialog, which should look like the image below. If it looks different and it doesn’t have a spot to import the publish profile, then the Azure SDK may not have been installed or may need to be reinstalled.&lt;/p&gt;  &lt;p&gt;&lt;img title="BlogEnginePublish02B" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="BlogEnginePublish02B" src="http://www.richonsoftware.com/image.axd?picture=BlogEnginePublish02B.png" width="724" height="344" /&gt;&lt;/p&gt;  &lt;p&gt;Import the publish profile and all the info necessary to publish to the azure website should be prepopulated.&lt;/p&gt;  &lt;p&gt;&lt;img title="BlogEnginePublish03" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="BlogEnginePublish03" src="http://www.richonsoftware.com/image.axd?picture=BlogEnginePublish03.png" width="724" height="565" /&gt;&lt;/p&gt;  &lt;p&gt;Hit the publish button and check the build output to see if the publish was successful.&lt;/p&gt;  &lt;p&gt;&lt;img title="BlogEnginePublish04" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="BlogEnginePublish04" src="http://www.richonsoftware.com/image.axd?picture=BlogEnginePublish04.png" width="724" height="317" /&gt;&lt;/p&gt;  &lt;p&gt;Navigate to the site url detailed in the build output and you should be good to go.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=BlogEnginePublish05_1.png"&gt;&lt;img title="BlogEnginePublish05" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="BlogEnginePublish05" src="http://www.richonsoftware.com/image.axd?picture=BlogEnginePublish05_thumb_1.png" width="724" height="479" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;h2&gt;Scaling Considerations&lt;/h2&gt;  &lt;p&gt;One thing to mention is that although we’ve deployed BlogEngine.NET to Windows Azure Web Sites, that in itself doesn’t make it inherently scalable. If we plan to scale out or have finally gotten to the point where it’s necessary to do so) we’d have to attack a few extra design considerations, which could be an entirely new blog post. I’ll just scratch the surface here of what needs to be considered.&lt;/p&gt;  &lt;p&gt;By default BlogEngine.NET stores blog posts and their associated images in the file system. When scaling out both posts and images will need to be centralized and available across multiple hosted instances of BlogEngine.NET. In the simplest sense, this could be accomplished by switching over to Sql Azure for post and image storage, since BlogEngine.NET supports this natively. &lt;/p&gt;  &lt;p&gt;Alternatively, you could use Azure’s Blob storage (see &lt;a href="https://www.windowsazure.com/en-us/home/features/data-management/"&gt;Azure Data management&lt;/a&gt; for an overview, Blob storage is described at bottom of page) to store the images individually, however this will require an additional BlogFileSystemProvider to be created so BlogEngine.NET can make use of it. Blob storage is made for this type of storage and is significantly cheaper per GB than Sql Azure.&lt;/p&gt;  &lt;p&gt;Personally, I like to compress my post images after the fact using &lt;a href="http://optipng.sourceforge.net/"&gt;OptiPNG&lt;/a&gt;, which runs at the command line and processes a directory of png images. In which case, neither Sql Azure nor using Blob storage directly would be all that helpful for me. I might lean towards Azure Drive (also described in &lt;a href="https://www.windowsazure.com/en-us/home/features/data-management/"&gt;Azure Data management&lt;/a&gt;), which stores a VHD in Blob storage, but acts like a shared drive. It’s a little clunky to work with but it’s another option to consider depending on your needs.&lt;/p&gt;  &lt;p&gt;As a side note, BlogEngine.NET doesn’t make use of session, so there are no changes necessary from that standpoint.&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;All in all, Azure Web Sites seem very easy to work with. Microsoft did a good job in making this a hassle free experience. The installation of BlogEngine.NET wasn’t that bad, however, I would of preferred for it to already be in the gallery, which would of meant we wouldn’t have had to deal with publishing from Visual Studio at all. It’ll be interesting to see how Azure Web Sites will ultimately be priced. Priced right, this could set a new bar for shared hosting standards and be a good entry point for those looking to get started with Windows Azure. &lt;/p&gt;</description>
      <link>http://feedproxy.google.com/~r/RichOnSoftware/~3/R7dp8n3SywM/post.aspx</link>
      <comments>http://www.richonsoftware.com/post/2012/06/20/Windows-Azure-WebSites-BlogEngineNET.aspx#comment</comments>
      <guid isPermaLink="false">http://www.richonsoftware.com/post.aspx?id=f32d496c-d746-4c7e-9ddf-0d18db7bd6ca</guid>
      <pubDate>Wed, 20 Jun 2012 01:34:00 -0400</pubDate>
      <category>Windows Azure</category>
      <dc:publisher>Rich Czyzewski</dc:publisher>
      <pingback:server>http://www.richonsoftware.com/pingback.axd</pingback:server>
      <pingback:target>http://www.richonsoftware.com/post.aspx?id=f32d496c-d746-4c7e-9ddf-0d18db7bd6ca</pingback:target>
      <slash:comments>6</slash:comments>
      <trackback:ping>http://www.richonsoftware.com/trackback.axd?id=f32d496c-d746-4c7e-9ddf-0d18db7bd6ca</trackback:ping>
      <wfw:comment>http://www.richonsoftware.com/post/2012/06/20/Windows-Azure-WebSites-BlogEngineNET.aspx#comment</wfw:comment>
      <wfw:commentRss>http://www.richonsoftware.com/syndication.axd?post=f32d496c-d746-4c7e-9ddf-0d18db7bd6ca</wfw:commentRss>
    <feedburner:origLink>http://www.richonsoftware.com/post.aspx?id=f32d496c-d746-4c7e-9ddf-0d18db7bd6ca</feedburner:origLink></item>
    <item>
      <title>Noninvasive Unit Testing in ASP.NET MVC4 – A Microsoft Fakes Deep Dive</title>
      <description>&lt;p&gt;A lot of today’s unit testing technologies require significant invasive code changes in order to unit test appropriately. I’ve always been of the mindset that testing your code should be as noninvasive as possible to the system under test, regardless of how that system is designed. &lt;/p&gt;  &lt;p&gt;The ability to test a system shouldn’t be dependent on whether or not that system was designed to be compatible with a certain set of testing tools. The design of systems should instead be driven by the needs of the problem domain, while complexity in applied patterns and concept count should only be escalated as it becomes necessary to do so. &lt;/p&gt;  &lt;p&gt;In combining the &lt;a href="http://en.wikipedia.org/wiki/KISS_principle"&gt;KISS principle&lt;/a&gt; and &lt;a href="http://en.wikipedia.org/wiki/You_ain't_gonna_need_it"&gt;YAGNI&lt;/a&gt; with agile architecture you get an architectural design, that at any given point in time, is the simplest to use, easiest to work with and the most maintainable as is allowable or possible in the problem domain in question.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The &lt;strong&gt;KISS&lt;/strong&gt; principle states that most systems work best if they are kept simple rather than made complex, therefore simplicity should be a key goal in design and unnecessary complexity should be avoided. – &lt;a href="http://en.wikipedia.org/wiki/KISS_principle"&gt;Wikipedia&lt;/a&gt;&lt;/p&gt;    &lt;p&gt;&amp;quot;You ain't gonna need it&amp;quot; or “You aren′t gonna need it” (acronym: &lt;strong&gt;YAGNI&lt;/strong&gt;) is the principle in extreme programming that programmers should not add functionality until it is necessary. – &lt;a href="http://en.wikipedia.org/wiki/You_ain't_gonna_need_it"&gt;Wikipedia&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Up until recently the ability to test without escalation of certain architectural patterns was not possible. Even if you wanted to practice a noninvasive testing style, the means to do so as well as community support weren’t generally available. &lt;/p&gt;  &lt;p&gt;Conceptually, noninvasive testing tools and methodologies represent a natural progression/evolution in unit testing practices and principles. This is most visible in the evolution of major commercial testing tools, such as &lt;a href="http://www.typemock.com/isolator-product-page"&gt;TypeMock’s Isolator&lt;/a&gt; and &lt;a href="http://www.telerik.com/products/mocking.aspx"&gt;Telerik’s JustMock&lt;/a&gt;, that now have features to test/mock everything, not just interfaces and base classes. Now, with the introduction of Microsoft Fakes in Visual Studio 11 (more specifically the ability to detour via shimming), we are given all the tools necessary to accomplish noninvasive unit testing built right in to our development environment. &lt;/p&gt;  &lt;p&gt;See my earlier blog posts on Microsoft Fakes for more background information: &lt;a href="http://www.richonsoftware.com/post/2012/04/05/Using-Stubs-and-Shim-to-Test-with-Microsoft-Fakes-in-Visual-Studio-11.aspx"&gt;Using Stubs and Shims to Test with Microsoft Fakes in Visual Studio 11&lt;/a&gt; and &lt;a href="http://www.richonsoftware.com/post/2012/04/20/Comparing-Microsoft-Moles-in-Visual-Studio-2010-to-Microsoft-Fakes-in-Visual-Studio-11.aspx"&gt;Comparing Microsoft Moles in VS2010 to Microsoft Fakes in VS11&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Additionally Fakes allows us to take the “mockist” approach of behavior verification described by Martin Fowler in his article &lt;a href="http://martinfowler.com/articles/mocksArentStubs.html"&gt;Mocks Aren’t Stubs&lt;/a&gt;. &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;But as often as not I see mock objects described poorly. In particular I see them often confused with stubs - a common helper to testing environments. I understand this confusion - I saw them as similar for a while too, but conversations with the mock developers have steadily allowed a little mock understanding to penetrate my tortoiseshell cranium. &lt;/p&gt;    &lt;p&gt;This difference is actually two separate differences. On the one hand there is a difference in how test results are verified: a distinction between state verification and behavior verification. On the other hand is a whole different philosophy to the way testing and design play together, which I term here as the classical and mockist styles of Test Driven Development.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Later on in his article Martin provides a more concrete example as he discusses the differences.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The key difference here is how we verify that the order did the right thing in its interaction with the warehouse. With state verification we do this by asserts against the warehouse's state. Mocks use &lt;b&gt;behavior verification&lt;/b&gt;, where we instead check to see if the order made the correct calls on the warehouse. We do this check by telling the mock what to expect during setup and asking the mock to verify itself during verification. Only the order is checked using asserts, and if the the method doesn't change the state of the order there's no asserts at all.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;With that said I’ll be using Microsoft Fakes to apply noninvasive and mockist testing techniques to test the &lt;em&gt;AccountController&lt;/em&gt; of a default MVC 4 project created using the &amp;quot;Internet Application” template, making absolutely no changes at all to the project. This example will use a mixture of both shimming and stubbing from Microsoft Fakes in order to get the job done. &lt;/p&gt;  &lt;h2&gt;Getting Started&lt;/h2&gt;  &lt;p&gt;Let’s take a quick look at the class definition for &lt;em&gt;AccountController&lt;/em&gt;.&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="MethodsToTest" border="0" alt="MethodsToTest" src="http://www.richonsoftware.com/image.axd?picture=MethodsToTest_1.png" width="462" height="477" /&gt;&lt;/p&gt;  &lt;p&gt;Looking through the implementations, a few of the methods are trivial enough for us to skip as part of this example. &lt;/p&gt;  &lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;public ActionResult ChangePassword() { return View(); }

public ActionResult ChangePasswordSuccess() { return View(); }

[AllowAnonymous]
public ActionResult Login() { return ContextDependentView(); }

[AllowAnonymous]
public ActionResult Register() { return ContextDependentView(); }&lt;/pre&gt;

&lt;p&gt;Additionally, we’re going to forego testing &lt;em&gt;ContextDependentView&lt;/em&gt;, &lt;em&gt;GetErrorsFromModelState &lt;/em&gt;&amp;amp; &lt;em&gt;ErrorCodeToString&lt;/em&gt; in favor of the more complex methods. That’s not to say you wouldn’t test these methods for appropriate coverage, just that we’re going to exclude them to keep this post somewhat reasonable in length.&lt;/p&gt;

&lt;p&gt;Before we get started though, we need to do some basic project setup.&amp;#160; &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Create a new &lt;em&gt;ASP.NET MVC 4 Application&lt;/em&gt; project using the &lt;em&gt;Internet Application&lt;/em&gt; template &lt;/li&gt;

  &lt;li&gt;Add a &lt;em&gt;Unit Test Project&lt;/em&gt;, I renamed the default cs to &lt;em&gt;AccountsControllerTests&lt;/em&gt; &lt;/li&gt;

  &lt;li&gt;Add references to the following items in the Unit Test project &lt;/li&gt;

  &lt;ul&gt;
    &lt;li&gt;the MVC 4 project &lt;/li&gt;

    &lt;li&gt;&lt;em&gt;System.Web&lt;/em&gt; &lt;/li&gt;

    &lt;li&gt;&lt;em&gt;System.Web.MVC &lt;/em&gt;&lt;/li&gt;
  &lt;/ul&gt;

  &lt;li&gt;Additionally I’ll be using NUnit for assertions, so pull down NUnit from &lt;a href="http://nuget.org/"&gt;Nuget&lt;/a&gt; and add the following using statement to the top of the &lt;em&gt;AccountsControllerTests&lt;/em&gt; file: &lt;/li&gt;
&lt;/ul&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;using Assert = NUnit.Framework.Assert;&lt;/pre&gt;

&lt;p&gt;After all that your solution should look something like this:&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="InitialSolutionConfig" border="0" alt="InitialSolutionConfig" src="http://www.richonsoftware.com/image.axd?picture=InitialSolutionConfig_6.png" width="398" height="570" /&gt;&lt;/p&gt;

&lt;h2&gt;LogOff Method&lt;/h2&gt;

&lt;p&gt;We’ll start off with the &lt;em&gt;LogOff&lt;/em&gt; method (as seen below), since this is one of the simpler methods we’re going to be looking at.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;public ActionResult LogOff()
{
    FormsAuthentication.SignOut();

    return RedirectToAction(&amp;quot;Index&amp;quot;, &amp;quot;Home&amp;quot;);
}&lt;/pre&gt;

&lt;p&gt;First off, let’s review our goals here. Since our intent with mocking is behavior verification, we want to test both that the correct &lt;em&gt;RedirectToAction&lt;/em&gt; was returned and that &lt;em&gt;FormsAuthentication.SignOut()&lt;/em&gt; was called. Testing that the correct &lt;em&gt;RedirectToAction&lt;/em&gt; was returned seems easy enough, so we’ll start with that.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;using System;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NoninvasiveMVC4Testing.Controllers;
using Assert = NUnit.Framework.Assert;

namespace NoninvasiveMVC4Testing.Tests
{
    [TestClass]
    public class AccountsControllerTests
    {
        [TestMethod]
        public void TestLogOff()
        {
            var accountController = new AccountController();
            var redirectToRouteResult = accountController.LogOff() as RedirectToRouteResult;

            Assert.NotNull(redirectToRouteResult);
            Assert.AreEqual(&amp;quot;Index&amp;quot;, redirectToRouteResult.RouteValues[&amp;quot;Action&amp;quot;]);
            Assert.AreEqual(&amp;quot;Home&amp;quot;, redirectToRouteResult.RouteValues[&amp;quot;controller&amp;quot;]);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;We get the following results when running our new unit test:&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="FailedInitialUnitTest" border="0" alt="FailedInitialUnitTest" src="http://www.richonsoftware.com/image.axd?picture=FailedInitialUnitTest.png" width="615" height="362" /&gt;&lt;/p&gt;

&lt;p&gt;Looking at the stack trace we can see that a &lt;em&gt;NullReferenceException&lt;/em&gt; was thrown from &lt;em&gt;FormsAuthentication.SignOut()&lt;/em&gt;. This makes sense as technically we’re not in the context of an actual web request and &lt;em&gt;FormsAuthentication&lt;/em&gt; depends on a valid &lt;em&gt;HttpContext&lt;/em&gt; to be available. This type of problem is common when testing web applications outside of the context of an actual request to a web server. &lt;/p&gt;

&lt;p&gt;The traditional guidance on how to test something like this is as follows (see this &lt;a href="http://stackoverflow.com/questions/366388/how-can-i-unit-test-my-asp-net-mvc-controller-that-uses-formsauthentication"&gt;StackOverflow post&lt;/a&gt; for more information):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Create a wrapping class around FormsAuthentication with a public method that runs the necessary method &lt;/li&gt;

  &lt;li&gt;Create an interface for this behavior &lt;/li&gt;

  &lt;li&gt;Use dependency injection in our controller to replace the direct call to FormsAuthentication with that of our wrapping class. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using this formula, our controller code (not the test code mind you) would have to be changed as follows:&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;public interface IAuthenticationProvider
{
    void SignOut();
}

public class FormsAuthWrapper : IAuthenticationProvider
{
    public void SignOut()
    {
        FormsAuthentication.SignOut();
    }
}

public class AccountController : Controller
{
    private readonly IAuthenticationProvider _authenticationProvider;

    public AccountController(IAuthenticationProvider authenticationProvider)
    {
        _authenticationProvider = authenticationProvider;
    }

    public ActionResult LogOff()
    {
        _authenticationProvider.SignOut();
        return RedirectToAction(&amp;quot;Index&amp;quot;, &amp;quot;Home&amp;quot;);
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see this pattern is invasive to the system under test and with the purpose of this post being to apply noninvasive testing techniques, we’re going to consider a different way of testing using Microsoft Fakes. Surprisingly enough, it makes short work of these types of scenarios.&lt;/p&gt;

&lt;h3&gt;The Noninvasive Approach&lt;/h3&gt;

&lt;p&gt;Let’s start off by putting in what’s minimally necessary to get our test to pass as is. Right click on the &lt;em&gt;System.Web&lt;/em&gt; reference in the test project and select &lt;em&gt;Add Fakes Assembly&lt;/em&gt;. Once a Fakes assembly is added for &lt;em&gt;System.Web&lt;/em&gt; we can use shims in Microsoft Fakes to detour the call to &lt;em&gt;FormsAuthentication.SignOut()&lt;/em&gt; to an implementation of our choosing, hopefully one that won’t throw a &lt;em&gt;NullReferenceException&lt;/em&gt;.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;using System;
using System.Web.Mvc;
using System.Web.Security.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NoninvasiveMVC4Testing.Controllers;
using Assert = NUnit.Framework.Assert;

namespace NoninvasiveMVC4Testing.Tests
{
    [TestClass]
    public class AccountsControllerTests
    {
        [TestMethod]
        public void TestLogOff()
        {
            var accountController = new AccountController();
            RedirectToRouteResult redirectToRouteResult;

            //Scope the detours we're creating
            using (ShimsContext.Create())
            {
                //Detours FormsAuthentication.SignOut() to an empty implementation
                ShimFormsAuthentication.SignOut = () =&amp;gt; { };
                redirectToRouteResult = accountController.LogOff() as RedirectToRouteResult;
            }

            Assert.NotNull(redirectToRouteResult);
            Assert.AreEqual(&amp;quot;Index&amp;quot;, redirectToRouteResult.RouteValues[&amp;quot;Action&amp;quot;]);
            Assert.AreEqual(&amp;quot;Home&amp;quot;, redirectToRouteResult.RouteValues[&amp;quot;controller&amp;quot;]);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;That’s simple enough and it does indeed pass.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="TestLogOffInitialSuccess" border="0" alt="TestLogOffInitialSuccess" src="http://www.richonsoftware.com/image.axd?picture=TestLogOffInitialSuccess.png" width="507" height="188" /&gt;&lt;/p&gt;

&lt;p&gt;We still have to test that &lt;em&gt;FormsAuthentication.SignOut()&lt;/em&gt; was actually called. All we have to do is flip a bit inside of the detoured &lt;em&gt;SignOut&lt;/em&gt; method (see lines 28 and 31) and assert it. Here’s the final method.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[TestMethod]
public void TestLogOff()
{
    var accountController = new AccountController();
    var formsAuthenticationSignOutCalled = false;
    RedirectToRouteResult redirectToRouteResult;

    //Scope the detours we're creating
    using (ShimsContext.Create())
    {
        //Detours FormsAuthentication.SignOut() to an empty implementation
        ShimFormsAuthentication.SignOut = () =&amp;gt;
        {
            //Set a boolean to identify that we actually got here
            formsAuthenticationSignOutCalled = true;
        };
        redirectToRouteResult = accountController.LogOff() as RedirectToRouteResult;
        Assert.AreEqual(true, formsAuthenticationSignOutCalled);
    }

    Assert.NotNull(redirectToRouteResult);
    Assert.AreEqual(&amp;quot;Index&amp;quot;, redirectToRouteResult.RouteValues[&amp;quot;Action&amp;quot;]);
    Assert.AreEqual(&amp;quot;Home&amp;quot;, redirectToRouteResult.RouteValues[&amp;quot;controller&amp;quot;]);
}&lt;/pre&gt;

&lt;p&gt;Testing that &lt;em&gt;FormsAuthentication&lt;/em&gt; was called seems pretty trivial here, however we’ll build on this approach as we test more and more complicated methods. &lt;/p&gt;

&lt;h2&gt;JsonLogin&lt;/h2&gt;

&lt;p&gt;Moving on, &lt;em&gt;JsonLogin&lt;/em&gt; is probably the next simplest method to test in order for us to ease our way into noninvasive testing with Fakes.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[AllowAnonymous]
[HttpPost]
public JsonResult JsonLogin(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return Json(new { success = true, redirect = returnUrl });
        }
        else
            ModelState.AddModelError(&amp;quot;&amp;quot;, &amp;quot;The user name or password provided is incorrect.&amp;quot;);
    }

    // If we got this far, something failed
    return Json(new { errors = GetErrorsFromModelState() });
}&lt;/pre&gt;

&lt;p&gt;Right off the bat, it’s pretty clear that &lt;em&gt;MemberShip.ValidateUser&lt;/em&gt; and &lt;em&gt;FormsAuthentication.SetAuthCookie&lt;/em&gt; will need to be detoured based on our prior experience with the &lt;em&gt;LogOff&lt;/em&gt; method. We’ll additionally test that the correct parameters were passed into each. &lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[TestMethod]
public void TestJsonLogin()
{
    string testUserName = &amp;quot;TestUserName&amp;quot;;
    string testPassword = &amp;quot;TestPassword&amp;quot;;
    bool testRememberMe = false;
    string testReturnUrl = &amp;quot;TestReturnUrl&amp;quot;;

    var loginModel = new LoginModel
    {
        UserName = testUserName,
        Password = testPassword,
        RememberMe = testRememberMe
    };

    var accountController = new AccountController();
    JsonResult jsonResult;
    //Scope the detours we're creating
    using (ShimsContext.Create())
    {
        //Sets up a detour for Membership.ValidateUser to our mocked implementation
        ShimMembership.ValidateUserStringString = (userName, password) =&amp;gt;
        {
            Assert.AreEqual(testUserName, userName);
            Assert.AreEqual(testPassword, password);
            return true;
        };

        //Sets up a detour for FormsAuthentication.SetAuthCookie to our mocked implementation
        ShimFormsAuthentication.SetAuthCookieStringBoolean = (userName, rememberMe) =&amp;gt;
        {
            Assert.AreEqual(testUserName, userName);
            Assert.AreEqual(testRememberMe, rememberMe);
        };

        jsonResult = accountController.JsonLogin(loginModel, testReturnUrl);
    }
}&lt;/pre&gt;

&lt;p&gt;Now on to the tricky part, testing &lt;em&gt;JsonResult&lt;/em&gt;. &lt;em&gt;JsonResult.Data&lt;/em&gt; is of type &lt;em&gt;Object&lt;/em&gt;, but is filled with an anonymous type.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="JsonResultProperties" border="0" alt="JsonResultProperties" src="http://www.richonsoftware.com/image.axd?picture=JsonResultProperties.png" width="225" height="96" /&gt;&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;return Json(new { success = true, redirect = returnUrl });&lt;/pre&gt;

&lt;p&gt;This makes it slightly more difficult to get at the properties we want to test.&lt;/p&gt;

&lt;h3&gt;Possible solutions&lt;/h3&gt;

&lt;p&gt;First off, we might try to cast &lt;em&gt;JsonResult.Data&lt;/em&gt; out of &lt;em&gt;Object&lt;/em&gt; into some type we could use to access the fields. This requires some runtime trickery and ends up being a bit of mess. See this &lt;a href="http://stackoverflow.com/questions/1409734/cast-to-anonymous-type"&gt;StackOverflow post&lt;/a&gt; for more info. &lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;private static T CastTo&amp;lt;T&amp;gt;(this Object value, T targetType) 
{ 
    // targetType above is just for compiler magic 
    // to infer the type to cast x to 
    return (T)x; 
}&lt;/pre&gt;

&lt;p&gt;Unfortunately, this only works if you’re working within the same assembly that defined the original anonymous type.&lt;/p&gt;

&lt;p&gt;Next up, we could cleverly stuff a dynamic type with the value from &lt;em&gt;JsonResult.Data&lt;/em&gt; and access the properties that way.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;dynamic data = jsonResult.Data;
Assert.AreEqual(true, data.success);
Assert.AreEqual(testReturnUrl, data.redirect);&lt;/pre&gt;

&lt;p&gt;This fails as well, since anonymous types are declared as internal as described by the blog post: &lt;a href="http://www.heartysoft.com/anonymous-types-c-sharp-4-dynamic"&gt;Anonymous Types are Internal, C# 4.0 Dynamic Beware!&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="JsonLoginDynamicFail" border="0" alt="JsonLoginDynamicFail" src="http://www.richonsoftware.com/image.axd?picture=JsonLoginDynamicFail.png" width="763" height="363" /&gt;&lt;/p&gt;

&lt;p&gt;Even though the dynamic &lt;em&gt;data&lt;/em&gt; variable has the &lt;em&gt;success&lt;/em&gt; property, we don’t have access to it. We could use the assembly attribute &lt;em&gt;InternalsVisibleTo&lt;/em&gt; in order to give our testing project access to internal types.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[assembly: InternalsVisibleTo(&amp;quot;NoninvasiveMVC4Testing.Tests&amp;quot;)]&lt;/pre&gt;

&lt;p&gt; I don’t consider this to be a bad technique, however since we’re trying to be completely noninvasive, I’m going to opt for a slightly different approach.&lt;/p&gt;

&lt;p&gt;We’ll use &lt;em&gt;PrivateObject&lt;/em&gt; (&lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx"&gt;MSDN Link&lt;/a&gt;) to get at the properties. &lt;em&gt;PrivateObject&lt;/em&gt;’s MSDN description:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Allows test code to call methods and properties on the code under test that would be inaccessible because they are not public.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;PrivateObject&lt;/em&gt; ultimately just uses reflection in order to expose the values we need to test.&amp;#160; The real value is in the fact that it abstracts the reflection code away from us. Here’s the code updated with &lt;em&gt;PrivateObject&lt;/em&gt;:&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;var success = (bool)(new PrivateObject(jsonResult.Data, &amp;quot;success&amp;quot;)).Target;
var redirect = (string)(new PrivateObject(jsonResult.Data, &amp;quot;redirect&amp;quot;)).Target;

Assert.AreEqual(true, success);
Assert.AreEqual(testReturnUrl, redirect);&lt;/pre&gt;

&lt;p&gt;And with that we now have successful tests&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="JsonLoginTestsSuccess" border="0" alt="JsonLoginTestsSuccess" src="http://www.richonsoftware.com/image.axd?picture=JsonLoginTestsSuccess.png" width="506" height="199" /&gt;&lt;/p&gt;

&lt;p&gt;Just for completeness, I’ve put together a test to validate the behavior of an invalid login.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[TestMethod]
public void TestInvalidJsonLogin()
{
    string testUserName = &amp;quot;TestUserName&amp;quot;;
    string testPassword = &amp;quot;TestPassword&amp;quot;;
    bool testRememberMe = false;
    string testReturnUrl = &amp;quot;TestReturnUrl&amp;quot;;

    var loginModel = new LoginModel
    {
        UserName = testUserName,
        Password = testPassword,
        RememberMe = testRememberMe
    };

    var accountController = new AccountController();
    JsonResult jsonResult;
    //Scope the detours we're creating
    using (ShimsContext.Create())
    {
        //Sets up a detour for Membership.ValidateUser to our mocked implementation
        ShimMembership.ValidateUserStringString = (userName, password) =&amp;gt; false;
        jsonResult = accountController.JsonLogin(loginModel, testReturnUrl);
    }

    var errors = (IEnumerable&amp;lt;string&amp;gt;)(new PrivateObject(jsonResult.Data, &amp;quot;errors&amp;quot;)).Target;
    Assert.AreEqual(&amp;quot;The user name or password provided is incorrect.&amp;quot;, errors.First());
}&lt;/pre&gt;

&lt;p&gt;And there we go, easy as pie.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="LogOff_ValidLogin_InvalidLogin_Tests" border="0" alt="LogOff_ValidLogin_InvalidLogin_Tests" src="http://www.richonsoftware.com/image.axd?picture=LogOff_ValidLogin_InvalidLogin_Tests.png" width="506" height="199" /&gt;&lt;/p&gt;

&lt;p&gt;For the remainder of the post, I’m just going to focus on the “happy” path for brevity. Testing the other paths is relatively straight forward given what we’ve already done.&lt;/p&gt;

&lt;h2&gt;Login Method&lt;/h2&gt;

&lt;p&gt;Stepping up in complexity we move on to the &lt;em&gt;Login&lt;/em&gt; method.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl))
                return Redirect(returnUrl);
            else
                return RedirectToAction(&amp;quot;Index&amp;quot;, &amp;quot;Home&amp;quot;);
        }
        else
            ModelState.AddModelError(&amp;quot;&amp;quot;, &amp;quot;The user name or password provided is incorrect.&amp;quot;);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;MemberShip.ValidateUser&lt;/em&gt; and &lt;em&gt;FormsAuthentication.SetAuthCookie&lt;/em&gt; are easy enough to test via Shimming. Under normal circumstances &lt;em&gt;Url.IsLocalUrl&lt;/em&gt; would be simple to Shim as well. Unfortunately I ran into an issue when faking the &lt;em&gt;System.Web.Mvc&lt;/em&gt; assembly containing it. Once you try to instantiate a controller (as part of your test project) after adding a Fakes assembly you get a &lt;em&gt;System.Security.VerificationException: Operation could destabilize the runtime&lt;/em&gt;. See my &lt;a href="http://connect.microsoft.com/VisualStudio/feedback/details/740778/verificationexception-when-faking-mvc4-and-instantiating-controller-in-unit-test#details"&gt;Microsoft Connect submission&lt;/a&gt; for more info.&lt;/p&gt;

&lt;p&gt;Fortunately enough, there’s a way to mock its implementation using the stubs portion of Microsoft Fakes as opposed to shims. This brings up an interesting dilemma, if a compatible stubbing technique is available should you use that instead of shimming? &lt;/p&gt;

&lt;p&gt;I would say the answer is generally “yes” provided that these criteria are met:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It doesn’t significantly decrease the readability of the test &lt;/li&gt;

  &lt;li&gt;It doesn’t require excessive measures (such as reflection dumpster diving) to figure out how to do it&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Stubbing Around System.Web.Mvc &lt;/h3&gt;

&lt;p&gt;The first problem we need to solve is that the &lt;em&gt;Url&lt;/em&gt; property (of type &lt;em&gt;UrlHelper&lt;/em&gt;) is null on our instance of &lt;em&gt;AccountController&lt;/em&gt;. The &lt;em&gt;ctor&lt;/em&gt; on &lt;em&gt;UrlHelper&lt;/em&gt; requires a &lt;em&gt;RequestContext&lt;/em&gt;. The &lt;em&gt;ctor&lt;/em&gt; on &lt;em&gt;RequestContext&lt;/em&gt; requires an &lt;em&gt;HttpContextBase&lt;/em&gt;. Since &lt;em&gt;HttpContextBase&lt;/em&gt; is an abstract class we can stub it easily and make our way back up the dependency hierarchy. &lt;/p&gt;

&lt;p&gt;Decompiling &lt;em&gt;UrlHelper&lt;/em&gt; with &lt;a href="http://wiki.sharpdevelop.net/ILSpy.ashx"&gt;ILSpy&lt;/a&gt; shows us that we’ll need to stub one more item in order to avoid the dreaded &lt;em&gt;NullReferenceException&lt;/em&gt;.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;public bool IsLocalUrl(string url)
{
    return this.RequestContext.HttpContext.Request.IsUrlLocalToHost(url);
}&lt;/pre&gt;

&lt;p&gt;We need to make sure that the &lt;em&gt;Request&lt;/em&gt; property on &lt;em&gt;HttpContextBase&lt;/em&gt; returns a value. As luck would have it the &lt;em&gt;Request&lt;/em&gt; property is of type &lt;em&gt;HttpRequestBase&lt;/em&gt; and we can easily stub it as well.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[TestMethod]
public void TestLogin()
{
    string testUserName = &amp;quot;TestUserName&amp;quot;;
    string testPassword = &amp;quot;TestPassword&amp;quot;;
    bool testRememberMe = false;
    string returnUrl = &amp;quot;/foo.html&amp;quot;;

    var loginModel = new LoginModel
    {
        UserName = testUserName,
        Password = testPassword,
        RememberMe = testRememberMe
    };

    var accountController = new AccountController();

    //Setup underpinning via stubbing such that UrlHelper 
    //can validate that our &amp;quot;foo.html&amp;quot; is local
    var stubHttpContext = new StubHttpContextBase();
    var stubHttpRequestBase = new StubHttpRequestBase();
    stubHttpContext.RequestGet = () =&amp;gt; stubHttpRequestBase;
    var requestContext = new RequestContext(stubHttpContext, new RouteData());
    accountController.Url = new UrlHelper(requestContext);

    RedirectResult redirectResult;
    //Scope the detours we're creating
    using (ShimsContext.Create())
    {
        //Sets up a detour for Membership.ValidateUser to our mocked implementation
        ShimMembership.ValidateUserStringString = (userName, password) =&amp;gt;
        {
            Assert.AreEqual(testUserName, userName);
            Assert.AreEqual(testPassword, password);
            return true;
        };

        //Sets up a detour for FormsAuthentication.SetAuthCookie to our mocked implementation
        ShimFormsAuthentication.SetAuthCookieStringBoolean = (userName, rememberMe) =&amp;gt;
        {
            Assert.AreEqual(testUserName, userName);
            Assert.AreEqual(testRememberMe, rememberMe);
        };

        redirectResult = accountController.Login(loginModel, returnUrl) as RedirectResult;
    }

    Assert.NotNull(redirectResult);
    Assert.AreEqual(redirectResult.Url, returnUrl);
}&lt;/pre&gt;

&lt;p&gt;With that, let’s run our tests and make sure everything is working.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="TestRunAfterLoginMethod" border="0" alt="TestRunAfterLoginMethod" src="http://www.richonsoftware.com/image.axd?picture=TestRunAfterLoginMethod.png" width="506" height="197" /&gt;&lt;/p&gt;

&lt;p&gt;One thing to notice here, is that the stubbing we’re doing (starting line 20 and continuing to line 27) doesn’t exactly convey what we’re trying to accomplish. All we care about doing is getting &lt;em&gt;Url.IsLocalUrl&lt;/em&gt; to return &lt;em&gt;true&lt;/em&gt;. Additionally, we had to know quite a bit about the internals of a &lt;em&gt;Controller, UrlHelper, HttpContextBase, HttpRequestBase&lt;/em&gt; just to get this behavior to work. &lt;/p&gt;

&lt;p&gt;In this scenario it would be preferable, readability wise, just to set and detour &lt;em&gt;Url.IsLocalUrl&lt;/em&gt;. In this case our hand was forced since Microsoft Fakes and &lt;em&gt;System.Web.Mvc&lt;/em&gt; aren’t currently cooperating, so I’m more than happy that at least a fallback was available.&lt;/p&gt;

&lt;h2&gt;JsonRegister Method&lt;/h2&gt;

&lt;p&gt;Both &lt;em&gt;JsonRegister&lt;/em&gt; and &lt;em&gt;Register&lt;/em&gt; are very similar, so we’ll just hit one of them. There’s really no new concepts here, just reapplying the what we used to test earlier methods.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[AllowAnonymous]
[HttpPost]
public ActionResult JsonRegister(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus;
        Membership.CreateUser(model.UserName, model.Password, model.Email, 
            passwordQuestion: null, passwordAnswer: null, isApproved: true, 
            providerUserKey: null, status: out createStatus);

        if (createStatus == MembershipCreateStatus.Success)
        {
            FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
            return Json(new { success = true });
        }
        else
            ModelState.AddModelError(&amp;quot;&amp;quot;, ErrorCodeToString(createStatus));
    }

    // If we got this far, something failed
    return Json(new { errors = GetErrorsFromModelState() });
}&lt;/pre&gt;

&lt;p&gt;For &lt;em&gt;JsonRegister&lt;/em&gt; we’ll need to shim &lt;em&gt;Membership.CreateUser&lt;/em&gt;, which is straightforward enough. We’ll need to add a reference to &lt;em&gt;System.Web.Security.ApplicationServices&lt;/em&gt; to our testing project for to work with &lt;em&gt;MembershipCreateStatus&lt;/em&gt; and we’re good to go.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[TestMethod]
public void TestJsonRegister()
{
    string testUserName = &amp;quot;TestUserName&amp;quot;;
    string testPassword = &amp;quot;TestPassword&amp;quot;;
    string testConfirmPassword = &amp;quot;TestPassword&amp;quot;;
    string testEmail = &amp;quot;TestEmail@Test.com&amp;quot;;

    var registerModel = new RegisterModel
    {
        UserName = testUserName,
        Password = testPassword,
        ConfirmPassword = testConfirmPassword,
        Email = testEmail
    };

    var accountController = new AccountController();
    JsonResult jsonResult;
    //Scope the detours we're creating
    using (ShimsContext.Create())
    {
        //Sets up a detour for Membership.CreateUser to our mocked implementation
        ShimMembership.CreateUserStringStringStringStringStringBooleanObjectMembershipCreateStatusOut =
            (string userName, string password, string email, string passwordQuestion, 
                string passwordAnswer, bool isApproved, object providerUserKey,
                out MembershipCreateStatus @createStatus) =&amp;gt;
            {
                Assert.AreEqual(testUserName, userName);
                Assert.AreEqual(testPassword, password);
                Assert.AreEqual(testEmail, email);
                Assert.Null(passwordQuestion);
                Assert.Null(passwordAnswer);
                Assert.True(isApproved);
                Assert.Null(providerUserKey);
                @createStatus = MembershipCreateStatus.Success;

                return null;
            };

        //Sets up a detour for FormsAuthentication.SetAuthCookie to our mocked implementation
        ShimFormsAuthentication.SetAuthCookieStringBoolean = (userName, rememberMe) =&amp;gt;
        {
            Assert.AreEqual(testUserName, userName);
            Assert.AreEqual(false, rememberMe);
        };

        var actionResult = accountController.JsonRegister(registerModel);
        Assert.IsInstanceOf(typeof(JsonResult), actionResult);
        jsonResult = actionResult as JsonResult;
    }

    Assert.NotNull(jsonResult);
    var success = (bool)(new PrivateObject(jsonResult.Data, &amp;quot;success&amp;quot;)).Target;
    Assert.True(success);
}&lt;/pre&gt;

&lt;p&gt;Running our tests once again, we can see everything’s passing&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="TestRunAfterJsonRegisterMethod" border="0" alt="TestRunAfterJsonRegisterMethod" src="http://www.richonsoftware.com/image.axd?picture=TestRunAfterJsonRegisterMethod.png" width="506" height="216" /&gt;&lt;/p&gt;

&lt;h2&gt;ChangePassword Method&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;ChangePassword&lt;/em&gt; method is slightly more difficult to work with, since we have additional items to fake and stub, but otherwise the concepts are pretty similar.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[HttpPost]
public ActionResult ChangePassword(ChangePasswordModel model)
{
    if (ModelState.IsValid)
    {

        // ChangePassword will throw an exception rather
        // than return false in certain failure scenarios.
        bool changePasswordSucceeded;
        try
        {
            MembershipUser currentUser = Membership.GetUser(User.Identity.Name, 
                userIsOnline: true);
            changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, 
                model.NewPassword);
        }
        catch (Exception)
        {
            changePasswordSucceeded = false;
        }

        if (changePasswordSucceeded)
            return RedirectToAction(&amp;quot;ChangePasswordSuccess&amp;quot;);
        else
            ModelState.AddModelError(&amp;quot;&amp;quot;, &amp;quot;The current password is incorrect or the new password is invalid.&amp;quot;);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}&lt;/pre&gt;

&lt;p&gt;We need to make sure that &lt;em&gt;User.Identity.Name&lt;/em&gt; returns properly. In order to do this, we’re going to have to make sure &lt;em&gt;AccountController&lt;/em&gt;’s &lt;em&gt;User&lt;/em&gt; property gets populated with an &lt;em&gt;Identity&lt;/em&gt; object. Again, due to the MVC faking issue, we’re going to approach this via stubbing, which is slightly less readable and requires some framework dumpster diving, but still gets the job done.&lt;/p&gt;

&lt;p&gt;Decompiling down into the &lt;em&gt;Controller&lt;/em&gt; class in &lt;em&gt;System.Web.Mvc&lt;/em&gt; to see what we need to stub show the following:&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;public IPrincipal User
{
    get
    {
        if (this.HttpContext != null)
        {
            return this.HttpContext.User;
        }
        return null;
    }
}&lt;/pre&gt;

&lt;p&gt;Drilling in this.HttpContext&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;public HttpContextBase HttpContext
{
    get
    {
        if (base.ControllerContext != null)
        {
            return base.ControllerContext.HttpContext;
        }
        return null;
    }
}&lt;/pre&gt;

&lt;p&gt;The &lt;em&gt;ControllerContext&lt;/em&gt; property is settable, so that’s our way in and it has a public &lt;em&gt;ctor&lt;/em&gt; taking elements we already have. Additionally, we already have a &lt;em&gt;StubHttpRequestBase&lt;/em&gt; which we can set the &lt;em&gt;User&lt;/em&gt; property on.&lt;/p&gt;

&lt;p&gt;We’ll need to add a Fakes Assembly for &lt;em&gt;mscorlib&lt;/em&gt; in order to stub an &lt;em&gt;IPrincipal&lt;/em&gt; for the &lt;em&gt;AccountController&lt;/em&gt;’s &lt;em&gt;User&lt;/em&gt; property. To add a Fakes assembly for &lt;em&gt;mscorlib&lt;/em&gt;, add one for the &lt;em&gt;System&lt;/em&gt; reference.&amp;#160; &lt;em&gt;System.Web.ApplicationServices&lt;/em&gt; needs a Fakes assembly as well in order to shim the &lt;em&gt;ChangePassword&lt;/em&gt; method on &lt;em&gt;MembershipUser&lt;/em&gt;.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;[TestMethod]
public void TestChangePassword()
{
    string testUserName = &amp;quot;TestUserName&amp;quot;;
    string testOldPassword = &amp;quot;TestOldPassword&amp;quot;;
    string testNewPassword = &amp;quot;TestNewPassword&amp;quot;;

    var changePasswordModel = new ChangePasswordModel
    {
        OldPassword = testOldPassword,
        NewPassword = testNewPassword
    };

    var accountController = new AccountController();

    //Stub HttpContext
    var stubHttpContext = new StubHttpContextBase();
    //Setup ControllerContext so AccountController will use our stubHttpContext
    accountController.ControllerContext = new ControllerContext(stubHttpContext, 
        new RouteData(), accountController);

    //Stub IPrincipal
    var principal = new StubIPrincipal();
    principal.IdentityGet = () =&amp;gt;
    {
        var identity = new StubIIdentity { NameGet = () =&amp;gt; testUserName };
        return identity;
    };
    stubHttpContext.UserGet = () =&amp;gt; principal;

    RedirectToRouteResult redirectToRouteResult;
    //Scope the detours we're creating
    using (ShimsContext.Create())
    {
        ShimMembership.GetUserStringBoolean = (identityName, userIsOnline) =&amp;gt;
        {
            Assert.AreEqual(testUserName, identityName);
            Assert.AreEqual(true, userIsOnline);

            var memberShipUser = new ShimMembershipUser();
            //Sets up a detour for MemberShipUser.ChangePassword to our mocked implementation
            memberShipUser.ChangePasswordStringString = (oldPassword, newPassword) =&amp;gt;
            {
                Assert.AreEqual(testOldPassword, oldPassword);
                Assert.AreEqual(testNewPassword, newPassword);
                return true;
            };
            return memberShipUser;
        };

        var actionResult = accountController.ChangePassword(changePasswordModel);
        Assert.IsInstanceOf(typeof(RedirectToRouteResult), actionResult);
        redirectToRouteResult = actionResult as RedirectToRouteResult;
    }
    Assert.NotNull(redirectToRouteResult);
    Assert.AreEqual(&amp;quot;ChangePasswordSuccess&amp;quot;, redirectToRouteResult.RouteValues[&amp;quot;Action&amp;quot;]);
}&lt;/pre&gt;

&lt;p&gt;After running tests, we see that our new unit test is passing.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="TestRunAfterChangePasswordMethod" border="0" alt="TestRunAfterChangePasswordMethod" src="http://www.richonsoftware.com/image.axd?picture=TestRunAfterChangePasswordMethod.png" width="506" height="238" /&gt;&lt;/p&gt;

&lt;h2&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;Through the use of Microsoft Fakes and the idea of noninvasive testing, with the mockist approach, we’ve been able to test the AccountController quite thoroughly without any project modifications. I imagine we could of easily hit 100% coverage if that was our goal. The only real issues we ran into were related to beta software.&lt;/p&gt;

&lt;p&gt;Oddly enough, I’m glad we ran into the &lt;em&gt;System.Web.Mvc&lt;/em&gt; faking issue. This forced us to use stubbing, and ultimately exposed both negative effects on overall readability and increased complexity in terms of the amount of framework decompiling needed to figure out what stubbing was necessary. Shimming in these cases would of better conveyed our intent and abstracted us away from having to deal with the guts of the underlying framework. &lt;/p&gt;

&lt;p&gt;With these results in mind, it’s evident that testing tools have truly reached a point where anything can be tested, regardless of design. We’re entering a time where ANY application with ANY architecture can be thoroughly unit tested without even the slightest change to code; a time when the ability to unit test a system is decoupled from the design and architecture of that system. &lt;/p&gt;

&lt;p&gt;All of this is for good reason. Today’s testing patterns and practices have arisen from limitations in our capabilities to isolate dependencies when unit testing code. Those limitations have been addressed, it’s time to reevaluate our approaches and move on. &lt;/p&gt;

&lt;p&gt;When you drive architecture with the goal of being structurally easier to test, the only thing you end up with is an architecture that is good at being tested. Let architecture be naturally shaped by the needs of the problem domain over time. Let complexity escalate only as needed and simplicity, maintainability and ease of use all be key goals in a system’s design.&lt;/p&gt;

&lt;p&gt;From now on, we can definitively say that any constraints or limitations in our abilities to thoroughly test any system with any design, are entirely self imposed.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The code for this post is available on &lt;a href="https://github.com/RichCzyzewski/NoninvasiveMVC4Testing"&gt;GitHub&lt;/a&gt;&lt;/p&gt;</description>
      <link>http://feedproxy.google.com/~r/RichOnSoftware/~3/0LKoUb-P1M8/post.aspx</link>
      <comments>http://www.richonsoftware.com/post/2012/05/02/Noninvasive-Unit-Testing-in-ASPNET-MVC-A-Microsoft-Fakes-Deep-Dive.aspx#comment</comments>
      <guid isPermaLink="false">http://www.richonsoftware.com/post.aspx?id=29e33099-8d9e-4bd3-bd0d-e8885a8e0fbf</guid>
      <pubDate>Wed, 02 May 2012 08:00:00 -0400</pubDate>
      <category>Unit Testing</category>
      <dc:publisher>Rich Czyzewski</dc:publisher>
      <pingback:server>http://www.richonsoftware.com/pingback.axd</pingback:server>
      <pingback:target>http://www.richonsoftware.com/post.aspx?id=29e33099-8d9e-4bd3-bd0d-e8885a8e0fbf</pingback:target>
      <slash:comments>59</slash:comments>
      <trackback:ping>http://www.richonsoftware.com/trackback.axd?id=29e33099-8d9e-4bd3-bd0d-e8885a8e0fbf</trackback:ping>
      <wfw:comment>http://www.richonsoftware.com/post/2012/05/02/Noninvasive-Unit-Testing-in-ASPNET-MVC-A-Microsoft-Fakes-Deep-Dive.aspx#comment</wfw:comment>
      <wfw:commentRss>http://www.richonsoftware.com/syndication.axd?post=29e33099-8d9e-4bd3-bd0d-e8885a8e0fbf</wfw:commentRss>
    <feedburner:origLink>http://www.richonsoftware.com/post.aspx?id=29e33099-8d9e-4bd3-bd0d-e8885a8e0fbf</feedburner:origLink></item>
    <item>
      <title>Comparing Microsoft Moles in VS2010 to Microsoft Fakes in VS11</title>
      <description>&lt;p&gt;In my previous post: &lt;a href="http://www.richonsoftware.com/post/2012/04/05/Using-Stubs-and-Shim-to-Test-with-Microsoft-Fakes-in-Visual-Studio-11.aspx"&gt;Using Stubs and Shims to Test with Microsoft Fakes in Visual Studio 11&lt;/a&gt; I went over Microsoft Fakes (a mocking framework built into Visual Studio 2011) in detail.&amp;nbsp; During my research I ran into Microsoft&amp;rsquo;s &lt;a href="http://research.microsoft.com/en-us/projects/moles/"&gt;Moles Isolation Framework&lt;/a&gt;, which is the prior version of Microsoft Fakes that&amp;rsquo;s been in Microsoft Research for a few years.&amp;nbsp;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates. Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types. Moles is freely available on Visual Studio Gallery or bundled with &lt;a href="http://research.microsoft.com/pex"&gt;Pex&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Just as with Microsoft Fakes, Moles provides a way to detour any .NET method as well as &lt;span style="background-color: #ffffff;"&gt;generally accepted basic Mocking functionality.&lt;/span&gt; The real interesting part about Moles is that it happens to be compatible with both Visual Studio 2010 and 2008. As I mentioned in the previous post there are only a handful of products that can detour .NET methods in VS 2010: &lt;a href="http://www.typemock.com/isolator-product-page"&gt;TypeMock&amp;rsquo;s Isolator&lt;/a&gt;, &lt;a href="http://www.telerik.com/products/mocking.aspx"&gt;Telerik&amp;rsquo;s JustMock&lt;/a&gt; and &lt;a href="http://research.microsoft.com/en-us/projects/moles/"&gt;Microsoft&amp;rsquo;s Moles&lt;/a&gt;, costing: $799, $299 and free respectively.&lt;/p&gt;
&lt;p&gt;I've been looking into &amp;ldquo;future proofing&amp;rdquo; some of our new testing initiatives and perhaps using Moles to bridge the gap between today&amp;rsquo;s testing and tomorrow&amp;rsquo;s tools. The &lt;a href="http://research.microsoft.com/en-us/projects/pex/default.aspx"&gt;Moles roadmap&lt;/a&gt; points out that Microsoft Fakes is the next generation of Moles and that a Moles to Fakes conversion will require a few modifications.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Fakes Framework in Visual Studio 11 is the next generation of Moles &amp;amp; Stubs, and will eventually replace it. Fakes is different from Moles, however, so moving from Moles to Fakes will require some modifications to your code. A guide for this migration will be available at a later date.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;span style="background-color: #ffffff;"&gt;That raises a few questions: &lt;/span&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;How different are the two versions?&lt;/li&gt;
&lt;li&gt;How many modifications will be required for conversion?&lt;/li&gt;
&lt;li&gt;Is it &amp;ldquo;safe&amp;rdquo; to use Moles in existing projects?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Under the covers things appear to have been refactored significantly for inclusion in VS 11. It&amp;rsquo;s hard to get a feel of how much movement there&amp;rsquo;s been since compare tools tend to breakdown when namespaces and class names are changed dramatically. After looking through the structures of both Moles and Fakes with ILSpy it&amp;rsquo;s pretty obviousthat the dev teams on this have been quite busy.&lt;/p&gt;
&lt;p&gt;Luckily enough though, after a decent amount of usage it looks as though &lt;strong&gt;Moles is nearly identical to Microsoft Fakes in terms of general usage&lt;/strong&gt;. With that in mind, the migration, even if it is a manual one, doesn&amp;rsquo;t look to be too bad and appears relatively straight forward. Despite the simplicity of conversion I&amp;rsquo;ll be holding out hope for an automated conversion out of the box or as a separate tool.&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The main user facing changes from Moles to Fakes are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Fakes refers to a detour as Shim, instead of as a Mole&lt;/li&gt;
&lt;li&gt;Generated classes that were prefixed with &amp;ldquo;M&amp;rdquo; for Mole&amp;nbsp; or &amp;ldquo;S&amp;rdquo; for Stub are instead prefixed with &amp;ldquo;Shim&amp;rdquo; and &amp;ldquo;Stub&amp;rdquo; respectively&lt;/li&gt;
&lt;li&gt;The HostType attribute is no longer necessary&lt;/li&gt;
&lt;li&gt;Some assembly attributes may no longer be necessary&lt;/li&gt;
&lt;li&gt;.moles configuration files are now .fakes configuration files&lt;/li&gt;
&lt;li&gt;Some configuration file options have been removed&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With that said here&amp;rsquo;s a quick overview of installation, usage and comparisons detailing the similarities, reusing examples from my previous post on Microsoft Fakes.&lt;/p&gt;
&lt;p&gt;&lt;span style="color: #ff0000;"&gt;Note: this post is a little lighter on the details of what Microsoft Fakes and Moles are and why you&amp;rsquo;d want to use it. If you find yourself wanting a little more background information and/or haven&amp;rsquo;t read my previous post on the subject, then you may want to take some time and &lt;a href="http://www.richonsoftware.com/post/2012/04/05/Using-Stubs-and-Shim-to-Test-with-Microsoft-Fakes-in-Visual-Studio-11.aspx"&gt;check it out first&lt;/a&gt;.&amp;nbsp; &lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;Installing Moles&lt;/h2&gt;
&lt;p&gt;Moles is available through Visual Studio&amp;rsquo;s Extension Manager. This eventually leads you to the &lt;a href="http://visualstudiogallery.msdn.microsoft.com/b3b41648-1c21-471f-a2b0-f76d8fb932ee/"&gt;product page&lt;/a&gt; in the Visual Studio Gallery.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="ExtensionManager" src="http://www.richonsoftware.com/image.axd?picture=ExtensionManager.png" alt="ExtensionManager" width="349" height="282" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Search for Moles.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=ExtensionManager2.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="ExtensionManager2" src="http://www.richonsoftware.com/image.axd?picture=ExtensionManager2_thumb.png" alt="ExtensionManager2" width="640" height="324" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Download and start the installer. &lt;span style="background-color: #ffffff;"&gt;Note: not all steps are shown here; the install is rather straight forward.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="MolesInstall1" src="http://www.richonsoftware.com/image.axd?picture=MolesInstall1.png" alt="MolesInstall1" width="509" height="398" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Pick the typical setup type as custom doesn&amp;rsquo;t really offer anything you&amp;rsquo;d want to change anyway.&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="MolesInstall1b" src="http://www.richonsoftware.com/image.axd?picture=MolesInstall1b.png" alt="MolesInstall1b" width="509" height="398" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Quick, easy, done.&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="MolesInstall1c" src="http://www.richonsoftware.com/image.axd?picture=MolesInstall1c.png" alt="MolesInstall1c" width="509" height="398" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Now we&amp;rsquo;re ready for some &amp;ldquo;Moling&amp;rdquo; action!&amp;nbsp; Hmmm&amp;hellip; perhaps it was for the better that they renamed this in Visual Studio 11.&lt;/p&gt;
&lt;h2&gt;Moling Example &amp;amp; Comparison&lt;/h2&gt;
&lt;p&gt;First off we have a little bit of boilerplate code to setup. Aside from the different namespaces and 1 different class name, this is essentially the same trivial cart example as the previous post, so feel free to skip ahead if your interested in the more &amp;ldquo;juicy&amp;rdquo; bits.&lt;/p&gt;
&lt;p&gt;In Visual Studio 2010 create a C# Class Library project called &lt;em&gt;MolesExample&lt;/em&gt;.&amp;nbsp; Rename the default class file to &lt;em&gt;CartToMole&lt;/em&gt; and modify the code to be as follows:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MolesExample
{
    public class CartToMole
    {
        public int CartId { get; private set; }
        public int UserId { get; private set; }
        private List&amp;lt;CartItem&amp;gt; _cartItems = new List&amp;lt;CartItem&amp;gt;();
        public ReadOnlyCollection&amp;lt;CartItem&amp;gt; CartItems { get; private set; }
        public DateTime CreateDateTime { get; private set; }

        public CartToMole(int cartId, int userId)
        {
            CartId = cartId;
            UserId = userId;
            CreateDateTime = DateTime.Now;
            CartItems = new ReadOnlyCollection&amp;lt;CartItem&amp;gt;(_cartItems);
        }
 
        public void AddCartItem(int productId)
        {
            var cartItemId = DataAccessLayer.SaveCartItem(CartId, productId);
            _cartItems.Add(new CartItem(cartItemId, productId));
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Add the &lt;em&gt;CartItem&lt;/em&gt; class.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;namespace MolesExample
{
    public class CartItem
    {
        public int CartItemId { get; private set; }
        public int ProductId { get; private set; }

        public CartItem(int cartItemId, int productId)
        {
            CartItemId = cartItemId;
            ProductId = productId;
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Add the &lt;em&gt;DataAccessLayer&lt;/em&gt; class. Again, don&amp;rsquo;t worry about the connection string, we&amp;rsquo;ll never end up hitting it anyway.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using System.Data;
using System.Data.SqlClient;

namespace MolesExample
{
    public static class DataAccessLayer
    {
        public static int SaveCartItem(int cartId, int productId)
        {
            using (var conn = new SqlConnection("RandomSqlConnectionString"))
            {
                var cmd = new SqlCommand("InsCartItem", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@CartId", cartId);
                cmd.Parameters.AddWithValue("@ProductId", productId);

                conn.Open();
                return (int)cmd.ExecuteScalar();
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Next add a Unit Test Project called &lt;em&gt;MolesExample.Tests&lt;/em&gt; and rename the default unit test class file to &lt;em&gt;CartToMoleTests&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;In the &lt;em&gt;&lt;em&gt;MolesExample&lt;/em&gt;.Tests&lt;/em&gt; project add a reference to the &lt;em&gt;MolesExample &lt;/em&gt;project.&amp;nbsp; You&amp;rsquo;re solution should look as follows:&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="InitialSolutionConfig" src="http://www.richonsoftware.com/image.axd?picture=InitialSolutionConfig_5.png" alt="InitialSolutionConfig" width="413" height="359" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Right click on the &lt;em&gt;&lt;em&gt;MolesExample &lt;/em&gt;&lt;/em&gt;reference in &lt;em&gt;&lt;em&gt;&lt;em&gt;MolesExample&lt;/em&gt;&lt;/em&gt;.Tests&lt;/em&gt; references and select the &amp;ldquo;Add Moles Assembly&amp;rdquo; option.&amp;nbsp; Note: Screen captures of the Fakes version are positioned either to the right or bottom depending on your available screen width.&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="AddFakesAssembly" src="http://www.richonsoftware.com/image.axd?picture=AddFakesAssembly_4.png" alt="AddFakesAssembly" width="413" height="301" border="0" /&gt;&amp;nbsp; &lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="AddFakesAssembly" src="http://www.richonsoftware.com/image.axd?picture=AddFakesAssembly_5.png" alt="AddFakesAssembly" width="409" height="253" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;This adds a couple of new items to the project. You may need to refresh to see the new items as they didn&amp;rsquo;t come up right away for me.&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="AfterFakes" src="http://www.richonsoftware.com/image.axd?picture=AfterFakes_4.png" alt="AfterFakes" width="413" height="314" border="0" /&gt;&amp;nbsp; &lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="AfterFakes" src="http://www.richonsoftware.com/image.axd?picture=AfterFakes_5.png" alt="AfterFakes" width="409" height="295" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;The new references add the following types. Also take note of how the namespacing between Moles and Fakes has changed.&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="NewTypes" src="http://www.richonsoftware.com/image.axd?picture=NewTypes_1.png" alt="NewTypes" width="412" height="579" border="0" /&gt;&amp;nbsp; &lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="NewTypes2" src="http://www.richonsoftware.com/image.axd?picture=NewTypes2.png" alt="NewTypes2" width="409" height="526" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;The generated .Moles/.Fakes assembly type naming has only changed slightly between versions, which is what we&amp;rsquo;ll be working with for the most part.&amp;nbsp;&lt;/p&gt;
&lt;table style="width: 401px;" border="0" cellspacing="0" cellpadding="0"&gt;
&lt;tbody&gt;
&lt;tr style="background-color: #f0f0f0;"&gt;&lt;th valign="top" width="199"&gt;&lt;strong&gt;VS 10&lt;/strong&gt;&lt;/th&gt;&lt;th valign="top" width="200"&gt;&lt;strong&gt;VS 11&lt;/strong&gt;&lt;/th&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="199"&gt;MCartItem&lt;/td&gt;
&lt;td valign="top" width="200"&gt;ShimCartItem&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="199"&gt;MCartItem.AllInstances&lt;/td&gt;
&lt;td valign="top" width="200"&gt;ShimCartItem.AllInstances&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="199"&gt;MCartToMole&lt;/td&gt;
&lt;td valign="top" width="200"&gt;ShimCartToShim&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="199"&gt;MCartToMole.AllInstances&lt;/td&gt;
&lt;td valign="top" width="200"&gt;ShimCartToShim.AllInstances&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="199"&gt;MDataAccessLayer&lt;/td&gt;
&lt;td valign="top" width="200"&gt;ShimDataAccessLayer&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="199"&gt;SCartItem&lt;/td&gt;
&lt;td valign="top" width="200"&gt;StubCartItem&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="199"&gt;SCartToMole&lt;/td&gt;
&lt;td valign="top" width="200"&gt;StubCartToShim&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The .moles configuration file has been appropriately renamed to .fakes and the internals renamed accordingly.&amp;nbsp; I&amp;rsquo;ll expand out the structure of the .moles file later on in the post and compare that to the expanded .fakes configuration file.&amp;nbsp; For now here are the differences between them in terms of our two projects:&lt;/p&gt;
&lt;pre class="brush: xml; toolbar: false;"&gt;&amp;lt;Moles xmlns="http://schemas.microsoft.com/moles/2010/"&amp;gt;
  &amp;lt;Assembly Name="MolesExample" /&amp;gt;
&amp;lt;/Moles&amp;gt;&lt;/pre&gt;
&lt;pre class="brush: xml; toolbar: false;"&gt;&amp;lt;Fakes xmlns="http://schemas.microsoft.com/fakes/2011/"&amp;gt;
  &amp;lt;Assembly Name="FakingExample"/&amp;gt;
&amp;lt;/Fakes&amp;gt;&lt;/pre&gt;
&lt;p&gt;Now, let&amp;rsquo;s create our first test method using a Mole.&amp;nbsp; Just as before we&amp;rsquo;re going to unit test the &lt;em&gt;AddCartItem&lt;/em&gt; method. &lt;em&gt;AddCartItem&lt;/em&gt; calls &lt;em&gt;SaveCartItem&lt;/em&gt; on &lt;em&gt;DataAccessLayer&lt;/em&gt;, which happens to be static.&amp;nbsp; We&amp;rsquo;re going to mock out that database call to isolate the logic in &lt;em&gt;AddCartItem&lt;/em&gt; in our unit test. Add the code below to &lt;em&gt;CartToMoleTests&lt;/em&gt;.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using Microsoft.Moles.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MolesExample.Tests
{
    [TestClass]
    public class CartToMoleTests
    {
        [TestMethod, HostType("Moles")]
        public void AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart()
        {
            //Create a context to scope and cleanup moles
            using (MolesContext.Create())
            {
                int cartItemId = 42, cartId = 1, userId = 33, productId = 777;

                //Mole SaveCartItem rerouting it to a delegate which 
                //always returns cartItemId
                Moles.MDataAccessLayer.SaveCartItemInt32Int32 = (c, p) =&amp;gt; cartItemId;

                var cart = new CartToMole(cartId, userId);
                cart.AddCartItem(productId);

                Assert.AreEqual(cartId, cart.CartItems.Count);
                var cartItem = cart.CartItems[0];
                Assert.AreEqual(cartItemId, cartItem.CartItemId);
                Assert.AreEqual(productId, cartItem.ProductId);
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Here&amp;rsquo;s the class file we used in the Microsoft Fakes example for reference.&amp;nbsp; The only real differences aside from namespacing are on lines 9 (Moles HostType is no longer needed), 13 (context name change) and 19 (actual detour) and all are quite minor.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
 
namespace FakingExample.Tests
{
    [TestClass]
    public class CartToShimTests
    {
        [TestMethod]
        public void AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart()
        {
            //Create a context to scope and cleanup shims
            using (ShimsContext.Create())
            {
                int cartItemId = 42, cartId = 1, userId = 33, productId = 777;
 
                //Shim SaveCartItem rerouting it to a delegate which 
                //always returns cartItemId
                Fakes.ShimDataAccessLayer.SaveCartItemInt32Int32 = (c, p) =&amp;gt; cartItemId;
 
                var cart = new CartToShim(cartId, userId);
                cart.AddCartItem(productId);
 
                Assert.AreEqual(cartId, cart.CartItems.Count);
                var cartItem = cart.CartItems[0];
                Assert.AreEqual(cartItemId, cartItem.CartItemId);
                Assert.AreEqual(productId, cartItem.ProductId);
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Now let&amp;rsquo;s run it in Unit Test Explorer and see it pass.&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="TestrunAfterMole" src="http://www.richonsoftware.com/image.axd?picture=TestrunAfterMole.png" alt="TestrunAfterMole" width="685" height="161" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Just as before, our mole/detour completely skipped over the &lt;em&gt;SaveCartItem&lt;/em&gt; method in &lt;em&gt;DataAccessLayer &lt;/em&gt;avoiding the exception due to &amp;ldquo;RandomSqlConnectionString&amp;rdquo; clearly not being a valid connection string. Start to finish, Moles ends up being just as easy to setup and use as Fakes for our simple cart example.&lt;/p&gt;
&lt;h2&gt;Stubs Example and Comparison&lt;/h2&gt;
&lt;p&gt;As with the Mole example above, there&amp;rsquo;s some boilerplate we need to setup before we get to the stub test.&amp;nbsp; Again, there are very few changes here, so if you&amp;rsquo;ve seen these before feel free to skip ahead.&lt;/p&gt;
&lt;p&gt;We&amp;rsquo;ll need to create an &lt;em&gt;ICartSaver &lt;/em&gt;interface and inject/pass it into the &lt;em&gt;CartToStub&lt;/em&gt; object.&amp;nbsp; At which point we can stub out &lt;em&gt;ICartSaver&lt;/em&gt; and have it return 42 just as we did for our Moling example.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Add a new interface &lt;em&gt;ICartSaver&lt;/em&gt; to the &lt;em&gt;MolesExample&lt;/em&gt; project.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;namespace MolesExample
{
    public interface ICartSaver
    {
        int SaveCartItem(int cartId, int productId);
    }
}&lt;/pre&gt;
&lt;p&gt;Next up, for completeness (although not necessary, since we&amp;rsquo;ll be stubbing around it), add a &lt;em&gt;CartSaver&lt;/em&gt; class to the &lt;em&gt;MolesExample&lt;/em&gt; project so we can replicate the implementation of &lt;em&gt;DataAccessLayer&lt;/em&gt;.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using System.Data;
using System.Data.SqlClient;

namespace MolesExample
{
    public class CartSaver : ICartSaver
    {
        public int SaveCartItem(int cartId, int productId)
        {
            using (var conn = new SqlConnection("RandomSqlConnectionString"))
            {
                var cmd = new SqlCommand("InsCartItem", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@CartId", cartId);
                cmd.Parameters.AddWithValue("@ProductId", productId);

                conn.Open();
                return (int)cmd.ExecuteScalar();
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Create a new &lt;em&gt;CartToStub&lt;/em&gt; class as follows similar to &lt;em&gt;CartToMole&lt;/em&gt; but allowing for manual dependency injection of &lt;em&gt;ICartSaver &lt;/em&gt;in the constructor:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MolesExample
{
    public class CartToStub
    {
        public int CartId { get; private set; }
        public int UserId { get; private set; }
        private List&amp;lt;CartItem&amp;gt; _cartItems = new List&amp;lt;CartItem&amp;gt;();
        public ReadOnlyCollection&amp;lt;CartItem&amp;gt; CartItems { get; private set; }
        public DateTime CreateDateTime { get; private set; }
        private ICartSaver _cartSaver;

        public CartToStub(int cartId, int userId, ICartSaver cartSaver)
        {
            CartId = cartId;
            UserId = userId;
            CreateDateTime = DateTime.Now;
            _cartSaver = cartSaver;
            CartItems = new ReadOnlyCollection&amp;lt;CartItem&amp;gt;(_cartItems);
        }

        public void AddCartItem(int productId)
        {
            var cartItemId = _cartSaver.SaveCartItem(CartId, productId);
            _cartItems.Add(new CartItem(cartItemId, productId));
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Moving back over to the &lt;em&gt;MolesExample.Tests&lt;/em&gt; project, add a new unit test file named &lt;em&gt;CartToStubTests&lt;/em&gt;.&amp;nbsp; Create/Modify the &lt;em&gt;AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart&lt;/em&gt; method to take into account the new changes.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MolesExample.Tests
{
    [TestClass]
    public class CartToStubTests
    {
        [TestMethod, HostType("Moles")]
        public void AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart()
        {
            int cartItemId = 42, cartId = 1, userId = 33, productId = 777;
 
            //Stub ICartSaver and customize the behavior via a 
            //delegate, to return cartItemId
            var cartSaver = new Moles.SICartSaver();
            cartSaver.SaveCartItemInt32Int32 = (c, p) =&amp;gt; cartItemId;
 
            var cart = new CartToStub(cartId, userId, cartSaver);
            cart.AddCartItem(productId);
 
            Assert.AreEqual(cartId, cart.CartItems.Count);
            var cartItem = cart.CartItems[0];
            Assert.AreEqual(cartItemId, cartItem.CartItemId);
            Assert.AreEqual(productId, cartItem.ProductId);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Here&amp;rsquo;s the class file we used in the Microsoft Fakes example for reference.&amp;nbsp; Differences are on lines 8 (Moles HostType) and 15 (generated Stub type name) and are quite minimal.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FakingExample.Tests
{
    [TestClass]
    public class CartToStubTests
    {
        [TestMethod]
        public void AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart()
        {
            int cartItemId = 42, cartId = 1, userId = 33, productId = 777;

            //Stub ICartSaver and customize the behavior via a 
            //delegate, ro return cartItemId
            var cartSaver = new Fakes.StubICartSaver();
            cartSaver.SaveCartItemInt32Int32 = (c, p) =&amp;gt; cartItemId;

            var cart = new CartToStub(cartId, userId, cartSaver);
            cart.AddCartItem(productId);

            Assert.AreEqual(cartId, cart.CartItems.Count);
            var cartItem = cart.CartItems[0];
            Assert.AreEqual(cartItemId, cartItem.CartItemId);
            Assert.AreEqual(productId, cartItem.ProductId);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Run the unit tests once more to see that everything&amp;rsquo;s passing.&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="TestrunAfterStub" src="http://www.richonsoftware.com/image.axd?picture=TestrunAfterStub_2.png" alt="TestrunAfterStub" width="674" height="171" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Just as with the Moling example, the code is very similar to what would be used in Microsoft Fakes.&lt;/p&gt;
&lt;h2&gt;.Moles and .Fakes Xml Configuration File Comparison&lt;/h2&gt;
&lt;p&gt;The changes in the .fakes xml configuration file may require more effort to convert depending on what features were used. Basic usage as in generated but never modified shouldn&amp;rsquo;t be a problem. However, there are a handful of attributes which could be problematic to convert, since they&amp;rsquo;ve been removed. I&amp;rsquo;ve included both files expanded out via intellisense, with a description of the removed elements.&lt;/p&gt;
&lt;pre class="brush: xml; toolbar: false;"&gt;&amp;lt;Moles xmlns="http://schemas.microsoft.com/moles/2010/"&amp;gt;
  &amp;lt;Assembly Name="" ExportedTypes="" Location="" ReflectionOnly="" x86="" /&amp;gt;

  &amp;lt;CodeStyle AssemblyAlias="" DisableUniqueAlias="" MaxIdentifierLength=""&amp;gt;
    &amp;lt;Copyright&amp;gt;&amp;lt;/Copyright&amp;gt;
    &amp;lt;FileHeader&amp;gt;&amp;lt;/FileHeader&amp;gt;
  &amp;lt;/CodeStyle&amp;gt;

  &amp;lt;StubGeneration Disable="" SkipVirtualIndexers="" SkipVirtualMethods=""&amp;gt;
    &amp;lt;Types&amp;gt;
      &amp;lt;Clear /&amp;gt;
      &amp;lt;Add AbstractClasses="" Classes="" FullName="" Interfaces="" Namespace="" TypeName=""/&amp;gt;
      &amp;lt;Remove AbstractClasses="" Classes="" FullName="" Interfaces="" Namespace="" Obsolete="" TypeName=""/&amp;gt;
    &amp;lt;/Types&amp;gt;
    &amp;lt;TypeFilter /&amp;gt; &amp;lt;!-- Deprecated --&amp;gt;
  &amp;lt;/StubGeneration&amp;gt;

  &amp;lt;MoleGeneration Disable=""&amp;gt;
    &amp;lt;Types&amp;gt;
      &amp;lt;Clear /&amp;gt;
      &amp;lt;Add FullName="" Namespace="" TypeName="" /&amp;gt;
      &amp;lt;Remove FullName="" Namespace="" Obsolete="" TypeName=""/&amp;gt;
    &amp;lt;/Types&amp;gt;
    &amp;lt;TypeFilter /&amp;gt; &amp;lt;!-- Deprecated --&amp;gt;
  &amp;lt;/MoleGeneration&amp;gt;

  &amp;lt;Compilation AssemblyName="" Debug="" DisableCodeContracts="" KeyFile="" ProjectTemplate=""&amp;gt;
    &amp;lt;COMReference Guid="" VersionMajor="" VersionMinor="" WrapperTool="" /&amp;gt;
    &amp;lt;Property Condition="" Name="" /&amp;gt;
  &amp;lt;/Compilation&amp;gt;
&amp;lt;/Moles&amp;gt;&lt;/pre&gt;
&lt;p&gt;Here&amp;rsquo;s the .fakes file intellisense expansion for reference.&amp;nbsp;&lt;/p&gt;
&lt;pre class="brush: xml; toolbar: false;"&gt;&amp;lt;Fakes xmlns="http://schemas.microsoft.com/fakes/2011/"&amp;gt;
  &amp;lt;Assembly Name="" Location="" Version="" x86=""/&amp;gt;

  &amp;lt;StubGeneration Disable="" SkipVirtualIndexers="" SkipVirtualMethods=""&amp;gt;
    &amp;lt;Clear /&amp;gt;
    &amp;lt;Add AbstractClasses="" FullName="" Interfaces="" Namespace="" TypeName=""/&amp;gt;
    &amp;lt;Remove AbstractClasses="" FullName="" Interfaces="" Namespace="" Obsolete="" TypeName=""/&amp;gt;
  &amp;lt;/StubGeneration&amp;gt;

  &amp;lt;ShimGeneration Disable=""&amp;gt;
    &amp;lt;Clear /&amp;gt;
    &amp;lt;Add FullName="" Namespace="" TypeName=""/&amp;gt;
    &amp;lt;Remove FullName="" Namespace="" Obsolete="" TypeName=""/&amp;gt;
  &amp;lt;/ShimGeneration&amp;gt;

  &amp;lt;Compilation Debug="" DisableCodeContracts="" KeyFile="" ProjectTemplate=""&amp;gt;
    &amp;lt;COMReference Guid="" VersionMajor="" VersionMinor="" WrapperTool=""/&amp;gt;
    &amp;lt;Property Condition="" Name="" /&amp;gt;
  &amp;lt;/Compilation&amp;gt;
&amp;lt;/Fakes&amp;gt;&lt;/pre&gt;
&lt;p&gt;Here&amp;rsquo;s an overview of the changes from Moles to Fakes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The &lt;em&gt;ExportedTypes&lt;/em&gt; attribute (.moles line 2) was removed from the &lt;em&gt;Assembly&lt;/em&gt; element. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;Per the schema &lt;em&gt;ExportedTypes&lt;/em&gt; is described as &amp;ldquo;Reflect over exported (visible outside the assembly) types only&amp;rdquo;. The only examples I can find for its usage are in moling the System assembly &lt;a href="http://stackoverflow.com/questions/8144653/moling-system-dll"&gt;here&lt;/a&gt; and &lt;a href="http://stackoverflow.com/questions/8476546/what-classes-have-methods-which-moles-can-redirect"&gt;here&lt;/a&gt;. We&amp;rsquo;ll have to wait for the migration guide to see what is a suitable replacement for this behavior. &lt;/li&gt;
&lt;li&gt;The &lt;em&gt;CodeStyle&lt;/em&gt; element (.moles &lt;span style="background-color: #ffffff;"&gt;line 4&lt;/span&gt;) was removed. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;Per the schema &lt;em&gt;CodeStyle&lt;/em&gt; is described as &amp;ldquo;Code generation settings&amp;rdquo;. Aside from the &lt;em&gt;Copyright&lt;/em&gt; and &lt;em&gt;FileHeader&lt;/em&gt; elements the child attributes generally looked like debug switches.&amp;nbsp; From the docs available at &lt;a href="http://research.microsoft.com/en-us/projects/pex/documentation.aspx"&gt;Microsoft Research&lt;/a&gt; there isn&amp;rsquo;t a whole lot of detail on when to use these settings or what purpose they serve.&amp;nbsp; Nobody&amp;rsquo;s going to miss these. &lt;/li&gt;
&lt;li&gt;The &lt;em&gt;Types&lt;/em&gt; elements (.moles lines 7 &amp;amp; 16) have been removed and everything below has shifted up one level. Sounds good to me.&lt;/li&gt;
&lt;li&gt;The &lt;em&gt;Classes&lt;/em&gt; attributes (.moles lines 9 &amp;amp; 10) were removed from the &lt;em&gt;Add&lt;/em&gt; &amp;amp; &lt;em&gt;Remove&lt;/em&gt; elements in &lt;em&gt;StubGeneration&lt;/em&gt;. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;Per the schema &lt;em&gt;Classes &lt;/em&gt;is described as &amp;ldquo;An optional filter to filter non-abstract classes&amp;rdquo;. Why this one was removed but not the inverse (&lt;em&gt;AbstractClasses&lt;/em&gt;) is anyone&amp;rsquo;s guess. I imagine you can achieve the desired results with the other filters, so this could require a little more effort to update if you make use of this it. &lt;/li&gt;
&lt;li&gt;The &lt;em&gt;AssemblyName&lt;/em&gt; attribute (.moles line 24) was removed from the &lt;em&gt;Compilation&lt;/em&gt; element. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;Per the Schema &lt;em&gt;AssemblyName&lt;/em&gt; is described as &amp;ldquo;Specifies the assembly name of the generated assembly&amp;rdquo;. This attribute only applies when compilation is disabled&amp;rdquo;. Again, no documentation available, no examples of usage, probably not going to miss it.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Additional Considerations for System &amp;amp; Mscorlib&lt;/h2&gt;
&lt;p&gt;Previously in Moles when adding a Moles assembly for mscorlib or System, Moles required a little bit of jury rigging.&amp;nbsp; Assembly attributes may be required in some cases.&amp;nbsp; See &lt;a href="http://social.msdn.microsoft.com/Forums/eu/vsunittest/thread/e1b00374-06b2-461d-b445-f3114bae22fa"&gt;this post&lt;/a&gt; at social.msdn.microsoft.com (code below quoted from post) and &lt;a href="http://stackoverflow.com/questions/5961982/using-moles-with-datetime"&gt;this one&lt;/a&gt; from StackOverflow for more info.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false; auto-links: false;"&gt;using System;
using System.Moles;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.DateTime))]

namespace Y2kMoles
{
    [TestClass]
    public class Y2kTest
    {
        [TestMethod]
        [HostType("Moles")] // add this attribute
        public void Y2k()
        {
            MDateTime.NowGet = () =&amp;gt; new DateTime(2000, 1, 1);

            if (DateTime.Now == new DateTime(2000, 1, 1))
                throw new Exception("y2k bug!!!!");
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Even with these changes I was still getting build errors. Supposedly there are issues related to the installation of SP1. See &lt;a href="http://stackoverflow.com/questions/5980076/moles-0-94-51023-0-error-on-vs-2010-sp1"&gt;this post&lt;/a&gt; on StackOverflow for more info.&lt;/p&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="BuildErrors" src="http://www.richonsoftware.com/image.axd?picture=BuildErrors_2.png" alt="BuildErrors" width="744" height="376" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;I ended up modifying the mscorlib.moles file using the type filters to only include DateTime and this fixed everything up.&lt;/p&gt;
&lt;pre class="brush: xml; toolbar: false; auto-links: false;"&gt;&amp;lt;Moles xmlns="http://schemas.microsoft.com/moles/2010/"&amp;gt;
  &amp;lt;Assembly Name="mscorlib" /&amp;gt;
  &amp;lt;StubGeneration Disable="true" /&amp;gt;
  &amp;lt;MoleGeneration&amp;gt;
    &amp;lt;Types&amp;gt;
      &amp;lt;Clear /&amp;gt;
      &amp;lt;Add TypeName="DateTime" /&amp;gt;
    &amp;lt;/Types&amp;gt;
  &amp;lt;/MoleGeneration&amp;gt;
&amp;lt;/Moles&amp;gt;&lt;/pre&gt;
&lt;p&gt;That&amp;rsquo;s a slightly suboptimal user experience for such a common case. &lt;strong&gt;Microsoft Fakes seems to have fixed these issues&lt;/strong&gt;. Adding a Fakes assembly to System also adds one for mscorlib and everything works just fine out of the box, which is the expected user experience. So during conversion to Fakes there may be some &amp;ldquo;dehacking&amp;rdquo; involved.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;It would seem that Microsoft Moles is quite capable and so similar in terms of usage to Microsoft Fakes that using it in the interim until Visual Studio 11 is released is a simple decision. The functionality gained as well as future proofing ongoing development is well worth any drawbacks related to migration or some of Moles&amp;rsquo; current issues. There will be some conversion effort involved (as the only conversion plans mentioned so far, are a guide for manual conversion steps), but it will be relatively simple and straight forward. Learn it, use it, love it!&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;span style="background-color: #ffffff;"&gt;The code for this post is available on &lt;a href="https://github.com/RichCzyzewski/MicrosoftMolesExamples"&gt;GitHub&lt;/a&gt;.&lt;/span&gt;&lt;/p&gt;</description>
      <link>http://feedproxy.google.com/~r/RichOnSoftware/~3/i43dpbgVT4o/post.aspx</link>
      <comments>http://www.richonsoftware.com/post/2012/04/20/Comparing-Microsoft-Moles-in-Visual-Studio-2010-to-Microsoft-Fakes-in-Visual-Studio-11.aspx#comment</comments>
      <guid isPermaLink="false">http://www.richonsoftware.com/post.aspx?id=209f2ba2-91b6-4e33-a97b-ed4b0396fa29</guid>
      <pubDate>Fri, 20 Apr 2012 05:54:00 -0400</pubDate>
      <category>Unit Testing</category>
      <dc:publisher>Rich Czyzewski</dc:publisher>
      <pingback:server>http://www.richonsoftware.com/pingback.axd</pingback:server>
      <pingback:target>http://www.richonsoftware.com/post.aspx?id=209f2ba2-91b6-4e33-a97b-ed4b0396fa29</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://www.richonsoftware.com/trackback.axd?id=209f2ba2-91b6-4e33-a97b-ed4b0396fa29</trackback:ping>
      <wfw:comment>http://www.richonsoftware.com/post/2012/04/20/Comparing-Microsoft-Moles-in-Visual-Studio-2010-to-Microsoft-Fakes-in-Visual-Studio-11.aspx#comment</wfw:comment>
      <wfw:commentRss>http://www.richonsoftware.com/syndication.axd?post=209f2ba2-91b6-4e33-a97b-ed4b0396fa29</wfw:commentRss>
    <feedburner:origLink>http://www.richonsoftware.com/post.aspx?id=209f2ba2-91b6-4e33-a97b-ed4b0396fa29</feedburner:origLink></item>
    <item>
      <title>Using Stubs and Shims to Test with Microsoft Fakes in Visual Studio 11</title>
      <description>&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx"&gt;Microsoft Fakes&lt;/a&gt; is a full featured mocking framework built into Visual Studio 11. Currently, the available documentation is limited and marked as “preview only”, however it does provide us with some very good descriptions.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Microsoft Fakes is an isolation framework for creating delegate-based test stubs and shims in .NET Framework applications. The Fakes framework can be used to shim any .NET method, including non-virtual and static methods in sealed types.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Additionally here is Wikipedia’s definition of &lt;a href="http://en.wikipedia.org/wiki/Mock_object"&gt;Mock Object&lt;/a&gt; for reference&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;In object-oriented programming, &lt;b&gt;mock objects&lt;/b&gt; are simulated objects that mimic the behavior of real objects in controlled ways. A programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.&lt;/p&gt; &lt;/blockquote&gt;  &lt;h2&gt;Shim any .NET Method&lt;/h2&gt;  &lt;p&gt;The real interesting part here is that Microsoft Fakes can shim&lt;em&gt;&lt;strong&gt; “any .NET method&lt;/strong&gt;, &lt;strong&gt;including non-virtual and static methods in sealed types”&lt;/strong&gt;&lt;/em&gt;&lt;strong&gt;.&lt;/strong&gt;&amp;#160; Existing mocking frameworks work by providing “on the fly” implementations to preexisting interfaces with a bit of &lt;a href="http://en.wikipedia.org/wiki/Dependency_injection"&gt;Dependency Injection&lt;/a&gt; to get them situated in the class/method under test. &lt;/p&gt;  &lt;p&gt;Microsoft Fakes is going a level deeper by mocking objects with no preexisting interfaces and allowing statics to be mocked in the process. This type of mocking is quite complex to pull off.&amp;#160; So much so, that there are only a handful of products out there that do this.&amp;#160; &lt;a href="http://www.typemock.com/isolator-product-page"&gt;TypeMock’s Isolator&lt;/a&gt;, &lt;a href="http://www.telerik.com/products/mocking.aspx"&gt;Telerik’s JustMock&lt;/a&gt; and the Microsoft Research project &lt;a href="http://research.microsoft.com/en-us/projects/moles/"&gt;Moles&lt;/a&gt; that ultimately lead to Microsoft Fakes.&amp;#160; &lt;/p&gt;  &lt;p&gt;TypeMock’s Isolator has been a regular so to speak in unit testing circles for a while now and I’ve actively considered it before, but the starting price of $799 has always been a little steep for my tastes. Telerik’s JustMock is the new kid on the block (past 2-3 years). JustMock has freemium edition supporting general mocking features and a pay version which has support for static, sealed &amp;amp; non virtual mocking with a base price of $299.&lt;/p&gt;  &lt;p&gt;The biggest surprise is the Microsoft Research project Moles, which seems to have about the same set of features as Microsoft Fakes, has apparently been available since 11/1/2010 and is compatible with both Visual Studio 2010 &amp;amp; 2008 (based on the &lt;a href="http://visualstudiogallery.msdn.microsoft.com/b3b41648-1c21-471f-a2b0-f76d8fb932ee/"&gt;Visual Studio 2010 Moles x86 - Isolation Framework for .NET&lt;/a&gt; download page).&amp;#160; Perhaps this is the internet’s best kept secret… well, maybe not.&amp;#160; Regardless, I’ll be creating a future blog post going over using Moles in Visual Studio 2010.&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h2&gt;Architectural Implications&lt;/h2&gt;  &lt;p&gt;Without a commercial mocking framework or Microsoft Fakes, if you’re going to do unit testing and you want to do it right as in truly isolate the code under test then you’re going to need to mock dependent objects.&amp;#160; However, just mocking the objects isn’t enough, you also need to instruct the code under test to use the mocks as opposed to its normal implementation.&amp;#160; Typically this requires some form of Dependency Injection.&amp;#160; &lt;/p&gt;  &lt;p&gt;For reference here is Wikipedia's definition of &lt;a href="http://en.wikipedia.org/wiki/Dependency_injection"&gt;Dependency Injection&lt;/a&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;b&gt;Dependency injection&lt;/b&gt; (&lt;b&gt;DI&lt;/b&gt;) is a design pattern in object-oriented computer programming whose purpose is to reduce the coupling between software components. It is similar to the factory method pattern. Frequently an object uses (depends on) work produced by another part of the system. With DI, the object does not need to know in advance about how the other part of the system works. Instead, the programmer provides (injects) the relevant system component in advance along with a contract that it will behave in a certain way.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;To truly isolate code in unit tests you’re typically bound to the following practices as part of Dependency Injection:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Any object that needs to be mocked needs to be non static and have an interface &lt;/li&gt;    &lt;li&gt;You’ll either need to have a Dependency Injection framework as part of the architecture or the right patterns in place to manually resolve and inject as needed &lt;/li&gt;    &lt;li&gt;Constructors will have to be modified to take in interface types for the dependent objects &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;That’s a lot of Architectural commitment.&amp;#160; As with any design pattern there are “trade offs” involved in usage.&amp;#160; With Dependency Injection you get reduced coupling and the ability to unit test thoroughly, increasing complexity and reducing maintainability by some level in the process.&amp;#160; The question with any design pattern’s usage is: are the trade offs worth it based on the functionality provided for the problem domain in question?&amp;#160; &lt;/p&gt;  &lt;p&gt;Microsoft Fakes changes the trade off evaluation for Dependency Injection.&amp;#160; Currently you trade increased complexity and reduced maintainability for increased code quality brought about by unit testing.&amp;#160; &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Microsoft Fakes decouples Dependency Injection from unit testing, therefore changing the value proposition for Dependency Injection to instead be weighed on its own merits of whether or not it adds value to the problem domain in question.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Proper unit testing can now be integrated into any codebase, legacy or new, small or large, and using Dependency Injection or not.&amp;#160; With this in mind Microsoft Fakes is a game changer.&amp;#160; Why a game changer now, presumably years after these features have been available in the wild?&amp;#160; &lt;/p&gt;  &lt;p&gt;The answer is widespread availability and acceptance.&amp;#160; Anyone running Visual Studio will be able to run this (hopefully this will be part of the bare SDK as well).&amp;#160; Additionally examples, documentation, blogs and training will be much more readily available.&amp;#160; Faking may very well become a recommended practice along with unit testing at which point it could become as pervasive as general unit testing in .NET solutions.&amp;#160; It’s a lot easier to justify its usage when everyone has access to it, not just those willing to shell out $299 to $799 a seat.&lt;/p&gt;  &lt;h2&gt;Shims vs Stubs&lt;/h2&gt;  &lt;p&gt;Let’s take a look at the current MSDN definition for &lt;a href="http://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx"&gt;Shims and Stubs&lt;/a&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;Stub types&lt;/strong&gt; Stub types make it easy to test code that consumes interfaces or non-sealed classes with overridable methods. A stub of the type T provides a default implementation of each virtual member of T, that is, any non-sealed virtual or abstract method, property, or event. The default behavior can be dynamically customized for each member by attaching a delegate to a corresponding property of the stub. A stub is realized by a distinct type which is generated by the Fakes Framework. As a result, all stubs are strongly typed.&lt;/p&gt;    &lt;p&gt;Although stub types can be generated for interfaces and non-sealed classes with overridable methods, they cannot be used for static or non-overridable methods. To address these cases, the Fakes Framework also generates shim types.&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;Shim types&lt;/strong&gt; Shim types allow detouring of hard-coded dependencies on static or non-overridable methods. A shim of type T can provide an alternative implementation for each non-abstract member of T. The Fakes Framework will redirect method calls to members of T to the alternative shim implementation. The shim types rely on runtime code rewriting that is provided by a custom profiler.&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;Delegates&lt;/strong&gt; Both stub types and shim types allow you to use delegates to dynamically customize the behavior of individual stub members.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Stub types appear to be what most free and/or open source mocking frameworks already do for us today, so there’s really no surprises here.&amp;#160; Shim types on the other hand are where the action is at allowing us to detour static or non-overridable methods.&amp;#160; &lt;/p&gt;  &lt;p&gt;MSDN mentions that the detouring in shims does degrade performance slightly.&amp;#160; In the brief amount of testing I’ve done there’s about a 20ms difference between shimmed vs stubbed implementation of the same code, which isn’t a deal breaker in terms of keeping tests fast.&amp;#160; It would make sense the cost could be additive based on the amount of detouring you end up doing.&amp;#160; So if you have the infrastructure to do either or, then pick stubbing over shimming.&amp;#160; &lt;/p&gt;  &lt;h2&gt;Getting Started with Shims&lt;/h2&gt;  &lt;p&gt;First off, you’ll need Visual Studio 11, fire it up and create a new C# Class Library project called &lt;em&gt;FakingExample&lt;/em&gt;.&amp;#160; For this example I’ve put together a very trivial cart example to play with.&lt;/p&gt;  &lt;p&gt;Rename the default class file to &lt;em&gt;CartToShim&lt;/em&gt; and modify the code to be as follows: &lt;/p&gt;  &lt;pre class="brush: csharp; toolbar: false;"&gt;using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace FakingExample
{
    public class CartToShim
    {
        public int CartId { get; private set; }
        public int UserId { get; private set; }
        private List&amp;lt;CartItem&amp;gt; _cartItems = new List&amp;lt;CartItem&amp;gt;();
        public ReadOnlyCollection&amp;lt;CartItem&amp;gt; CartItems { get; private set; }
        public DateTime CreateDateTime { get; private set; }

        public CartToShim(int cartId, int userId)
        {
            CartId = cartId;
            UserId = userId;
            CreateDateTime = DateTime.Now;
            CartItems = new ReadOnlyCollection&amp;lt;CartItem&amp;gt;(_cartItems);
        }

        public void AddCartItem(int productId)
        {
            var cartItemId = DataAccessLayer.SaveCartItem(CartId, productId);
            _cartItems.Add(new CartItem(cartItemId, productId));
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Add the &lt;em&gt;CartItem&lt;/em&gt; class.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false;"&gt;namespace FakingExample
{
    public class CartItem
    {
        public int CartItemId { get; private set; }
        public int ProductId { get; private set; }

        public CartItem(int cartItemId, int productId)
        {
            CartItemId = cartItemId;
            ProductId = productId;
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Add the &lt;em&gt;DataAccessLayer&lt;/em&gt; class. Don’t worry about the connection string, we’ll never end up hitting it anyway.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false;"&gt;using System.Data;
using System.Data.SqlClient;

namespace FakingExample
{
    public static class DataAccessLayer
    {
        public static int SaveCartItem(int cartId, int productId)
        {
            using (var conn = new SqlConnection(&amp;quot;RandomSqlConnectionString&amp;quot;))
            {
                var cmd = new SqlCommand(&amp;quot;InsCartItem&amp;quot;, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue(&amp;quot;@CartId&amp;quot;, cartId);
                cmd.Parameters.AddWithValue(&amp;quot;@ProductId&amp;quot;, productId);

                conn.Open();
                return (int)cmd.ExecuteScalar();
            }
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Next add a Unit Test Project called &lt;em&gt;FakingExample.Tests&lt;/em&gt; and rename the default unit test class file to &lt;em&gt;CartToShimTests&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;In the &lt;em&gt;FakingExample.Tests&lt;/em&gt; project add a reference to the &lt;em&gt;FakingExample&lt;/em&gt; project.&amp;#160; You’re solution should look as follows:&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="InitialSolutionConfig" border="0" alt="InitialSolutionConfig" src="http://www.richonsoftware.com/image.axd?picture=InitialSolutionConfig_4.png" width="409" height="346" /&gt;&lt;/p&gt;

&lt;p&gt;Right click on the &lt;em&gt;FakingExample&lt;/em&gt; reference in &lt;em&gt;FakingExample.Tests&lt;/em&gt; references and select the “Add Fakes Assembly”.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="AddFakesAssembly" border="0" alt="AddFakesAssembly" src="http://www.richonsoftware.com/image.axd?picture=AddFakesAssembly_3.png" width="409" height="253" /&gt;&lt;/p&gt;

&lt;p&gt;This adds a couple of new items to the project.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="AfterFakes" border="0" alt="AfterFakes" src="http://www.richonsoftware.com/image.axd?picture=AfterFakes_3.png" width="409" height="295" /&gt;&lt;/p&gt;

&lt;p&gt;The new references add the following types.&lt;/p&gt;

&lt;p&gt;&lt;font style="background-color: #ffff00"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="NewTypes" border="0" alt="NewTypes" src="http://www.richonsoftware.com/image.axd?picture=NewTypes.png" width="457" height="526" /&gt;&lt;/font&gt;&lt;/p&gt;

&lt;p&gt;The .fakes file created under the Fakes folder turns out to be an xml file.&amp;#160; The file provides a configuration file for the generation of the fakes assembly. I’ll cover more about what can be done in this file later on in the post.&amp;#160; For now here’s a look at the default code generated output.&lt;/p&gt;

&lt;pre class="brush: xml; toolbar: false;"&gt;&amp;lt;Fakes xmlns=&amp;quot;http://schemas.microsoft.com/fakes/2011/&amp;quot;&amp;gt;
  &amp;lt;Assembly Name=&amp;quot;FakingExample&amp;quot;/&amp;gt;
&amp;lt;/Fakes&amp;gt;&lt;/pre&gt;

&lt;p&gt;Now we’re ready to do some faking.&amp;#160; Let’s take a look at unit testing the &lt;em&gt;AddCartItem&lt;/em&gt; method.&amp;#160; &lt;em&gt;AddCartItem&lt;/em&gt; calls &lt;em&gt;SaveCartItem&lt;/em&gt; on &lt;em&gt;DataAccessLayer&lt;/em&gt;, which happens to be static.&amp;#160; We’re going to mock out that database call to isolate the logic in &lt;em&gt;AddCartItem&lt;/em&gt; in our unit test. Add the code below to &lt;em&gt;CartToShimTests&lt;/em&gt;.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false;"&gt;using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FakingExample.Tests
{
    [TestClass]
    public class CartToShimTests
    {
        [TestMethod]
        public void AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart()
        {
            //Create a context to scope and cleanup shims
            using (ShimsContext.Create())
            {
                int cartItemId = 42, cartId = 1, userId = 33, productId = 777;

                //Shim SaveCartItem rerouting it to a delegate which 
                //always returns cartItemId
                Fakes.ShimDataAccessLayer.SaveCartItemInt32Int32 = (c, p) =&amp;gt; cartItemId;

                var cart = new CartToShim(cartId, userId);
                cart.AddCartItem(productId);

                Assert.AreEqual(cartId, cart.CartItems.Count);
                var cartItem = cart.CartItems[0];
                Assert.AreEqual(cartItemId, cartItem.CartItemId);
                Assert.AreEqual(productId, cartItem.ProductId);
            }
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Line 13 creates a ShimsContext , which limits the scope of our shimming.&amp;#160; Line 19 defines our shim/detour for the &lt;em&gt;SaveCartItem&lt;/em&gt; method.&amp;#160; Notice how we set the new behavior through a property named SaveCartItemInt32Int32. The Int32Int32 on the end is the type signature of parameters accepted by &lt;em&gt;SaveCartItem&lt;/em&gt;. Microsoft Fakes has to keep the generated property names unique and predictable for methods, since they could have overloads or be refactored to have them someday.&amp;#160; Now let’s run it in Unit Test Explorer and see if it passes.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="TestrunAfterShim" border="0" alt="TestrunAfterShim" src="http://www.richonsoftware.com/image.axd?picture=TestrunAfterShim_1.png" width="756" height="220" /&gt;&lt;/p&gt;

&lt;p&gt;It does indeed pass.&amp;#160; Notice that our shim/detour completely skipped over the &lt;em&gt;SaveCartItem&lt;/em&gt; method in &lt;em&gt;DataAccessLayer&lt;/em&gt;, if it hadn’t then we would’ve received a nasty exception since “RandomSqlConnectionString” is clearly not a valid connection string . Start to finish, this ends up being pretty easy to setup and use for our simple cart example.&amp;#160; &lt;/p&gt;

&lt;h2&gt;Stubs Example&lt;/h2&gt;

&lt;p&gt;For the stubs example our code will be very similar to the shim example however we’ll need to create an &lt;em&gt;ICartSaver &lt;/em&gt;interface and inject it into the &lt;em&gt;CartToStub&lt;/em&gt; object.&amp;#160; At which point we can stub out &lt;em&gt;ICartSaver&lt;/em&gt; and have it return 42 just as we did for shimming.&amp;#160; We’ll manually inject the dependency as opposed to pulling down a DI framework.&lt;/p&gt;

&lt;p&gt;Add a new interface &lt;em&gt;ICartSaver&lt;/em&gt; to the &lt;em&gt;FakingExample&lt;/em&gt; project.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false;"&gt;namespace FakingExample
{
    public interface ICartSaver
    {
        int SaveCartItem(int cartId, int productId);
    }
}&lt;/pre&gt;

&lt;p&gt;Next up add, for completeness (although not necessary) add a &lt;em&gt;CartSaver&lt;/em&gt; class to the &lt;em&gt;FakingExample&lt;/em&gt; project so we can replicate the implementation of &lt;em&gt;DataAccessLayer&lt;/em&gt;.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false;"&gt;using System.Data;
using System.Data.SqlClient;

namespace FakingExample
{
    public class CartSaver : ICartSaver
    {
        public int SaveCartItem(int cartId, int productId)
        {
            using (var conn = new SqlConnection(&amp;quot;RandomSqlConnectionString&amp;quot;))
            {
                var cmd = new SqlCommand(&amp;quot;InsCartItem&amp;quot;, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue(&amp;quot;@CartId&amp;quot;, cartId);
                cmd.Parameters.AddWithValue(&amp;quot;@ProductId&amp;quot;, productId);

                conn.Open();
                return (int)cmd.ExecuteScalar();
            }
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Create a new &lt;em&gt;CartToStub&lt;/em&gt; class as follows similar to &lt;em&gt;CartToShim&lt;/em&gt; but allowing for manual dependency injection of &lt;em&gt;ICartSaver &lt;/em&gt;in the constructor:&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false;"&gt;using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace FakingExample
{
    public class CartToStub
    {
        public int CartId { get; private set; }
        public int UserId { get; private set; }
        private List&amp;lt;CartItem&amp;gt; _cartItems = new List&amp;lt;CartItem&amp;gt;();
        public ReadOnlyCollection&amp;lt;CartItem&amp;gt; CartItems { get; private set; }
        public DateTime CreateDateTime { get; private set; }
        private ICartSaver _cartSaver;

        public CartToStub(int cartId, int userId, ICartSaver cartSaver)
        {
            CartId = cartId;
            UserId = userId;
            CreateDateTime = DateTime.Now;
            _cartSaver = cartSaver;
            CartItems = new ReadOnlyCollection&amp;lt;CartItem&amp;gt;(_cartItems);
        }

        public void AddCartItem(int productId)
        {
            var cartItemId = _cartSaver.SaveCartItem(CartId, productId);
            _cartItems.Add(new CartItem(cartItemId, productId));
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Moving back over to the &lt;em&gt;FakingExample.Tests&lt;/em&gt; project, add a new unit test file named &lt;em&gt;CartToStubTests&lt;/em&gt;.&amp;#160; Create/Modify the &lt;em&gt;AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart&lt;/em&gt; method to take into account the new changes.&lt;/p&gt;

&lt;pre class="brush: csharp; toolbar: false;"&gt;using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FakingExample.Tests
{
    [TestClass]
    public class CartToStubTests
    {
        [TestMethod]
        public void AddCartItem_GivenCartAndProduct_ThenProductShouldBeAddedToCart()
        {
            int cartItemId = 42, cartId = 1, userId = 33, productId = 777;

            //Stub ICartSaver and customize the behavior via a 
            //delegate, ro return cartItemId
            var cartSaver = new Fakes.StubICartSaver();
            cartSaver.SaveCartItemInt32Int32 = (c, p) =&amp;gt; cartItemId;

            var cart = new CartToStub(cartId, userId, cartSaver);
            cart.AddCartItem(productId);

            Assert.AreEqual(cartId, cart.CartItems.Count);
            var cartItem = cart.CartItems[0];
            Assert.AreEqual(cartItemId, cartItem.CartItemId);
            Assert.AreEqual(productId, cartItem.ProductId);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Run the unit tests once more to see that everything’s passing.&lt;/p&gt;

&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="TestrunAfterStub" border="0" alt="TestrunAfterStub" src="http://www.richonsoftware.com/image.axd?picture=TestrunAfterStub_1.png" width="756" height="220" /&gt;&lt;/p&gt;

&lt;p&gt;Just as with shims, start to finish, this ends up being pretty easy overall for our simple cart example.&lt;/p&gt;

&lt;h2&gt;The Fakes Xml File&lt;/h2&gt;

&lt;p&gt;The current MSDN library documentation details the nature of the .fakes xml file as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The generation of stub types is configured in an XML file that has the .fakes file extension. The Fakes framework integrates in the build process through custom MSBuild tasks and detects those files at build time. The Fakes code generator compiles the stub types into an assembly and adds the reference to the project.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The .fakes file provides fine grained control of how stub and shim generation work for a particular assembly.&amp;#160; Luckily enough the file has intellisense and pretty good descriptions when hovering, so exploration of features is rather straight forward.&amp;#160; Expanding out all attributes and elements using intellisense provides us with the following structures.&lt;/p&gt;

&lt;pre class="brush: xml; toolbar: false;"&gt;&amp;lt;Fakes xmlns=&amp;quot;http://schemas.microsoft.com/fakes/2011/&amp;quot;&amp;gt;
  &amp;lt;Assembly Name=&amp;quot;&amp;quot; Location=&amp;quot;&amp;quot; Version=&amp;quot;&amp;quot; x86=&amp;quot;&amp;quot;/&amp;gt;

  &amp;lt;StubGeneration Disable=&amp;quot;&amp;quot; SkipVirtualIndexers=&amp;quot;&amp;quot; SkipVirtualMethods=&amp;quot;&amp;quot;&amp;gt;
    &amp;lt;Clear /&amp;gt;
    &amp;lt;Add AbstractClasses=&amp;quot;&amp;quot; FullName=&amp;quot;&amp;quot; Interfaces=&amp;quot;&amp;quot; Namespace=&amp;quot;&amp;quot; TypeName=&amp;quot;&amp;quot;/&amp;gt;
    &amp;lt;Remove AbstractClasses=&amp;quot;&amp;quot; FullName=&amp;quot;&amp;quot; Interfaces=&amp;quot;&amp;quot; Namespace=&amp;quot;&amp;quot; Obsolete=&amp;quot;&amp;quot; TypeName=&amp;quot;&amp;quot;/&amp;gt;
  &amp;lt;/StubGeneration&amp;gt;

  &amp;lt;ShimGeneration Disable=&amp;quot;&amp;quot;&amp;gt;
    &amp;lt;Clear /&amp;gt;
    &amp;lt;Add FullName=&amp;quot;&amp;quot; Namespace=&amp;quot;&amp;quot; TypeName=&amp;quot;&amp;quot;/&amp;gt;
    &amp;lt;Remove FullName=&amp;quot;&amp;quot; Namespace=&amp;quot;&amp;quot; Obsolete=&amp;quot;&amp;quot; TypeName=&amp;quot;&amp;quot;/&amp;gt;
  &amp;lt;/ShimGeneration&amp;gt;

  &amp;lt;Compilation Debug=&amp;quot;&amp;quot; DisableCodeContracts=&amp;quot;&amp;quot; KeyFile=&amp;quot;&amp;quot; ProjectTemplate=&amp;quot;&amp;quot;&amp;gt;
    &amp;lt;COMReference Guid=&amp;quot;&amp;quot; VersionMajor=&amp;quot;&amp;quot; VersionMinor=&amp;quot;&amp;quot; WrapperTool=&amp;quot;&amp;quot;/&amp;gt;
    &amp;lt;Property Condition=&amp;quot;&amp;quot; Name=&amp;quot;&amp;quot; /&amp;gt;
  &amp;lt;/Compilation&amp;gt;
&amp;lt;/Fakes&amp;gt;&lt;/pre&gt;

&lt;p&gt;Based on this we see the following features:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Either shimming or stubbing can be completely turned off &lt;/li&gt;

  &lt;li&gt;Shims and stubs can be filtered such that only specific items from an assembly are shimmed and/or stubbed &lt;/li&gt;

  &lt;li&gt;Strong signing can be overridden via the &lt;em&gt;KeyFile&lt;/em&gt; attribute, based on the MSDN docs the Fakes framework will automatically sign the .Fakes assembly with the same key the source assembly was signed with unless overridden here &lt;/li&gt;

  &lt;li&gt;There’s a facility to reference/deal with a COM component with &lt;em&gt;COMReference &lt;/em&gt;if necessary.&amp;#160; Hopefully it won’t be… &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Aside from items within the compilation element everything is along the lines of what we’d expect to be available here.&amp;#160; I imagine in most circumstances this file won’t need to be touched, however if you’re faking a larger library like mscorlib, then it would seem almost mandatory to filter the types generated otherwise the compiler could be chewing on it for a while.&amp;#160; The classic DateTime.Now shimming examples should probably be doing this type of filtering.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;All in all I’m really excited about Microsoft Fakes.&amp;#160; It has the capacity to drive change in the .NET testing landscape similarly to how adding unit testing to Visual Studio (back in the 2005 version I believe) did so.&amp;#160; Widespread inclusion, usage and education of faking/mocking will be very beneficial for the community and will help drive innovation of testing techniques. Projects which would’ve been considered difficult if not impossible to add some level of unit testing to, without large amounts of refactoring, can now be unit tested easily.&amp;#160; Microsoft Fakes is a definitive win in my book.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The code for this post is available on &lt;a href="https://github.com/RichCzyzewski/MicrosoftFakesExamples"&gt;GitHub&lt;/a&gt;&lt;/p&gt;</description>
      <link>http://feedproxy.google.com/~r/RichOnSoftware/~3/asRhvZAF004/post.aspx</link>
      <comments>http://www.richonsoftware.com/post/2012/04/05/Using-Stubs-and-Shim-to-Test-with-Microsoft-Fakes-in-Visual-Studio-11.aspx#comment</comments>
      <guid isPermaLink="false">http://www.richonsoftware.com/post.aspx?id=2b8dd2f4-9c58-4350-9d86-6231fc604b7f</guid>
      <pubDate>Thu, 05 Apr 2012 23:29:00 -0400</pubDate>
      <category>Unit Testing</category>
      <dc:publisher>Rich Czyzewski</dc:publisher>
      <pingback:server>http://www.richonsoftware.com/pingback.axd</pingback:server>
      <pingback:target>http://www.richonsoftware.com/post.aspx?id=2b8dd2f4-9c58-4350-9d86-6231fc604b7f</pingback:target>
      <slash:comments>18</slash:comments>
      <trackback:ping>http://www.richonsoftware.com/trackback.axd?id=2b8dd2f4-9c58-4350-9d86-6231fc604b7f</trackback:ping>
      <wfw:comment>http://www.richonsoftware.com/post/2012/04/05/Using-Stubs-and-Shim-to-Test-with-Microsoft-Fakes-in-Visual-Studio-11.aspx#comment</wfw:comment>
      <wfw:commentRss>http://www.richonsoftware.com/syndication.axd?post=2b8dd2f4-9c58-4350-9d86-6231fc604b7f</wfw:commentRss>
    <feedburner:origLink>http://www.richonsoftware.com/post.aspx?id=2b8dd2f4-9c58-4350-9d86-6231fc604b7f</feedburner:origLink></item>
    <item>
      <title>Windows 8 Consumer Preview on Lenovo S10-3T</title>
      <description>&lt;p&gt;With the announcement of the 2nd release of Windows 8 “The Consumer preview edition” back in February I thought it would be a good time to finally crack it open and take a look.&amp;#160; I’m interested from several different perspectives:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Is this thing even usable as a tablet and subsequently as a desktop. &lt;/li&gt;    &lt;li&gt;How consumer and corporation friendly is it. &lt;/li&gt;    &lt;li&gt;How polished is it in it’s current state (perhaps inferring some relative release timeframe). &lt;/li&gt;    &lt;li&gt;Is Html5/JavaScript app development done in such a way that it’s likely to catch on the way Microsoft expects. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;To start with though, I need to get Windows 8 installed somewhere and that’s what this post is all about.&amp;#160; Luckily enough I’ve had a Lenovo S10-3T netbook for a little while now and it generally acts as a living room/kitchen browsing machine.&amp;#160; In other words, the perfect machine to cannibalize!&amp;#160; Windows 8 will install onto the S10-3T with a little elbow grease. To get started, let’s take a look at the installation requirements of Windows 8 and the hardware specs for the S10-3T. &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="IMG_0902" border="0" alt="IMG_0902" src="http://www.richonsoftware.com/image.axd?picture=IMG_0902.jpg" width="575" height="480" /&gt;&lt;/p&gt;  &lt;h2&gt;S10-3T Specs:&lt;/h2&gt;  &lt;table border="0" cellspacing="0" cellpadding="2" width="444"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="108"&gt;Processor&lt;/td&gt;        &lt;td valign="top" width="334"&gt;Intel Atom 1.66GHz N450&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="108"&gt;Ram&lt;/td&gt;        &lt;td valign="top" width="334"&gt;2GB DDR2&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="108"&gt;Hard drive&lt;/td&gt;        &lt;td valign="top" width="334"&gt;320GB 6400RPM SATA&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="108"&gt;Wi-Fi&lt;/td&gt;        &lt;td valign="top" width="334"&gt;802.11b/g/n&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="108"&gt;Screen type&lt;/td&gt;        &lt;td valign="top" width="334"&gt;Multi Touch Touch Screen - Swivel and Rotatable&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="108"&gt;Screen size&lt;/td&gt;        &lt;td valign="top" width="334"&gt;10.1&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="108"&gt;Resolution&lt;/td&gt;        &lt;td valign="top" width="334"&gt;1024 × 600&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;Note:&amp;#160; The Lenovo S10-3T&amp;#160; had several flavors of hardware, so your S10-3T may not necessarily have the same specs.&lt;/p&gt;  &lt;h2&gt;Windows 8 Consumer Preview’s Minimum System Requirements&lt;/h2&gt;  &lt;p&gt;From &lt;a href="http://windows.microsoft.com/en-US/windows-8/faq"&gt;Windows 8 Consumer Preview: Frequently asked questions&lt;/a&gt;&lt;/p&gt;  &lt;table border="0" cellspacing="0" cellpadding="2" width="527"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="106"&gt;Processor&lt;/td&gt;        &lt;td valign="top" width="419"&gt;1GHz or faster 32 Bit or 64 Bit&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="106"&gt;Ram&lt;/td&gt;        &lt;td valign="top" width="419"&gt;1GB for 32 Bit and 2GB for 64 Bit&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="106"&gt;Hard disk space&lt;/td&gt;        &lt;td valign="top" width="419"&gt;16GB Available hard disk Space for 32 Bit and 20 GB Available Hard Disk Space for 64 Bit PC's&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="106"&gt;Graphics card&lt;/td&gt;        &lt;td valign="top" width="419"&gt;DirectX 9 Graphics Device with WDDM 1.0 or higher driver.&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="106"&gt;Resolution&lt;/td&gt;        &lt;td valign="top" width="419"&gt;???&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;Additional requirements to use certain features:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;To use touch, you need a tablet or a monitor that supports multitouch. &lt;/li&gt;    &lt;li&gt;To access the Windows Store and to download and run apps, you need an active Internet connection and a screen resolution of at least 1024 x 768. &lt;/li&gt;    &lt;li&gt;To snap apps, you need a screen resolution of at least 1366 x 768. &lt;/li&gt; &lt;/ul&gt;  &lt;h2&gt;Resolution Issue&lt;/h2&gt;  &lt;p&gt;Initially this looks to be a pretty grim issue.&amp;#160; The S10-3T only has a max resolution of (1024 x 600) and the minimal resolution “To access the Windows Store and to download and run apps” is 1024 x 768.&amp;#160; Oddly enough Windows 8 will let you install on lower resolutions (perhaps this’ll be changed by release), however I can’t imagine the experience being all that spectacular without being able to download and run apps. &lt;/p&gt;  &lt;p&gt;Searching the internet for workarounds reveals a handful of people already having installed Windows 8 on the S10-3T (albeit the previous preview) using a registry hack to enable higher resolutions via down scaling (more specifically 1024 x 768 and 1152 x 864).&amp;#160; See &lt;a href="http://liliputing.com/2011/09/how-to-enable-windows-8-metro-style-apps-on-an-older-netbook.html"&gt;liliputing.com&lt;/a&gt; and &lt;a href="http://www.lenovos103t.com/2010/05/change-resolutions.html"&gt;lenovos103t.com&lt;/a&gt;/&lt;a href="http://www.jessebandersen.com/2012/02/lenovo-ideapad-s10-3t-increase-dpi-and.html"&gt;jessebandersen.com&lt;/a&gt; for more information. But what is down scaling actually doing?&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;In &lt;a href="http://en.wikipedia.org/wiki/Numerical_weather_prediction"&gt;numerical modeling&lt;/a&gt;, &lt;b&gt;downscaling&lt;/b&gt; refers to techniques that take output from the model and add information at scales smaller than the &lt;a href="http://en.wikipedia.org/w/index.php?title=Grid_spacing&amp;amp;action=edit&amp;amp;redlink=1"&gt;grid spacing&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;font size="1"&gt;Quoted from: &lt;/font&gt;&lt;a href="http://en.wikipedia.org/wiki/Downscaling"&gt;&lt;font size="1"&gt;http://en.wikipedia.org/wiki/Downscaling&lt;/font&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;In other words we still only have 600 physical pixels, we’re just jamming 768/864 worth of pixel data into 600 pixels of space and hoping for the best.&amp;#160; Display properties will show the increased resolution of 1024 x 768 and 1152 x 864, but under the covers the operating system will down scale that to 600 pixels.&amp;#160; The other downside is that the aspect ratios are slightly different, so the display is going to look somewhat stretched horizontally. All in all this isn’t a perfect solution, however it’s the only solution.&amp;#160; Additionally looking at some screen shots online was reassuring enough in that the horizontal stretch isn’t unreasonable.&amp;#160; If it’s between down scaling or no apps, I’ll take the down scaling. &lt;/p&gt;  &lt;p&gt;Note: I’ll get into the exact details of how to do this during implementation.&lt;/p&gt;  &lt;h2&gt;32 Bit or 64 Bit&lt;/h2&gt;  &lt;p&gt;With the Windows 8 Consumer Preview we have the choice of pulling down either the 32 bit version or the 64 bit version.&amp;#160; Additionally the S10-3T’s hardware is 64 bit compatible.&amp;#160; After a little bit research it looks like 32 bit is the clear winner in this case.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;There are very few advantages to 64 bit for the S10-3T.&amp;#160; 64 bit windows programs actually take a little extra RAM because their memory pointers are a little bit bigger.&amp;#160; Therefore even at Idle the 64 bit system is taking more RAM memory.&lt;/p&gt;    &lt;p&gt;RAM usage with 32 bit OS at idle: about 480MB&lt;/p&gt;    &lt;p&gt;RAM usage with 64 bit OS at idle: about 650MB&lt;/p&gt;    &lt;p&gt;Also you have to remember that now the OS will try to run compatibility programs and therefore more processes which will slow your CPU and take RAM space.&lt;/p&gt;    &lt;p&gt;2GB is not a large amount of RAM and you are better of with the 32 bit os.&amp;#160; If you have 4GB RAM in a system then 64 bit seems like a better idea.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;font size="1"&gt;Quoted from: &lt;/font&gt;&lt;a href="http://www.lenovos103t.com/2010/03/32-bit-vs-64-bit-windows-7-on-s10-3t.html"&gt;&lt;font size="1"&gt;http://www.lenovos103t.com/2010/03/32-bit-vs-64-bit-windows-7-on-s10-3t.html&lt;/font&gt;&lt;/a&gt;&lt;/p&gt;  &lt;h2&gt;A Good Time for a Backup&lt;/h2&gt;  &lt;p&gt;I really had nothing important on my S10-3T, however I still created a full backup in just in case something did go horribly wrong.&amp;#160; Depending on your situation you may not need this step at all or may need to just backup a handful of files. Regardless, I have a license for &lt;a href="http://www.acronis.com/homecomputing/products/trueimage/"&gt;Acronis True Image&lt;/a&gt; and just used that to do a quick backup over the network.&amp;#160; The pricing is good and the product works, good enough in my book.&amp;#160; Only needed 20GB of space, which transferred over the LAN at a reasonable pace.&lt;/p&gt;  &lt;h2&gt;Warning Before Installation&lt;/h2&gt;  &lt;p&gt;After installation the WIFI was in the “off” state (as if it had been turned off via the fn key) and the necessary driver for fn key functionality is Lenovo specific and not part of Windows 8 Consumer Preview.&amp;#160; In my case I just plugged in an Ethernet cable and downloaded the necessary drivers.&amp;#160; You may want to download the drivers to a usb key first before continuing with installation if you’re only on WIFI. See the drivers section for more information.&lt;/p&gt;  &lt;h2&gt;Web Installer or ISO&lt;/h2&gt;  &lt;p&gt;The Web Installer option is probably the easiest option to use for installation, since the S10-3T doesn’t have a DVD drive, if you used the Web Installer skip to the next section.&amp;#160; &lt;/p&gt;  &lt;p&gt;In my case I started out looking for the ISO and didn’t even realize there was an installer until afterwards.&amp;#160; If you do go the ISO route, then you will need an external USB DVD drive.&amp;#160; I happened to have one lying around collecting dust so this option worked out pretty good. &lt;/p&gt;  &lt;p&gt;   &lt;table border="0" cellspacing="0" cellpadding="2" width="630"&gt;&lt;tbody&gt;       &lt;tr&gt;         &lt;td valign="top" width="200"&gt;Web Installer Download:&lt;/td&gt;          &lt;td valign="top" width="428"&gt;&lt;a href="http://windows.microsoft.com/en-US/windows-8/download"&gt;http://windows.microsoft.com/en-US/windows-8/download&lt;/a&gt;&lt;/td&gt;       &lt;/tr&gt;        &lt;tr&gt;         &lt;td valign="top" width="200"&gt;ISO Download:&lt;/td&gt;          &lt;td valign="top" width="428"&gt;&lt;a title="http://windows.microsoft.com/en-US/windows-8/iso" href="http://windows.microsoft.com/en-US/windows-8/iso"&gt;http://windows.microsoft.com/en-US/windows-8/iso&lt;/a&gt;&lt;/td&gt;       &lt;/tr&gt;     &lt;/tbody&gt;&lt;/table&gt; &lt;/p&gt;  &lt;p&gt;Burn the ISO to DVD using “Windows Disc Image Burner”, which should be in the Context Menu in Windows 7, unless you have another ISO burning program installed in which case you need to select “Open With” and then select “Windows Disc Image Burner”.&lt;/p&gt;  &lt;p&gt;Next up, hook up a USB DVD and boot from the DVD.&amp;#160; For some reason the S10-3T refused to boot from the DVD even with the boot order updated correctly to have the DVD before the hard drive.&amp;#160; I removed everything else (besides the DVD) from the bootable options and this forced it to boot from the DVD.&amp;#160; &lt;/p&gt;  &lt;p&gt;Once booted in to the installation DVD let it work it’s magic.&amp;#160; If you opted for the DVD/ISO install you need this product key during installation: NF32V-Q9P3W-7DR7Y-JGWRW-JFCK8 as detailed on the &lt;a href="http://windows.microsoft.com/en-US/windows-8/faq"&gt;Windows 8 Consumer Preview: Frequently asked questions&lt;/a&gt; page.&amp;#160; &lt;/p&gt;  &lt;p&gt;After the first reboot make sure to set your boot options back to normal in the bios.&lt;/p&gt;  &lt;h2&gt;A Couple of Reboots Later&lt;/h2&gt;  &lt;p&gt;Windows 8 Consumer Preview should be installed after a couple of reboots. Go ahead and do all of the initial configuration and log in. Notice that Windows 8 appears to be working relatively fine despite our low resolution (the true minimum resolution must be less than 1024 x 600).&amp;#160; Note: I had already logged in and customized a few things by the time this screen shot was taken so you’re Start screen may look slightly different.&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="Win8StartLowRes" border="0" alt="Win8StartLowRes" src="http://www.richonsoftware.com/image.axd?picture=Win8StartLowRes.png" width="640" height="375" /&gt;&lt;/p&gt;  &lt;h2&gt;Increasing the Resolution&lt;/h2&gt;  &lt;p&gt;Now that we have Windows 8 running it’s time to tackle the resolution issue.&amp;#160; Per the Minimum System Requirements “To access the Windows Store and to download and run apps, you need an active Internet connection and a screen resolution of at least 1024 x 768. ”&amp;#160; and we certainly want to download and run apps otherwise running the preview wouldn’t be very interesting or useful. &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Swipe from right to left towards the right edge of the screen and select the Search icon in the upper right. &lt;/li&gt;    &lt;li&gt;Type “regedit” into the “Search&amp;#160; Apps” box and then start regedit.      &lt;br clear="all" /&gt;      &lt;br clear="all" /&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="Win8RegeditSearch" border="0" alt="Win8RegeditSearch" src="http://www.richonsoftware.com/image.axd?picture=Win8RegeditSearch.png" width="640" height="375" /&gt;      &lt;br clear="all" /&gt;&lt;/li&gt;    &lt;li&gt;Search for “Display1_DownScalingSupported” (Ctrl-F) in the registry and change the value from 0 to 1      &lt;br clear="all" /&gt;      &lt;br clear="all" /&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=Win8RegistrySearch.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="Win8RegistrySearch" border="0" alt="Win8RegistrySearch" src="http://www.richonsoftware.com/image.axd?picture=Win8RegistrySearch_thumb.png" width="640" height="440" /&gt;&lt;/a&gt;      &lt;br clear="all" /&gt;      &lt;br clear="all" /&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=Win8RegistryEdit.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="Win8RegistryEdit" border="0" alt="Win8RegistryEdit" src="http://www.richonsoftware.com/image.axd?picture=Win8RegistryEdit_thumb.png" width="640" height="439" /&gt;&lt;/a&gt;      &lt;br clear="all" /&gt;&lt;/li&gt;    &lt;li&gt;&lt;font style="background-color: #ffff00"&gt;&lt;/font&gt;&lt;font style="style"&gt;Repeat for additional entries of “Display1_DownScalingSupported” (F3 for Find Next) in the registry&lt;/font&gt;&lt;/li&gt;    &lt;li&gt;Reboot&lt;/li&gt;    &lt;li&gt;Go back to the Search entry as done in step 1&lt;/li&gt;    &lt;li&gt;Select the “Settings” option and type in “display” into the search box&lt;/li&gt;    &lt;li&gt;Select “Change display settings” and adjust the screens resolution to either 1024x768 or 1152x864.     &lt;br clear="all" /&gt;      &lt;br clear="all" /&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=NewResolutionScreen.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="NewResolutionScreen" border="0" alt="NewResolutionScreen" src="http://www.richonsoftware.com/image.axd?picture=NewResolutionScreen_thumb.png" width="640" height="375" /&gt;&lt;/a&gt;      &lt;br clear="all" /&gt;&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;&lt;font style="background-color: #ffff00"&gt;&lt;/font&gt;&lt;font style="style"&gt;Now we have a resolution that we can experience most of Windows 8 with.&amp;#160; The only thing we’re missing out on is the ability to “snap” apps, which isn’t that big a deal.&lt;/font&gt;&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="Win8StartHighRes" border="0" alt="Win8StartHighRes" src="http://www.richonsoftware.com/image.axd?picture=Win8StartHighRes.png" width="640" height="480" /&gt;&lt;/p&gt;    &lt;h2&gt;Drivers&lt;/h2&gt;  &lt;p&gt;As mentioned above in the “Warning Before Installation” section, after installation there may be issues with the fn keys not working.&amp;#160; The WIFI started in the “off” state and without the fn key combo functionality there was no way to turn it on.&amp;#160; After plugging in an Ethernet cable and a few Google searches later I found &lt;a href="http://www.lenovos103t.com/2010/03/tip-3-upgrade-windows-and-optimize.html?showComment=1269632966441#c8967968288909525843"&gt;this post&lt;/a&gt; from Jesse B Andersen describing the drivers required to get the fn keys and power management to work.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Sam, thanks for sharing the 64bit experience! I'm unsure if the drivers from Lenovo are meant to work with 64bit, but you are our first 64bit tester.     &lt;br /&gt;The brightness setting could be part of Lenovo's Energy Management. The Fn stuff is from the Intel Chipset driver if I remember right.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Go to &lt;a href="http://consumersupport.lenovo.com/us/en/DriversDownloads/drivers_list.aspx?CategoryID=45252"&gt;Lenovo’s drivers download page&lt;/a&gt; and install the drivers from the Chipset category for Windows 7.&amp;#160; &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="ChipDriver" border="0" alt="ChipDriver" src="http://www.richonsoftware.com/image.axd?picture=ChipDriver.png" width="612" height="302" /&gt;&lt;/p&gt;  &lt;p&gt;At this point most fn keys should be working.&amp;#160; Since Lenovo’s drivers wire up the fn key for WIFI to Lenovo’s Energy Management suite, it needs to be installed as well.&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="PowerDriver" border="0" alt="PowerDriver" src="http://www.richonsoftware.com/image.axd?picture=PowerDriver.png" width="618" height="238" /&gt;&lt;/p&gt;  &lt;p&gt;After the installation WIFI should now be toggleable with the fn key and we’re good to go.&amp;#160; Note that the toggle window will only show in desktop mode.&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;Although installing Windows 8 Consumer Preview on the S10-3T can be a little involved and tricky at times, the payout in terms of usability and performance are well worth it.&amp;#160; Windows 8 has given my S10-3T a new lease on life.&amp;#160; It’s like a brand new machine.&amp;#160; The touch features are dead on, touch dragging, touch scrolling and pinch zooming work smoothly.&amp;#160; After seeing the performance benefits I’d have a hard time justifying reverting to Windows 7. Now I just have to figure out how to use it and how to put together a few test apps. &lt;/p&gt;  &lt;p&gt;If you’re interested in dual booting with Windows 7 there’s a good guide posted at &lt;a href="http://lucienkblog.wordpress.com/2012/03/04/installing-dual-boot-windows-8-on-lenovo-s10-3t/"&gt;lucienkblog.wordpress.com&lt;/a&gt;&lt;/p&gt;</description>
      <link>http://feedproxy.google.com/~r/RichOnSoftware/~3/EjIC_eg_BPs/post.aspx</link>
      <comments>http://www.richonsoftware.com/post/2012/03/30/Windows-8-Consumer-Preview-on-Lenovo-S10-3T.aspx#comment</comments>
      <guid isPermaLink="false">http://www.richonsoftware.com/post.aspx?id=da5fb6a6-f44f-4ca8-8d44-288bbcd7f350</guid>
      <pubDate>Fri, 30 Mar 2012 21:29:00 -0400</pubDate>
      <category>Windows 8</category>
      <dc:publisher>Rich Czyzewski</dc:publisher>
      <pingback:server>http://www.richonsoftware.com/pingback.axd</pingback:server>
      <pingback:target>http://www.richonsoftware.com/post.aspx?id=da5fb6a6-f44f-4ca8-8d44-288bbcd7f350</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://www.richonsoftware.com/trackback.axd?id=da5fb6a6-f44f-4ca8-8d44-288bbcd7f350</trackback:ping>
      <wfw:comment>http://www.richonsoftware.com/post/2012/03/30/Windows-8-Consumer-Preview-on-Lenovo-S10-3T.aspx#comment</wfw:comment>
      <wfw:commentRss>http://www.richonsoftware.com/syndication.axd?post=da5fb6a6-f44f-4ca8-8d44-288bbcd7f350</wfw:commentRss>
    <feedburner:origLink>http://www.richonsoftware.com/post.aspx?id=da5fb6a6-f44f-4ca8-8d44-288bbcd7f350</feedburner:origLink></item>
    <item>
      <title>Converting BlogEngine.NET 2.5 to a Web Application</title>
      <description>&lt;p&gt;BlogEngine.NET 2.5 is currently distributed as a Web Site Project (WSP).&amp;nbsp; The project makes use of some of the WSP&amp;rsquo;s features to be more flexible for non technical end users.&amp;nbsp; For more technical users, who can recompile as necessary and don&amp;rsquo;t mind getting their hands dirty, a Web Application Project (WAP) conversion can provide some utility that the WSP can not.&amp;nbsp; You can find a guide of the pros and cons of each approach on MSDN: &lt;a href="http://msdn.microsoft.com/en-us/library/dd547590.aspx"&gt;Web Application Projects versus Web Site Projects&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Aside from a general preference of WAPs over WSPs my main reasons for converting are as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Deploying to Windows Azure is simpler with WAPs (I&amp;rsquo;ve been toying with the idea of putting this puppy up there, with the recent price drop)&lt;/li&gt;
&lt;li&gt;A single compiled assembly is easier to manage during deployment&lt;/li&gt;
&lt;li&gt;Web.config transforms can only be done on WAPs&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;At the time of this post there are a handful of forums posts, wiki articles and blog posts which somewhat describe the process of conversion (I&amp;rsquo;ve included links to all of these at the end of the post).&amp;nbsp; None of them capture all of the steps involved in conversion and the steps that were included weren&amp;rsquo;t always well detailed as one would like.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;After reviewing all of the available info and performing the conversion several times myself.&amp;nbsp; Here are the steps I&amp;rsquo;ve come up with and that I followed for the conversion of this site:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Pull down the BlogEngine.NET source code and open the solution in Visual Studio.&lt;/li&gt;
&lt;li&gt;Remove the BlogEngine.Net Website project from the solution.&lt;/li&gt;
&lt;li&gt;Navigate to the solution directory in Windows Explorer and rename the Website project&amp;rsquo;s folder from BlogEngine.NET to BlogEngine.NETOld or something similar.&amp;nbsp; Leave Windows Explorer open, we&amp;rsquo;ll be back there again. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="02_RenameFolder" src="http://www.richonsoftware.com/image.axd?picture=02_RenameFolder_2.png" alt="02_RenameFolder" width="497" height="226" border="0" /&gt;&lt;/li&gt;
&lt;li&gt;Add an ASP.NET Web Application project called &amp;ldquo;BlogEngine.NET&amp;rdquo; to the solution. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=03_NewWebApplicationProject_1.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="03_NewWebApplicationProject" src="http://www.richonsoftware.com/image.axd?picture=03_NewWebApplicationProject_thumb_1.png" alt="03_NewWebApplicationProject" width="640" height="442" border="0" /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Remove most of the default files from the new Web Application project, such that it looks like the image below. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="04_DeleteDefaultFiles" src="http://www.richonsoftware.com/image.axd?picture=04_DeleteDefaultFiles_2.png" alt="04_DeleteDefaultFiles" width="240" height="186" border="0" /&gt;&lt;/li&gt;
&lt;li&gt;In Windows Explorer, copy all files except Bin &amp;amp; Obj from the renamed BlogEngine.NETOld folder&amp;nbsp; to the new created BlogEngine.NET folder.&lt;/li&gt;
&lt;li&gt;In Visual Studio, click the &amp;ldquo;Show All Files&amp;rdquo; icon in the Solution Explorer.&lt;/li&gt;
&lt;li&gt;
&lt;div&gt;Right click the newly displayed files (with the exception of the aspnet_client and obj folders) and select &amp;ldquo;Include in Project&amp;rdquo; until your Solution looks like the image below.&amp;nbsp; Note: don&amp;rsquo;t forget to include the files and folders below the Account, Add_Data, Scripts &amp;amp; Styles folders. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="05_IncludedFilesAfterCopy" src="http://www.richonsoftware.com/image.axd?picture=05_IncludedFilesAfterCopy_2.png" alt="05_IncludedFilesAfterCopy" width="313" height="664" border="0" /&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Add a new folder called Custom_Code and move everything except the Helpers folder from App_Code folder to Custom_Code folder.&amp;nbsp; &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;
&lt;blockquote&gt;The app code directory is one of the major differences between WAP and WSP. Most of the files in app code need to be moved out of app code, to a non-magic-name directory. The Helpers, however, are Razor helper classes and will only work if you paste the directly into the razor views, or leave them in the App_Code directory.&lt;/blockquote&gt;
&lt;br clear="all" /&gt;
&lt;blockquote&gt;One consequence of moving the Extensions folder out of App_Code and into Custom_Code is that it will no longer be possible to view or edit the source code of an extension from the browser. This is good from a security perspective.
&lt;p&gt;If, however, you want that functionality, create an App_Code/Extension folder and place those extensions in there. Do not, however, put all the extensions back because some of the extensions that ship with the product have dependencies and need to be included in the main dll (like the captcha extension).&lt;/p&gt;
&lt;/blockquote&gt;
&lt;span style="font-size: x-small;"&gt; &lt;br clear="all" /&gt;Quoted from: &lt;/span&gt;&lt;a href="http://dev.milesquaretech.com/Blog/post/2011/08/18/Converting-BlogEnginenet-25-to-Web-Application-Project.aspx"&gt;&lt;span style="font-size: x-small;"&gt;Converting BlogEngine.net 2.5 to Web Application Project&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Create a Helpers folder under Custom_Code and move RazorHelpers.cs there from the Helpers folder in App_Code.&amp;nbsp; After steps 8 &amp;amp; 9 your Solution should be structured like the below image. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="06_FilesAfterMoves" src="http://www.richonsoftware.com/image.axd?picture=06_FilesAfterMoves_2.png" alt="06_FilesAfterMoves" width="288" height="498" border="0" /&gt;&lt;/li&gt;
&lt;li&gt;After moving the files from App_Code to Custom_Code the build action may be incorrect on many of the class files.&amp;nbsp; For each of the files in Custom_Code change the build action to Compile in the Properties window. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;&lt;a href="http://www.richonsoftware.com/image.axd?picture=07_CustomCodeBuildActions_1.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="07_CustomCodeBuildActions" src="http://www.richonsoftware.com/image.axd?picture=07_CustomCodeBuildActions_thumb_1.png" alt="07_CustomCodeBuildActions" width="640" height="420" border="0" /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;In the BlogEngine.NET project make sure you have the following references (use the 1.0.0.0 versions if there are multiple versions available): &lt;br clear="all" /&gt;
&lt;p&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="08_NewReferences" src="http://www.richonsoftware.com/image.axd?picture=08_NewReferences_1.png" alt="08_NewReferences" width="296" height="309" border="0" /&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;Add a project reference to BlogEngine.Core.&lt;/li&gt;
&lt;li&gt;Since we&amp;rsquo;ve technically moved the App_Code into a new assembly, we need to let the app know where it&amp;rsquo;s at.&amp;nbsp; Update the Web.Config pages section as follows:
&lt;pre class="brush: xml; toolbar: false;"&gt;&amp;lt;pages enableSessionState="false" enableViewStateMac="true" enableEventValidation="true" 
  controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"&amp;gt;
    &amp;lt;controls&amp;gt;
    &amp;lt;!--WAP FIX--&amp;gt;
    &amp;lt;!--&amp;lt;add namespace="App_Code.Controls" tagPrefix="blog"/&amp;gt;--&amp;gt;
    &amp;lt;add namespace="App_Code.Controls" assembly="BlogEngine.NET" tagPrefix="blog"/&amp;gt;
  &amp;lt;/controls&amp;gt;
&amp;lt;/pages&amp;gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;I had the async ctp installed on my pc, which makes async a reserved word and causes a handful of exceptions, so we&amp;rsquo;ll need to fix that.&amp;nbsp; Rename parameter async to asyncResult in BlogEngine.NET/Custom_Code/Controls/Blogroll.ProcessResponse. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;//WAP FIX
//private static void ProcessResponse(IAsyncResult async)
private static void ProcessResponse(IAsyncResult asyncResult)
{
    //WAP FIX
    //GetRequestData data = (GetRequestData)async.AsyncState;
    GetRequestData data = (GetRequestData)asyncResult.AsyncState;
    Blog.InstanceIdOverride = data.BlogInstanceId;
    var blogReq = data.BlogRequest;

    try
    {
        //WAP FIX
        //using (var response = (HttpWebResponse)blogReq.Request.EndGetResponse(async))
        using (var response = (HttpWebResponse)blogReq.Request.EndGetResponse(asyncResult))
        {
            var doc = new XmlDocument();
            var responseStream = response.GetResponseStream();&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;There&amp;rsquo;s a naming collision in themes between StandardSite and TitaniumX (WAP class names need to be unique). Rename BlogEngine.NET/themes/TitaniumX/site.master.cs from StandardSite to TitaniumSite class, change inherits in BlogEngine.NET/themes/TitaniumX/site.master as well. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;
&lt;pre class="brush: xml; toolbar: false;"&gt;&amp;lt;%@ Master Language="C#" AutoEventWireup="true" Inherits="TitaniumSite " Codebehind="site.master.cs" %&amp;gt;
&amp;lt;%@ Import Namespace="BlogEngine.Core" %&amp;gt;
&amp;lt;% //WAP FIX 
   //&amp;lt;%@ Master Language="C#" AutoEventWireup="true" CodeFile="site.master.cs" Inherits="StandardSite " %&amp;gt;&lt;/pre&gt;
&lt;br clear="all" /&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using BlogEngine.Core;

//WAP FIX
//public partial class StandardSite : System.Web.UI.MasterPage
public partial class TitaniumSite : System.Web.UI.MasterPage
{&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Update the BlogEngine.Core/Utils.CodeAssemblies method by replacing assembly names with BlogEngine.NET. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;public static IEnumerable&amp;lt;Assembly&amp;gt; CodeAssemblies()
{
    var codeAssemblies = new List&amp;lt;Assembly&amp;gt;();
    CompilationSection s = null;
    //WAP FIX
    //var assemblyName = "__code";
    var assemblyName = "BlogEngine.NET";
    try
    {
        try
        {
            s = (CompilationSection)WebConfigurationManager.GetSection("system.web/compilation");
        }
        catch (SecurityException)
        {
            // No read permissions on web.config due to the trust level (must be High or Full)
        }

        if (s != null &amp;amp;&amp;amp; s.CodeSubDirectories != null &amp;amp;&amp;amp; s.CodeSubDirectories.Count &amp;gt; 0)
        {
            for (var i = 0; i &amp;lt; s.CodeSubDirectories.Count; i++)
            {
                assemblyName = string.Format("App_SubCode_{0}", s.CodeSubDirectories[i].DirectoryName);
                codeAssemblies.Add(Assembly.Load(assemblyName));
            }
        }
        else
        {
            //WAP FIX
            //var assemblyName = "App_Code";
            assemblyName = "BlogEngine.NET";
            codeAssemblies.Add(Assembly.Load(assemblyName));
        }&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Update BlogEngine.Core/Web/Extensions/ManagedExtension.GetPathAndFilename&amp;nbsp; to point to the proper filename. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;public string GetPathAndFilename(bool checkExistence)
{
    string filename = string.Empty;
    var appRoot = HostingEnvironment.MapPath("~/");
    var codeAssemblies = Utils.CodeAssemblies();
    foreach (Assembly a in codeAssemblies)
    {
        var types = a.GetTypes();
        foreach (var type in types.Where(type =&amp;gt; type.Name == Name))
        {
            var assemblyName = type.Assembly.FullName.Split(".".ToCharArray())[0];
            assemblyName = assemblyName.Replace("App_SubCode_", "App_Code\\");
            var fileExt = assemblyName.Contains("VB_Code") ? ".vb" : ".cs";
            //WAP FIX
            //filename = appRoot + Path.Combine(Path.Combine(assemblyName, "Extensions"), Name + fileExt);
            filename += Path.Combine("Custom_Code\\Extensions", Name + fileExt);
        }
    }
&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Although this may not be absolutely necessary, since in WAP we won&amp;rsquo;t be writing changes to cs files from the admin screens anyway, it&amp;rsquo;s a good idea to clean up loose ends just the same. Update BlogEngine.NET/admin/Extensions/Editor.cshtml. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;var extensionFilename = ext.GetPathAndFilename(false);
//WAP FIX
//var canWrite = Utils.CanWrite(Href(Utils.ApplicationRelativeWebRoot + "App_Code/Extensions"));
var canWrite = Utils.CanWrite(Href(Utils.ApplicationRelativeWebRoot + "Custom_Code/Extensions"));
var fileExists = !string.IsNullOrWhiteSpace(extensionFilename) &amp;amp;&amp;amp; File.Exists(extensionFilename);
&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Convert to Web Application. &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="09_ConvertToWebApplication" src="http://www.richonsoftware.com/image.axd?picture=09_ConvertToWebApplication.png" alt="09_ConvertToWebApplication" width="372" height="420" border="0" /&gt; &lt;br clear="all" /&gt; &lt;br clear="all" /&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="10_WarningYes" src="http://www.richonsoftware.com/image.axd?picture=10_WarningYes.png" alt="10_WarningYes" width="488" height="178" border="0" /&gt;&lt;/li&gt;
&lt;li&gt;Success!&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;All in all the conversion wasn&amp;rsquo;t the most straight forward process, but not excessively complex by any means.&amp;nbsp; The most difficult part was nailing down the correct steps and the correct sequence.&amp;nbsp; After that, the conversion could be performed in under 30 mins.&amp;nbsp; If there&amp;rsquo;s enough interest, I&amp;rsquo;ll upload a converted solution to GitHub.&lt;/p&gt;
&lt;p&gt;For more information about BlogEngine.NET &lt;a title="http://www.dotnetblogengine.net/" href="http://www.dotnetblogengine.net/"&gt;http://www.dotnetblogengine.net/&lt;/a&gt; or &lt;a title="http://blogengine.codeplex.com/" href="http://blogengine.codeplex.com/"&gt;http://blogengine.codeplex.com/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;References&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://blogengine.codeplex.com/discussions/270218"&gt;Any have BE 2.5 running as Web Application Project?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://dev.milesquaretech.com/Blog/post/2011/08/18/Converting-BlogEnginenet-25-to-Web-Application-Project.aspx"&gt;Converting BlogEngine.net 2.5 to Web Application Project&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blogengine.codeplex.com/wikipage?title=Convert%20to%20Web%20Application"&gt;BlogEngine.NET - Convert to Web Application&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.jnouel.net/post/2011/04/15/Converting-BlogEngineNET-20-to-Web-Application-Project-(WAP).aspx"&gt;Converting BlogEngine.NET 2.0 to Web Application Project (WAP)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/aa983476.aspx"&gt;Walkthrough: Converting a Web Site Project to a Web Application Project in Visual Studio&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</description>
      <link>http://feedproxy.google.com/~r/RichOnSoftware/~3/iIk1n1btJQY/post.aspx</link>
      <comments>http://www.richonsoftware.com/post/2012/02/26/Converting-BlogEngineNET-25-to-a-Web-Application.aspx#comment</comments>
      <guid isPermaLink="false">http://www.richonsoftware.com/post.aspx?id=77d171f8-5ca8-4b77-b1b4-bfed78f612a6</guid>
      <pubDate>Sun, 26 Feb 2012 11:43:00 -0400</pubDate>
      <category>.NET</category>
      <category>ASP.NET</category>
      <category>C#</category>
      <category>Open Source</category>
      <dc:publisher>Rich Czyzewski</dc:publisher>
      <pingback:server>http://www.richonsoftware.com/pingback.axd</pingback:server>
      <pingback:target>http://www.richonsoftware.com/post.aspx?id=77d171f8-5ca8-4b77-b1b4-bfed78f612a6</pingback:target>
      <slash:comments>7</slash:comments>
      <trackback:ping>http://www.richonsoftware.com/trackback.axd?id=77d171f8-5ca8-4b77-b1b4-bfed78f612a6</trackback:ping>
      <wfw:comment>http://www.richonsoftware.com/post/2012/02/26/Converting-BlogEngineNET-25-to-a-Web-Application.aspx#comment</wfw:comment>
      <wfw:commentRss>http://www.richonsoftware.com/syndication.axd?post=77d171f8-5ca8-4b77-b1b4-bfed78f612a6</wfw:commentRss>
    <feedburner:origLink>http://www.richonsoftware.com/post.aspx?id=77d171f8-5ca8-4b77-b1b4-bfed78f612a6</feedburner:origLink></item>
  </channel>
</rss>
