Exemplo n.º 1
0
        public static (Dictionary <string, TesterModel>, string) reportGenerate(WorkItemQueryResult result, VssConnection connection)
        {
            var    resultDictionary = new Dictionary <string, TesterModel>();
            string fail             = "";

            if (result.WorkItems.Any())
            {
                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
                        var             witClient = connection.GetClient <WorkItemTrackingHttpClient>();
                        List <WorkItem> workItems = witClient.GetWorkItemsAsync(workItemRefs.Select(wir => wir.Id)).Result;
                        resultDictionary.Add("0", new TesterModel());
                        foreach (WorkItem workItem in workItems)
                        {
                            // первый тестер должен иметь 2 парамета, второй либо имеет оба парамета, либо ни одного, при этом сложность и ветка должны быть указаны
                            if (IsCorrect(workItem))
                            {
                                fail += " <" + workItem.Fields["System.Title"] + "> "; continue;
                            }

                            // номер для группировки

                            var i = 1; // показывает сколько у нас тестеров
                            while (workItem.Fields.ContainsKey("Custom.FeatureTester" + i))
                            {
                                // id группы, если такой еще не создали, то создаем
                                var id = ((IdentityRef)workItem.Fields["Custom.FeatureTester" + i]).Id;
                                if (!resultDictionary.ContainsKey(id))
                                {
                                    resultDictionary.Add(id, new TesterModel());
                                }
                                // получить имя
                                var name = ((IdentityRef)workItem.Fields["Custom.FeatureTester" + i]).DisplayName;
                                // Определяем данные о такске(сложность и время)
                                var compl = int.Parse(workItem.Fields["Custom.TestingComplexity"].ToString());
                                var time  = int.Parse(workItem.Fields["Custom.FeatureTestingTime" + i].ToString());
                                //записать
                                resultDictionary[id].lastName = name;
                                resultDictionary[id].AddTaskData(compl, time);

                                resultDictionary["0"].AddTaskData(compl, time);

                                // next
                                i++;
                            }
                        }
                    }
                    skip += batchSize;
                }while (workItemRefs.Count() == batchSize);
            }
            fail += "-Incorrect field card, task is not counted";
            return(resultDictionary, fail);
        }
Exemplo n.º 2
0
        private async Task <IEnumerable <Wit> > InternalGetWorkItemsAsync(string query, string[] fields, int?top, bool?timePrecision,
                                                                          WorkItemExpand?expand, WorkItemErrorPolicy?errorPolicy,
                                                                          CancellationToken cancellationToken)
        {
            log?.WriteLine(LogLevel.Query, query);

            Wiql wiql = new Wiql {
                Query = query
            };

            if (errorPolicy == null)
            {
                errorPolicy = ErrorPolicy;
            }

            using var mc = log?.Enter(LogLevel.RawApis, new object[] { wiql, timePrecision, top, null, cancellationToken }, "QueryByWiqlAsync");

            // Return a list of URLs + Ids for matching workItems.
            WorkItemQueryResult queryResult = await WorkItemClient.QueryByWiqlAsync(wiql, timePrecision, top, userState : null, cancellationToken)
                                              .ConfigureAwait(false);

            if (queryResult.WorkItems?.Any() == true)
            {
                var ids = queryResult.WorkItems.Select(wi => wi.Id).ToList();

                // Get the actual work items from the IDs; chunked.
                return(await InternalGetWitsByIdChunked(ids, fields, queryResult.AsOf, expand, errorPolicy, cancellationToken)
                       .ConfigureAwait(false));
            }

            return(Enumerable.Empty <Wit>());
        }
Exemplo n.º 3
0
        public void WorkItemTracking_WorkItems_UpdateWorkItemsByQueryResults_Success()
        {
            // arrange
            IList <WorkItemReference> workItemsList = new List <WorkItemReference>();

            string[] workItemsArr = _configuration.WorkItemIds.Split(','); // get the list of ids from our app.config

            // build a list of work item references for ids we know exist
            foreach (string item in workItemsArr)
            {
                workItemsList.Add(new WorkItemReference()
                {
                    Id = Convert.ToInt32(item)
                });
            }

            WorkItemQueryResult workItemQueryResult = new WorkItemQueryResult();

            workItemQueryResult.WorkItems = workItemsList;

            // act
            WorkItems workItems = new WorkItems(_configuration);
            var       result    = workItems.UpdateWorkItemsByQueryResults(workItemQueryResult, _configuration.Identity);

            // assert
            Assert.AreEqual("success", result);
        }
        private List <TeamItem> ProcessHierarchyItems(WorkItemQueryResult result, WorkItemTrackingHttpClient witClient)
        {
            var hierarchyItems = new Dictionary <int, TeamItem>();
            var sortedItems    = new List <TeamItem>();

            if (result.WorkItemRelations.Any())
            {
                foreach (var relation in result.WorkItemRelations)
                {
                    Console.Write(".");

                    var workItem = witClient.GetWorkItemAsync(relation.Target.Id).Result;

                    // create our own object to hold the item info
                    var item = CreateTeamItem(workItem);

                    if (relation.Source != null)
                    {
                        // it's a child, so add it to its parent
                        var parentItem = hierarchyItems[relation.Source.Id];
                        parentItem.Items.Add(item);
                    }
                    else
                    {
                        // it's a parent, so add it to our list of parents
                        hierarchyItems[item.Id] = item;
                        sortedItems.Add(item);
                    }
                }
            }

            return(sortedItems);
        }
