TFS 2010 API - Create WorkItems (Bugs)
WorkItems (Bugs) can be filed in an automated way by using TFS 2010 API.
You first need to add a reference to Microsoft.TeamFoundation.Client.dll and Microsoft.TeamFoundation.WorkItemTracking.Client.
These DLLs can be found under C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies
The below code describes how to create a bug:
// Supply the credentials of the user who will be impersonated to create the bug
ICredentials credentials = new NetworkCredential(userName, password, domain);
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("http://<;server>:8080/tfs/<collection>"), credentials);
WorkItemStore workItemStore = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
WorkItemTypeCollection workItemTypes = workItemStore.Projects[teamProject].WorkItemTypes;
// Define the Work Item type as Bug
WorkItemType workItemType = workItemTypes["Bug"];
// Assign values to each mandatory field
workItem = new WorkItem(workItemType);
// testcaseID is the ID of the test case which failed in a test run. Refer http://social.technet.microsoft.com/wiki/contents/articles/3279.aspx for how to obtain this ID
workItem.Fields["System.Title"].Value = "Testcase #" + testcaseID + " - CI Bug";
workItem.Fields["System.AssignedTo"].Value = "Test Team";
workItem.Fields["Microsoft.VSTS.Common.Severity"].Value = "1-Critical";
workItem.Fields["Microsoft.VSTS.Common.Priority"].Value = "1";
workItem.Fields["System.AreaPath"].Value = "Area";
workItem.Fields["System.IterationPath"].Value = "Iteration";
workItem.Fields["System.State"].Value = "Proposed";
workItem.Fields["Microsoft.VSTS.ED.Type"].Value = "Code Defect";
workItem.Fields["Microsoft.VSTS.ED.BugSource"].Value = "Customer";
workItem.Fields["Microsoft.VSTS.CMMI.FoundInEnvironment"].Value = "7-Continuous Integration";
workItem.Fields["Microsoft.VSTS.Build.FoundIn"].Value = build;
workItem.Fields["Microsoft.VSTS.CMMI.HowFound"].Value = "Automated Test";
workItem.Fields["Microsoft.VSTS.CMMI.Symptom"].Value = HttpUtility.HtmlEncode("Symptom");
workItem.Fields["Microsoft.VSTS.TCM.ReproSteps"].Value = "CI Run";
// Link the failed test case to the Bug
workItem.Links.Add(new RelatedLink(testcaseID));
// Check for validation errors before saving the Bug
ArrayList validationErrors = workItem.Validate();
if (validationErrors.Count == 0)
{
workItem.Save();
Console.WriteLine(message + _workItem.Id);
}
else
{
foreach (Field field in validationErrors)
{
Console.WriteLine("Validation Error in field " + field.ReferenceName);
}
}
Similarly other types of work items can be created by defining the work item type as workItemTypes["Task"], workItemTypes["Test Case"], etc.