I found myself in a situation recently where I needed the ability to copy a build definition in TFS on a fairly consistent basis. While this is a feature that has been requested before, unfortunately it hasn’t yet made it into the product. So I thought I would see if I could create a Visual Studio extension that would provide this functionality in reasonably short order.
I started off researching how I might use the TFS API to perform the copy. Of course, I couldn’t find much about how to create the copy, other than the various posts asking about or requesting this functionality. What I did find though was a blog post by Jakob Ehn on creating a build definition programmatically, which served as the basis for how I would perform the copy.
You start by getting a reference to the build server via a call to the GetService method on the TfsTeamProjectCollection instance as shown in the code snippet below. Once we have the build server reference we can then load the build definition that we’re making a copy of. The key to copying the build definition is making sure that you pick up all the original build attributes. That means iterating over all of the workspace mappings and process parameters, among the other build definition settings, as shown. Once we’re done creating the copy, simply call Save() on the new build definition to commit the changes to TFS.
One of the tricks of creating the copy is coming up with a meaningful name for the new build definition. You’ll see in the code snippet above at line 12 a call to GetNewBuildName(). I decided to take an approach similar to how Visual Studio creates copies of files within a project. That is, I look at the name of the build definition being copied and create the new build definition with a name of “Copy (n) of buildDefinitionName”. The implementation of this approach is shown in the following code snippet.
That’s all there is to it. The completed Visual Studio extension is available for install from the Extension Manager in Visual Studio (search for "copy build" in the online gallery) or you can download it directly from the Visual Studio Gallery.