TFS 2010 - Bulk Updating Build Definitions (Retention Policies)
In this post, I just want to help those of you out there that have upgraded from 2008 and need to bulk update all of your definitions. In this particular example, I will be updating the retention policies to remove the deletion of the label with the deletion of the build. This code is not complicated but does pull in a lot of different areas. So, I wanted to provide an example for everyone...
Here's the code:
using System;
using System.Collections.Generic;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
namespace UpdateAllDefinitions
{
class Program
{
static void Main(string[] args)
{
Uri serverUrl = new Uri("https://jpricket-test3:8080/tfs/defaultcollection");
TfsTeamProjectCollection collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(serverUrl);
IBuildServer buildServer = collection.GetService<IBuildServer>();
ICommonStructureService css = collection.GetService<ICommonStructureService>();
// Get a query spec for each team project
List<IBuildDefinitionSpec> specs = new List<IBuildDefinitionSpec>();
foreach (ProjectInfo pi in css.ListProjects())
{
specs.Add(buildServer.CreateBuildDefinitionSpec(pi.Name));
}
// Query for all the definitions
IBuildDefinitionQueryResult[] results = buildServer.QueryBuildDefinitions(specs.ToArray());
// Update all the definition objects
List<IBuildDefinition> definitionsToSave = new List<IBuildDefinition>();
foreach (IBuildDefinitionQueryResult result in results)
{
if (result.Failures != null && result.Failures.Length > 0)
{
// print out the errors
foreach (IFailure f in result.Failures)
{
Console.WriteLine(f.Code + ": " + f.Message);
}
}
// There still might be some definitions to modify in this result
foreach (IBuildDefinition definition in result.Definitions)
{
// Check for null, but we have already printed the error for this bad result above
if (definition != null)
{
ChangeRetentionPolicies(definition);
definitionsToSave.Add(definition);
}
}
}
// Save all the definitions back to the server
buildServer.SaveBuildDefinitions(definitionsToSave.ToArray());
}
private static void ChangeRetentionPolicies(IBuildDefinition definition)
{
// Update the retention policies to not delete labels
foreach (IRetentionPolicy rp in definition.RetentionPolicyList)
{
rp.DeleteOptions = rp.DeleteOptions & ~DeleteOptions.Label;
}
}
}
}
Hope this saves you some time!