Exemplo n.º 5
0
 private static IEnumerable <int> Ids(WorkItemQueryResult result, int skip = 0)
 {
     return(result.WorkItemRelations.Where(r => r.Target != null).Select(r => r.Target.Id)
            .Union(result.WorkItemRelations.Where(r => r.Source != null).Select(r => r.Source.Id))
            .Skip(skip)
            .Take(100));
 }
Exemplo n.º 6
0
        /// <summary>
        /// Processes the cmdlet record.
        /// </summary>
        protected override void ProcessCmdletRecord()
        {
            var request = new RestRequest("/wit/wiql");

            request.AddJsonBody(this.Query);

            var response = this.Client.Post <WorkItemQueryResult>(request);

            if (!response.IsSuccessful)
            {
                this.ThrowTerminatingError(new ErrorRecord(response.ErrorException, this.BuildStandardErrorId(DevOpsModelTarget.WorkItem), ErrorCategory.NotSpecified, response));
            }

            this.queryResults = response.Data;

            var queryFields = string.Join(",", this.queryResults.Columns.Select(i => i.Name));

            foreach (var item in this.queryResults.WorkItems)
            {
                var arguments = new Dictionary <string, object> {
                    { "Id", item.Id }, { "Fields", queryFields }
                };
                var workItem = this.InvokeModuleCmdlet <WorkItem>("Get-WorkItem", arguments).First();

                this.workItems.Add(workItem);
            }
        }
        public WorkItem GetWorkItem(string title = "RFA", string type = Constants.PBI, string area = "sitefinity\\CMS\\Arke", string iteration = "@currentIteration('[sitefinity]\\Arke <id:22bafa7e-b3fa-4e91-8f41-0702715d148a>')", string state = "Committed")
        {
            WorkItemTrackingHttpClient witClient = this.connection.GetClient <WorkItemTrackingHttpClient>();

            var teamContext = new TeamContext(Constants.SitefinityProjectName);

            var query = "SELECT * FROM workitems " +
                        $"WHERE [Work Item Type] = '{type}' " +
                        $"AND [{Constants.Area}] = '{area}' " +
                        $"AND [{Constants.Iteration}] = {iteration} " +
                        $"AND [{Constants.State}] = '{state}' " +
                        $"AND [{Constants.Title}] CONTAINS WORDS '{title}' ";

            var wiqlQuery = new Wiql()
            {
                Query = query
            };

            WorkItemQueryResult queryResults = witClient.QueryByWiqlAsync(wiqlQuery, teamContext).Result;

            if (queryResults != null && queryResults.WorkItems.Count() != 0)
            {
                var id = queryResults.WorkItems.First().Id;
                return(witClient.GetWorkItemAsync(id, expand: WorkItemExpand.Relations).Result);
            }

            return(null);
        }
        private List <RteWorkItem> GetRequirements(string project, string query)
        {
            List <RteWorkItem> result       = new List <RteWorkItem>();
            var currentQuery                = FindQuery(project, query);
            WorkItemQueryResult queryResult = witClient.QueryByIdAsync(currentQuery.Id).Result;

            if (queryResult.WorkItems.Any())
            {
                int       skip      = 0;
                const int batchSize = 100;
                IEnumerable <WorkItemReference> workItemRefs;
                do
                {
                    workItemRefs = queryResult.WorkItems.Skip(skip).Take(batchSize);
                    if (workItemRefs.Any())
                    {
                        var batch = witClient.GetWorkItemsAsync(workItemRefs.Select(wir => wir.Id)).Result;
                        foreach (var workItem in batch)
                        {
                            var states = GetWorkItemStatuses((int)workItem.Id);
                            result.Add(new RteWorkItem(workItem, states));
                        }
                    }
                    skip += batchSize;
                }while (workItemRefs.Count() == batchSize);
            }
            return(result);
        }
