Example #1
0
        private WebApiWorkItem FetchWorkItem(int id, int revision, DateTime?asOf, WorkItemExpand expand, IEnumerable <string> fields, WorkItemTrackingHttpClient client)
        {
            if (expand != WorkItemExpand.None)
            {
                fields = null;
            }
            else
            {
                fields = FixWellKnownFields(fields).ToList();
            }

            try
            {
                if (revision > 0)
                {
                    return(client.GetRevisionAsync(id, revision, expand)
                           .GetResult($"Error getting work item '{id}'"));
                }
                else if (asOf.HasValue && asOf.Value > DateTime.MinValue)
                {
                    return(client.GetWorkItemAsync(id, fields, asOf, expand)
                           .GetResult($"Error getting work item '{id}'"));
                }
                else
                {
                    return(client.GetWorkItemAsync(id, fields, null, expand)
                           .GetResult($"Error getting work item '{id}'"));
                }
            }
            catch (Exception ex)
            {
                Cmdlet.WriteError(new ErrorRecord(ex, ex.InnerException.GetType().Name, ErrorCategory.ReadError, id));
                return(null);
            }
        }
        public async Task <WorkItem> GetWorkItemAsync(int id, WorkItemExpand expand = WorkItemExpand.None)
        {
            var content = await _vsts.GetStringAsync($"/_apis/wit/workitems/{id}?$expand={expand.ToString()}");

            return(_workItemMapper.Map(content));
        }
        public IEnumerable <WorkItem> QueryWorkItemSummary(out string[] columnSequence, IEnumerable <string> fileds = null, WorkItemExpand expandOption = WorkItemExpand.All)
        {
            columnSequence = new string[] { };
            var workItems = Enumerable.Empty <WorkItem>();

            if (this.wiqlInstance != null)
            {
                var result = this.VssWorkItemTrackingHttpClient.QueryByWiqlAsync(this.wiqlInstance, this.ProjectName).Result;


                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Found {0} record(s) from VSO.", result.WorkItems.Count()));

                if (result.WorkItems.Count() > 0)
                {
                    var desiredColumns = result.Columns.Select(c => c.ReferenceName).ToList();

                    // If any asked fields missing in the result columns, need expend the fields for further query
                    if (fileds != null)
                    {
                        var additionalColumns = fileds.Except(result.Columns.Select(c => c.ReferenceName)).ToList();

                        if (additionalColumns.Count > 0)
                        {
                            desiredColumns.AddRange(additionalColumns);
                            expandOption = WorkItemExpand.Fields;
                        }
                    }

                    columnSequence = desiredColumns.ToArray();

                    //// Note that if the field is not set with any value, the workItems returned value will not contain the field even
                    //// Fixing this with filling in empty string
                    workItems = this.VssWorkItemTrackingHttpClient.GetWorkItemsAsync(result.WorkItems.Select(w => w.Id),
                                                                                     expandOption == WorkItemExpand.None ? (fileds == null ? result.Columns.Select(c => c.ReferenceName) : result.Columns.Where(c => fileds.Contains(c.ReferenceName)).Select(c => c.ReferenceName))
                        : (expandOption == WorkItemExpand.Fields ? fileds : null), expand: expandOption).Result;

                    foreach (var wi in workItems)
                    {
                        var missingFields = desiredColumns.Except(wi.Fields.Select(w => w.Key));

                        foreach (var missingField in missingFields)
                        {
                            wi.Fields.Add(missingField, string.Empty);
                        }
                    }

                    //Sorting the result
                    var sortColumns = result.SortColumns.ToArray();
                    IOrderedEnumerable <WorkItem> orderedResult = null;

                    if (sortColumns.Length > 0)
                    {
                        for (int i = 0; i < sortColumns.Length; i++)
                        {
                            var sorting = sortColumns[i];

                            if (i == 0)
                            {
                                if (sorting.Descending)
                                {
                                    orderedResult = workItems.OrderByDescending(wi => wi.Fields.GetValueOrDefault(sorting.Field.ReferenceName, string.Empty));
                                }
                                else
                                {
                                    orderedResult = workItems.OrderBy(wi => wi.Fields.GetValueOrDefault(sorting.Field.ReferenceName, string.Empty));
                                }
                            }
                            else
                            {
                                if (sorting.Descending)
                                {
                                    orderedResult = orderedResult.ThenByDescending(wi => wi.Fields.GetValueOrDefault(sorting.Field.ReferenceName, string.Empty));
                                }
                                else
                                {
                                    orderedResult = orderedResult.ThenBy(wi => wi.Fields.GetValueOrDefault(sorting.Field.ReferenceName, string.Empty));
                                }
                            }
                        }

                        workItems = orderedResult;
                    }
                }
            }

            return(workItems);
        }
