TFS API: Accessing build definition values programmatically

I’m working on some build customization and I needed to be able to access parameter values from my build definition programmatically.  It turned out to be pretty easy once I knew where to look:

We start off by connecting to TFS and then to the Build Service:

TfsTeamProjectCollection server = new TfsTeamProjectCollection(new Uri("http://myTFS:8080/tfs"));
server.EnsureAuthenticated(); 
IBuildServer build = (IBuildServer)server.GetService(typeof(IBuildServer));

That is followed by retrieving the build definition…you have a couple of options here, as you can use the build definition URL (something like vstfs:///Build/Definition/36), or you can supply the project name and build definition name, which makes things more readable:

IBuildDefinition buildDefinition = build.GetBuildDefinition("MyProject", "MyDefinition");

Build definition has a property called ProcessParameters where you can get all the names and values of the parameters that are defined in your build definition.  Don’t confuse that with buildDefinition.Process.Parameters, as that gives you the values as found in the underlying build template.  The ProcessParameters property is a string, but it stores a serialized Dictionary with all the keys and values found in the definition.  This code helps you get the values out of it (in my case I was looking for a string array):

object argumentValue;
if (WorkflowHelpers.DeserializeProcessParameters(buildDefinition.ProcessParameters).TryGetValue("MyArgumentName", out argumentValue))
{
    return (string[])argumentValue;
}

About esteban

Esteban is the Founder and Chief Technologist at Nebbia Technology, an ALM consulting and Azure-powered technology company. He is a software developer with a passion for ALM, TFS, Azure, and software development best practices. Esteban is a Microsoft Visual Studio ALM MVP and ALM Ranger, Pluralsight author, and the president of ONETUG (Orlando .NET User Group).

2 thoughts on “I’m on Radio TFS # 103!

  1. Renato Bento

    Thank you,
    this really helped me out!
    I was on a hard path trying to parse this parameters as a XmlDoc.

  2. Jorge Sanchez

    Hey I being using your code to accomplish the same thing but I never work with TFS before, I think I got it to the part that I could pass the ProjectFilePath and NewAssemblyName, but I not sure how to pass the Workspace InArgument do you have an example of how do I specify this on MsBuild?

    BTW i also change

    var workspace = context.GetValue(this.Workspace);
    to
    var workspace = (Workspace)context.GetValue(Workspace);

    is this correct?

    Thank you very much


Leave a Reply

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

Are you human? *