Exemplo n.º 9
0
            /// <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 <System.Web.Util.WorkItem> > RunGetBugsQueryUsingClientLib()
            {
                Uri    uri = new Uri(_uri);
                string personalAccessToken = _personalAccessToken;
                string project             = _project;

                VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken);

                //create a wiql object and build our query
                Wiql 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"
                };

                //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>();
                        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";

                        //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);

                        //loop though work items and write to console
                        foreach (var workItem in workItems)
                        {
                            Console.WriteLine("{0} {1}  {2}", workItem.Id, workItem.Fields["System.Title"], workItem.Fields["System.State"]);
                        }

                        return(workItems);
                    }

                    return(null);
                }
            }
Exemplo n.º 10
0
        private async Task <List <WorkItem> > GetWorkItems(WorkItemQueryResult result)
        {
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();
            var id = Ids(result);

            return(await witClient.GetWorkItemsAsync(id, null, null, WorkItemExpand.Fields));
        }
Exemplo n.º 11
0
        private void executeUpdates_Click(object sender, EventArgs e)
        {
            executeUpdates.Enabled = false;

            var t = new Task(() =>
            {
                workItemQueryResult = GetWorkItems().Result;
                totalThreadCount    = workItemQueryResult.WorkItems.Count();
            });

            t.Start();
            t.Wait();

            progressBar1.Maximum = totalThreadCount;
            progressBar1.Minimum = 0;

            var t2 = new Task(() =>
            {
                if (workItemQueryResult.WorkItems.Count() != 0)
                {
                    List <int> list = new List <int>();
                    foreach (var item in workItemQueryResult.WorkItems)
                    {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                        this.UpdateBugWithChildTasks(item.Id);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    }
                }
            });

            t2.Start();
            t2.Wait();
        }
Exemplo n.º 12
0
 internal WorkItemInfo GetWorkItemById(string workItemId)
 {
     WorkItemStatus[] array = (WorkItemStatus[])Enum.GetValues(typeof(WorkItemStatus));
     using (ProxyWrapper <UpgradeHandlerClient, IUpgradeHandler> workloadClient = new ProxyWrapper <UpgradeHandlerClient, IUpgradeHandler>(this.WorkloadUri, this.Certificate))
     {
         WorkItemStatus[] array2 = array;
         for (int i = 0; i < array2.Length; i++)
         {
             SymphonyTaskBase.< > c__DisplayClass7 CS$ < > 8__locals3 = new SymphonyTaskBase.< > c__DisplayClass7();
             CS$ < > 8__locals3.status = array2[i];
             WorkItemQueryResult result = new WorkItemQueryResult();
             WorkItemInfo        workItemInfo;
             do
             {
                 workloadClient.CallSymphony(delegate
                 {
                     result = workloadClient.Proxy.QueryWorkItems(null, null, null, CS$ < > 8__locals3.status, 1000, result.Bookmark);
                 }, this.WorkloadUri.ToString());
                 workItemInfo = result.WorkItems.SingleOrDefault((WorkItemInfo w) => string.Equals(w.WorkItemId, workItemId));
             }while (workItemInfo == null && result.HasMoreResults);
             if (workItemInfo != null)
             {
                 return(workItemInfo);
             }
         }
         throw new WorkItemNotFoundException(workItemId);
     }
Exemplo n.º 13
0
        public async Task WriteWorkItemDetails(ISink sink)
        {
            WorkItemQueryResult queryResult = await witClient.QueryByWiqlAsync(new Wiql()
            {
                Query = $"SELECT {TitleFieldName}, " +
                        $"       {TeamProjectFieldName}, " +
                        $"       {AreaPathFieldName}, " +
                        $"       {IterationPathFieldName}, " +
                        $"       {WorkItemTypeFieldName}, " +
                        $"       {StateFieldName}, " +
                        $"       {ReasonFieldName}, " +
                        $"       {AssignedToFieldName}, " +
                        $"       {CreatedDateFieldName}, " +
                        $"       {CreatedByFieldName}, " +
                        $"       {ChangedDateFieldName}, " +
                        $"       {ChangedByFieldName}, " +
                        $"       {ResolvedDateFieldName}, " +
                        $"       {ResolvedByFieldName}, " +
                        $"       {ClosedDateFieldName}, " +
                        $"       {ClosedByFieldName}, " +
                        $"       {PriorityFieldName}, " +
                        $"       {SeverityFieldName} " +
                        "FROM workitems"
            });

            await InitialiseSink(sink);

            foreach (WorkItemReference workItemReference in queryResult.WorkItems)
            {
                await WriteWorkItemDetails(witClient, workItemReference.Id, sink);
            }
        }
Exemplo n.º 14
0
        internal const string vstsCollectionUrl = "https://myaccount.visualstudio.com"; //change to the URL of your VSTS account; NOTE: This must use HTTPS
        // internal const string vstsCollectioUrl = "http://*****:*****@Me"
            };
            WorkItemQueryResult queryResults = witClient.QueryByWiqlAsync(query).Result;

            //Display reults in console
            if (queryResults == null || queryResults.WorkItems.Count() == 0)
            {
                Console.WriteLine("Query did not find any results");
            }
            else
            {
                foreach (var item in queryResults.WorkItems)
                {
                    Console.WriteLine(item.Id);
                }
            }
        }
