Monday, April 4, 2011

MSBuild - sort an ItemGroup

An automated MSBuild script that creates a database from scratch started failing after switching from vcvarall.bat provided by a Visual Studio 2008 install to the Visual Studio 2010 version.

For some unknown reason, the order of files listed in a ItemGroup was reversed. With files beginning with an underscore running last rather than first.

The issue was resolved by explicitly sorting the ItemGroup using a custom task from the MSBuild Extension Pack.

    <!-- Have a fallback check depending on path locally or on build server -->
        <TPath Condition="Exists('C:\Program Files (x86)\MSBuild\ExtensionPack\MSBuild.ExtensionPack.tasks')">C:\Program Files (x86)\MSBuild\ExtensionPack\MSBuild.ExtensionPack.tasks</TPath>
    <Import Project="$(TPath)"/>

    <!-- ... -->

    <Target Name="MainData">
        <Message Text="Inserting Data Main (Main Data)" />

        <!-- Sort an ItemGroup alphabetically -->
        <MSBuild.ExtensionPack.Framework.MsBuildHelper TaskAction="Sort" InputItems1="@(MainDataFiles)">
            <Output TaskParameter="OutputItems" ItemName="sorted"/>
        <Message Text="Sorted Items: %(sorted.Identity)"/>
        <Exec Command="$(SqlCmdPrefix) -i %(sorted.Identity)" />

See Also: