<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bugfree.dk - Ronnie Holm&#039;s blog &#187; .Net</title>
	<atom:link href="http://www.bugfree.dk/blog/tag/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bugfree.dk/blog</link>
	<description>Not anti-anything, just pro-quality</description>
	<lastBuildDate>Wed, 08 Sep 2010 13:57:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Unit testing LINQ to SQL using TypeMock</title>
		<link>http://www.bugfree.dk/blog/2010/05/04/unit-testing-linq-to-sql-using-typemock/</link>
		<comments>http://www.bugfree.dk/blog/2010/05/04/unit-testing-linq-to-sql-using-typemock/#comments</comments>
		<pubDate>Tue, 04 May 2010 19:23:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1050</guid>
		<description><![CDATA[Recent months have brought about a proliferation of mocking frameworks that mocks what more traditional framework like Rhino Mocks cannot. Instead of creating and loading a mock implementation at runtime, the new breed of mocking frameworks hooks into the CLR to intercept and redirect calls. This opens up virtually every aspect of a class to [...]]]></description>
			<content:encoded><![CDATA[<p>Recent months have brought about a proliferation of mocking frameworks that mocks what more traditional framework like <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a> cannot. Instead of creating and loading a mock implementation at runtime, the new breed of mocking frameworks hooks into the CLR to <a href="http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock">intercept and redirect calls</a>. This opens up virtually every aspect of a class to mocking, which is useful for testing code not written with explicit testability in mind. Until recently, <a href="http://site.typemock.com/typemock-isolator-product">TypeMock</a> was the only mocking framework around that took the latter approach, but it’s now being challenged by <a href="http://research.microsoft.com/en-us/projects/moles">Moles</a> from Microsoft Research and <a href="http://www.telerik.com/products/mocking.aspx">JustMock</a> from Telerik.</p>
<h4>Why traditional dependency-breaking techniques come short</h4>
<p>After watching a screencast on how to <a href="http://www.dimecasts.net/Casts/CastDetails/170">use Moles to unit test LINQ to SQL</a> without hitting the database, I thought it would be interesting to do the same with TypeMock. But first, let’s make sure we understand why traditional dependency-breaking techniques come short in testing LINQ to SQL. Assuming we want to put a repository under test, our goal is to mock how it accesses the database. Here’s a simple implementation of a repository that queries the Employee table of the <a href="http://sqlserversamples.codeplex.com">AdventureWorks</a> database:</p>
<pre class="prettyprint lang-cs">    public class EmployeeRepository {
        public List&lt;Employee&gt; GetEmployeesByHireDate(DateTime start, DateTime end) {
            using (var ctx = new AdventureWorksDataContext())
                return (from e in ctx.Employees
                        where e.HireDate &gt;= start &amp;&amp; e.HireDate &lt;= end
                        select e).ToList();
        }
    }
</pre>
<p>All calls to the database are routed through the AdventureWorksDataContext generated by Visual Studio. To mock access to the database, we therefore have to mock part of the data context. Easier said than done, though, for the context doesn’t expose an interface that a fake can implement. In addition, the tables are accessed through properties on the context that return a type of <a href="http://msdn.microsoft.com/en-us/library/bb358844">Table&lt;TEntity&gt;</a>. Unfortunately, the constructor of Table&lt;TEntity&gt; is internal and the class itself is sealed, eliminating the hope of instantiating or subclassing the type by traditional means:</p>
<pre class="prettyprint lang-cs">    public sealed class Table&lt;TEntity&gt; : IQueryProvider,
            ITable, IListSource, ITable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;,
            IEnumerable&lt;TEntity&gt;, IQueryable, IEnumerable
            where TEntity : class {
        internal Table(DataContext context, MetaTable metaTable) {
            ...
        }
    }</pre>
<p>For an example of how the data context itself creates an instance of Table&lt;TEntity&gt;, take a look at the Employees property on the AdventureWorksDataContext. It relies on the GetTable&lt;Employee&gt; method on the DataContext class to create an instance of Table&lt;Employee&gt;. Despite its constructors being internal, the GetTable&lt;TEntity&gt; method has no trouble constructing an instance of the Table&lt;TEntity&gt; type, as they both reside in the System.Data.Linq assembly:</p>
<pre class="prettyprint lang-cs">    public partial class AdventureWorksDataContext : DataContext {
        public Table&lt;Employee&gt; Employees {
            get {
                return GetTable&lt;Employee&gt;();
            }
        }
    }</pre>
<h4>How to break the unbreakable</h4>
<p>The design of LINQ to SQL leaves us short of a traditional testing seam, as <a href="http://www.amazon.com/Working-Effectively-Legacy-Robert-Martin/dp/0131177052">Michael Feathers</a> would phrase it; a place at which we can alter the behavior of a program without editing in that place. This explains why, with LINQ to SQL, traditionally we’ve had to test against a real database with all its constraints, making our tests brittle, slow, and painful to write and maintain. With the new breed of mocking frameworks the issues of not being able to subclass or not being able to call an internal constructor go away (and new issues take their place). Regardless, here’s how to write a unit test for the CustomerRepository that doesn’t hit the database:</p>
<pre class="prettyprint lang-cs">    [TestClass]
    public class CustomerRepositoryTest {
        private EmployeeRepository _repository;

        [TestInitialize]
        public void Initialize() {
            _repository = new EmployeeRepository();

            var fakeEmployees = new List&lt;Employee&gt; {
                new Employee {EmployeeID = 1, HireDate = new DateTime(2004, 12, 1)},
                new Employee {EmployeeID = 2, HireDate = new DateTime(2006, 7, 1)},
                new Employee {EmployeeID = 3, HireDate = new DateTime(2009, 3, 1)}
            }.AsQueryable();

            var fakeDataContext = Isolate.Fake.Instance&lt;AdventureWorksDataContext&gt;();
            Isolate.Swap.NextInstance&lt;AdventureWorksDataContext&gt;().With(fakeDataContext);

            // var fakeEmployeeTable = Isolate.Fake.Instance&lt;Table&lt;Employee&gt;&gt;();
            // Isolate.WhenCalled(() =&gt; fakeDataContext.Employees).WillReturn(fakeEmployeeTable);
            // Isolate.WhenCalled(() =&gt; fakeEmployeeTable).WillReturnCollectionValuesOf(fakeEmployees);
            // or by transitivity
            Isolate.WhenCalled(() =&gt; fakeDataContext.Employees).WillReturnCollectionValuesOf(fakeEmployees);
        }

        [TestMethod]
        public void GetEmployeesByHireDate_should_return_hires_from_2008_until_present() {
            var employees = _repository.GetEmployeesByHireDate(new DateTime(2008, 1, 1), DateTime.Now);
            Assert.AreEqual(1, employees.Count());
            Assert.AreEqual(3, employees[0].EmployeeID);
        }
    }
</pre>
<p>The test method itself looks exactly as if we’d been testing against a real database. The difference lies in the Initialize method, where we setup the fake data context and database contents. We instruct TypeMock to return the fake context in place of the real one inside EmployeeRepository. And whenever someone calls the Employees property on the fake context, we have TypeMock intercept the call and return a fake collection of type <a href="http://msdn.microsoft.com/en-us/library/bb351562.aspx">IQueryable&lt;Employee&gt;</a>. We could’ve returned an instance of Table&lt;Employee&gt;, which implements IQueryable&lt;Employee&gt;, but in this case returning the collection is simpler and sufficient. Had we had more methods on our repository, we likely would’ve added additional rows to the Employee table and populated more of its columns.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2010/05/04/unit-testing-linq-to-sql-using-typemock/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using VS linked files for strong naming assemblies</title>
		<link>http://www.bugfree.dk/blog/2009/02/17/using-vs-linked-files-for-strong-naming-assemblies/</link>
		<comments>http://www.bugfree.dk/blog/2009/02/17/using-vs-linked-files-for-strong-naming-assemblies/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 21:43:39 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Tip]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2009/02/17/using-vs-linked-files-for-strong-naming-assemblies/</guid>
		<description><![CDATA[Visual Studio has the ability to add a file as a link, making other parts of Visual Studio believe the file is actually located where it&#8217;s added. One useful application of the link feature is for signing assemblies by way of a key file. Signing an assembly using a digital signature may serve one or [...]]]></description>
			<content:encoded><![CDATA[<p>Visual Studio has the ability to add a file as a link, making other parts of Visual Studio believe the file is actually located where it&#8217;s added. One useful application of the link feature is for signing assemblies by way of a key file. Signing an assembly using a digital signature may serve one or more purposes: It&#8217;s a precondition for deploying an assembly to the Global Assembly Cache (GAC), sharing an assembly among applications, and making <a href="http://msdn.microsoft.com/en-us/library/fdhkd3a5.aspx">side-by-side execution</a> possible. Also, signing an assembly is useful for asserting its integrity, GAC deployed or otherwise.
</p>
<p>The reason for bringing up the linked file feature in conjunction with assembly signing is that to me the feature seems particularly well-suited for linking one and only key file into multiple Visual Studio projects. Yet people seem to be unaware of the feature and so common approaches to signing is to either create a new key file for each assembly &#8212; most likely because Visual Studio makes it so easy to create a new key file from the Project Settings dialog &#8212; or signing assemblies by creating one key file and then copy/paste it to other projects in the solution.
</p>
<p>Below is an example from the GAC showcasing how assemblies related to <a href="http://research.microsoft.com/en-us/projects/pex/">Pex</a> naturally go together and are therefore signed using the same key (they share 76a274db078248c8, their public key token). The same goes for  assemblies relating to other Microsoft products, such as the ones comprising a particular version of the .Net framework (because of the side-by-side execution, different versions of .Net framework assemblies are signed using different keys). So why not apply the same principle to what you deploy to the GAC?</p>
<p><img src="http://www.bugfree.dk/blog/wp-content/uploads/2009/02/example-of-public-key-from-the-gac.png" /></p>
<p>While using the same key (copy or not) makes it possible to differentiate your assemblies from everyone else and for your <a href="http://en.csharp-online.net/.NET_CLR_Components%E2%80%94Assembly_Names">four-part assembly name</a> in web.config and spread around the code to be uniform &#8212; SharePoint developers often need to provide the four-part name for their assemblies to other parts of the solution &#8212; copying the key around is still a violation of the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a> and as such is indicative of a <a href="http://martinfowler.com/bliki/CodeSmell.html">code smell</a>. More importantly, using the link feature of Visual Studio, there&#8217;s no reason to keep the bad smell around.
</p>
<p>Assuming you&#8217;ve already created a solution (in Visual Studio 2008) and added a project to it, the way to share a key file is to first create one by right clicking a project in Solution Explorer and selecting Properties. Now click the Signing tab and check the Sign the assembly check box. The dropdown lets you create a new key file by selecting New and filling out the information in the Create Name Key window. Alternatively, a key file is created using <a href="http://msdn.microsoft.com/en-us/library/k5b5tt23.aspx">sn.exe</a>, the strong name utility that comes with the <a href="http://blogs.msdn.com/windowssdk/archive/2008/09/25/winsdk-in-vs2008-sp1-patch-what-changed.aspx">Microsoft Windows SDK</a>. On my machine, sn.exe is located in C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin and is invoked like so:
</p>
<pre>
    > sn -k MySharedKeyPair.snk
</pre>
</p>
<p>How the key file is created isn&#8217;t particularly relevant to the rest of this post. Just make sure to place the key file in a common location, e.g., the top-level directory holding the Visual Studio solution file. Now go to Solution Explorer, right click on your project, and select Add existing Item. Then locate the key file within the solution directory and make sure to click the arrow on the Add button and select Add as Link. Note how the file is added to the project and marked by an arrow indicating it&#8217;s a link:</p>
<p style="margin: 0px; padding: 0px;">
<img style="float:left;" src="http://www.bugfree.dk/blog/wp-content/uploads/2009/02/add-existing-item-as-link.png" />&nbsp;&nbsp;&nbsp;<img style="float:" src="http://www.bugfree.dk/blog/wp-content/uploads/2009/02/linked-file-in-solution-explorer.png" />
</p>
<p>Returning to the Signing tab and selecting the dropdown, it now includes the linked key file. Don&#8217;t mind the absolute path; once you select MySharedKeyPair.snk, Visual Studio converts the path to a relative one (close and reopen the Signing tab and see for yourself). Also note that if you select Browse, the key file you select is copied to the project folder and added to the project as a regular file.</p>
<p><img src="http://www.bugfree.dk/blog/wp-content/uploads/2009/02/select-linked-file-in-signing-tab-of-project-properties.png" /></p>
<p>Another way to associate a key file with an assembly is through the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assemblykeyfileattribute.aspx">AssemblyKeyFile</a> attribute. The attribute instructs the compiler of where to look for the key file and, although not used by the runtime, the attribute is included in the assembly along with any other attribute for everyone to see.</p>
<p><img src="http://www.bugfree.dk/blog/wp-content/uploads/2009/02/key-file-attribute-in-assembly-info.png" /></p>
<p>Using AssemblyKeyFile is probably the simplest approach to sharing a key file between projects, but now compiling the assembly results in a compiler warning as displayed above. The <a href="http://msdn.microsoft.com/en-us/library/xh3fc3x0(VS.80).aspx">use of the AssemblyKeyFile attribute has been deprecated</a> by Microsoft because it may lead to you inadvertently disclosing sensitive information through the embedded path and because working with a relative path may confuse users and the build system (the relative path is retained in the assembly, though). However, it appears AssemblyKeyFile is still the preferred way for MS to sign their assemblies. Inspecting a couple of .Net 3.5 assemblies with Reflector, here&#8217;s what their AssemblyKeyFile looks like:
</p>
<pre class="prettyprint lang-cs">
    [assembly: AssemblyKeyFile(@"f:\\dd\\tools\\devdiv\\EcmaPublicKey.snk")]
    [assembly: AssemblyKeyFile(@"f:\\dd\\tools\\devdiv\\35MSSharedLib1024.snk")]
    [assembly: AssemblyKeyFile(@"f:\\dd\\tools\\devdiv\\FinalPublicKey.snk")]
    …
</pre>
<p>To come full circle, the question of how Visual Studio, or rather MSBuild, actually signs an assembly using the information provided in the Properties dialog (real file or link) remains to be answered. Since a Visual Studio project file acts as input to MSBuild, we can see what&#8217;s going on under the hood of MSBuild by invoking a compile from the command line. On my machine <a href="http://msdn.microsoft.com/en-us/library/ms164311.aspx">msbuild.exe</a> is located in C:\Windows\Microsoft.NET\Framework\v3.5 and assuming you have a console window open with its current directory set to the directory of your project file, msbuild is invoked like so:
</p>
<pre>
    > msbuild /verbosity:diagnostic &gt; log.txt
</pre>
</p>
<p>Bring up log.txt in your favorite editor and eventually you&#8217;ll come across where <a href="http://msdn.microsoft.com/en-us/library/78f4aasd.aspx">csc.exe</a>, the C# compiler, is invoked:</p>
<p><img src="http://www.bugfree.dk/blog/wp-content/uploads/2009/02/key-file-and-msbuild.png" /></p>
<p>As you might have guessed, MSBuild carries over the location of the key file by passing the /keyfile argument to csc.exe.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/02/17/using-vs-linked-files-for-strong-naming-assemblies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An example of unit testing using TypeMock</title>
		<link>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/</link>
		<comments>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 04:00:07 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Quality]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/</guid>
		<description><![CDATA[This post details my first use of TypeMock, a commercial mocking framework, for testing a web part that displays a dropdown bound to a LINQ query. Based on the item selected, the web part then displays a result bound to another LINQ query. For the purpose of becoming familiar with TypeMock, though, the focus of [...]]]></description>
			<content:encoded><![CDATA[<p>This post details my first use of <a href="http://www.typemock.com">TypeMock</a>, a commercial mocking framework, for testing a web part that displays a dropdown bound to a LINQ query. Based on the item selected, the web part then displays a result bound to another LINQ query. For the purpose of becoming familiar with TypeMock, though, the focus of this post is on testing the code that initializes the LINQ data context. It does so by reading a connection string from a configuration file and passing it to the data context.
</p>
<p>In order to test code whose branching behavior depends on a value read from a configuration file, the test should provide various inputs and assert that the code under test acts accordingly. In addition, the test should run in milliseconds to encourage frequent runs and it should be self-contained, meaning no setup should be required before running the test. These requirements are best met with the web part running in a controlled environment. Yet, as far as the code under test goes, it should behave as if part of an Asp.Net page.
</p>
<p>For the sake of brevity, here&#8217;s my web part with the code to initialize the data context:</p>
<pre class="prettyprint lang-cs">
    public class MyWebPart : WebPart {
        MyDataContext _db;    /* LINQ database context */
        string _error;        /* Early stage error message */    	

        public MyWebPart() {
            Initialize();
        }

        private void Initialize() {
            string c = GetMyConnectionString();
            if (c == null)
                 _error = "Unable to do something";
            else
                _db = new MyDataContext(c);
        }

        private string GetMyConnectionString() {
            System.Configuration.ConnectionStringSettings c =
                System.Configuration.ConfigurationManager.
                    ConnectionStrings["MyConnection"];
            return c == null ? null : c.ConnectionString;
        }

        protected override void Render(HtmlTextWriter w) {
            // display error message if set
        }
    }
</pre>
<p>Notice how the constructor calls out to an Initialize method. Otherwise code within the constructor would fire before I&#8217;d have a chance to setup a controlled environment around the web part and I wouldn&#8217;t be able to test it. Turning the attention to Initialize itself, it’s made up of only a simple if statement. The idea is that if I can&#8217;t mock something as simple as reading a value from a configuration file, most likely I can&#8217;t mock something more involved either. On the other hand, for a developer already familiar with TypeMock and test first development, the code above may be born of the need to satisfy a failing test.
</p>
<p>I want to test Initialize by controlling how GetMyConnectionString gets to return the connection string. While running in an Asp.Net context, GetMyConnectionString would attempt to read the string from web.config. Within my controlled environment, however, I want to inject into the web part an alternate implementation that returns a value of my choosing. That way I can control the path through Initialize and inspecting the state of the  _error or _db fields, I&#8217;m able to determine if the code behaved as intended.
</p>
<p>Using the method chaining DSL of TypeMock, the test takes on this form (of course, having more tests, I&#8217;d move shared code into helper methods decreasing the test to code ratio):
</p>
<pre class="prettyprint lang-cs">
    [TestClass, ClearMocks]
    public class MyWebPartTest {
        [TestMethod, Isolated, VerifyMocks]
        public void Should_set_error_message_when_no_
                    connection_string_is_configured() {
            // arrange
            MyWebPart fake = Isolate.Fake.Instance&lt;MyWebPart&gt;();
            Isolate.NonPublic.WhenCalled(fake,
                "Initialize").CallOriginal();
            Isolate.NonPublic.WhenCalled(fake,
                "GetMyConnectionString").WillReturn(null);
            PrivateObject handle = new PrivateObject(fake);

            // act
            handle.Invoke("Initialize", null); 

            // assert
            Isolate.Verify.NonPublic.WasCalled(fake,
                "GetMyConnectionString");
            string error = (string)handle.GetField("_error");
            MyDataContext ctx = (MyDataContext)handle.GetField("_db");
            Assert.AreEqual("Unable to do something", error);
            Assert.AreEqual(null, ctx);
        }
    }
</pre>
<p>There&#8217;re three parts to tests using TypeMock: (1) the arrange part sets up expectations of what’s going to happen when a method, a property, or some other part of the code under test is invoked; (2) the act part carries out the actual interaction with the object under test, turning to <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx">PrivateObject</a> to invoke the Initialize method; and finally (3) the assert part verifies that what was supposed to happen did happen. Worth noting is that this test asserts both state and behavior, i.e., as part of executing the code under test, _error or _db should&#8217;ve been set to an appropriate state and GetMyConnectionString should’ve been called once and only once.
</p>
<p>This concludes my example, which I believe illustrates the basics of testing and mocking using MS Test and TypeMock. Comparing and contrasting TypeMock to <a href="http://weblogs.asp.net/rosherove/archive/2007/04/26/choosing-a-mock-object-framework.aspx">other popular mocking frameworks</a>, TypeMock has the distinct feature that it can mock almost anything, with or without using interfaces. <a href="http://www.mockobjects.com/2007/03/stop-designing-for-testability.html">Some</a> argue that not enforcing the use of interfaces is also the disadvantage of TypeMock, because for code to be truly testable, it should be modularized using the <a href="http://en.wikipedia.org/wiki/Inversion_of_control">Inversion of Control principle</a>. However, with legacy code, such as the .Net framework or the SharePoint API, to me TypeMock appears to bridge the two worlds nicely, leaving the developer in charge.</p>
<p>To learn more about the basic concepts of mocking, Inversion of Control, and Dependency Injection (containers), I&#8217;d recommend listening to a couple of <a href="http://altnetpodcast.com">Alt.Net podcasts</a>: <a href="http://altnetpodcast.com/episodes/5-di-and-ioc">Dependency Injection and Inversion of Control</a> and <a href="http://altnetpodcast.com/episodes/6-more-di-and-ioc">More Dependency Injection and Inversion of Control</a>.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Prototyping LINQ using LINQPad</title>
		<link>http://www.bugfree.dk/blog/2008/06/29/prototyping-linq-using-linqpad/</link>
		<comments>http://www.bugfree.dk/blog/2008/06/29/prototyping-linq-using-linqpad/#comments</comments>
		<pubDate>Sun, 29 Jun 2008 12:44:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2008/06/29/prototyping-linq-using-linqpad/</guid>
		<description><![CDATA[I&#8217;ve been doing some LINQ development lately. What I typically do is write a LINQ query within the production code and then attach a debugger to see what the query returns and perhaps what the underlying SQL statement looks like. For simple queries this technique is sufficient, but for more complex ones, several, cumbersome round-trips [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing some LINQ development lately. What I typically do is write a LINQ query within the production code and then attach a debugger to see what the query returns and perhaps what the underlying SQL statement looks like. For simple queries this technique is sufficient, but for more complex ones, several, cumbersome round-trips through the debugger are often necessary to get the query right.
</p>
<p>Researching the issue I came across <a href="http://www.linqpad.net">LINQPad</a> (<a href="http://www.dimecasts.net/Casts/CastFeedDetails/22">see</a> LINQPad <a href="http://www.dimecasts.net/Casts/CastDetails/6">in</a> <a href="http://oreilly.com/pub/e/909">action</a>). The tool is a generic testbed for molding expressions or statements (LINQ being one such class) before embedding them into code. Also, because LINQPad is written by one of the authors of <a href="http://www.amazon.com/gp/product/0596527578?ie=UTF8&amp;tag=cinanu-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596527578">C# in a Nutshell</a>, the tool comes with a lot of samples from the book.
</p>
<p><a href="http://www.bugfree.dk/blog/wp-content/uploads/2008/06/LINQPadExample.png" target="_blank"><img src="http://www.bugfree.dk/blog/wp-content/uploads/2008/06/LINQPadExample.png" alt=""/></a>
</p>
<p>On the implementation side, LINQPad works by emitting MSIL behind the scenes, conceptually similar to the DataContext classes generated by Visual Studio when using the database design surface.</p>
<p>As an interesting side note, LINQPad can also show the query after it has been transformed into lambdas, anonymous types, and the like:
</p>
<pre class="prettyprint lang-cs">
   Users
      .Join (
         Macs,
         u => u.UserId,
         m => m.UserId,
         (u, m) =>
            new
            {
               u = u,
               m = m
            }
      )
      .Where (temp0 => (temp0.u.Created < DateTime.Now.AddHours (-24)))
      .Select (
         temp0 =>
            new
            {
               UserId = temp0.u.UserId,
               UserCreated = temp0.u.Created,
               Mac = temp0.m.Mac,
               Active = temp0.m.Active
            }
      )
      .Take (15)
</pre>
<p>Keep in mind how the .Net 3.5 framework and the .Net 3.5 compiler play together to ultimately transform the LINQ query into MSIL. What the framework does is transform the LINQ query into the above expression by applying a transform to the abstract syntax tree of the LINQ query. The .Net 3.5 compiler then transforms the lambdas, the anonymous types, and the like into .Net 2.0 MSIL (there&#8217;s no such thing as a .Net 3.5 CLR. For an overview of how the various versions of the framework, the compiler, and the CLR relate to each other, see Scott Hanselman&#8217;s <a href="http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx">blog entry</a>).</p>
<p>But back to LINQPad. The only downside that I&#8217;ve encountered is that there&#8217;s no IntelliSense support in the current 1.24 release. However, even without IntelliSense support LINQPad is still a very valuable tool.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2008/06/29/prototyping-linq-using-linqpad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Purging inactive users from e107</title>
		<link>http://www.bugfree.dk/blog/2007/10/29/purging-inactive-users-from-e107/</link>
		<comments>http://www.bugfree.dk/blog/2007/10/29/purging-inactive-users-from-e107/#comments</comments>
		<pubDate>Mon, 29 Oct 2007 21:35:02 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2007/10/29/purging-inactive-users-from-e107/</guid>
		<description><![CDATA[Download E107InactiveUserPurger-1.0.zip. As part of my use of the e107 open source contents management system, I want to purge the user accounts that’ve not logged in recently. This is something not supported out of the box, but by going through MySQL and accessing the e107_user table directly, the date of last login is accessible to [...]]]></description>
			<content:encoded><![CDATA[<p>Download <a href="/software/E107InactiveUserPurger-1.0.zip">E107InactiveUserPurger-1.0.zip</a>.</p>
<p>As part of my use of the <a href="http://e107.org/news.php">e107</a> open source contents management system, I want to purge the user accounts that’ve not logged in recently. This is something not supported out of the box, but by going through MySQL and accessing the e107_user table directly, the date of last login is accessible to anyone.</p>
<p>I’ve therefore written a small command-line tool in C# that makes use of the e107_user information to sent inactive users a warning email that their accounts are about to be purged (or whatever you want to happen).</p>
<p>The tool may be run in one of two modes, determined by a command-line switch.<br />
</p>
<ul>
<li>GenerateWarningMails: emails users that have not logged in during the last WarningPeriod days.</li>
<li>GeneratePurgeMailForAdministrator: emails site administrator a list of users that have not logged in during the last PurgePeriod days.</li>
</ul>
<p>Before running E107InactiveUserPurger, make sure to go to the Debug directory and adjust the settings in E107InactiveUserPurger.exe.xml to match your environment. You might also want to adjust the WarningMailTemplate.txt, which serves as a template for generating the body of warning emails. </p>
<p>Note that within the WarningMailTemplate.txt file, you&#8217;re free to add placeholders for fields within the e107_user table. Thus, if you want to include the login name of a user within the warning email, you’d write $user_loginname$.</p>
<p>Now you might run E107InactiveUserPurger as a scheduled task. Keep in mind, though, that the tool doesn’t actually purge the user accounts. Therefore, running it too often with the GenerateWarningMails switch may result in users receiving more than one warning email.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2007/10/29/purging-inactive-users-from-e107/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Good SharePoint development practices</title>
		<link>http://www.bugfree.dk/blog/2007/07/29/good-sharepoint-development-practices/</link>
		<comments>http://www.bugfree.dk/blog/2007/07/29/good-sharepoint-development-practices/#comments</comments>
		<pubDate>Sun, 29 Jul 2007 14:25:23 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2007/07/29/future-sharepoint-development-environment/</guid>
		<description><![CDATA[Lately I&#8217;ve been working on creating a portal with Windows SharePoint Services 2007 (WSS 3.0) for a large customer. The easy and intuitive way to create such a portal is to configure it through the web browser and using SharePoint Designer (a renamed and spruced up FrontPage) for everything not code-related. Unfortunately, using the web [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been working on creating a portal with <a href="http://www.microsoft.com/sharepoint/default.mspx">Windows SharePoint Services 2007</a> (WSS 3.0) for a large customer. The easy and intuitive way to create such a portal is to configure it through the web browser and using SharePoint Designer (a renamed and spruced up FrontPage) for everything not code-related. </p>
<p>Unfortunately, using the web interface and SharePoint Designer doesn&#8217;t scale well. With the drag and drop tools there is just no real support for deploying your portal to another server, and hence to unify the individual contributions of team members.</p>
<p>Therefore, the <a href="http://msdn2.microsoft.com/en-us/library/bb530302.aspx">current</a> way to go for any real SharePoint development is to work with the 12 Hive directly. Named after Office 12 (Office 2007), the 12 Hive is a hierarchy of xml files residing in &#8220;Program Files\Common Files\Microsoft Shared\web server extensions\12&#8243; that controls almost everything about how SharePoint and your portal behaves.</p>
<p>Using Visual Studio (VS), you’d create a 12 Hive parallel file hierarchy of new folders and files and work within VS as usual. Like with any other project, you&#8217;d use version control, <a href="2006/11/19/cruisecontrolnet-and-build-queues/">continuous integration</a>, and so on, on xml and .Net code. With VS, deployment (to your development box) would then involve checking out xml and code from source control and compiling the code. </p>
<p>Then, using a build script, you&#8217;d xcopy the xml and binary into the 12 Hive and GAC, respectively, and possibly run various stsadm commands to activate your features. Alternatively, you&#8217;d create a SharePoint solution package that pretty much does the same thing when invoked by SharePoint.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2007/07/29/good-sharepoint-development-practices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CruiseControl.net and build queues</title>
		<link>http://www.bugfree.dk/blog/2006/11/19/cruisecontrolnet-and-build-queues/</link>
		<comments>http://www.bugfree.dk/blog/2006/11/19/cruisecontrolnet-and-build-queues/#comments</comments>
		<pubDate>Sun, 19 Nov 2006 09:07:10 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Process]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2006/11/19/build-queues-with-cruisecontrolnet/</guid>
		<description><![CDATA[(I&#8217;ve created a Download page for the tool described in this post, with a short description of prerequisites and how to install it.) For team development a way is needed to ensure that team members doesn&#8217;t inadvertently break the shared code, e.g., a developer forgets to commit all files related to a change, which is [...]]]></description>
			<content:encoded><![CDATA[<p>(I&#8217;ve created a <a href="http://www.bugfree.dk/blog/software/ccnetserializer/">Download</a> page for the tool described in this post, with a short description of prerequisites and how to install it.)</p>
<p>For team development a way is needed to ensure that team members doesn&#8217;t inadvertently break the shared code, e.g., a developer forgets to commit all files related to a change, which is something not easily fixable by other developers.</p>
<p>Also, the team might want to run post-compile tasks, such as unit tests, on a dedicated machine to avoid the works-on-my-machine syndrome.</p>
<p>Ideally, the project’s code should always go from one stable state to another so that a developer doesn’t get broken code the next time he synchronizes with source control. </p>
<p>One way to achieve this is by means of <a href="http://www.martinfowler.com/articles/continuousIntegration.html">continuous integration</a> of changes into the code. Either by rolling your own build script that monitors source control for changes to trigger a build and inform developers of the result or by leveraging an existing continuous integration solution, such as <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET">CruiseControl.net</a> (ccnet): a continuous integration server, an asp.net based front-end, and a desktop client.</p>
<p>Although CruiseControl (both the Java and .Net incarnation) appears to be a popular choice among developers, I find it somewhat immature: it violates the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">dry principle</a> in its projects configuration file and, worst of all, it doesn&#8217;t support build queues to ensure that only one of several projects are actually building at once. </p>
<p>It&#8217;s not a problem for ccnet itself to perform parallel continuous integration. However, the build chain is no stronger than the weakest link, which in my case is devenv.exe, the Visual Studio executable used by ccnet to build the application (by running devenv.exe from the command line with a couple of arguments, you can leverage the build system within Visual Studio from a script). </p>
<p>The downside to using devenv.exe, however, is that all running instances share a temporary build folder for compiler output. Thus, when ccnet does continuous integration of branches in parallel, the instances of devenv.exe spawned by ccnet compete for write access to identically named files, namely the executables generated by the compiler.</p>
<p>Not surprisingly, this results in build failures for one or more ccnet projects, although there is nothing wrong with the code. </p>
<p>In my experience from the trenches this happens too often to be ignored for any serious use of ccnet: It&#8217;s just too common for a developer to cross-commit a bugfix to several branches or for independent developers to commit to their working branches in between when ccnet checks the branch for updates. </p>
<p>Having these false negatives make the team members not trust ccnet and not take proper action whenever they see a build failure, thus rendering continuous integration useless.</p>
<p>One solution to the above file locking problem is to serialize the builds manually by building branches at predefined intervals, thus interleaving the builds so that they shouldn&#8217;t be able to overlap. As a result the developer may have to wait a fair amount of time to be sure his latest commit doesn&#8217;t breaks anything. Also, if a build has not finished when the next is scheduled to start, it may cause a cascade of broken builds to occur until the interleaving is properly realigned. </p>
<p>Another solution is to head over to <a href="http://jayflowers.com/WordPress/?p=72">Jay Flowers</a>. He has branched off the official 1.0 version of ccnet and created a ccnet that allows for a lot more constraints than just serializing builds. It happens at the expense of running the non-official, not-recent version of ccnet, though.</p>
<p>My solution to the parallel build problem was to write a front-end for ccnet that implements build queues without the knowledge of ccnet, i.e., by means of checking for changes on a configurable number of branches. If a change is detected, the branch is enqueued. Then when all branches are checked, the tool force builds each branch, monitoring the state of the ccnet server to ensure that only one branch is building at a time. </p>
<p>With this solution you integrate the nice features of ccnet, such as the nice webgui for displaying what went wrong with a build and the systray application that goes green, yellow, or red depending on the state of your builds, with rapid feedback in a way that is compatible with Visual Studio&#8217;s integrated build engine.</p>
<p>The biggest downside, however, is that you can no longer see the changes that triggered a build from the web gui as ccnet is no longer in charge of cvs operations.</p>
<p>The tool is roughly 100 lines of <a href=”http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython”>IronPython</a> code and works by spawning cvs.exe, synchronizing a number of working copies with the cvs repository, and in the process  monitors the output of cvs.exe for changes, additions, and removals of files to the working copies. </p>
<p>The state of CruiseControl is determined by screen scraping the webgui and builds are forced by simulating a click on the &#8220;build&#8221; button for the ccnet project in the webgui for which a change was detected.</p>
<p>The url of the ccnet webgui, the path to the cvs.exe, and mappings between the path on disk where each working copy resides and the corresponding name of the ccnet project are stored in the tools configuration file, which is itself Python code loaded into the tool on startup. </p>
<p>Using Python as a language for your configuration file, you don’t have to invent your own language or use verbose xml, which requires you to write code for parsing it.</p>
<p>PS: I recently stumbled across the <a href="http://ccnetplugins.sourceforge.net/">Sequential Task Plug In</a> that I want to try out sometime.</p>
<p><b>Update, April 16</b>: It has come to my attention that there is a way to minimize duplication in the configuration file. It involves &#8220;&#8230; users to set up DTD entities within the CCNet configuration&#8221; as mentionen <a href="http://dotnetjunkies.com/WebLog/exortech/archive/2007/04/15/225924.aspx">here</a>. I haven&#8217;t tried it, though.</p>
<p><b>Update, August 10</b>: CruiseControl.net 1.3 now comes with a build-in queue feature.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2006/11/19/cruisecontrolnet-and-build-queues/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