Exemplo n.º 15
0
        private void GetWorkItemsByWiql(HttpClient client, Team team)
        {
            //string _personalAccessToken = "your personal access token";
            //string _credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _personalAccessToken)));

            ////this is needed because we want to create a project scoped query
            //string project = "fabrikam";

            //create wiql object
            var wiql = new
            {
                query = "Select [State], [Title] [AssignedTo]" +
                        "From WorkItems " +
                        "Where [Work Item Type] = 'Bug' " +
                        "And [System.TeamProject] = '" + team.Project + "' " +
                        "And [System.State] = 'New' " +
                        "Order By [State] Asc, [Changed Date] Desc"
            };

            //using (var client = new HttpClient())
            //{
            //client.BaseAddress = new Uri("https://account.visualstudio.com");
            //client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials);

            //serialize the wiql object into a json string
            var postValue = new StringContent(JsonConvert.SerializeObject(wiql), Encoding.UTF8, "application/json");     //mediaType needs to be application/json for a post call

            var    method             = new HttpMethod("POST");
            string query              = $"{GetPath(team)}/_apis/wit/wiql?api-version=2.2";
            var    httpRequestMessage = new HttpRequestMessage(method, query)
            {
                Content = postValue
            };
            var httpResponseMessage = client.SendAsync(httpRequestMessage).Result;

            if (httpResponseMessage.IsSuccessStatusCode)
            {
                WorkItemQueryResult workItemQueryResult = httpResponseMessage.Content.ReadAsAsync <WorkItemQueryResult>().Result;

                //now that we have a bunch of work items, build a list of id's so we can get details
                var builder = new System.Text.StringBuilder();
                foreach (var item in workItemQueryResult.workItems)
                {
                    builder.Append(item.id.ToString()).Append(",");
                }

                //clean up string of id's
                string ids = builder.ToString().TrimEnd(new char[] { ',' });

                string workItemQuery = "_apis/wit/workitems?ids=" + ids + "&fields=System.Id,System.Title,System.State&asOf=" + workItemQueryResult.asOf + "&api-version=2.2";
                HttpResponseMessage getWorkItemsHttpResponse = client.GetAsync(workItemQuery).Result;

                if (getWorkItemsHttpResponse.IsSuccessStatusCode)
                {
                    var result = getWorkItemsHttpResponse.Content.ReadAsStringAsync().Result;
                }
            }
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            Uri orgUrl = new Uri("https://dev.azure.com/raman9900");         // Organization URL, for example: https://dev.azure.com/fabrikam
            // String personalAccessToken = "2ukhabsogznygn32rkegpo7jtk5kcwmljrqndzyyytma2g4r2tla";  // See https://docs.microsoft.com/azure/devops/integrate/get-started/authentication/pats
            //  string authInfo = "carsten:Work@123";  // Enter your user name and password. If you are not using PAT, then use this method. I used this method.
            // string _credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authInfo)); //needed if you are passing user name and password


            string project = "MyFirstProject";

            Wiql 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"
            };
            // Create a connection

            // VssCredentials credentials = new VssBasicCredential("Basic", _credentials);
            VssCredentials credentials = new VssBasicCredential("carsten", "Work@123");
            //VssConnection connection = new VssConnection(orgUrl, credentials);
            WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(orgUrl, credentials);
            WorkItemQueryResult        workItemQueryResult        = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

            //VssConnection connection = new VssConnection(orgUrl, new VssCredentials());


            // Show details a work item
            //ShowWorkItemDetails(connection, workItemId);
            Console.WriteLine(workItemQueryResult);
            Console.ReadLine();
        }
Exemplo n.º 17
0
        static private async Task AddOrUpdateApplicationDetail(VssConnection connection, SqlConnection con)
        {
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();

            try
            {
                Wiql wiql = new Wiql();

                wiql.Query = "SELECT QUERY";

                WorkItemQueryResult tasks = await witClient.QueryByWiqlAsync(wiql);

                IEnumerable <WorkItemReference> tasksRefs;
                tasksRefs = tasks.WorkItems.OrderBy(x => x.Id);
                List <WorkItem> tasksList = witClient.GetWorkItemsAsync(tasksRefs.Select(wir => wir.Id)).Result;
            }
            catch (AggregateException aex)
            {
                VssServiceException vssex = aex.InnerException as VssServiceException;
                if (vssex != null)
                {
                    Console.WriteLine(vssex.Message);
                }
            }
        }
Exemplo n.º 18
0
        public void GetTfsData()
        {
            String dtRegistroLocal = _LogReg.ConsultaDtRegistro();

            string _credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _personalAccessToken)));

            var wiql = new
            {
                query = "Select [Id] " +
                        " From WorkItems " +
                        " Where [System.ChangedDate] > '" + dtRegistroLocal + "' " +    //pega so qm teve changedDate superior a
                        " AND [ONS.Fornecedor] = 'BRQ' "
            };

            using (var client = new HttpClient())
            {
                HttpResponseMessage _client = validateCliente(url, client, _credentials, wiql);

                if (_client.IsSuccessStatusCode)
                {
                    WorkItemQueryResult workItemQueryResult = _client.Content.ReadAsAsync <WorkItemQueryResult>().Result;

                    StringBuilder ids = new StringBuilder();

                    foreach (var item in workItemQueryResult.workItems)
                    {
                        var id = item.id;

                        GetDataWorkItem(id.ToString(), _credentials, client);
                    }
                }
            }
        }
Exemplo n.º 19
0
        public List <WorkItems> ObterWorkItems(int ultimoId)
        {
            // Recupera os work items no azure devops
            var    WItems = new List <WorkItems>();
            var    uri    = new Uri(_uri);
            string personalAccessToken = _token;
            string project             = _projeto;

            VssBasicCredential credentials = new VssBasicCredential("", _token);

            Wiql wiql = new Wiql()
            {
                Query = "Select [Id], [Title], [Work Item Type], [Changed Date] " +
                        "From WorkItems " +
                        "Where [System.TeamProject] = '" + project + "' " +
                        "And [Id] > " + ultimoId + " " +
                        "Order By [Changed Date] Desc"
            };

            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, credentials))
            {
                WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

                if (workItemQueryResult.WorkItems.Any())
                {
                    List <int> list = new List <int>();
                    foreach (var item in workItemQueryResult.WorkItems)
                    {
                        list.Add(item.Id);
                    }
                    int[] arr = list.ToArray();

                    string[] fields = new string[5];
                    fields[0] = "System.Id";
                    fields[1] = "System.Title";
                    fields[2] = "System.WorkItemType";
                    fields[3] = "System.ChangedDate";

                    var workItems = workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf).Result;

                    Console.WriteLine("Query Results: {0} items found", workItems.Count);

                    foreach (var workItem in workItems)
                    {
                        var WItem = new WorkItems
                        {
                            Id     = workItem.Id,
                            Titulo = workItem.Fields["System.Title"].ToString(),
                            Tipo   = workItem.Fields["System.WorkItemType"].ToString(),
                            Data   = (DateTime)workItem.Fields["System.ChangedDate"]
                        };

                        WItems.Add(WItem);
                    }
                }

                return(WItems);
            }
        }
Exemplo n.º 20
0
        private async Task <string> GenerateReleaseNotesMarkdown()
        {
            Wiql wiql = new Wiql()
            {
                Query = "SELECT [System.Title],[Custom.Notes] " +
                        "FROM WorkItems " +
                        "WHERE [System.WorkItemType] = 'Product Backlog Item' " +
                        "AND [Custom.ReleaseNotes] = true " +
                        "And [System.TeamProject] = '" + _project + "' " +
                        "AND [System.IterationPath] = @currentIteration('" + _teamName + "')"
            };
            StringBuilder sb = new StringBuilder();

            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(_uri, credentials))
            {
                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[2];
                    fields[0] = "System.Title";
                    fields[1] = "Custom.Notes";

                    //get work items for the ids found in query
                    List <WorkItem> workItems = await workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields);

                    Converter converter = new Converter(new CustomScheme());

                    sb.Append("# Features\n");
                    foreach (var workItem in workItems)
                    {
                        string title = workItem.Fields["System.Title"].ToString();
                        string link  = Regex.Replace(title, @"\s+", "-");
                        sb.Append($"- [{title}](#{link})\n\n\n");
                    }

                    //loop though work items and write to console
                    foreach (var workItem in workItems)
                    {
                        string title = workItem.Fields["System.Title"].ToString();
                        sb.Append($"# {title}\n");
                        string md = converter.Convert(workItem.Fields["Custom.Notes"].ToString());
                        sb.Append(md);
                    }
                }
            }
            return(sb.ToString());
        }
