public QueryHierarchyItem GetQueryOrFolderByName() { Guid projectId = ClientSampleHelpers.FindAnyProject(this.Context).Id; string queryName = "Shared Queries/Current Iteration/Active Bugs"; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); try { QueryHierarchyItem query = workItemTrackingClient.GetQueryAsync(projectId, queryName).Result; Console.WriteLine("Id: {0}", query.Id); Console.WriteLine("Name: {0}", query.Name); Console.WriteLine("Path: {0}", query.Path); return(query); } catch (AggregateException ex) { Console.WriteLine("Error getting query: " + ex.InnerException.Message); return(null); } }
public QueryHierarchyItem GetDeletedQueryOrFolderById() { Guid projectId = ClientSampleHelpers.FindAnyProject(this.Context).Id; string queryId = "2614c4de-be48-4735-9fdc-9656f55c495f"; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); try { QueryHierarchyItem query = workItemTrackingClient.GetQueryAsync(projectId, queryId, null, 1, true).Result; Console.WriteLine("Id: {0}", query.Id); Console.WriteLine("Name: {0}", query.Name); Console.WriteLine("Path: {0}", query.Path); return(query); } catch (AggregateException ex) { Console.WriteLine("Error getting query: " + ex.InnerException.Message); return(null); } }
public QueryHierarchyItem GetFolderByName() { Guid projectId = ClientSampleHelpers.FindAnyProject(this.Context).Id; string folderName = _folder; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); try { QueryHierarchyItem query = workItemTrackingClient.GetQueryAsync(projectId, folderName).Result; //save the ID of the query we are getting this.Context.SetValue <Guid>("$sampleQueryFolderId", query.Id); Console.WriteLine("Id: {0}", query.Id); Console.WriteLine("Name: {0}", query.Name); Console.WriteLine("Path: {0}", query.Path); return(query); } catch (AggregateException ex) { Console.WriteLine("Error getting query: " + ex.InnerException.Message); return(null); } }
public QueryHierarchyItem GetDeletedQueryById() { Guid projectId = ClientSampleHelpers.FindAnyProject(this.Context).Id; Guid queryId = this.Context.GetValue <Guid>("$sampleQueryId"); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); try { QueryHierarchyItem query = workItemTrackingClient.GetQueryAsync(projectId, queryId.ToString(), null, 1, true).Result; Console.WriteLine("Id: {0}", query.Id); Console.WriteLine("Name: {0}", query.Name); Console.WriteLine("Path: {0}", query.Path); return(query); } catch (AggregateException ex) { Console.WriteLine("Error getting query: " + ex.InnerException.Message); return(null); } }
public QueryHierarchyItem GetQueryOrFolderById() { Guid projectId = ClientSampleHelpers.FindAnyProject(this.Context).Id; string queryId = "a2108d31-086c-4fb0-afda-097e4cc46df4"; //assigned to me query VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); try { QueryHierarchyItem query = workItemTrackingClient.GetQueryAsync(projectId, queryId).Result; Console.WriteLine("Id: {0}", query.Id); Console.WriteLine("Name: {0}", query.Name); Console.WriteLine("Path: {0}", query.Path); return(query); } catch (AggregateException ex) { Console.WriteLine("Error getting query: " + ex.InnerException.Message); return(null); } }
/// <summary> /// Verify if the query exists in the database. Also a check used to validate connection /// </summary> /// <param name="client"></param> /// <param name="project"></param> /// <param name="queryName"></param> /// <returns></returns> public static Task <QueryHierarchyItem> GetQueryAsync(WorkItemTrackingHttpClient client, string project, string queryName) { Logger.LogInformation(LogDestination.File, $"Getting query for {client.BaseAddress.Host}"); return(RetryHelper.RetryAsync(async() => { return await client.GetQueryAsync(project, queryName, expand: QueryExpand.Wiql); }, 5)); }
/// <summary> /// Run stored query on azure devops service /// </summary> /// <param name="project">Team Project Name</param> /// <param name="queryPath">Path to Query</param> static List <int> RunStoredQuery(string project, string queryPath) { QueryHierarchyItem query = WitClient.GetQueryAsync(project, queryPath, QueryExpand.Wiql).Result; string wiqlStr = query.Wiql; return(GetQueryResult(wiqlStr, project)); }
static List <int> GetStoredQueryWorkItemIds(string project, string queryPath) { var query = WitClient.GetQueryAsync(project, queryPath, QueryExpand.Wiql).Result; string wiqlStr = query.Wiql; return(GetQueryResult(wiqlStr, project)); }
/// <summary> /// Perform Query to TFS and return the results /// </summary> /// <param name="queryTitle">the title of the query</param> /// <param name="queryGuid">the query's guid </param> /// <returns>DataTable with the returned information</returns> public DataTable Query(Guid queryGuid, string queryTitle = null) { DataTable dataTable = new DataTable(); WorkItemQueryResult workItemQueryResult; List <WorkItem> workItems; Uri uri = new Uri(BaseUrl); using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, new VssCredentials())) { if (queryTitle == null) { var queryWorkItem = workItemTrackingHttpClient.GetQueryAsync(ProjectGuid, queryGuid.ToString()).Result; queryTitle = queryWorkItem.Name; } // get a list of referenced work items workItemQueryResult = workItemTrackingHttpClient.QueryByIdAsync(ProjectGuid, queryGuid).Result; if (!workItemQueryResult.WorkItems.Any()) { return(dataTable); } dataTable.TableName = queryTitle; List <int> workItemsIds = workItemQueryResult.WorkItems.Select(item => item.Id).ToList(); // now get the actual work items workItems = workItemTrackingHttpClient.GetWorkItemsAsync(ProjectGuid, workItemsIds).Result; } IEnumerable <WorkItemFieldReference> importantColumns = workItemQueryResult.Columns; // prepare the datatable dataTable.Columns.AddRange(importantColumns.Select(field => new DataColumn(field.Name)).ToArray()); foreach (WorkItem workItem in workItems) { DataRow row = dataTable.NewRow(); foreach (var importantColumn in importantColumns) { if (workItem.Fields.ContainsKey(importantColumn.ReferenceName)) { row[importantColumn.Name] = workItem.Fields[importantColumn.ReferenceName]; } if (importantColumn.Name == "ID" && workItem.Id != null) { row["ID"] = workItem.Id; } } dataTable.Rows.Add(row); } return(dataTable); }
/// <summary> /// Get Content from Query Folders /// </summary> /// <param name="project">Team Project Name</param> /// <param name="queries">Folder List</param> static void GetFolderContent(string project, List <QueryHierarchyItem> queries) { foreach (QueryHierarchyItem query in queries) { if (query.IsFolder != null && (bool)query.IsFolder) { Console.WriteLine("Folder: " + query.Path); if ((bool)query.HasChildren) { QueryHierarchyItem detiledQuery = WitClient.GetQueryAsync(project, query.Path, QueryExpand.All, 1).Result; GetFolderContent(project, detiledQuery.Children.ToList()); } } else { Console.WriteLine("Query: " + query.Path); } } }
public string QueryWorkItems_Query() { string project = _configuration.Project; string query = _configuration.Query; using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(_uri, _credentials)) { QueryHierarchyItem queryItem; try { // get the query object based on the query name and project queryItem = workItemTrackingHttpClient.GetQueryAsync(project, query).Result; } catch (Exception ex) { return(ex.InnerException.Message); } // now we have the query id, so lets execute the query and get the results WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByIdAsync(queryItem.Id).Result; // some error handling if (workItemQueryResult == null) { return("failure"); } else if (workItemQueryResult.WorkItems.Count() == 0) { return("no records found for query '" + query + "'"); } else { // need to get the list of our work item id's and put them into an array List <int> list = new List <int>(); foreach (var item in workItemQueryResult.WorkItems) { list.Add(item.Id); } int[] arr = list.ToArray(); // build a list of the fields we want to see string[] fields = new string[3]; fields[0] = "System.Id"; fields[1] = "System.Title"; fields[2] = "System.State"; var workItems = workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf).Result; return("success"); } } }
public IEnumerable <WorkItem> GetWorkItemsFromQuery() { string project = ClientSampleHelpers.FindAnyProject(this.Context).Name; string queryName = "Shared Queries/Current Sprint"; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); QueryHierarchyItem queryItem; try { // get the query object based on the query name and project queryItem = workItemTrackingClient.GetQueryAsync(project, queryName).Result; } catch (Exception ex) { // query was likely not found Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(ex.InnerException.Message); Console.ForegroundColor = ConsoleColor.White; return(null); } // now we have the query, so let'ss execute it and get the results WorkItemQueryResult queryResult = workItemTrackingClient.QueryByIdAsync(queryItem.Id).Result; if (queryResult.WorkItems.Count() == 0) { return(new List <WorkItem>()); } else { // need to get the list of our work item id's and put them into an array int[] workItemIds = queryResult.WorkItems.Select <WorkItemReference, int>(wif => { return(wif.Id); }).ToArray(); // build a list of the fields we want to see string[] fields = new [] { "System.Id", "System.Title", "System.State" }; IEnumerable <WorkItem> workItems = workItemTrackingClient.GetWorkItemsAsync(workItemIds, fields, queryResult.AsOf).Result; return(workItems); } }
public QueryHierarchyItem GetQueryByName(string project, string queryName) { VssConnection connection = new VssConnection(_uri, _credentials); WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>(); QueryHierarchyItem query = workItemTrackingHttpClient.GetQueryAsync(project, queryName).Result; if (query != null) { return(query); } else { throw new NullReferenceException("Query '" + queryName + "' not found in project"); } }
public QueryHierarchyItem GetQueryByName(string project, string queryName) { using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(_uri, _credentials)) { QueryHierarchyItem query = workItemTrackingHttpClient.GetQueryAsync(project, queryName).Result; if (query != null) { return(query); } else { throw new NullReferenceException("Query '" + queryName + "' not found in project"); } } }
public async Task <IEnumerable <WorkItemReference> > QueryWorkItemsAsync(string projectName, string fullyQualifiedQueryName) { if (string.IsNullOrWhiteSpace(projectName)) { throw new ArgumentException("This argument is required.", nameof(projectName)); } if (string.IsNullOrWhiteSpace(fullyQualifiedQueryName)) { throw new ArgumentException("This argument is required.", nameof(fullyQualifiedQueryName)); } var queryItem = await _witClient.GetQueryAsync(projectName, fullyQualifiedQueryName); return((await _witClient.QueryByIdAsync(queryItem.Id)).WorkItems); }
public QueryHierarchyItem GetQueryByName() { string project = ClientSampleHelpers.FindAnyProject(this.Context).Name; string queryName = "Shared Queries/Current Sprint"; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); QueryHierarchyItem query = workItemTrackingClient.GetQueryAsync(project, queryName).Result; if (query != null) { return(query); } else { throw new Exception(String.Format("Query '{0}' not found", queryName)); } }
private IEnumerable <QueryHierarchyItem> GetItemsRecursively(QueryHierarchyItem item, string pattern, string projectName, bool queriesOnly, WorkItemTrackingHttpClient client) { if (!(item.HasChildren ?? false) && (item.Children == null || item.Children.ToList().Count == 0)) { this.Log($"Fetching child nodes for node '{item.Path}'"); item = client.GetQueryAsync(projectName, item.Path, QueryExpand.All, 2, false) .GetResult($"Error retrieving folder from path '{item.Path}'"); } if (item.Children == null) { yield break; } foreach (var c in item.Children) { var isFolder = c.IsFolder ?? false; if ((c.Path.IsLike(pattern) || c.Name.IsLike(pattern)) && (!isFolder == queriesOnly)) { yield return(c); } } foreach (var c in item.Children) { var isFolder = c.IsFolder ?? false; if (!isFolder) { continue; } foreach (var c1 in GetItemsRecursively(c, pattern, projectName, queriesOnly, client)) { yield return(c1); } } }
public QueryHierarchyItem GetQueryOrFolderByFolderPath() { string project = ClientSampleHelpers.FindAnyProject(this.Context).Name; string queryName = "Shared Queries/Current Iteration"; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); try { QueryHierarchyItem query = workItemTrackingClient.GetQueryAsync(project, queryName, null, 2).Result; if (query == null) { Console.WriteLine("No queries found for path '{0}'", queryName); } else { Console.WriteLine("Queries:"); foreach (var item in query.Children) { Console.WriteLine("{0}", item.Name); Console.WriteLine(" {0}", item.Id); Console.WriteLine(" {0}", item.Path); Console.WriteLine(); } } return(query); } catch (AggregateException ex) { Console.WriteLine("Error getting query or folder: " + ex.InnerException.Message); return(null); } }
private async Task PopulateQueries(String actualPath, WorkItemTrackingHttpClient witClient, IEnumerable <QueryHierarchyItem> queries) { foreach (var query in queries) { if (query.IsFolder != true) { Queries.Add(new QueryViewModel(this, actualPath, query)); } if (query.HasChildren == true) { var newPath = actualPath + '/' + query.Name; if (query.Children == null) { //need to requery the store to grab reference to the query. var queryReloaded = await witClient.GetQueryAsync(SelectedTeamProject.Id, query.Path, depth : 2, expand : QueryExpand.Wiql); await PopulateQueries(newPath, witClient, queryReloaded.Children); } else { await PopulateQueries(newPath, witClient, query.Children); } } } }
public List <PrList> GetBugPrList(string strQueryLnk) { var PRLists = new List <PrList>(); string strCaption = "CRM :: Pull Request Status"; //var collectionUri = "https://dynamicscrm.visualstudio.com"; var conur = "http://vstfmbs:8080/tfs/CRM"; var teamProjectName = "Engineering"; var strError = ""; VssConnection conn = new VssConnection(new Uri(conur), new VssCredentials()); WorkItemTrackingHttpClient witClient = conn.GetClient <WorkItemTrackingHttpClient>(); List <QueryHierarchyItem> queryHierarchyItems = witClient.GetQueriesAsync(teamProjectName, depth: 1).Result; try { string temp = System.Net.WebUtility.UrlDecode(strQueryLnk); string queryFullPath = Regex.Split(temp, "#path=", RegexOptions.IgnoreCase)[1]; //strQueryURL.Split(new string[] { "#path=" }, StringSplitOptions.None)[1]; queryFullPath = queryFullPath.Substring(0, queryFullPath.ToLower().IndexOf("&_a=query")); string[] queryArr = Regex.Split(queryFullPath, "/", RegexOptions.IgnoreCase); string rootFolderName = queryArr[0]; string strQueryName = queryArr[queryArr.Length - 1]; int qFolderCount = queryArr.Length; QueryHierarchyItem myQueriesFolder = queryHierarchyItems.FirstOrDefault(qhi => qhi.Name.Equals(rootFolderName)); if (myQueriesFolder != null) { QueryHierarchyItem query = witClient.GetQueryAsync(teamProjectName, queryFullPath).Result; WorkItemQueryResult result = witClient.QueryByIdAsync(query.Id).Result; VssConnection connection2 = new VssConnection(new Uri($"https://dynamicscrm.visualstudio.com"), new VssAadCredential()); var apiStatus = new GetStatusAPI(connection2); if (result.WorkItems.Any()) { int skip = 0; const int batchSize = 100; string status = ""; IEnumerable <WorkItemReference> workItemRefs; do { workItemRefs = result.WorkItems.Skip(skip).Take(batchSize); if (workItemRefs.Any()) { List <WorkItem> workItems = witClient.GetWorkItemsAsync(workItemRefs.Select(wir => wir.Id)).Result; addlog("Getting PR Status....."); addlog("Bug ID# PR Number# PR Status"); for (int i = 0; i < workItems.Count(); i++) { PrList prList = new PrList(); prList.BugId = workItems[i].Id.ToString(); if (workItems[i].Fields.ContainsKey("Microsoft.CRM.PRLink")) { if (workItems[i].Fields["Microsoft.CRM.PRLink"].ToString() != "" || workItems[i].Fields["Microsoft.CRM.PRLink"].ToString() != "NA") { prList.PRLink = workItems[i].Fields["Microsoft.CRM.PRLink"].ToString(); prList.PRStatus = getStatus(prList.PRLink.ToString(), apiStatus).Result; prList.PRNum = PRNum.ToString(); if (prList.PRNum == "0") { addlog(prList.BugId + " " + "Invalid" + " " + prList.PRStatus); } else { addlog(prList.BugId + " " + prList.PRNum + " " + prList.PRStatus); } } else { prList.PRLink = ""; addlog(prList.BugId + " " + "Invalid" + " " + prList.PRStatus); } } else { prList.PRLink = ""; addlog(prList.BugId + " " + "Invalid" + " " + prList.PRStatus); } PRLists.Add(prList); } } skip += batchSize; }while (workItemRefs.Count() == batchSize); } else { MessageBox.Show("No work items were returned from query.", strCaption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(PRLists); } } else { MessageBox.Show("The folder does not contain any query.", strCaption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(PRLists); } } catch (Exception ex) { strError = ex.Message; clsStatus.WriteLog("GetBugPrList()-->" + ex.Message); } return(PRLists); }
public DataSet GetAllBugs(string queryFullPath) { string warningMsg = string.Empty; try { dsWorkItems.Tables["tblWorkITems"].Rows.Clear(); string teamProjectName = "Engineering"; string WorkItemDetails = string.Empty; string[] queryArr = Regex.Split(queryFullPath, "/", RegexOptions.IgnoreCase); string rootFolderName = queryArr[0]; string strQueryName = queryArr[queryArr.Length - 1]; addlog("Connecting to TFS to get the query data..."); // Create instance of WorkItemTrackingHttpClient using VssConnection WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>(); // Get 1 levels of query hierarchy items List <QueryHierarchyItem> queryHierarchyItems = witClient.GetQueriesAsync(teamProjectName, depth: 1).Result; // Search for root folder ( My Queries/Shared Queries) QueryHierarchyItem myQueriesFolder = queryHierarchyItems.FirstOrDefault(qhi => qhi.Name.Equals(rootFolderName)); if (myQueriesFolder == null) { warningMsg = "This folder " + rootFolderName + " is empty, please create a query to run the program."; addlog(warningMsg); MessageBox.Show(warningMsg, strCaption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } // See if our query already exists under 'My Queries/Shared Queries' folder. QueryHierarchyItem query = witClient.GetQueryAsync(teamProjectName, queryFullPath).Result; // Run the query WorkItemQueryResult result = witClient.QueryByIdAsync(query.Id).Result; if (result.WorkItems.Any()) { addlog("Getting list of bugs from query..."); int skip = 0; const int batchSize = 100; IEnumerable <WorkItemReference> workItemRefs; do { workItemRefs = result.WorkItems.Skip(skip).Take(batchSize); if (workItemRefs.Any()) { // get details for each work item in the batch List <WorkItem> workItems = witClient.GetWorkItemsAsync(workItemRefs.Select(wir => wir.Id)).Result; foreach (WorkItem workItem in workItems) { if (workItem.Fields.ContainsKey("Microsoft.CRM.PRLink")) { if (workItem.Fields["Microsoft.CRM.PRLink"].ToString() != "" || workItem.Fields["Microsoft.CRM.PRLink"].ToString() != "NA") { WorkItemDetails = "Bug--" + workItem.Id + " | PR Link---" + workItem.Fields["Microsoft.CRM.PRLink"].ToString(); addlog(WorkItemDetails); dsWorkItems.Tables["tblWorkITems"].Rows.Add(workItem.Id, workItem.Fields["Microsoft.CRM.PRLink"].ToString(), ""); } } else { WorkItemDetails = "Bug--" + workItem.Id + " | PR Link--- Not Present"; addlog(WorkItemDetails); dsWorkItems.Tables["tblWorkITems"].Rows.Add(workItem.Id, "", ""); } } } skip += batchSize; }while (workItemRefs.Count() == batchSize); return(dsWorkItems); } else { warningMsg = "No work items were returned from query."; addlog(warningMsg); MessageBox.Show(warningMsg, strCaption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } } catch (Exception ex) { warningMsg = ex.Message; if (ex.InnerException != null) { warningMsg = ex.InnerException.Message; if (warningMsg.Contains(":")) { warningMsg = warningMsg.Split(':')[1].Trim(); } } clsStaticMethods.WriteLog("GetAllBugs()-->" + warningMsg); MessageBox.Show(warningMsg, strCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } }
static void Main(string[] args) { //Pre-req: Create a query of test cases with Work item queries to be bulk deleted and then use this sample //Command line usage: //BulkDeleteTestCaseWorkItems.exe <account or tfs server> <team project name> <query in quotes> <pat token> //Example: BulkDeleteTestCaseWorkItems.exe https://manojbableshwar.visualstudio.com HealthClinic "Shared Queries/Troubleshooting/P4 Test Cases" <pat token> Uri accountUri; string teamProjectName, witTestCaseQuery, personalAccessToken; VssConnection connection; if (args.Length < 3 || args.Length > 4) { Console.WriteLine("Incomplete arguments. See: https://github.com/ManojBableshwar/VstsTestRestApiSamples/tree/master/BulkDeleteTestCaseWorkItems"); return; } accountUri = new Uri(args[0]); teamProjectName = args[1]; witTestCaseQuery = args[2]; if (args.Length == 4) { // Create a connection to the account - use this for pat auth personalAccessToken = args[3]; // See https://www.visualstudio.com/docs/integrate/get-started/authentication/pats connection = new VssConnection(accountUri, new VssBasicCredential(string.Empty, personalAccessToken)); } else { // Create a connection to the account using client auth when pat is not available, so that users can auth using username/password connection = new VssConnection(accountUri, new VssClientCredentials()); } // Get an instance of the work item tracking client to query test case work items to be deleted WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>(); // Get an instance of the work item tracking client to delete test cases TestManagementHttpClient testClient = connection.GetClient <TestManagementHttpClient>(); //Get the ID of the query specified... QueryHierarchyItem query = witClient.GetQueryAsync(teamProjectName, witTestCaseQuery).Result; //Query work item ids in the query... WorkItemQueryResult TestCaseIdsToDelete = witClient.QueryByIdAsync(query.Id).Result; if (TestCaseIdsToDelete.WorkItems.Count() > 0) { Console.WriteLine("Found {0} work items in query '{1}'.. Proceeding to delete...", TestCaseIdsToDelete.WorkItems.Count(), witTestCaseQuery); } else { Console.WriteLine("Found {0} work items returned in query '{1}'; Exiting... ", TestCaseIdsToDelete.WorkItems.Count(), witTestCaseQuery); return; } //Extract work item Ids to fetch work item details.. int[] workItemIds = TestCaseIdsToDelete.WorkItems.Select <Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItemReference, int>(wif => { return(wif.Id); }).ToArray(); string[] fields = new[] { "System.Id", "System.Title", "System.WorkItemType" }; // Fetch work item details.. IEnumerable <WorkItem> TestCasesToDelete = witClient.GetWorkItemsAsync(workItemIds, fields, TestCaseIdsToDelete.AsOf).Result; foreach (var testcase in TestCasesToDelete) { // Skip if work item type is not test case, since DeleteTestCaseAsync is only for test case work item delete... if (testcase.Fields["System.WorkItemType"].ToString() != "Test Case") { Console.WriteLine("Not a test case work item, skipping: {0} => {1}", testcase.Id, testcase.Fields["System.Title"]); } else { try { //delete test case work item... testClient.DeleteTestCaseAsync(teamProjectName, Convert.ToInt32(testcase.Id)).SyncResult(); Console.WriteLine("Deleted testcase: {0} => {1}", testcase.Id, testcase.Fields["System.Title"]); } catch (Exception e) { Console.WriteLine("Failed to delete testcase {0} => {1}. Error: {2}", testcase.Id, testcase.Fields["System.Title"], e.Message); } } } }