Search code examples
tfstfs-sdk

How to update a custom TFS field programmatically


We have a custom build process (not using MS Build) and during that process I am adding a "fake" build to the global builds list. The reason I am doing that is so that you can select the build for a given work item (found in build). We have a custom field, build included, which is intended to show which build that work item was fixed in. I am having trouble figuring out how to update this field programmatically. The idea is I will have a small app that does this that I will call during the build process, finding all work items since the last build, then updating the field for those work items. Any ideas?


Solution

  • Something like this should work for you:

    public void UpdateTFSValue(string tfsServerUrl, string fieldToUpdate, 
       string valueToUpdateTo, int workItemID)
    {   
        // Connect to the TFS Server
        TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(tfsUri));
        // Connect to the store of work items.
        _store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
        // Grab the work item we want to update
        WorkItem workItem = _store.GetWorkItem(workItemId);
        // Open it up for editing.  (Sometimes PartialOpen() works too and takes less time.)
        workItem.Open();
        // Update the field.
        workItem.Fields[fieldToUpdate] = valueToUpdateTo;
        // Save your changes.  If there is a constraint on the field and your value does not 
        // meet it then this save will fail. (Throw an exception.)  I leave that to you to
        // deal with as you see fit.
        workItem.Save();    
    }
    

    An example of calling this would be:

    UpdateTFSValue("http://tfs2010dev:8080/tfs", "Integration Build", "Build Name", 1234);
    

    The variable fieldToUpdate should be the name of the field, not the refname (ie. Integration Build, not Microsoft.VSTS.Build.IntegrationBuild)

    You could probably get away with using PartialOpen(), but I am not sure.

    You will probably need to add Microsoft.TeamFoundation.Client to your project. (And maybe Microsoft.TeamFoundation.Common)