Exemplo n.º 21
0
        public List <Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItem> RunGetBugsQueryUsingClientLib()
        {
            Uri    uri = new Uri(_uri);
            string personalAccessToken = _personalAccessToken;
            string project             = _project;

            VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken);

            //create a wiql object and build our query
            Wiql wiql = new Wiql()
            {
                Query = "Select [State], [Title], [System.TeamProject], [System.WorkItemType], [System.IterationPath]" +
                        "From WorkItems " +
                        "Where [Work Item Type] in ('Task','Bug') " +
                        //"And [System.TeamProject] = '" + project + "' " +
                        "And [System.State] = 'To Do'  " +
                        "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 = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

                //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[6];
                    fields[0] = "System.Id";
                    fields[1] = "System.Title";
                    fields[2] = "System.State";
                    fields[3] = "System.TeamProject";
                    fields[4] = "System.WorkItemType";
                    //fields[5] = "System.AssignedTo";
                    fields[5] = "System.IterationPath";


                    //get work items for the ids found in query
                    var workItems = workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf).Result;

                    Console.WriteLine("Query Results: {0} items found", workItems.Count);

                    return(workItems);
                }

                return(null);
            }
        }
        static void Main(string[] args)
        {
            Uri    uri     = new Uri("https://{account}.visualstudio.com");
            string PAT     = "TokenHere";
            string project = "ProjectName";

            VssBasicCredential credentials = new VssBasicCredential("", PAT);

            //create a wiql object and build our query
            Wiql wiql = new Wiql()
            {
                Query = "Select * " +
                        "From WorkItems " +
                        "Where [Work Item Type] IN ('Product Backlog Item', 'Task') " +
                        "And [System.TeamProject] = '" + project + "' " +
                        "And [System.State] <> 'Closed' " +
                        "And [System.RelatedLinkCount] > '0'" +
                        "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 = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

                //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[3];
                    fields[0] = "System.Id";
                    fields[1] = "System.Title";
                    fields[2] = "System.RelatedLinkCount";

                    //get work items for the ids found in query
                    var workItems = workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf).Result;

                    Console.WriteLine("Query Results: {0} items found", workItems.Count);

                    //loop though work items and write to console
                    foreach (var workItem in workItems)
                    {
                        Console.WriteLine("ID:{0} Title:{1}  RelatedLinkCount:{2}", workItem.Id, workItem.Fields["System.Title"], workItem.Fields["System.RelatedLinkCount"]);
                    }

                    Console.ReadLine();
                }
            }
        }
        public ActionResult GetCount()
        {
            ApiResponseViewModel response = new ApiResponseViewModel();

            WorkItemQueryResult results = _workItemsRepo.QueryWorkItems();
            int count = results != null?results.WorkItems.Count() : 0;

            return(new StandardResponseObjectResult(count, StatusCodes.Status200OK));
        }
Exemplo n.º 24
0
        public List <Models.WorkItem> GetTFSItems(TfsProject project, string iteration)
        {
            VssBasicCredential credentials = new VssBasicCredential("", PersonalAccessToken);
            Uri  uri   = new Uri("https://bofaz.visualstudio.com/");
            var  items = new List <Models.WorkItem>();
            Wiql wiql  = new Wiql()
            {
                Query = "Select [System.State], [System.Title], [System.Id]" +
                        "From WorkItems " +
                        "WHERE [System.TeamProject] = '" + project.Name + "' " +
                        "AND [System.IterationPath] = '" + iteration + "' " +
                        "AND [System.AssignedTo] = @Me "
            };

            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, credentials))
            {
                //execute the query to get the list of work items in the results
                WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

                //some error handling
                if (workItemQueryResult.WorkItems.ToList().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[3];
                    fields[0] = "System.Id";
                    fields[1] = "System.Title";
                    fields[2] = "System.State";

                    //get work items for the ids found in query
                    var workItems = workItemTrackingHttpClient.GetWorkItemsAsync(arr, fields, workItemQueryResult.AsOf).Result;

                    //loop though work items and write to console
                    foreach (var workItem in workItems)
                    {
                        var it = new Models.WorkItem()
                        {
                            Description = workItem.Fields["System.Title"].ToString(),
                            State       = workItem.Fields["System.State"].ToString(),
                            Iteration   = iteration,
                        };

                        items.Add(it);
                    }
                }
            }

            return(items);
        }
