Custom Ad-hoc Code in TFS Build scripts

Last week I discovered an extremely coo feature in TFS build process.  Apparently you can write custom tasks that can compile and run .NET code on the fly.  I used to write various command line utilities to do that. They do give me a lot of control, but they require some extra work. Wouldn’t be cool to just have in-line C# code I can run as part of build by adding it to TFSBuild.proj file. It is possible, who knew…  As a result, I want to spread the news, as I think other folks may not know this feature exists.

First of all, we need to write a task.

<UsingTask TaskName="ReplaceTextInFile" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)Microsoft.Build.Tasks.v4.0.dll">
    <ParameterGroup>
        <FilePath ParameterType="System.String" Required="true" />
        <OldText ParameterType="System.String" Required="true" />
        <NewText ParameterType="System.String" Required="true" />
    </ParameterGroup>
    <Task>
        <Code Type="Fragment" Language="cs">
            <![CDATA[
string content = File.ReadAllText(FilePath);
content = content.Replace(OldText, NewText);
File.WriteAllText(FilePath, content);
]]>
        </Code>
    </Task>
</UsingTask>

I wish I remembered where on the web I found this little ide so that I can give the author proper creds.

This sample task above replaces text in a file with a different text. I actually had a utility for that that was updating version and configuration files for QA and production. I know, there are community tasks as well that update version, but we had custom requirement to versioning.

To call this task from the main script I simply do this in a target, in my case AfterGet target.

<ReplaceTextInFile FilePath="$(DropLocation)$(BuildNumber)MyAppIndex.htm" 
OldText="Latest" NewText="%(VersionToBeBuilt.Version)"/>

The usage above replaces key work Latest in my htm file that is included with ClickOnce application with the actual version that is set inside the main TFS build script. So easy…

Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *