<?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>Mon, 28 Nov 2011 07:32:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Expressing a domain specific language of propositions in F#</title>
		<link>http://www.bugfree.dk/blog/2011/11/25/expressing-a-domain-specific-language-of-propositions-in-f/</link>
		<comments>http://www.bugfree.dk/blog/2011/11/25/expressing-a-domain-specific-language-of-propositions-in-f/#comments</comments>
		<pubDate>Fri, 25 Nov 2011 21:23:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1077</guid>
		<description><![CDATA[One aspect of many functional languages that’s always fascinated me is the ease with which you can express a recursive structure, such as a language, and have it evaluated. Suppose you want to define the grammar of a DSL of propositions, in F# you could do so using the discriminated union type: type Proposition = [...]]]></description>
			<content:encoded><![CDATA[<p>One aspect of many functional languages that’s always fascinated me is the ease with which you can express a recursive structure, such as a language, and have it evaluated. Suppose you want to define the grammar of a <a href="http://en.wikipedia.org/wiki/Domain-specific_language">DSL</a> of propositions, in F# you could do so using the discriminated union type:</p>
<pre class="prettyprint lang-ml">type Proposition =
    | True
    | And of Proposition * Proposition
    | Or of Proposition * Proposition
    | Not of Proposition</pre>
<p>In an object-oriented language like C#, this definition would be analogous to a hierarchy of classes. Proposition would be the base class of True, And, Or, and Not. Each would then have a constructor that accepts some number of arguments, e.g., the And constructor would accept a two-tuple, two propositions, making the Proposition type recursive. In C# you might even model the recursive relationship using the <a href="http://en.wikipedia.org/wiki/Composite_pattern">Composite pattern</a>.</p>
<p>In F#, an instance of the Proposition type may be created using a constructor syntax that resembles that of a function call:</p>
<pre class="prettyprint lang-ml">let p = And(Or(True, Not(True)), Not(Not(True)))</pre>
<p>Now, because of the recursive nature of the Proposition type, instances of it form a <a href="http://en.wikipedia.org/wiki/Parse_tree">parse tree</a>-like structure:</p>
<pre>                        And
                        /\
                       /  \
                      Or  Not
                      /\    \
                     /  \    \
                  True  Not  Not
                          \    \
                           \    \
                          True  True</pre>
<p>Having a parse tree is not very useful in itself. What you need is some way to execute or evaluate it. Given the recursive nature of the grammar, it makes sense for the evaluator to be recursively defined as well. The evaluator would do pattern matching on the node type, deconstructing it into the parts needed to evaluate it. Since our language of propositions maps directly to the boolean operations of F#, it’s very simple to evaluate the parse tree:</p>
<pre class="prettyprint lang-ml">let rec eval (p: Proposition) =
    match p with
    | True -&gt; true
    | And(p1, p2) -&gt; eval p1 &amp;&amp; eval p2
    | Or (p1, p2) -&gt; eval p1 || eval p2
    | Not(p1) -&gt; not (eval p1)

let e = eval p // e : bool = true</pre>
<p>The simple language of propositions doesn’t take into account operator precedence and associativity, variables, and so on. But the features of F# used here allow for more complicated languages to be expressed and evaluated directly. With C#, you’d often fallback to describing the grammar of more complex languages in <a href="http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form">Backus-Naur</a> form and feeding it to a <a href="http://en.wikipedia.org/wiki/Parser_generator">parser generator</a> that would map the node types of the parse tree to classes and be able to form a valid parse tree of some input.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2011%2F11%2F25%2Fexpressing-a-domain-specific-language-of-propositions-in-f%2F&amp;title=Expressing%20a%20domain%20specific%20language%20of%20propositions%20in%20F%23" id="wpa2a_2"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2011/11/25/expressing-a-domain-specific-language-of-propositions-in-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using a generic command-line runner for utility tasks</title>
		<link>http://www.bugfree.dk/blog/2011/11/23/using-a-generic-command-line-runner-for-utility-tasks/</link>
		<comments>http://www.bugfree.dk/blog/2011/11/23/using-a-generic-command-line-runner-for-utility-tasks/#comments</comments>
		<pubDate>Wed, 23 Nov 2011 10:04:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1075</guid>
		<description><![CDATA[Most enterprise projects have one or more console applications for utility tasks such as cleaning up or importing data into the database. These utilities tend to be project-specific and small in terms of code size, and instead of several smaller assemblies, it makes sense to combine these into a single assembly. The generic runner would [...]]]></description>
			<content:encoded><![CDATA[<p>Most enterprise projects have one or more console applications for utility tasks such as cleaning up or importing data into the database. These utilities tend to be project-specific and small in terms of code size, and instead of several smaller assemblies, it makes sense to combine these into a single assembly. The generic runner would read the utility, called the command, and arguments from the command-line and use the <a href="http://en.wikipedia.org/wiki/Command_pattern">command pattern</a> to create and execute it.</p>
<p>For the generic runner to work, each command has to fulfill the contract.</p>
<pre class="prettyprint lang-cs">public enum ExitCode {
    Success = 0,
    Failure
};

public interface ICommand {
    string Usage { get; }
    string Description { get; }
    ExitCode Execute(string[] args);
}</pre>
<p>I want the runner to adhere to the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">open/closed principle</a>. For its behavior to be modified without altering its core delegation logic. This requires the use of reflection to retrieve and instantiate a command based on command-line arguments.</p>
<pre class="prettyprint lang-cs">class Program {
    static IEnumerable&lt;ICommand&gt; GetCommands() {
        var iCommand = typeof (ICommand);
        return System.Reflection.Assembly.GetExecutingAssembly().GetTypes().ToList()
            .Where(t =&gt; iCommand.IsAssignableFrom(t) &amp;&amp; t != iCommand)
            .Select(t =&gt; Activator.CreateInstance(t) as ICommand);
    }

    static void DisplayHelp() {
        Console.WriteLine(&quot;Console [Command] [Arg1] [Arg2] [ArgN]\n\n&quot;);
        GetCommands().ToList().ForEach(command =&gt;
            Console.WriteLine(command.Usage + &quot;\n&quot; + command.Description + &quot;\n\n&quot;));
    }

    static int Main(string[] args) {
        if (args.Length == 0) {
            DisplayHelp();
            return (int)ExitCode.Failure;
        }

        var commandName = args[0];
        var command = GetCommands().Where(t =&gt; t.GetType().Name == commandName).SingleOrDefault();
        if (command == null)
            throw new ArgumentException(string.Format(&quot;Command '{0}' not found&quot;, commandName));

        var executeArguments = new List&lt;string&gt;(args);
        executeArguments.RemoveAt(0);

        var exitCode = command.Execute(executeArguments.ToArray());
        return (int)exitCode;
    }
}</pre>
<p>A trivial example of a command that adds two numbers would be the following:</p>
<pre class="prettyprint lang-cs">// $&gt; GenericRunner.exe Calculator 2 3 =&gt; 2 + 3 = 5
public class Calculator : ICommand {
    public string Usage {
        get { return &quot;Calculator [Op1] [Op2]&quot;; }
    }

    public string Description {
        get { return &quot;World's simplest calculator&quot;; }
    }

    public ExitCode Execute(string[] args) {
        try {
            Console.WriteLine(
                string.Format(
                    &quot;{0} + {1} = {2}&quot;,
                    args[0], args[1], int.Parse(args[0]) + int.Parse(args[1])));
            return ExitCode.Success;
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
            return ExitCode.Failure;
        }
    }
}</pre>
<p>Now multiple smaller assemblies can be grouped into one, with a description of all commands automatically being assembled, and without commands interfering (too much) with each other.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2011%2F11%2F23%2Fusing-a-generic-command-line-runner-for-utility-tasks%2F&amp;title=Using%20a%20generic%20command-line%20runner%20for%20utility%20tasks" id="wpa2a_4"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2011/11/23/using-a-generic-command-line-runner-for-utility-tasks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# + SharePoint = a list attachment versioning event receiver</title>
		<link>http://www.bugfree.dk/blog/2011/11/21/f-sharepoint-a-list-attachment-versioning-event-receiver/</link>
		<comments>http://www.bugfree.dk/blog/2011/11/21/f-sharepoint-a-list-attachment-versioning-event-receiver/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 07:37:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[SharePoint]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1074</guid>
		<description><![CDATA[It’s been a while since I last took a serious look at F#. Back then I did a simple random fractal terrain generator which, even though the algorithm is simple, I found challenging to do. Nevertheless, functional programming is just one of those areas that I keep returning to. This time around I want to [...]]]></description>
			<content:encoded><![CDATA[<p>It’s been a while since I last took a serious look at F#. Back then I did a simple <a href="http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/">random fractal terrain generator</a> which, even though the algorithm is simple, I found challenging to do. Nevertheless, functional programming is just one of those areas that I keep returning to. This time around I want to use the event receiver for <a href="http://www.bugfree.dk/blog/2011/11/17/versioning-attachments-in-a-sharepoint-list-using-snapshotting/">versioning attachments in SharePoint lists</a> to get familiar with object-oriented F#. Of course, translating a C# class to an F# class, the result will look like C# with different syntax and better type inference. The point here is to use classes in F# as a way to expose functionality to other .NET languages. In a real-world F# application the core logic would likely not be object-oriented.</p>
<pre class="prettyprint lang-ml">namespace Dk.Bugfree

open System
open System.Globalization
open Microsoft.SharePoint

type public ListAttachmentVersioningEventReceiver() =
    inherit SPItemEventReceiver()

    member private r.CustomVersion = &quot;CustomVersion&quot;
    member private r.ShadowLibrary = &quot;ShadowLibrary&quot;

    // override ItemAdded : properties:SPItemEventProperties -&gt; unit
    override r.ItemAdded properties =
        base.ItemAdded properties
        r.SetCustomVersionLabel properties.ListItem
        r.CreateSnapshot properties

    // override ItemUpdated : properties:SPItemEventProperties -&gt; unit
    override r.ItemUpdated properties =
        base.ItemUpdated properties
        let item = properties.ListItem

        if r.RollbackHappened item then
            r.RestoreSnapshot properties
            r.SetCustomVersionLabel item
            r.CreateSnapshot properties
        else
            r.CreateSnapshot properties
            r.SetCustomVersionLabel item

    // member private CreateSnapshot : properties:SPItemEventProperties -&gt; unit
    member private r.CreateSnapshot properties =
        use site = properties.OpenWeb()
        let item = properties.ListItem
        let shadowLibrary = site.Lists.[r.ShadowLibrary] :?&gt; SPDocumentLibrary
        let path = String.Format(&quot;Versions/{0}/{1}&quot;, item.ID, r.GetOfficialVersionLabel(item))
        let shadowFolder = r.CreateFolderPath shadowLibrary path

        item.Attachments |&gt; Seq.cast |&gt; Seq.iter (fun fileName -&gt;
            let existingFile = item.ParentList.ParentWeb.GetFile(item.Attachments.UrlPrefix + fileName)
            let newFile = shadowFolder.Files.Add(fileName, existingFile.OpenBinaryStream())
            newFile.Item.Update())

    // member private RollbackHappened : item:SPListItem -&gt; bool
    member private r.RollbackHappened item =
        let culture = CultureInfo.InvariantCulture
        let currentVersion = Single.Parse(r.GetOfficialVersionLabel(item), culture)
        let lastVersion = Single.Parse(r.GetCustomVersionLabel(item), culture)
        currentVersion &gt; lastVersion + 1.0f

    // member private RestoreSnapshot : properties:SPItemEventProperties -&gt; unit
    member private r.RestoreSnapshot properties =
        let item = properties.ListItem
        let restoreVersion = r.GetCustomVersionLabel item
        r.EventFiringEnabled &lt;- false    

        item.Attachments |&gt; Seq.cast |&gt; Seq.map (fun fileName -&gt; unbox&lt;string&gt; fileName) |&gt; Seq.toList
                         |&gt; Seq.iter (fun fileName -&gt; item.Attachments.Delete(fileName))

        use site = properties.OpenWeb()
        let path = String.Format(&quot;Versions/{0}/{1}&quot;, item.ID, restoreVersion)
        let shadowLibrary = site.Lists.[r.ShadowLibrary] :?&gt; SPDocumentLibrary
        let source = r.CreateFolderPath shadowLibrary path

        source.Files |&gt; Seq.cast |&gt; Seq.iter (fun file -&gt;
            let unboxedFile = unbox&lt;SPFile&gt; file
            item.Attachments.Add(unboxedFile.Name, unboxedFile.OpenBinary()))

        item.SystemUpdate false
        r.EventFiringEnabled &lt;- true

    // member private CreateFolderPath : list:SPDocumentLibrary -&gt; path:string -&gt; SPFolder
    member private r.CreateFolderPath list path : SPFolder =
        r.CreateFolderPathRecursive list.RootFolder (path.Split [|'/'|] |&gt; Array.toList)

    // member private CreateFolderPathRecursive : folder:SPFolder -&gt; pathComponents:string list -&gt; SPFolder
    member private r.CreateFolderPathRecursive folder pathComponents =
        match pathComponents with
        | [] -&gt; folder
        | head :: tail -&gt;
            try
                let existingFolder = folder.SubFolders.[head]
                r.CreateFolderPathRecursive existingFolder tail
            with
                :? ArgumentException -&gt;
                    let newFolder = folder.SubFolders.Add head
                    r.CreateFolderPathRecursive newFolder tail

    // member private SetCustomVersionLabel : item:SPListItem -&gt; unit
    member private r.SetCustomVersionLabel item =
        r.EventFiringEnabled &lt;- false
        item.[r.CustomVersion] &lt;- r.GetOfficialVersionLabel item
        item.SystemUpdate false
        r.EventFiringEnabled &lt;- true  

    // member private GetCustomVersionLabel : item:SPListItem -&gt; string
    member private r.GetCustomVersionLabel item =
        item.[r.CustomVersion] :?&gt; string

    // member private GetOfficialVersionLabel : item:SPListItem -&gt; string
    member private r.GetOfficialVersionLabel item =
        item.Versions.[0].VersionLabel</pre>
<p>A couple of things to note about the F# implementation: first, it hardly specifies any types. They’re inferred by the compiler. Where type names do appear, it’s mainly because they’re required to unbox elements of an IEnumerable collection. Secondly, F# has <a href="http://stackoverflow.com/questions/5355334/what-are-the-benefits-of-such-flexible-self-identifiers-in-f">flexible self identifiers</a>. Methods must explicitly specify the name of the this reference in C# and use it when accessing members. Thirdly, arguments to general .NET methods are passed as a tuple value, i.e., as comma-delimited arguments surrounded by parenthesis.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2011%2F11%2F21%2Ff-sharepoint-a-list-attachment-versioning-event-receiver%2F&amp;title=F%23%20%2B%20SharePoint%20%3D%20a%20list%20attachment%20versioning%20event%20receiver" id="wpa2a_6"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2011/11/21/f-sharepoint-a-list-attachment-versioning-event-receiver/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding event receivers to SharePoint lists on the fly</title>
		<link>http://www.bugfree.dk/blog/2011/11/19/adding-event-receivers-to-sharepoint-lists-on-the-fly/</link>
		<comments>http://www.bugfree.dk/blog/2011/11/19/adding-event-receivers-to-sharepoint-lists-on-the-fly/#comments</comments>
		<pubDate>Sat, 19 Nov 2011 21:53:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1073</guid>
		<description><![CDATA[In versioning attachments in a SharePoint list using snapshotting, an event receiver was responsible for the heavy lifting. To enable versioning of a list, I could therefore have associated the receiver with a list by adding the usual registration XML to a feature. But versioning is a truly reusable building block that shouldn’t be restricted [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.bugfree.dk/blog/2011/11/17/versioning-attachments-in-a-sharepoint-list-using-snapshotting/">versioning attachments in a SharePoint list using snapshotting</a>, an event receiver was responsible for the heavy lifting. To enable versioning of a list, I could therefore have associated the receiver with a list by adding the usual registration XML to a feature. But versioning is a truly reusable building block that shouldn’t be restricted to lists that are known when the feature is created. A better solution would be to extend the SharePoint list settings page for all lists on a site on which the versioning feature is enabled. The user may then activate or deactivate attachment versioning on the fly.</p>
<p>This would involve adding or removing event receivers from a list as the user enables or disables versioning. The following extension method is one way to accomplish the addition-part in a type-safe manner:</p>
<pre class="prettyprint lang-cs">// definition
public static class SPListExtensions {
    public static void RegisterEventReceiver&lt;TReceiver&gt;(this SPList list,
            SPEventReceiverType receiverType,
            int sequenceNumber) where TReceiver : SPItemEventReceiver {
        var assemblyName = typeof(TReceiver).Assembly.FullName;
        var className = typeof(TReceiver).FullName;

        (from SPEventReceiverDefinition definition in list.EventReceivers
         where definition.Assembly == assemblyName &amp;&amp;
               definition.Class == className &amp;&amp;
               definition.Type == receiverType
         select list.EventReceivers[definition.Id])
        .ToList()
        .ForEach(receiverToDelete =&gt; receiverToDelete.Delete());

        var receiver = list.EventReceivers.Add();
        receiver.Type = receiverType;
        receiver.Assembly = assemblyName;
        receiver.Class = className;
        receiver.SequenceNumber = sequenceNumber;
        receiver.Update();
        list.Update();
    }
}

// use
list.RegisterEventReceiver&lt;ListAttachmentVersioningEventReceiver&gt;(
    SPEventReceiverType.ItemAdded, 10000);
list.RegisterEventReceiver&lt;ListAttachmentVersioningEventReceiver&gt;(
    SPEventReceiverType.ItemUpdated, 10001);</pre>
<p>Under rare circumstances the (assembly, class, type) tuple may not be unique, i.e., the same receiver may be registered multiple times, albeit with different sequence numbers. In practice I never found any use for this functionality, though, which is why I didn’t include the sequence number in the where clause above, causing all registrations matching the tuple to be removed.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2011%2F11%2F19%2Fadding-event-receivers-to-sharepoint-lists-on-the-fly%2F&amp;title=Adding%20event%20receivers%20to%20SharePoint%20lists%20on%20the%20fly" id="wpa2a_8"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2011/11/19/adding-event-receivers-to-sharepoint-lists-on-the-fly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handy SharePoint 2010 extension methods for list definitions</title>
		<link>http://www.bugfree.dk/blog/2011/11/15/handy-sharepoint-2010-extension-methods-for-list-definitions/</link>
		<comments>http://www.bugfree.dk/blog/2011/11/15/handy-sharepoint-2010-extension-methods-for-list-definitions/#comments</comments>
		<pubDate>Tue, 15 Nov 2011 05:59:18 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1068</guid>
		<description><![CDATA[A quick word on organizing extension methods: I usually collect them in an Extensions folder, appending Extensions to the name of class being extended and keeping with the one class per file convention. For brevity I’ve left out the using and the namespace part below. SPListCollection extensions In SharePoint 2010 the TryGetList method has been [...]]]></description>
			<content:encoded><![CDATA[<p>A quick word on organizing extension methods: I usually collect them in an Extensions folder, appending Extensions to the name of class being extended and keeping with the one class per file convention. For brevity I’ve left out the using and the namespace part below.</p>
<h4>SPListCollection extensions</h4>
<p>In SharePoint 2010 the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistcollection.trygetlist.aspx">TryGetList</a> method has been added to the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistcollection.aspx">SPListCollection</a> class. The method returns either an <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splist.aspx">SPList</a> instance matching the display name or null. Oftentimes, however, you want to do a lookup based on the internal name. Here’s an extension method that adheres to the semantics of TryGetList, but using the internal name. It relies on the fact that the RootFolder property of a list is actually its internal name:</p>
<pre class="prettyprint lang-cs">// definition
public static class SPListCollectionExtensions {
    public static SPList TryGetListByInternalName(this SPListCollection lists, string internalName) {
        return (from SPList l in lists
            where l.RootFolder.Name == internalName
            select l).SingleOrDefault();
    }
}

// use
if (site.Lists.TryGetListByInternalName(internalListName) == null)
   // list not found</pre>
<h4>SPFieldCollection extensions</h4>
<p>Using the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldcollection.createnewfield.aspx">CreateNewField</a> method of the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldcollection.aspx">SPFieldCollection</a> you can add new fields to a list. The particular annoying aspect of this method, however, is that when you want to continue working with its result, oftentimes you have to cast it to one of the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfield.aspx">SPField</a> subclasses. But since the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldtype.aspx">SPFieldType</a>, provided as one of the arguments to CreateNewField, closely relates to the actual SPField return type, an extension method is able to do the casting. This’ll expose mismatches at compile time instead of at runtime.</p>
<p>All it takes is for us to map out the relation between SPField and SPFieldType:</p>
<pre class="prettyprint lang-cs">// definition
public static class SPFieldCollectionExtensions {
    public static TSPField CreateField&lt;TSPField&gt;(this SPFieldCollection fields,
            string internalName, string displayName) where TSPField : SPField {
        var spFieldToFieldType = new Dictionary&lt;Type, SPFieldType&gt; {
            { typeof(SPFieldDateTime), SPFieldType.DateTime },
            { typeof(SPFieldNumber), SPFieldType.Number },
            { typeof(SPFieldUser), SPFieldType.User },
            { typeof(SPFieldBoolean), SPFieldType.Boolean },
            { typeof(SPFieldMultiLineText), SPFieldType.Note },
            { typeof(SPFieldText), SPFieldType.Text }
        };

        var fieldType = spFieldToFieldType[typeof(TSPField)];
        var list = fields.List;
        var field = list.Fields[list.Fields.Add(internalName, fieldType, false)];
        field.Title = displayName;
        field.Update();
        return field as TSPField;
    }
}

// use
l.Fields.CreateField&lt;SPFieldBoolean&gt;(internalName, &quot;displayName&quot;);</pre>
<p>Taking the CreateField extension method one step further, oftentimes you want to set properties besides internal name and display name. For that purpose I’ve defined a CreateField method that accepts an Action&lt;TField&gt;. This allows you to reuse common property settings across fields for brevity and consistency while at the same time maintaining strong typing.</p>
<pre class="prettyprint lang-cs">// definition
public static TSPField CreateField&lt;TSPField&gt;(this SPFieldCollection fields,
        string internalName, string displayName,
        Action&lt;TSPField&gt; setAdditionalProperties) where TSPField : SPField {
    var newField = CreateField&lt;TSPField&gt;(fields, internalName, displayName);
    setAdditionalProperties(newField);
    newField.Update();
    return newField;
}

// use
public static Action&lt;SPFieldMultiLineText&gt; RichTextProperties = f =&gt; {
    f.RichText = true;
    f.RichTextMode = SPRichTextMode.FullHtml;
};

l.Fields.CreateField&lt;SPFieldBoolean&gt;(internalName, &quot;displayName&quot;, f =&gt; f.Required = true);
l.Fields.CreateField(internalName, &quot;displayName&quot;, RichTextProperties);</pre>
<p>With the Comment field, you can leave out the type argument because the compiler infers it based on the type of the Action delegate.</p>
<p>Similar to CreateField, I’ve defined two additional extension methods for creating lookup fields:</p>
<pre class="prettyprint lang-cs">// definition
public static TSPField CreateLookup&lt;TSPField&gt;(this SPFieldCollection fields,
        string lookupListName, string internalName,
        string displayName) where TSPField : SPFieldLookup {
    var currentList = fields.List;
    var lookupList = currentList.ParentWeb.Lists.TryGetListByInternalName(lookupListName);
    var newField = currentList.Fields[currentList.Fields.AddLookup(internalName, lookupList.ID, false)];
    newField.Title = displayName;
    newField.Update();
    return newField as TSPField;
}

public static TSPField CreateLookup&lt;TSPField&gt;(this SPFieldCollection fields,
        string lookupListName, string internalName, string displayName,
        Action&lt;TSPField&gt; setAdditionalProperties) where TSPField : SPFieldLookup {
    var newField = CreateLookup&lt;TSPField&gt;(fields, lookupListName, internalName, displayName);
    setAdditionalProperties(newField);
    newField.Update();
    return newField;
}

// use
l.Fields.CreateLookup&lt;SPFieldLookup&gt;(lookupListName, internalName, displayName, f =&gt; f.AllowMultipleValues = true);</pre>
<p>These extension methods makes using the SharePoint API more type-safe and concise, and defining lists using these methods and the <a href="http://www.bugfree.dk/blog/2010/01/11/sharepoint-list-definition-using-the-template-pattern/">template approach</a> saves me from writing a lot of repetitive code.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2011%2F11%2F15%2Fhandy-sharepoint-2010-extension-methods-for-list-definitions%2F&amp;title=Handy%20SharePoint%202010%20extension%20methods%20for%20list%20definitions" id="wpa2a_10"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2011/11/15/handy-sharepoint-2010-extension-methods-for-list-definitions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A table-driven approach to creating SharePoint sites with PowerShell</title>
		<link>http://www.bugfree.dk/blog/2011/11/13/a-table-driven-approach-to-creating-sharepoint-sites-with-powershell/</link>
		<comments>http://www.bugfree.dk/blog/2011/11/13/a-table-driven-approach-to-creating-sharepoint-sites-with-powershell/#comments</comments>
		<pubDate>Sun, 13 Nov 2011 15:31:29 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Powershell]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1069</guid>
		<description><![CDATA[While cleaning up some PowerShell installations scripts that I wrote some time ago, I come across the following piece of code (modified slightly for anonymity) for creating a hierarchy of SharePoint sites and setting the locale for a subset of the sites. It works but it sure doesn’t adhere to the DRY principle. New-SPWeb -url [...]]]></description>
			<content:encoded><![CDATA[<p>While cleaning up some PowerShell installations scripts that I wrote some time ago, I come across the following piece of code (modified slightly for anonymity) for creating a hierarchy of SharePoint sites and setting the locale for a subset of the sites. It works but it sure doesn’t adhere to the DRY principle.</p>
<pre class="prettyprint">New-SPWeb -url $base_url -addtoquicklaunch -template "STS#1" -name "Base"
New-SPWeb -url $base_url/Dk -addtoquicklaunch -template "STS#1" -name "Dk"
New-SPWeb -url $base_url/Uk -addtoquicklaunch -template "STS#1" -name "Uk"
New-SPWeb -url $base_url/Dk/BusinessUnit1 -addtoquicklaunch -template "STS#1" -name "BusinessUnit1"
New-SPWeb -url $base_url/Dk/BusinessUnit2 -addtoquicklaunch -template "STS#1" -name "BusinessUnit2"
New-SPWeb -url $base_url/Uk/BusinessUnit1 -addtoquicklaunch -template "STS#1" -name "BusinessUnit1"
New-SPWeb -url $base_url/Uk/BusinessUnit2 -addtoquicklaunch -template "STS#1" -name "BusinessUnit2"

$dk = Get-SPWeb $base_url/Dk
$dkBusinessUnit1 = Get-SPWeb $base_url/Dk/BusinessUnit1
$dkBusinessUnit2 = Get-SPWeb $base_url/Dk/BusinessUnit2

$locale = [System.Globalization.CultureInfo]::CreateSpecificCulture("da-DK")
$dk.Locale = $locale
$dk.Update()

$dkBusinessUnit1.Locale = $locale
$dkBusinessUnit1.Update()

$dkBusinessUnit2.Locale = $locale
$dkBusinessUnit2.Update()</pre>
<p>How can we reduce this repetition? Well, it repeats because we’ve made the common mistake of mixing logic with data. One way to separate the two is using a table-driven approach, i.e., extract the varying parts, the data, into a table and rewrite the logic so it’s parameterized by the table. After some trial and error with PowerShell here’s the code I ended up with:</p>
<pre class="prettyprint">$sites = @( @("", "Base"),
            @("Dk", "Dk", "da-DK"),
            @("Uk", "Uk"),
            @("Dk/BusinessUnit1", "BusinessUnit1", "da-DK"),
            @("Dk/BusinessUnit2", "BusinessUnit2", "da-DK"),
            @("Uk/BusinessUnit1", "BusinessUnit1"),
            @("Uk/BusinessUnit2", "BusinessUnit2") )

$sites | foreach {
  $url, $title, $culture = $_
  $newSite = New-SPWeb -url "$base_url/$url" -addtoquicklaunch -template "STS#1" -name $title

  if ($culture -ne "") {
    $locale = [System.Globalization.CultureInfo]::CreateSpecificCulture($culture)
    $newSite.Locale = $locale
    $newSite.Update()
  }
}</pre>
<p>So far so good. The un-installation part of the script, however, follows the same pattern of repetition:</p>
<pre class="prettyprint">Remove-SPWeb -identity $base_url/Uk/BusinessUnit2 -confirm:$false -ErrorAction SilentlyContinue
Remove-SPWeb -identity $base_url/Uk/BusinessUnit1 -confirm:$false -ErrorAction SilentlyContinue
Remove-SPWeb -identity $base_url/Dk/BusinessUnit2 -confirm:$false -ErrorAction SilentlyContinue
Remove-SPWeb -identity $base_url/Dk/BusinessUnit1 -confirm:$false -ErrorAction SilentlyContinue
Remove-SPWeb -identity $base_url/Dk -confirm:$false -ErrorAction SilentlyContinue
Remove-SPWeb -identity $base_url/Uk -confirm:$false -ErrorAction SilentlyContinue
Remove-SPWeb -identity $base_url -confirm:$false</pre>
<p>But now that we have the table of sites at hand, we can easily make the site removal table-driven as well:</p>
<pre class="prettyprint">function Reverse($array) {
  $clone = $array.Clone()
  [Array]::Reverse($clone)
  $clone
}

Reverse($sites) | foreach {
  $url = $_[0]
  Remove-SPWeb -identity "$base_url/$url" -confirm:$false -ErrorAction SilentlyContinue
}</pre>
<p>I’m sure the code could be written more elegantly, but given my working knowledge of PowerShell I’m satisfied with the result. I especially like the functional programming style.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2011%2F11%2F13%2Fa-table-driven-approach-to-creating-sharepoint-sites-with-powershell%2F&amp;title=A%20table-driven%20approach%20to%20creating%20SharePoint%20sites%20with%20PowerShell" id="wpa2a_12"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2011/11/13/a-table-driven-approach-to-creating-sharepoint-sites-with-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes from Geek Night talk on Advanced Windsor Tricks</title>
		<link>http://www.bugfree.dk/blog/2010/12/19/notes-from-geek-night-talk-on-advanced-windsor-tricks/</link>
		<comments>http://www.bugfree.dk/blog/2010/12/19/notes-from-geek-night-talk-on-advanced-windsor-tricks/#comments</comments>
		<pubDate>Sun, 19 Dec 2010 11:03:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1066</guid>
		<description><![CDATA[My notes from a talk on Windsor by Mogens Heller Grabe which I attended this week. Slides and code are available through Dropbox, but I don’t know for how long. Use an Inversion of Control container (IoC) like Windsor to create an architecture that responds well to change, i.e., an architecture that promotes looser coupling [...]]]></description>
			<content:encoded><![CDATA[<p>My notes from a <a href="http://secure.trifork.com/aarhus-2010/freeevent/index.jsp?eventOID=2756">talk on Windsor</a> by <a href="http://mookid.dk/oncode">Mogens Heller Grabe</a> which I attended this week. <a href="http://dl.dropbox.com/u/8614955/Avancerede%20Windsor-tricks%20-%20H%C3%B8je%20Taastrup.pdf">Slides</a> and <a href="http://dl.dropbox.com/u/8614955/Avancerede%20Windsor-tricks.zip">code</a> are available through Dropbox, but I don’t know for how long.</p>
<ul>
<li>Use an Inversion of Control container (IoC) like <a href="http://stw.castleproject.org/Windsor.MainPage.ashx">Windsor</a> to create an architecture that responds well to change, i.e., an architecture that promotes looser coupling and higher cohesion </li>
<li>The ability to write unit tests against a code base is a good measure of its degree of coupling </li>
<li>By having components depend on interfaces, you’re free to switch the implementation at runtime, introducing flexibility into the software </li>
<li>Avoid having concrete components talk to each other. It makes it hard for the two to vary independently, e.g., adding logging later can only be done by tearing components apart and putting them back together </li>
<li>At runtime the IoC container recursively composes these smaller components into an object graph, e.g., by passing concrete implementations through the constructors to satisfy the dependencies </li>
<li>One alternative to using an IoC container is using a service locator. Each component’s constructor would then ask the locator for its dependent components. While this approach works, it makes testing components in isolation difficult because all dependencies are now locked away inside the service locator. Instead, by having all dependencies supplied in the constructor, unit tests can directly supply fakes implementations </li>
<li>When software is only used in one environment it tends to be fairly inflexible because it’s only suited for that one purpose. As soon as you design it to be used in two or more environments it becomes more flexible. Thing of different environments as unit test, staging, production, and so on </li>
<li>The idea is for components to not have to be modified depending on the where they’re running. It’s the IoC container that dynamically tie components together based on the environment </li>
<li>Suppose you didn’t use a IoC container. Then ultimately the top-level object would have to pass concrete instances down the chain. The top-level object may well be the UI layer. But having the UI layer know about data access components, service components, and logging components isn’t ideal. Instead use an IoC container, which is nothing more than a factory for components </li>
<li>With the Windsor IoC container (and most others), the usage pattern typically involves three stages
<ul>
<li>Register: tie together interfaces with concrete implementations </li>
<li>Resolve: return concrete implementations of interfaces required to satisfy the dependencies of an object </li>
<li>Release: dispose of concrete implementations </li>
</ul>
</li>
<li>Most people only use a fraction of the functionality of an IoC container. Instead of taking dependency of a full-blown container, you could easily <a href="http://msdn.microsoft.com/en-us/magazine/cc337885.aspx">roll your own IoC container</a> that implements the core functionality in a few dozen lines of code &#8212; in an associated <a href="http://www.dotnetrocks.com/default.aspx?showNum=362">.NET Rocks</a> and <a href="http://www.dnrtv.com/default.aspx?showNum=126">DnrTV</a> episode <a href="http://www.jameskovacs.com">James Kovacs</a> elaborates on his original article </li>
<li>The goal of using a container isn’t to get rid of calls to the new operator. It’s to not use the new operator for the parts of an applications where flexibility is required </li>
<li>Simple forms of <a href="http://en.wikipedia.org/wiki/Aspect_oriented_programming">Aspect Oriented Programming</a> are possible using interceptors </li>
<li>Windsor supports the decorator pattern so you can have one component wrap another at runtime. This lets you implement features such as logging without actually modifying the original component. It’s an example of adhering to the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">open/close principle</a> by which classes should be open for extension, but closed for modification. In other words: don’t edit the original source code to introduce new behavior. Instead use methods of composition </li>
<li>Avoid configuring Windsor through XML and instead use the fluent interface &#8212; perhaps in a separate assembly so only it needs to be redeployed when the configuration changes. When a value, such as a connection string needs to be configurable, create a section in app.config and add the value there. Windsor will know how to locate the value when instantiating objects</li>
</ul>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2010%2F12%2F19%2Fnotes-from-geek-night-talk-on-advanced-windsor-tricks%2F&amp;title=Notes%20from%20Geek%20Night%20talk%20on%20Advanced%20Windsor%20Tricks" id="wpa2a_14"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2010/12/19/notes-from-geek-night-talk-on-advanced-windsor-tricks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes from Geek Night talk on SOA Done Right Using NServiceBus</title>
		<link>http://www.bugfree.dk/blog/2010/12/11/notes-from-geek-night-talk-on-soa-done-right-using-nservicebus/</link>
		<comments>http://www.bugfree.dk/blog/2010/12/11/notes-from-geek-night-talk-on-soa-done-right-using-nservicebus/#comments</comments>
		<pubDate>Sat, 11 Dec 2010 08:39:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1065</guid>
		<description><![CDATA[My notes from a talk on NServiceBus by Mogens Heller Grabe which I attended this week. Slides and code are available through Dropbox, but I don’t know for how long. Enterprise service bus An architectural pattern rather than a specific technology or product The ethernet of SOA Types of service bus Centralized: a broker more [...]]]></description>
			<content:encoded><![CDATA[<p>My notes from a <a href="https://secure.trifork.com/aarhus-2010/freeevent/index.jsp?eventOID=2758">talk on NServiceBus</a> by <a href="http://mookid.dk/oncode">Mogens Heller Grabe</a> which I attended this week. <a href="http://dl.dropbox.com/u/8614955/SOA%20Done%20Right%21%20-%20H%C3%B8je%20Taastrup.pdf">Slides</a> and <a href="http://dl.dropbox.com/u/8614955/SOA%20Done%20Right%21.zip">code</a> are available through Dropbox, but I don’t know for how long.</p>
<ul>
<li>Enterprise service bus
<ul>
<li>An architectural pattern rather than a specific technology or product </li>
<li>The ethernet of SOA </li>
</ul>
</li>
<li>Types of service bus
<ul>
<li>Centralized: a broker more than a bus, e.g., BizTalk </li>
<li>Decentralized: a real service bus, e.g., <a href="http://www.nservicebus.com">NServiceBus</a>, <a href="http://code.google.com/p/masstransit">Mass Transit</a>, <a href="http://ayende.com/Blog/archive/2008/12/17/rhino-service-bus.aspx">Rhino Service Bus</a>, <a href="http://msdn.microsoft.com/en-us/magazine/dd569756.aspx">MS .NET Service bus</a> </li>
</ul>
</li>
<li>The current version 2.0 of NServiceBus is free whereas the binary version 2.5 will contain limitations. The limitations can be disabled by downloading and compiling the source code yourself </li>
<li>NServiceBus is designed to address the <a href="http://en.wikipedia.org/wiki/Fallacies_of_Distributed_Computing">fallacies of distributed computing</a>
<ul>
<li>It primarily addresses the fallacies through the use of reliable one-way messaging </li>
<li>Reliable means messages are stored in a queue, such a MSMQ, which is part of all recent Windows installations. The assumption being that the queue is always present and ready to receive messages </li>
<li>One-way means messages are asynchronous and fire-and-forget. The destination service doesn’t have to be online when a message goes into its queue, which makes services temporally independent. At some point in the future the service may post a reply to the client’s queue </li>
<li>Messaging means that any action is accomplished by posting a self-contained message, containing the type of operation and its parameters, to the queue of a service </li>
<li>With NServiceBus, a class is marked with an interface to describe that it’s a type of message. Instances of the class are then serialized using a standard XML or binary serializer and stored in a queue </li>
</ul>
</li>
<li>NServiceBus service != traditional web service
<ul>
<li>An NServiceBus service is a class that implements an interface </li>
<li>Using a message queue is more reliable when the service has to make calls to other services as part of its operation. With a traditional web service, calling other services from within makes the service slower and less reliable. If only one dependent service is down it’s like with old Christmas lights wired in series: the entire stack may be down. Queues on the other hand introduce a save place, a <a href="http://elegantcode.com/2010/12/17/christmas-light-architectures-are-not-that-shiny">stabilization point</a>, to temporarily store messages </li>
<li>A service is typically configured with an input queue that identifies it to others and an error queue that messages are routed to after some number of retries. In addition, each service may be configured with a number of threads to use to parallelize message processing </li>
</ul>
</li>
</ul>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2010%2F12%2F11%2Fnotes-from-geek-night-talk-on-soa-done-right-using-nservicebus%2F&amp;title=Notes%20from%20Geek%20Night%20talk%20on%20SOA%20Done%20Right%20Using%20NServiceBus" id="wpa2a_16"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2010/12/11/notes-from-geek-night-talk-on-soa-done-right-using-nservicebus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes from Tech Talk on Advanced .NET debugging with Windbg</title>
		<link>http://www.bugfree.dk/blog/2010/11/28/notes-from-tech-talk-on-advanced-net-debugging-with-windbg/</link>
		<comments>http://www.bugfree.dk/blog/2010/11/28/notes-from-tech-talk-on-advanced-net-debugging-with-windbg/#comments</comments>
		<pubDate>Sun, 28 Nov 2010 11:02:20 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1064</guid>
		<description><![CDATA[My notes from a talk on Windbg by Brian Rasmussen which I attended this week. The talk was recorded and parts one and two are available though Channel 9. Windbg isn’t a replacement for VS, but VS doesn’t handle some advanced cases Windbg is a free user mode/kernel mode debugger which is part of the [...]]]></description>
			<content:encoded><![CDATA[<p>My notes from a <a href="http://kodehoved.dk/?p=696">talk on Windbg</a> by <a href="http://kodehoved.dk/?page_id=27">Brian Rasmussen</a> which I attended this week. The talk was recorded and parts <a href="http://channel9.msdn.com/posts/MDCC-TechTalk-Advanced-NET-Debugging-part-1">one</a> and <a href="http://channel9.msdn.com/posts/MDCC-TechTalk-Advanced-NET-Debugging-part-2">two</a> are available though Channel 9.</p>
<ul>
<li>Windbg isn’t a replacement for VS, but VS doesn’t handle some advanced cases </li>
<li>Windbg is a free user mode/kernel mode debugger which is part of the <a href="http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx">Debugger Tools for Windows</a> </li>
<li>Customers may not be happy installing VS to debug code in production since it installs a lot of components and requires restarts
<ul>
<li>Windbg requires only a simple installation once you extract the redistributable from the Debugger Tools for Windows <!--EndFragment--></li>
</ul>
</li>
<li>Loading <a href="http://msdn.microsoft.com/en-us/library/bb190764(v=VS.100).aspx">SOS.dll</a> from the Microsoft .NET folder into Windbg makes it understand .NET
<ul>
<li>With SOS.dll loaded, you can look into the CLR and its data structures </li>
<li>Make sure to load the right SOS.dll for your runtime </li>
<li>SOS.dll is also available for the Silverlight runtime </li>
</ul>
</li>
<li>Debugger Markup Language support is available for version 4 of SOS.dll
<ul>
<li>Provides hyperlinks in the command output of SOS </li>
</ul>
</li>
<li>Like with the VS debugger, you can insert Debug.Break() in your demo app and have Windbg halt on it
<ul>
<li>Release builds can be debugged with Windbg </li>
<li>Release builds also contain symbols. Like with debug builds, symbols are stored in a separate file </li>
<li>Release builds make debugging harder because the jitter kicks in and modifies the code </li>
<li>The 64 bit calling convention of passing arguments via registers makes it harder to locate information when debugging </li>
</ul>
</li>
<li>Windbg generally needs symbols loaded, although it’s less important when debugging managed code
<ul>
<li>Use MS’ public symbol server to load symbols on demand </li>
<li>Set the <a href="http://support.microsoft.com/kb/311503">_NT_SYMBOL_PATH</a> environment variable to point to your symbols (will affect VS as well) </li>
<li>Or use the <a href="http://msdn.microsoft.com/en-us/library/ff565400(VS.85).aspx">.symfix</a> command from within Windbg </li>
</ul>
</li>
<li>Popular extensions to Windbg: <a href="http://www.stevestechspot.com/SOSEXV40NowAvailable.aspx">SOSEX</a> and <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=5c068e9f-ebfe-48a5-8b2f-0ad6ab454ad4&amp;displaylang=en">Psscor2</a> (replacement for SOS, useful for ASP.NET debugging) </li>
<li>Create dump file to analyze: use task manager or <a href="http://support.microsoft.com/kb/286350">ADPlus</a> or <a href="http://technet.microsoft.com/en-us/sysinternals/dd996900.aspx">ProcDump</a> from Sysinternals, which can dump based on triggers </li>
<li>ADPlus collects crash dumps or hang dumps
<ul>
<li>Hang dumps can be captured from the same process multiple times and may be useful when debugging deadlocks or resource leaks </li>
<li>When you capture a hang dump, the process is halted for the dump period and is then restarted </li>
</ul>
</li>
<li>A *32 process in task manager is actually a 64 bit process when you dump it
<ul>
<li><a href="http://en.wikipedia.org/wiki/WoW64">WoW64.dll</a> is involved when dumping from the task manager </li>
<li>Not what you typically want because you don’t get full access to 32 bit process information </li>
</ul>
</li>
<li>A .NET application is hosted within the CLR which is itself hosted within a regular Windows process
<ul>
<li>Looking at memory usage with the task manager therefore doesn’t tell you much about the .NET part </li>
</ul>
</li>
</ul>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2010%2F11%2F28%2Fnotes-from-tech-talk-on-advanced-net-debugging-with-windbg%2F&amp;title=Notes%20from%20Tech%20Talk%20on%20Advanced%20.NET%20debugging%20with%20Windbg" id="wpa2a_18"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2010/11/28/notes-from-tech-talk-on-advanced-net-debugging-with-windbg/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Essential requirements for a developer automation tool</title>
		<link>http://www.bugfree.dk/blog/2010/09/26/essential-requirements-for-a-developer-automation-tool/</link>
		<comments>http://www.bugfree.dk/blog/2010/09/26/essential-requirements-for-a-developer-automation-tool/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 11:19:26 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Powershell]]></category>
		<category><![CDATA[Process]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1058</guid>
		<description><![CDATA[Developer automation is a subject that I&#8217;ve always felt passionate about. Unit testing may be the most common example, but other tasks may include check-out of source code, build, deploy, setup, and warm-up of an application. I may even want one system rule them all and have the same automation drive continuous integration. Whatever the [...]]]></description>
			<content:encoded><![CDATA[<p>Developer automation is a subject that I&#8217;ve always felt passionate about. Unit testing may be the most common example, but other tasks may include check-out of source code, build, deploy, setup, and warm-up of an application. I may even want <a href="http://simpleprogrammer.com/2010/09/03/one-build-to-rule-them-all">one system rule them all</a> and have the same automation drive <a href="http://martinfowler.com/articles/continuousIntegration.html">continuous integration</a>. Whatever the use, to fully reap the benefits of automation, a developer should master at least one automation tool the same way he masters other developer tools. This and later posts capture my experiences with a few such automation tools centered around Windows and .NET, starting with why the ubiquitous <a href="http://en.wikipedia.org/wiki/Batch_files">batch file</a> is best avoided and how to characterize better solutions in terms of it.</p>
<p>Although Visual Studio, in tandem with the <a href="http://en.wikipedia.org/wiki/Msbuild">MSBuild engine</a>, generally takes good care of compilation, I rarely want to rely on it solely. Instead, I’d prefer that any developer task be easily run from the command-line. This ensures that no magic is going on, that the task is kept simple and flexibility, and that it doesn’t rely on Visual Studio to work. The challenge, however, is which of the many tools available to pick. It must be one that’s flexible enough to meet most requirements with relative ease or the automation will likely not be a valid documentation medium in itself.</p>
<h4>Why not to use Windows batch files</h4>
<p>As a general example, consider the deployment of a <a href="http://www.bugfree.dk/blog/2010/03/31/getting-started-with-sharepoint-presentation">SharePoint 2007 solution</a>. With SharePoint a good deal more than compiling is needed to bring new functionality into a SharePoint installation. Whereas Visual Studio and MSBuild may still compile the code and <a href="http://wspbuilder.codeplex.com">WSPBuilder</a> create the WSP installation package, both from within Visual Studio and from the command-line, getting everything setup cries for automation, even locally. A common approach (possibly inspired by <a href="http://www.amazon.com/Microsoft-Windows-SharePoint-Services-Developer/dp/0735623201/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1285960936&amp;sr=8-1">popular</a> SharePoint 2007 literature) is that of the batch file applying various operations to a WSP. For the sake of brevity, I&#8217;ve kept the example short, but imagine extending it with a check-out source code task, a compilation task, a WSPBuilder task, and a feature deactivation and activation task, and possibly a warm-up task. Add to this a master script that orchestrate the whole thing. In the end, I’d end up with scripts that become increasingly harder to maintain as they grow in number and size.</p>
<pre class="prettyprint lang-sh">    @set STSADM=&quot;c:\program files\common files\microsoft shared\web server extensions\12\bin\stsadm&quot;

    if &quot;%1&quot; == &quot;uninstall&quot; goto uninstall
    if &quot;%1&quot; == &quot;install&quot; goto install
    if &quot;%1&quot; == &quot;&quot; goto reinstall

    :uninstall
        %STSADM% -o retractsolution -name Foo.wsp -immediate
        %STSADM% -o execadmsvcjobs
        %STSADM% -o deletesolution -name Foo.wsp -override
        goto end

    :install
        %STSADM% -o addsolution -filename Foo.wsp
        %STSADM% -o deploysolution -name Foo.wsp -immediate -allowGacDeployment -force
        %STSADM% -o execadmsvcjobs
        goto end

    :reinstall
        call Foo uninstall
        call Foo install
        goto end

    :end</pre>
<p>Still, because of the ubiquitous nature of command.com and cmd.exe, the batch file interpreters, batch files are everywhere. Regardless that the technology is a left-over from the days of MS DOS and haven&#8217;t evolved much since. Not only are the branching and looping constructs limited, so are the <a href="http://technet.microsoft.com/en-us/library/dd560674(WS.10).aspx">available commands</a>. Suppose I want to find out if a command was indeed successful. This turns out to be really hard when all I have to work with is the <a href="http://en.wikipedia.org/wiki/Errorlevel">errorlevel</a> of the most recently executed command. Assuming the command adheres to the errorlevel convention, for the script to fail as early and as close to the real error as possible, I’d have to inspect the property after each command, causing the batch file to grow quite verbose. Sadly, batch files lack the equivalent of <a href="http://www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2399158">set -o errexit</a> of <a href="http://en.wikipedia.org/wiki/Bash_(Unix_shell)">Bash</a>, where the interpreter checks for success after each command and aborts immediately on error. Relying solely on the errorlevel is oftentimes insufficient anyway. To determine success, I’d typically have to parse actual command output or inspect some system property by downloading additional commands or building my own.</p>
<h4>Essential vs. incidental requirements</h4>
<p>Unless I plan to sit idle and stare at the screen and be a human error detector while the batch file run, I think it’s safe to say that it’s mostly unsuitable for developer automation. Hence in late 2005 I <a href="http://www.bugfree.dk/blog/2006/01/04/being-a-functional-pythonian">rolled my own automation tool in Python</a>. With Python or Ruby or a similar dynamic language acting as the glue that ties everything together, almost any task can be automated in a robust way. Of course, I could also automate with a static language like C# (it&#8217;s surprisingly common). But for script-like tasks, I don’t particularly fancy the long cycle of editing source code in Visual Studio, compiling it, deploying it, and having a hard time debugging it in environment without Visual Studio. A dynamic language, on the other hand, short-circuits the development cycle and allows for interactive programming through a <a href="http://en.wikipedia.org/wiki/REPL">REPL</a>.</p>
<p>With a dynamic language that interacts with .NET, such as <a href="http://en.wikipedia.org/wiki/Ironpython">IronPython</a>, <a href="http://en.wikipedia.org/wiki/IronRuby">IronRuby</a>, or <a href="http://en.wikipedia.org/wiki/Powershell">Powershell</a>, possibly with supporting DSLs like <a href="http://www.blueskyonmars.com/projects/paver">Paver</a>, <a href="http://en.wikipedia.org/wiki/Rake_(software)">Rake</a>, or <a href="http://en.wikipedia.org/wiki/Psake">psake</a> on top, the need for writing custom commands to interact with the operating system or the application almost vanishes. The question, then, is which of the dynamic languages to go with when at their technical core they’re so much alike. Besides sharing the concept of a REPL, the notion of a tuple, a list, a map, and operations on each are baked into their syntax, making code quite terse. It even makes it convenient to express any configuration in the language itself and not in XML where I’d first have to come up with a schema, and then create an instance of it before parsing it. On Windows, however, Powershell is gradually becoming the next ubiquitous interpreter, with applications shipping with cmdlets, whereas IronPython or IronRuby is a separate download.</p>
<h4>Conclusion</h4>
<p>No matter the tool, what I end up doing is defining tasks, form dependencies between tasks, and have the tool execute tasks in an order that satisfies their dependencies. As the tool traverses the dependency graph and executes tasks, it’s up to each task to detect success, and up to the tool to report on progress. A good tool is therefore characterized by the ease with which I can express these things, the available language constructs, the ease of debugging, and the tool’s ability to converse in foreign languages.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2010%2F09%2F26%2Fessential-requirements-for-a-developer-automation-tool%2F&amp;title=Essential%20requirements%20for%20a%20developer%20automation%20tool" id="wpa2a_20"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2010/09/26/essential-requirements-for-a-developer-automation-tool/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2010%2F05%2F04%2Funit-testing-linq-to-sql-using-typemock%2F&amp;title=Unit%20testing%20LINQ%20to%20SQL%20using%20TypeMock" id="wpa2a_22"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F02%2F17%2Fusing-vs-linked-files-for-strong-naming-assemblies%2F&amp;title=Using%20VS%20linked%20files%20for%20strong%20naming%20assemblies" id="wpa2a_24"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F02%2F11%2Fan-example-of-unit-testing-using-typemock%2F&amp;title=An%20example%20of%20unit%20testing%20using%20TypeMock" id="wpa2a_26"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2008%2F06%2F29%2Fprototyping-linq-using-linqpad%2F&amp;title=Prototyping%20LINQ%20using%20LINQPad" id="wpa2a_28"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2008/06/29/prototyping-linq-using-linqpad/feed/</wfw:commentRss>
		<slash:comments>1</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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2007%2F10%2F29%2Fpurging-inactive-users-from-e107%2F&amp;title=Purging%20inactive%20users%20from%20e107" id="wpa2a_30"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2007%2F07%2F29%2Fgood-sharepoint-development-practices%2F&amp;title=Good%20SharePoint%20development%20practices" id="wpa2a_32"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2006%2F11%2F19%2Fcruisecontrolnet-and-build-queues%2F&amp;title=CruiseControl.net%20and%20build%20queues" id="wpa2a_34"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></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>