Exemplo n.º 25
0
        public static async Task GetTask(VssConnection connection, string projeto)
        {
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();

            //WorkItem workitem = await witClient.GetWorkItemAsync(4621);

            List <QueryHierarchyItem> queryHierarchyItems = witClient.GetQueriesAsync(projeto, depth: 2).Result;

            QueryHierarchyItem myQueriesFolder = queryHierarchyItems.FirstOrDefault(qhi => qhi.Name.Equals("Shared Queries"));

            if (myQueriesFolder != null)
            {
                string queryName = "Integra";

                // See if our 'REST Sample' query already exists under 'My Queries' folder.
                QueryHierarchyItem newBugsQuery = null;
                if (myQueriesFolder.Children != null)
                {
                    newBugsQuery = myQueriesFolder.Children.FirstOrDefault(qhi => qhi.Name.Equals(queryName));
                }
                if (newBugsQuery == null)
                {
                    // if the 'REST Sample' query does not exist, create it.
                    newBugsQuery = new QueryHierarchyItem()
                    {
                        Name     = queryName,
                        Wiql     = "SELECT [System.Id],[System.WorkItemType],[System.Title],[System.AssignedTo],[System.State],[System.Tags] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.WorkItemType] = 'Bug' AND [System.State] = 'New'",
                        IsFolder = false
                    };
                    newBugsQuery = witClient.CreateQueryAsync(newBugsQuery, projeto, myQueriesFolder.Name).Result;
                }

                WorkItemQueryResult result = witClient.QueryByIdAsync(newBugsQuery.Id).Result;

                if (result.WorkItems.Any())
                {
                    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)
                            {
                                var teste = workItem;
                            }
                        }
                        skip += batchSize;
                    }while (workItemRefs.Count() == batchSize);
                }
            }
        }
Exemplo n.º 26
0
        private IEnumerable <int> Ids(WorkItemQueryResult result, int skip = 0)
        {
            IEnumerable <WorkItemLink> workitems = result.WorkItemRelations;
            IEnumerator <WorkItemLink> test      = workitems.GetEnumerator();

            return(workitems.Where(r => r.Target != null).Select(r => r.Target.Id)
                   .Union(result.WorkItemRelations.Where(r => r.Source != null).Select(r => r.Source.Id))
                   .Skip(skip)
                   .Take(100));
        }
Exemplo n.º 27
0
        public JObject RunQuery(Guid projectID, string queryContent)
        {
            Wiql query = new Wiql()
            {
                Query = queryContent
            };
            WorkItemQueryResult queryResults = this._WorkItemClient.QueryByWiqlAsync(query, projectID).Result;

            return(JObject.FromObject(queryResults));
        }
Exemplo n.º 28
0
        public IEnumerable <ProductBacklog> GetAllProductBacklog(string projectName)
        {
            Wiql wiql = new Wiql()
            {
                Query = "Select * " +
                        "From WorkItems " +
                        "Where System.TeamProject='" + projectName + "' " +
                        "Order By [Changed Date] Desc"
            };

            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(_uri, _credentials))
            {
                WorkItemQueryResult queryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

                if (queryResult != null && queryResult.WorkItems.Count() > 0)
                {
                    // return queryResult;
                    var workItems = GetWorkItemsWithSpecificFields(queryResult.WorkItems.Select(t => t.Id));
                    List <ProductBacklog> productBacklogs = new List <ProductBacklog>();
                    var detailsFromDb = _FrameworxProjectDatabaseContext.Query <ProductBacklog>().ToList();

                    foreach (var item in workItems)
                    {
                        var productBacklogItem = new ProductBacklog()
                        {
                            Id            = int.Parse(item.Fields["System.Id"].ToString()),
                            Title         = item.Fields["System.Title"].ToString(),
                            State         = item.Fields["System.State"].ToString(),
                            Type          = item.Fields.ContainsKey("System.WorkItemType") ? item.Fields["System.WorkItemType"].ToString() : Constants.InformationNotAvailableText,
                            Area          = item.Fields.ContainsKey("System.AreaPath") ? item.Fields["System.AreaPath"].ToString() : Constants.InformationNotAvailableText,
                            AssigneeEmail = detailsFromDb.Any(t => t.Id == item.Id) ? detailsFromDb.FirstOrDefault(t => t.Id == item.Id).AssigneeEmail : "",
                            AssignedBy    = detailsFromDb.Any(t => t.Id == item.Id) ? detailsFromDb.FirstOrDefault(t => t.Id == item.Id).AssignedBy : "",
                            TimeAllocated = item.Fields.ContainsKey("Microsoft.VSTS.Scheduling.OriginalEstimate") ? (double)item.Fields["Microsoft.VSTS.Scheduling.OriginalEstimate"] : 0.00,
                            TimeSpent     = item.Fields.ContainsKey("Microsoft.VSTS.Scheduling.CompletedWork") ? (double)item.Fields["Microsoft.VSTS.Scheduling.CompletedWork"] : 0.0,
                            CreatedDate   = (DateTime)item.Fields["System.CreatedDate"],
                            ChangedDate   = (DateTime)item.Fields["System.ChangedDate"]
                        };
                        productBacklogItem.AssigneeDisplayName = detailsFromDb.Any(t => t.Id == item.Id) ? detailsFromDb.FirstOrDefault(t => t.Id == item.Id).AssigneeDisplayName : "Unassigned";

                        if (string.IsNullOrWhiteSpace(productBacklogItem.AssigneeDisplayName))
                        {
                            productBacklogItem.AssigneeDisplayName = "Unassigned";
                        }

                        productBacklogs.Add(productBacklogItem);
                    }

                    return(productBacklogs);
                }
                else
                {
                    throw new NullReferenceException("Wiql '" + wiql.Query + "' did not find any results");
                }
            }
        }
