private async Task <List <int> > GetWorkItemIds(Wiql query) { var result = await _client.QueryByWiqlAsync(query); List <int> ids = new List <int>(); foreach (var item in result.WorkItems) { ids.Add(item.Id); } return(ids); }
public async static Task <IQueryable <AzureWorkItem> > GetWorkItems(AzureDevOpsConnectionInfo connInfo, WorkItemTrackingHttpClient witClient, string whereCond) { var q = new Wiql() { Query = $"SELECT [System.Id] FROM WorkItems WHERE {whereCond}" }; var result = await witClient.QueryByWiqlAsync(q); var wait = await Task.WhenAll(result.WorkItems.Select(x => GetWorkItem(connInfo, witClient, x.Id))); return(wait.AsQueryable()); }
public VisualStudioWorkItemHelper(string query) { var project = string.Empty; Uri uri = null; this.wiqlInstance = VisualStudioUtils.CreateWiql(query, out uri, out project); this.TeamUri = uri ?? DefaultTeamUri; this.ProjectName = project; this.VssWorkItemTrackingHttpClient = VisualStudioHttpClientPool.GetVssHttpClient <WorkItemTrackingHttpClient>(this.TeamUri); }
public async Task UpdateBugWithChildTasks(int bugId) { int cumulativeCompletedWork = 0; int cumulativeRemainingWork = 0; Wiql wiql = new Wiql() { Query = string.Format("SELECT * FROM WorkItemLinks WHERE [Source].[System.Id] = '{0}' and [Target].[System.WorkItemType] = 'Task' and [Source].[System.WorkItemType] = 'Bug'", bugId.ToString()) }; var result = await witClient.QueryByWiqlAsync(wiql); if (result.WorkItemRelations.Count() != 0) { log.Info(string.Format("Update has started for bug: {0}", bugId)); List <int> list = new List <int>(); var bug = await this.GetWorkItem(bugId); foreach (var item in result.WorkItemRelations) { if (item.Source != null && item.Target != null) { var task = await this.GetWorkItem(item.Target.Id); if (!task.Fields[fieldReferences[iterationPath]].ToString().Contains("INTCORE3\\v4.0") && !task.Fields[fieldReferences[iterationPath]].ToString().Contains("INTCORE3\\v3.2")) { continue; } log.Info(string.Format("Bug: {0} - Task: {1} Completed Work: {2}, Remaining Work: {3}", bugId, item.Target.Id, task.Fields[fieldReferences[completedWork]].ToString(), task.Fields[fieldReferences[remainingWork]].ToString())); var completedRemainingPair = GetSafeCompletedAndRemainig(task.Fields); cumulativeCompletedWork += completedRemainingPair[0]; cumulativeRemainingWork += completedRemainingPair[1]; } } await UpdateFieldOfWorkItem(bugId, cumulativeRemainingWork, cumulativeCompletedWork); } totalThreadCount--; UpdateProgress(); if (totalThreadCount == 0) { SetEnable(); } }
private async Task <List <WorkItem> > GetWorkItemGroupsInternal(WorkItemTrackingHttpClient client, DevOpsConfiguration configuration) { try { var stopWatch = new Stopwatch(); stopWatch.Start(); var allItems = new List <WorkItem>(); var query = new Wiql { Query = configuration.WorkItemQuery }; var workItemGroupResult = await client.QueryByWiqlAsync(query); var workItemGroups = (from i in Enumerable.Range(0, workItemGroupResult.WorkItems.Count()) group workItemGroupResult.WorkItems.ToList()[i] by i / 200).ToList(); _logger.LogInformation($"Got {workItemGroupResult.WorkItems.Count()} split into {workItemGroups.Count()} groups. Elapsed: {stopWatch.ElapsedMilliseconds}"); foreach (var queryGroup in workItemGroups) { if (!queryGroup.Any()) { continue; } var newIds = queryGroup.ToList().Select(s => s.Id).ToArray(); List <WorkItem> workItems; if (configuration.GetWorkItemFields().Length == 0) { workItems = await client.GetWorkItemsAsync(ids : newIds, asOf : workItemGroupResult.AsOf, expand : WorkItemExpand.Relations); } else { workItems = await client.GetWorkItemsAsync(ids : newIds, fields : configuration.GetWorkItemFields(), asOf : workItemGroupResult.AsOf); } allItems.AddRange(workItems); } if (!string.IsNullOrEmpty(configuration.OrderByWorkItemFieldName) && configuration.GetWorkItemFields().Contains(configuration.OrderByWorkItemFieldName)) { allItems = allItems.OrderByDescending(s => s.Fields[configuration.OrderByWorkItemFieldName]).ToList(); } _logger.LogInformation($"Found {allItems.Count} items, Elapsed: {stopWatch.ElapsedMilliseconds}"); return(allItems); } catch (Exception e) { _logger.LogCritical($"Failed to fetch DevOp items {e}"); throw; } }
private async Task <List <WorkItem> > QueryWorkItemsAsync(WorkItemTrackingHttpClient client, string query) { var _query = new Wiql(); _query.Query = query; var ids = (await client .QueryByWiqlAsync(_query)) .WorkItems .Select(x => x.Id); return(await client.GetWorkItemsAsync(ids, expand : WorkItemExpand.All)); }
/// <summary> /// Gets all the work item ids for the query, with special handling for the case when the query results /// can exceed the result cap. /// </summary> public async static Task <IDictionary <int, string> > GetWorkItemIdAndReferenceLinksAsync(WorkItemTrackingHttpClient client, string project, string queryName, string postMoveTag, int queryPageSize) { Logger.LogInformation(LogDestination.File, $"Getting work item ids for {client.BaseAddress.Host}"); var queryHierarchyItem = await GetQueryAsync(client, project, queryName); var workItemIdsUris = new Dictionary <int, string>(); var baseQuery = ParseQueryForPaging(queryHierarchyItem.Wiql, postMoveTag); var watermark = 0; var id = 0; var page = 0; while (true) { Logger.LogInformation(LogDestination.File, $"Getting work item ids page {page++} with last id {id} for {client.BaseAddress.Host}"); var wiql = new Wiql { Query = GetPageableQuery(baseQuery, watermark, id) }; var queryResult = await RetryHelper.RetryAsync(async() => { return(await client.QueryByWiqlAsync(wiql, project: project, top: queryPageSize)); }, 5); workItemIdsUris.AddRange(queryResult.WorkItems.Where(w => !workItemIdsUris.ContainsKey(w.Id)).ToDictionary(k => k.Id, v => RemoveProjectGuidFromUrl(v.Url))); Logger.LogTrace(LogDestination.File, $"Getting work item ids page {page} with last id {id} for {client.BaseAddress.Host} returned {queryResult.WorkItems.Count()} results and total result count is {workItemIdsUris.Count}"); //keeping a list as well because the Dictionary doesnt guarantee ordering List <int> workItemIdsPage = queryResult.WorkItems.Select(k => k.Id).ToList(); if (!workItemIdsPage.Any()) { break; } else { id = workItemIdsPage.Last(); var workItem = await RetryHelper.RetryAsync(async() => { return(await client.GetWorkItemAsync(id, queryFields)); }, 5); watermark = (int)(long)workItem.Fields[FieldNames.Watermark]; } } return(workItemIdsUris); }
RunGetTasksQuery(Project project) { VssBasicCredential credentials = new VssBasicCredential("", project.PersonalAccessToken); //create a wiql object and build our query Wiql wiql = new Wiql() { Query = "Select " + " [System.Id], [System.WorkItemType], [System.Title], [System.CreatedDate] " + "From WorkItems " + "Where " + "[System.TeamProject] = '" + project.Name.ToString() + "' " + "And [System.State] <> 'Closed' " + "Order By [State] Asc, [Changed Date] Desc" }; //create instance of work item tracking http client using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(new Uri(project.Url.ToString()), credentials)) { //execute the query to get the list of work items in the results WorkItemQueryResult workItemQueryResult = await workItemTrackingHttpClient.QueryByWiqlAsync(wiql); //some error handling if (workItemQueryResult.WorkItems.Count() != 0) { //need to get the list of our work item ids 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[4]; fields[0] = "System.Id"; fields[1] = "System.WorkItemType"; fields[2] = "System.Title"; fields[3] = "System.CreatedDate"; //get work items for the ids found in query var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf); Console.WriteLine("Query Results: {0} items found", workItems.Count); return(workItems); } return(null); } }
/// <summary> /// Execute a WIQL query to return a list of bugs using the .NET client library /// </summary> /// <returns>List of Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem</returns> public async Task <List <WorkItem> > ExecuteWorkItemsQuery() { Uri uri = new Uri(GlobalConfiguration.Instance._uri); string personalAccessToken = GlobalConfiguration.Instance._tokenPA; string project = GlobalConfiguration.Instance._project; VssBasicCredential credentials = new VssBasicCredential("", GlobalConfiguration.Instance._tokenPA); //create a wiql object and build our query Wiql wiql = new Wiql() { Query = "Select [Id], [State], [Title],[Changed Date]" + "From WorkItems " + "Order By [State] Asc, [Changed Date] Desc" }; //create instance of work item tracking http client using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, credentials)) { //execute the query to get the list of work items in the results WorkItemQueryResult workItemQueryResult = await workItemTrackingHttpClient.QueryByWiqlAsync(wiql); //some error handling if (workItemQueryResult.WorkItems.Count() != 0) { //need to get the list of our work item ids and put them into an array List <int> list = new List <int>(); foreach (var item in workItemQueryResult.WorkItems) { list.Add(item.Id); } int[] arrWIQueryResult = list.ToArray(); //build a list of the fields we want to see string[] wiProperties = new string[4]; wiProperties[0] = "System.Id"; wiProperties[1] = "System.State"; wiProperties[2] = "System.Title"; wiProperties[3] = "System.ChangedDate"; //get work items for the ids found in query var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arrWIQueryResult, wiProperties, workItemQueryResult.AsOf); return(workItems); } return(null); } }
public List <AzureTestCase> FindTestCasesByAssociatedAutomation(string fullTestName, string testStorage) { // Create a wiql object and build our query var wiql = new Wiql() { // NOTE: Even if other columns are specified, only the ID & URL will be available in the WorkItemReference Query = "Select [Id] " + "From WorkItems " + "Where [Work Item Type] = 'Test Case' " + "And [System.TeamProject] = '" + _project + "' " + $"And [Microsoft.VSTS.TCM.AutomatedTestName] = '{fullTestName}'" + $"And [Microsoft.VSTS.TCM.AutomatedTestStorage] = '{testStorage}'", }; var credentials = new VssBasicCredential(string.Empty, _personalAccessToken); try { // create instance of work item tracking http client using var httpClient = new WorkItemTrackingHttpClient(new Uri(_uri), credentials); // execute the query to get the list of work items in the results var result = httpClient.QueryByWiqlAsync(wiql).Result; var ids = result.WorkItems.Select(item => item.Id).ToArray(); // some error handling if (ids.Length == 0) { return(new List <AzureTestCase>()); } var resultTestCases = new List <AzureTestCase>(); // build a list of the fields we want to see var fields = new[] { "System.Id", "System.Title", "System.State" }; foreach (var item in httpClient.GetWorkItemsAsync(ids, expand: WorkItemExpand.Relations).Result) { resultTestCases.Add(ConvertWorkItemToAzureTestCase(item)); } return(resultTestCases); } catch { return(new List <AzureTestCase>()); } return(new List <AzureTestCase>()); }
public WorkItemQueryResult ExecuteByWiql(Wiql wiql, string project) { VssConnection connection = new VssConnection(_uri, _credentials); WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>(); WorkItemQueryResult queryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql, project).Result; if (queryResult != null && queryResult.WorkItems.Count() > 0) { return(queryResult); } else { throw new NullReferenceException("Wiql '" + wiql.Query + "' did not find any results"); } }
/// <summary> /// Get the count of childs from the query result /// </summary> /// <param name="pWiql"></param> /// <returns></returns> static int GetChildsCountFromQueryResult(string pWiql) { Wiql _wiql = new Wiql { Query = pWiql }; WorkItemQueryResult result = WITClient.QueryByWiqlAsync(_wiql).Result; if (result.WorkItemRelations != null) { return((from links in result.WorkItemRelations where links.Source != null select links.Target.Id).Count()); } return(0); }
/// <summary> /// Get the list of parent ids from the query result /// </summary> /// <param name="pWiql"></param> /// <returns></returns> static List <int> GetParentIdsFromQueryResult(string pWiql) { Wiql _wiql = new Wiql { Query = pWiql }; WorkItemQueryResult result = WITClient.QueryByWiqlAsync(_wiql).Result; if (result.WorkItemRelations != null) { return((from links in result.WorkItemRelations where links.Source == null select links.Target.Id).ToList()); } return(new List <int>()); }
/// <summary> /// Run Query with Wiql /// </summary> /// <param name="wiqlStr">Wiql String</param> /// <returns></returns> static WorkItemQueryResult RunQueryByWiql(string wiqlStr, string teamProject) { Wiql wiql = new Wiql(); wiql.Query = wiqlStr; if (teamProject == "") { return(WitClient.QueryByWiqlAsync(wiql).Result); } else { return(WitClient.QueryByWiqlAsync(wiql, teamProject).Result); } }
public WorkItemQueryResult ExecuteByWiql() { string project = ClientSampleHelpers.FindAnyProject(this.Context).Name; Wiql wiql = new Wiql() { Query = "Select ID, Title from Issue where (State = 'Active') order by Title" }; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); WorkItemQueryResult queryResult = workItemTrackingClient.QueryByWiqlAsync(wiql, project).Result; return(queryResult); }
/// <summary> /// Find work items by title containing substring /// </summary> /// <param name="title">work item title</param> /// <returns></returns> public static async Task <List <Models.WorkItem> > FindWorkItemsByTitle(string title) { var workitemClient = await GetTFSHttpClient <WorkItemTrackingHttpClient>(); if (workitemClient != null) { var list = new List <Models.WorkItem>(); var workItemIds = new List <int>(); var wiql = new Wiql() { // NOTE: Even if other columns are specified, only the ID & URL will be available in the WorkItemReference Query = "Select [Id] " + "From WorkItems " + "Where [Work Item Type] = '" + Settings.settings.WorkItemType + "' " + "And [System.TeamProject] = '" + Settings.settings.ProjectName + "' " + "And [System.Title] Contains '" + title.Replace("'", "''") + "' " + "And [System.State] <> 'Closed' " + "Order By [State] Asc, [Changed Date] Desc", }; var result = await workitemClient.QueryByWiqlAsync(wiql); if (result.WorkItems.Count() > 0) { var workItems = await workitemClient.GetWorkItemsAsync(result.WorkItems.Select(a => a.Id), new List <string> { "System.State", "System.Title", Models.WorkItem.CategoryByComplexityReferenceName }, cancellationToken : GetCancellationToken(20)); foreach (var workItem in workItems) { // avoid cases when id is null if (!workItem.Id.HasValue) { continue; } list.Add(new Models.WorkItem { Id = workItem.Id.Value, Title = (string)workItem.Fields["System.Title"], State = (string)workItem.Fields["System.State"], Complexity = workItem.Fields.ContainsKey(Models.WorkItem.CategoryByComplexityReferenceName) ? (string)workItem.Fields[Models.WorkItem.CategoryByComplexityReferenceName] : null }); } } return(list); } // in reality this case will not occur throw new System.Exception("bad settings file"); }
public async Task <WorkItemQueryResult> GetWorkItems() { Wiql wiql; string query = "Select [ID], [State], [Title] " + "From WorkItems " + "WHERE [System.WorkItemType] = 'Bug' " + " AND (" + fieldReferences[iterationPath] + " UNDER 'INTCORE3\\v4.0' OR " + fieldReferences[iterationPath] + " UNDER 'INTCORE3\\v3.2' )"; wiql = new Wiql() { Query = query }; witClient = vssConnection.GetClient <WorkItemTrackingHttpClient>(); return(await witClient.QueryByWiqlAsync(wiql)); }
public async Task QueryItemsAsync() { var wiql = new Wiql() { Query = "Select [State], [Title] " + "From WorkItems " + "Where [Work Item Type] = 'Bug' " + "And [System.TeamProject] = '" + _project + "' " + "And [System.State] <> 'Closed' " + "Order By [State] Asc, [Changed Date] Desc" }; var client = GetClient <WorkItemTrackingHttpClient>(); var result = await client.QueryByWiqlAsync(wiql); }
//private JObject ConvertToHierarchy(JArray items) //{ // var dict = new Dictionary<int, JToken>(); // foreach (var item in items) // { // var id = Int32.Parse(item["ID"].ToString()); // dict.Add(id, item); // } // foreach (var item in dict.Values) // { // if (item["System.Parent"] != null) // { // int parentNumber = Int32.Parse(item["System.Parent"].ToString()); // var parentItem = (JObject)dict[parentNumber]; // if (parentItem.ContainsKey("items") == false) { parentItem.Add("items", new JArray()); } // var subItems = (JArray)parentItem["items"]; // subItems.Add(item); // } // } // return (JObject)dict.FirstOrDefault().Value; //} private async Task <List <WorkItem> > GetItems(string uri, string pat, string project) { var credentials = new VssBasicCredential(string.Empty, pat); // create a wiql object and build our query var wiql = new Wiql() { // NOTE: Even if other columns are specified, only the ID & URL will be available in the WorkItemReference Query = "Select [Id] " + "From WorkItems " + //"Where [Work Item Type] = 'Epic' " + "Where [System.TeamProject] = '" + project + "'", }; // create instance of work item tracking http client using (var httpClient = new WorkItemTrackingHttpClient(new Uri(uri), credentials)) { // execute the query to get the list of work items in the results var result = await httpClient.QueryByWiqlAsync(wiql).ConfigureAwait(false); var ids = result.WorkItems.Select(item => item.Id).ToArray(); // some error handling if (ids.Length == 0) { return(null); } // build a list of the fields we want to see //var fields = new[] { "System.Id", "System.Title", "System.State, System.Parent" }; //System.AreaPath //System.TeamProject //System.IterationPath //System.WorkItemType //System.State //System.Reason //System.CreatedDate //System.CreatedBy //System.ChangedDate //System.ChangedBy //System.CommentCount // get work items for the ids found in query //return await httpClient.GetWorkItemsAsync(ids, fields, result.AsOf).ConfigureAwait(false); return(await httpClient.GetWorkItemsAsync(ids, expand : WorkItemExpand.Relations).ConfigureAwait(false)); } }
public IEnumerable <WorkItem> GetWorkItemsFromWiql() { string project = ClientSampleHelpers.FindAnyProject(this.Context).Name; // create a query to get your list of work items needed Wiql wiql = new Wiql() { Query = "Select [State], [Title] " + "From WorkItems " + "Where [Work Item Type] = 'Bug' " + "And [System.TeamProject] = '" + project + "' " + "And [System.State] = 'New' " + "Order By [State] Asc, [Changed Date] Desc" }; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>(); // execute the query WorkItemQueryResult queryResult = workItemTrackingClient.QueryByWiqlAsync(wiql).Result; // check to make sure we have some results 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 string QueryWorkItems_Wiql() { string project = _configuration.Project; // create a query to get your list of work items needed Wiql wiql = new Wiql() { Query = "Select [State], [Title] " + "From WorkItems " + "Where [Work Item Type] = 'Bug' " + "And [System.TeamProject] = '" + project + "' " + "And [System.State] = 'New' " + "Order By [State] Asc, [Changed Date] Desc" }; // create instance of work item tracking http client using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(_uri, _credentials)) { // execute the query WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result; // check to make sure we have some results if (workItemQueryResult == null || workItemQueryResult.WorkItems.Count() == 0) { return("Wiql '" + wiql.Query + "' did not find any results"); } 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 Dictionary <string, EscortItemModel> Extract(DateTime atime) { Wiql wiql = new Wiql() { Query = string.Format(@"SELECT * FROM WorkItems WHERE [Team Project] = 'Mooncake' AND [Work Item Type] = 'Escort Request' AND [Created Date] >='{0}'", atime) }; using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(this.uri, this.vssBasic)) { //execute the query to get the list of work items in the results WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result; //create a dic to hold process result Dictionary <String, EscortItemModel> results = new Dictionary <string, EscortItemModel>(); workItemQueryResult.AsOf = DateTime.Now; if (workItemQueryResult.WorkItems.Count() != 0) //get fileds if query result is not empty { //need to get the list of our work item ids 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 = createFieldMapper(); //execute var workItems = workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf).Result; //Console.WriteLine("Query Results: {0} items found", tickets.Count); //process query data and holdem with object foreach (var workItem in workItems) { EscortItemModel item = new EscortItemModel(workItem); item.tfsObj = workItem; results.Add(item.iD, item); } } return(results); } }
public async Task <IEnumerable <Message> > ReceiveMessages(DateTime dateTime, CancellationToken cancellationToken) { var wiql = new Wiql { Query = this.GetQueryString(dateTime) }; var items = await this.client.QueryByWiqlAsync(wiql, this.configuration.TfsProject, true, cancellationToken : cancellationToken); if (!items.WorkItems.Any()) { return(Enumerable.Empty <Message>()); } var ids = items.WorkItems.Select(x => x.Id); var entries = await client.GetWorkItemsAsync(ids, cancellationToken : cancellationToken); return(entries.Select(this.CreateMessage)); }
static async Task Main(string[] args) { VssConnection connection = new VssConnection(new Uri("https://tfs.opm.gov/tfs/RecruitmentSystems"), new VssClientCredentials()); WorkItemService workItemService = new WorkItemService(connection); if (4 > args.Length) { Console.WriteLine("You must pass Iteration Path, Project, Start Date, and Target Date"); } TaskTrackerArguments arguments = new TaskTrackerArguments() { IterationPath = args[0], Project = args[1], StartDate = args[2], TargetDate = args[3] }; Wiql wiql = new Wiql() { Query = $"Select [Title], [System.IterationId] From WorkItems Where [System.TeamProject] = '{arguments.Project}' " + $"And [System.IterationPath] = '{arguments.IterationPath}' And [System.WorkItemType] <> 'Task' And [Required Attendee 1] = '{connection.AuthorizedIdentity.DisplayName}'" }; List <WorkItem> workItems = await workItemService.GetWorkItemsByWIQL(wiql); List <CsvWorkItem> csvWorkItems = new List <CsvWorkItem>(); foreach (WorkItem item in workItems) { csvWorkItems.Add(new CsvWorkItem() { ID = item.Id.HasValue ? item.Id.Value : 0, Title = item.Fields["System.Title"].ToString(), StartDate = arguments.StartDate, TargetDate = arguments.TargetDate }); } Directory.CreateDirectory(@"C:\TaskTracker\CSV"); using (var writer = new StreamWriter(@"C:\TaskTracker\CSV\workitems.csv")) using (var csv = new CsvWriter(writer)) { csv.WriteRecords(csvWorkItems); } }
public static async Task <IList <WorkItem> > QueryWorkItemRevisionsById(string organization, int id) { var uri = new Uri($"https://dev.azure.com/{organization}"); var credentials = GetVssCredentials(); //var project = "VNC Agile"; var wiql = new Wiql() { // NOTE: Even if other columns are specified, only the ID & URL are available in the WorkItemReference Query = "Select [Id] " + "From WorkItems " + "Where Id = " + id }; using (var witHttpClient = new WorkItemTrackingHttpClient(uri, credentials)) { // execute the query to get the list of work item revisions var revisions = await witHttpClient.GetRevisionsAsync(id, expand : WorkItemExpand.All); //var result = await witHttpClient.QueryByWiqlAsync(wiql).ConfigureAwait(false); var ids = revisions.Select(item => item.Id); // some error handling if (ids.Count() == 0) { return(Array.Empty <WorkItem>()); } // TODO(crhodes) // How can we efficiently get more details depending on WorkItem Type string[] fields = GetFieldList(); //Get WorkItem details(fields) for the ids found in query //return await witHttpClient.GetWorkItemsAsync(ids, fields, null, null, null, null); //var foo = await witHttpClient.GetWorkItemsAsync(ids, fields).ConfigureAwait(false); ////return await witHttpClient.GetWorkItemsAsync((IEnumerable<int>)ids, fields).ConfigureAwait(false); //return foo; return(revisions); } }
public async Task <IActionResult> GetWorkItemsByTag(string tag) { var uriLookup = await lookupRepo.GetLookupConfigByName(0, "Y", "DevOps_Uri"); Uri accountUri = new Uri(uriLookup.Lvalue); var tokenLookup = await lookupRepo.GetLookupConfigByName(0, "Y", "DevOps_AccessToken"); String personalAccessToken = tokenLookup.Lvalue; // Create a connection to the account VssConnection connection = new VssConnection(accountUri, new VssBasicCredential(string.Empty, personalAccessToken)); // Get an instance of the work item tracking client WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>(); //create a wiql object and build our query Wiql wiql = new Wiql() { Query = "Select [System.Id], [System.Title], [System.State] From WorkItems " + "Where [State] <> 'Closed' AND [State] <> 'Removed' AND [System.Tags] Contains '" + tag + "' " + "order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc" }; try { //execute the query to get the list of work items in the results WorkItemQueryResult workItemQueryResult = witClient.QueryByWiqlAsync(wiql).Result; List <WorkItem> workItemList = new List <WorkItem>(); foreach (WorkItemReference wi in workItemQueryResult.WorkItems) { workItemList.Add(witClient.GetWorkItemAsync(wi.Id).Result); } return(Ok(workItemList)); } catch (AggregateException aex) { VssServiceException vssex = aex.InnerException as VssServiceException; if (vssex != null) { throw vssex; } throw aex; } }
public override Task <WorkItemQueryResult> QueryByWiqlAsync(Wiql wiql, Guid project, bool?timePrecision = null, int?top = null, object userState = null, CancellationToken cancellationToken = default(CancellationToken)) { var t = new Task <WorkItemQueryResult>(() => new WorkItemQueryResult() { QueryType = QueryType.Flat, WorkItems = new List <WorkItemReference>() { new WorkItemReference() { Id = 33, Url = $"{BaseAddress.AbsoluteUri}/{project}/_apis/wit/workItems/33" } } }); t.RunSynchronously(); return(t); }
private WorkItemQueryResult WorkItemResponse(Uri azureDevOpsUri, VssBasicCredential personalAccessToken, string azureDevOpsWiqlString) { WorkItemQueryResult workItemQueryResult; Wiql azureDevOpsWiqlQuery = new Wiql() { Query = azureDevOpsWiqlString }; using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(azureDevOpsUri, personalAccessToken)) { //execute the query to get the list of work items in the results workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(azureDevOpsWiqlQuery).Result; } return(workItemQueryResult); }
/// <summary> /// Execute une requete WIQL pour retourner une liste de workItem en utilisant la librairie .NET client /// </summary> /// <returns>List of Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem</returns> public async Task <List <WorkItem> > GetWorkItemByQuery(string query) { Uri uri = new Uri(_uri); VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken); // Création de la requete Wiql wiql = new Wiql() { Query = query }; // instance http client using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, credentials)) { // execute la requete WorkItemQueryResult workItemQueryResult = await workItemTrackingHttpClient.QueryByWiqlAsync(wiql); //Au cas ou il y aurait un problème ou qu'il n'y ai pas de workitem if (workItemQueryResult.WorkItems.Count() != 0) { //listing des ID des WorkItem à charger List <int> list = new List <int>(); foreach (var item in workItemQueryResult.WorkItems) { list.Add(item.Id); } int[] arr = list.ToArray(); //List des champs a récuperer dans le workItem //string[] fields = new string[3]; //fields[0] = "System.Id"; //fields[1] = "System.Title"; //fields[2] = "System.State"; //var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf); //Récupération des workItems selon leurs ID avec tous leur champs var workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arr, asOf : workItemQueryResult.AsOf); return(workItems); } return(null); } }
public static string GetClosedItems(VssConnection connection, DateTime releaseSpan) { string project = Environment.GetEnvironmentVariable("ProjectName"); var workItemTrackingHttpClient = connection.GetClient <WorkItemTrackingHttpClient>(); //Query that grabs all of the Work Items marked "Done" in the last 14 days Wiql wiql = new Wiql() { Query = "Select [State], [Title] " + "From WorkItems Where " + "[System.TeamProject] = '" + project + "' " + "And [System.State] = 'Done' " + "And [Closed Date] >= '" + releaseSpan.ToString() + "' " + "Order By [State] Asc, [Changed Date] Desc" }; using (workItemTrackingHttpClient) { WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result; if (workItemQueryResult.WorkItems.Count() != 0) { List <int> list = new List <int>(); foreach (var item in workItemQueryResult.WorkItems) { list.Add(item.Id); } //Extraxt desired work item fields string[] fields = { "System.Id", "System.Title" }; var workItems = workItemTrackingHttpClient.GetWorkItemsAsync(list, fields, workItemQueryResult.AsOf).Result; //Format Work Item info into text string txtWorkItems = string.Empty; foreach (var workItem in workItems) { txtWorkItems += String.Format("\n 1. #{0}-{1}", workItem.Id, workItem.Fields["System.Title"]); } return(txtWorkItems); } return(string.Empty); } }