Example #4
0
        protected override IEnumerable <WebApiWorkItem> DoGetItems()
        {
            var workItem      = GetParameter <object>(nameof(GetWorkItem.WorkItem));
            var revision      = GetParameter <int>(nameof(GetWorkItem.Revision));
            var asOf          = GetParameter <DateTime?>(nameof(GetWorkItem.AsOf));
            var ever          = GetParameter <bool>(nameof(GetWorkItem.Ever));
            var query         = GetParameter <string>(nameof(GetWorkItem.Query));
            var filter        = GetParameter <string>(nameof(GetWorkItem.Where));
            var fields        = GetParameter <string[]>(nameof(GetWorkItem.Fields));
            var showWindow    = GetParameter <bool>(nameof(GetWorkItem.ShowWindow));
            var deleted       = GetParameter <bool>(nameof(GetWorkItem.Deleted));
            var timePrecision = GetParameter <bool>(nameof(GetWorkItem.TimePrecision));
            var includeLinks  = GetParameter <bool>(nameof(GetWorkItem.IncludeLinks));

            WorkItemExpand expand = (includeLinks? WorkItemExpand.Relations: WorkItemExpand.None);

            var(_, tp) = GetCollectionAndProject();
            var client = GetClient <WorkItemTrackingHttpClient>();

            var done = false;

            while (!done)
            {
                switch (workItem)
                {
                case int id:
                {
                    workItem = new[] { id };
                    continue;
                }

                case object[] wis:
                {
                    var list = new List <int>();
                    foreach (var o in wis)
                    {
                        switch (o)
                        {
                        case int i: list.Add(i); break;

                        case WebApiWorkItem wi: list.Add((int)wi.Id); break;
                        }
                    }
                    workItem = list.ToArray();
                    continue;
                }

                case null when deleted:
                case object o when deleted:
                {
                    IEnumerable <WorkItemDeleteReference> result;

                    if (workItem is int[] ids)
                    {
                        result = client.GetDeletedWorkItemsAsync(ids)
                                 .GetResult($"Error getting deleted work items {string.Join(", ", ids)}");
                    }
                    else
                    {
                        var refs = client.GetDeletedWorkItemShallowReferencesAsync(tp.Name)
                                   .GetResult($"Error getting references for deleted work items")
                                   .Select(r => (int)r.Id)
                                   .ToList();

                        if (refs.Count == 0)
                        {
                            yield break;
                        }

                        result = client.GetDeletedWorkItemsAsync(refs)
                                 .GetResult($"Error getting deleted work items");
                    }

                    foreach (var wi in result)
                    {
                        yield return(new WebApiWorkItem()
                            {
                                Id = wi.Id,
                                Fields = new Dictionary <string, object>()
                                {
                                    ["System.WorkItemType"] = wi.Type,
                                    ["System.Title"] = wi.Name,
                                    ["System.AreaPath"] = wi.Project,
                                    ["System.State"] = "<Deleted>",
                                    ["System.IterationPath"] = wi.Project,
                                    ["System.ChangedDate"] = wi.DeletedDate,
                                    ["DeletedBy"] = wi.DeletedBy,
                                    ["DeletedDate"] = wi.DeletedDate,
                                    ["WorkItemDeleteReference"] = wi
                                },
                                Url = wi.Url
                            });
                    }
                    yield break;
                }

                case WebApiWorkItem wi when showWindow || (includeLinks && wi.Relations == null):
                {
                    workItem = new[] { (int)wi.Id };
                    continue;
                }

                case WebApiWorkItem wi:
                {
                    yield return(wi);

                    continue;
                }

                case WorkItemReference wiRef:
                {
                    workItem = wiRef.Id;
                    continue;
                }

                case WorkItemRelation rel:
                {
                    workItem = new Uri(rel.Url);
                    continue;
                }

                case Uri url:
                {
                    if (!url.LocalPath
                        .Substring(0, url.LocalPath.Length - url.Segments[url.Segments.Length - 1].Length)
                        .EndsWith("/_apis/wit/workItems/", StringComparison.OrdinalIgnoreCase))
                    {
                        yield break;
                    }

                    if (!int.TryParse(url.Segments[url.Segments.Length - 1], out var id))
                    {
                        yield break;
                    }

                    workItem = id;
                    continue;
                }

                case int[] ids:
                {
                    foreach (int id in ids)
                    {
                        yield return(FetchWorkItem(id, revision, asOf, expand, fields, client));
                    }

                    yield break;
                }

                case null when !string.IsNullOrEmpty(filter):
                {
                    query  = $"SELECT [System.Id] FROM WorkItems WHERE {filter}";
                    filter = null;
                    continue;
                }

                case null when !string.IsNullOrEmpty(query) && query.StartsWith("SELECT ", StringComparison.OrdinalIgnoreCase):
                {
                    var result = client.QueryByWiqlAsync(new Wiql()
                        {
                            Query = query
                        }, tp.Name, timePrecision)
                                 .GetResult($"Error running work item query '{query}'");

                    foreach (var wiRef in result.WorkItems)
                    {
                        yield return(FetchWorkItem(wiRef.Id, 0, DateTime.MinValue, expand, fields, client));
                    }

                    yield break;
                }

                case null when !string.IsNullOrEmpty(query):
                {
                    var savedQuery = client.GetQueryAsync(tp.Name, query)
                                     .GetResult($"Error running work item query '{query}'");
                    query = savedQuery.Wiql;
                    continue;
                }

                default:
                {
                    query = BuildSimpleQuery(timePrecision, ever);
                    continue;
                }
                }
            }
        }
 public IEnumerable <WorkItem> QueryWorkItemSummary(IEnumerable <string> fileds = null, WorkItemExpand expandOption = WorkItemExpand.All)
 {
     string[] columnSequence = null;
     return(QueryWorkItemSummary(out columnSequence, fileds, expandOption));
 }