Exemplo n.º 29
0
        public List <Feature> GetFeatures(DateTime fromdate, DateTime?toDate)
        {
            List <Feature>     features      = new List <Feature>();
            QueryHierarchyItem featuresQuery = _queriesFolder.Children?.FirstOrDefault(qhi => qhi.Name.Equals(FeaturesQueryName, StringComparison.InvariantCulture));

            if (featuresQuery == null)
            {
                featuresQuery = new QueryHierarchyItem()
                {
                    Name = FeaturesQueryName,
                    Wiql = string.Format(CultureInfo.InvariantCulture,
                                         "SELECT [System.Id]," +
                                         "[System.IterationId]," +
                                         "[System.CreatedDate]," +
                                         "[System.Title]," +
                                         "[System.State]" +
                                         "FROM WorkItems WHERE [System.TeamProject] = @project AND [System.WorkItemType] = 'Feature' AND [System.State] <> 'Removed' AND [System.CreatedDate] >= '{0:MM/dd/yyyy}'", fromdate),
                    IsFolder = false
                };
                if (toDate?.Year != 1)
                {
                    featuresQuery.Wiql += string.Format(CultureInfo.InvariantCulture, Environment.NewLine + "AND [System.CreatedDate] <= '{1:MM/dd/yyyy}'", toDate);
                }
            }
            featuresQuery = _workItemTrackingClient.CreateQueryAsync(featuresQuery, OnlineTfsTeamProjectName, _queriesFolder.Id.ToString()).Result;
            WorkItemQueryResult featuresQueryResult = _workItemTrackingClient.QueryByIdAsync(featuresQuery.Id).Result;

            if (featuresQueryResult.WorkItems.Any())
            {
                int       skip      = 0;
                const int batchSize = 100;
                IEnumerable <WorkItemReference> workItemRefs;
                do
                {
                    workItemRefs = featuresQueryResult.WorkItems.Skip(skip).Take(batchSize);
                    if (workItemRefs.Any())
                    {
                        List <string> columnptions = new List <string>
                        {
                            "System.Id", "System.IterationId", "System.CreatedDate", "System.Title", "System.State"
                        };
                        List <WorkItem> workItems = _workItemTrackingClient.GetWorkItemsAsync(workItemRefs.Select(wir => wir.Id), columnptions).Result;
                        foreach (WorkItem workItem in workItems)
                        {
                            Feature feature = new Feature();
                            FillFeaturesData(feature, workItem.Fields);
                            features.Add(feature);
                        }
                    }
                    skip += batchSize;
                } while (workItemRefs.Count() == batchSize);
            }
            return(features);
        }
Exemplo n.º 30
0
        public WorkItemQueryResult ExecuteQuery()
        {
            Guid queryId = Guid.Parse("6e511ae8-aafe-455a-b318-a4158bbd0f1e"); // TODO

            VssConnection connection = Context.Connection;
            WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient <WorkItemTrackingHttpClient>();

            WorkItemQueryResult queryResult = workItemTrackingClient.QueryByIdAsync(queryId).Result;

            return(queryResult);
        }
Exemplo n.º 31
0
 private static IEnumerable<int> Ids(WorkItemQueryResult result, int skip = 0)
 {
     return result.WorkItemRelations.Where(r => r.Target != null).Select(r => r.Target.Id)
         .Union(result.WorkItemRelations.Where(r => r.Source != null).Select(r => r.Source.Id))
         .Skip(skip)
         .Take(100);
 }
Exemplo n.º 32
0
 private async Task<List<WorkItem>> GetWorkItems(WorkItemQueryResult result)
 {
     return await WorkItemsClient.GetWorkItemsAsync(Ids(result), null, null, WorkItemExpand.Fields);
     //var items = new List<WorkItem>();
     //var added = 1;
     //var skip = 0;
     //while (added > 0) {
     //    var add = await WorkItemsClient.GetWorkItemsAsync(Ids(result, skip), null, null, WorkItemExpand.Fields);
     //    items.AddRange(add);
     //    added = add.Count();
     //    skip += added;
     //}
     //return items;
 }