예제 #1
0
        private static void GetJiraIssues()
        {
            List <string> keys = issueAssociations.Keys.Distinct().ToList();
            Jira          jira = GetJiraClient();

            // use LINQ syntax to retrieve issues
            IPagedQueryResult <Atlassian.Jira.Issue> issues = null;
            var success = false;

            do
            {
                try
                {
                    var jql = $"issueKey in ({string.Join(',', keys)})";
                    issues  = jira.Issues.GetIssuesFromJqlAsync(jql, maxIssues: keys.Count).Result;
                    success = true;
                }
                catch (Exception e)
                {
                    if (e.Message.IsJiraIssue(out string[] errorKeys))
                    {
                        keys.RemoveAll(k => errorKeys.Contains(k));
                    }
                    else
                    {
                        throw;
                    }
                }
            } while (!success);
            jiraIssues = issues?.ToList() ?? default;
        }
예제 #2
0
        private async Task <bool> TestLogin()
        {
            Atlassian.Jira.Jira tempJira = Atlassian.Jira.Jira.CreateRestClient(Setting.Value.Jira_Link, Username.Text, Password.Text, new JiraRestClientSettings()
            {
                EnableRequestTrace = true
            });

            bool pass = false;

            tempJira.Issues.MaxIssuesPerRequest = 5; //Set the Max Issues per Request to 25
            IPagedQueryResult <Issue> issues = null; //Creates a variable to store the issues in outside the try-catch statement

            try
            {
                issues = await tempJira.Issues.GetIssuesFromJqlAsync("project = LAC"); //Attempt to pull the issues

                if (issues.Count() == 5)
                {
                    pass = true;
                }
            }
            catch
            {
                pass = false;
            }

            return(pass);
        }
예제 #3
0
        private async void LoadIssues(string jql)
        {
            infoLabel.ForeColor = Color.Black;
            infoLabel.Text      = "Loading";
            IPagedQueryResult <Issue> issues = null;

            try
            {
                if (StaticHandler._Main != null)
                {
                    StaticHandler._Main._Jira.Issues.MaxIssuesPerRequest = (int)maxIssuesPerRequest.Value;
                    issues = await StaticHandler._Main._Jira.Issues.GetIssuesFromJqlAsync(jql); //Attempt to pull the issues
                }
                if (StaticHandler._ThemedMain != null)
                {
                    JiraChecker._Jira.Issues.MaxIssuesPerRequest = (int)maxIssuesPerRequest.Value;
                    issues = await JiraChecker._Jira.Issues.GetIssuesFromJqlAsync(jql); //Attempt to pull the issues
                }
                infoLabel.Text      = "Loaded " + issues.Count <Issue>() + " issues";
                infoLabel.ForeColor = Color.Black;
                Issues.Clear();
                Issues.AddRange(issues);
                PopulateLists();
            }
            catch (Exception e)
            {
                infoLabel.Text = "Failed to load";
                MessageBox.Show(e.Message);
                infoLabel.ForeColor = Color.Red;
            }

            this.Size = new Size(461, 433);
        }
예제 #4
0
        private static PagedQueryResult <T> CreateInternalPagedQueryResult <T>([NotNull] this IPagedQueryResult <T> oldValue, bool cachedUsed = false)
        {
            Guard.NotNull(oldValue, nameof(oldValue));

            return(new PagedQueryResult <T>(oldValue.Result, oldValue.Total)
            {
                CacheUsed = cachedUsed
            });
        }
예제 #5
0
        private IEnumerable <WorkEntry> GetJiraIssues(IPagedQueryResult <Issue> issues)
        {
            ICollection <WorkEntry> jiraIssues = new List <WorkEntry>();

            foreach (var i in issues)
            {
                jiraIssues.Add(new WorkEntry(false, i.Key.ToString(), i.Summary, i.Description, DateTime.Now, DateTime.Now, _jira.Url + "browse/" + i.Key, i.Reporter, "Jira"));
            }
            return(jiraIssues);
        }
예제 #6
0
        protected override IActionResult RenderIndex(IPagedQueryResult <RoleReadModel> model)
        {
            var indexModel = new RoleIndexViewModel
            {
                Items       = model.Items,
                TotalCount  = model.TotalCount,
                Permissions = ReadPermissionList()
            };

            return(Request.IsAjaxRequest()
                ? (IActionResult)PartialView(indexModel)
                : View(indexModel));
        }
        private void LoadIssues(int page)
        {
            // Load in a seperate thread
            Settings.Default.Save();
            this.Issues.Clear();
            this.PageInfo  = "Loading...";
            this.IsLoading = true;
            this.IsNavigatingBackEnabled = false;
            this.IsNavigatingNextEnabled = false;

            Task.Factory.StartNew(() =>
            {
                Jira jiraClient;
                if (string.IsNullOrEmpty(this.User) && string.IsNullOrEmpty(this.passwordBox.Password))
                {
                    jiraClient = Jira.CreateRestClient(this.ProjectUrl);
                }
                else
                {
                    jiraClient = Jira.CreateRestClient(this.ProjectUrl, this.User, this.passwordBox.Password);
                }

                int startAt       = (page - 1) * ItemsPerPage;
                this.searchResult = jiraClient.Issues.GetIssuesFromJqlAsync(this.Jql, maxIssues: ItemsPerPage, startAt: startAt).GetAwaiter().GetResult();
            })
            .ContinueWith(ui =>
            {
                if (ui.Status == TaskStatus.Faulted)
                {
                    this.PageInfo = string.Format("Error: {0}", ui.Exception.Message);
                }
                else
                {
                    int totalPages  = (this.searchResult.TotalItems / this.searchResult.ItemsPerPage) + 1;
                    int currentPage = (this.searchResult.StartAt / this.searchResult.ItemsPerPage) + 1;

                    this.PageInfo = $"{currentPage} of {totalPages}";
                    this.IsNavigatingBackEnabled = currentPage > 1;
                    this.IsNavigatingNextEnabled = currentPage < totalPages;
                    this.IsLoading = false;

                    foreach (var issue in this.searchResult)
                    {
                        this.Issues.Add(issue);
                    }

                    this.listView.SelectAll();
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
예제 #8
0
파일: JiraJob.cs 프로젝트: mmikirtumov/ISA
        private async Task UploadIssuesBatch(IPagedQueryResult <Issue> jiraResponse)
        {
            var elasticRequest = new JiraElasticUpsertRequest
            {
                Entities = CreateUpsertData(jiraResponse)
            };

            await _elasticsearchClient.UpsertManyAsync(elasticRequest);

            var titlesWithIds = jiraResponse.Select(s => $" {s.Summary}-{s.Key}");

            _logger.LogInformation("JiraJob | {BatchUploadDate} | remains to load: {countOfRemaining} | batch loaded: [{uploadedDataIdentifiers}]",
                                   DateTime.Now,
                                   jiraResponse.TotalItems,
                                   string.Join(',', titlesWithIds));
        }
        /// <summary>
        /// 请求Issues
        /// </summary>
        /// <param name="jiraUri">公司/组织的Jira地址,如https://jira.huawei.com</param>
        /// <param name="jqlText"></param>
        /// <returns></returns>
        public static async Task <List <Issue> > RequestAsync(string jiraUri, string jqlText)
        {
            IPagedQueryResult <Issue> issues = null;

            try
            {
                //之前的版本,Atlassian已经弃用
                // Jira jira = new Jira(url, "admin", "password");
                var jira = Jira.CreateRestClient(jiraUri, CustomUtils.Account, CustomUtils.Password);
                //GetIssuesFromJqlAsync相当于 $"{jiraUri}/rest/api/2/search?jql={requestText}";
                issues = await jira.Issues.GetIssuesFromJqlAsync(jqlText, 100000);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(issues?.ToList() ?? new List <Issue>());
        }
예제 #10
0
        public async Task <List <Issue> > GetSubTasksAsync(Issue issue, CancellationToken token = default(CancellationToken))
        {
            List <Issue> result = new List <Issue>();

            int incr  = 0;
            int total = 0;


            do
            {
                IPagedQueryResult <Issue> response = await issue.GetSubTasksAsync(10, incr, token).ConfigureAwait(false);

                total = response.TotalItems;

                incr += response.Count();

                result.AddRange(response);
            }while (incr < total);

            return(result);
        }
        public async Task <List <Issue> > GetIssuesAsync(string jql, string updateIssueStartDate, SyncSystemDTO syncSystem)
        {
            int          itemsPerPage = 1000;
            int          counter      = 0;
            List <Issue> result       = new List <Issue>();

            if (syncSystem.ActualsStartDate.HasValue)
            {
                jql = $"({jql}) and ((updated >= {updateIssueStartDate} and issuetype != 'Epic') or issuetype = 'Epic')";
            }
            logger.Info($"GetIssuesAsync jql: {jql}");
            IPagedQueryResult <Issue> query = await JiraConnection.Issues
                                              .GetIssuesFromJqlAsync(jql, itemsPerPage, counter);

            logger.Info($"GetIssuesAsync counter: {counter}; query.TotalItems: {query.TotalItems}; " +
                        $"query.ItemsPerPage: {query.ItemsPerPage}; query.StartAt: {query.StartAt}");

            result.AddRange(query.ToList());

            counter += itemsPerPage;

            while (query.TotalItems >= counter)
            {
                logger.Info("GetIssuesAsync while1 counter " + counter);

                query = await JiraConnection.Issues
                        .GetIssuesFromJqlAsync(jql, itemsPerPage, counter);

                counter += itemsPerPage;

                logger.Info($"GetIssuesAsync while2 counter: {counter}; query.TotalItems: {query.TotalItems}; " +
                            $"query.ItemsPerPage: {query.ItemsPerPage}; query.StartAt: {query.StartAt}");

                result.AddRange(query.ToList());
            }
            logger.Info("GetIssuesAsync result.Count " + result.Count);
            return(result);
        }
예제 #12
0
 public static bool IsFirstPage(this IPagedQueryResult source)
 {
     return(source.PageNumber <= 1);
 }
예제 #13
0
 public static bool IsLastPage(this IPagedQueryResult source)
 {
     return(source.PageCount <= source.PageNumber);
 }
        public static IActionResult ReturnObjectResult <TView, TQueryResult>(this ControllerBase controller, IPagedQueryResult queryResult, IMapper mapper)
            where TView : class, IPagedResultView
            where TQueryResult : class, IPagedQueryResult
        {
            var viewModel      = mapper.Map <TView>(queryResult); // todo: can we remove mapper as a parameter?
            var responseObject = ApiResponse.ApiResponseFactory <TView>(viewModel, queryResult.Paging);

            switch (queryResult.ResultStatus)
            {
            case QueryResultStatus.NotYetProcessed:
                throw new Exception("A query result has been returned to the controller in its default state.  Implement a try-catch-finally and set the appropriate status.");

            case QueryResultStatus.SuccessfullyProcessed:
                return(new OkObjectResult(responseObject));

            case QueryResultStatus.NoResultData:
                return(new NotFoundObjectResult(responseObject));

            case QueryResultStatus.CriticalError:
                return(new ObjectResult(responseObject)
                {
                    StatusCode = (int)System.Net.HttpStatusCode.InternalServerError
                });

            default: throw new ArgumentException("The result enum has no appropriate HTTP status code mapped.");
            }
        }
예제 #15
0
 protected virtual IActionResult RenderIndex(IPagedQueryResult <TReadModel> model)
 {
     return(Request.IsAjaxRequest()
         ? (IActionResult)PartialView(model)
         : View(model));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PagedQueryResult{TResult}"/> class.
 /// </summary>
 /// <param name="result">The paged result.</param>
 internal PagedQueryResult(IPagedQueryResult <TResult> result) : this(result.Result, result.Total)
 {
 }
예제 #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CachePagedQueryResult{TResult}"/> class.
 /// </summary>
 /// <param name="hashedKey">The hashed key.</param>
 /// <param name="result">The result.</param>
 public CachePagedQueryResult([NotNull] string hashedKey, [CanBeNull] IPagedQueryResult <TResult> result) : base(hashedKey, result)
 {
 }
예제 #18
0
        public async Task <IList <IssueLight> > GetAllIssuesInProject(IReadOnlyCollection <JiraNamedObjectLight> customFields)
        {
            if (customFields == null)
            {
                throw new ArgumentNullException(nameof(customFields));
            }

            var epicField        = customFields.First(cf => cf.Name == _jiraContext.EpicLinkName);
            var storyPointsField = customFields.First(cf => cf.Name == _jiraContext.StoryPointsName);

            bool   useStatus        = _jiraContext.ExcludedStatuses?.LongLength > 0;
            bool   useCreated       = false;
            bool   useEpics         = _jiraContext.Epics?.Any() ?? false;
            string epics            = string.Join(',', _jiraContext.Epics?.Select(i => $"\"{i}\"") ?? Enumerable.Empty <string>());
            string excludedStatuses = string.Join(',',
                                                  _jiraContext.ExcludedStatuses ?? Enumerable.Empty <string>());

            var createdFilterPart =
                $@" AND Created > ""{DateTime.Today.AddDays(-_jiraContext.DaysBackToFetchIssues).Date:yyyy-MM-dd}"" ";
            var statusFilterPart = $" AND Status NOT IN ( {excludedStatuses} ) ";
            var epicFilterPart   = $@" AND (""{epicField.Name}"" in ({epics}) OR parent in ({epics}) OR id in ({epics}) ) ";


            var searchOptions =
                new IssueSearchOptions(
                    $@" Project = ""{_jiraContext.Project}""{(useStatus ? statusFilterPart:"")}{(useEpics ? epicFilterPart:"")}{(useCreated ? createdFilterPart: "")} ")
            {
                StartAt          = 0,
                FetchBasicFields = false,
                AdditionalFields = new[]
                {
                    "key",
                    "assignee",
                    "reporter",
                    "created",
                    "summary",
                    "status",
                    "issuetype",
                    epicField.Id,
                    storyPointsField.Id,
                    "parent",
                    "labels"
                }
            };

            Console.WriteLine($"JQL: {searchOptions.Jql}");

            var result = new List <IssueLight>();
            IPagedQueryResult <Issue> pages = null;

            do
            {
                pages = await _jira.Issues.GetIssuesFromJqlAsync(searchOptions).ConfigureAwait(false);

                Debug.Assert(pages != null);
                result.AddRange(pages.Select(i => i.ToIssueLight(epicField.Id, storyPointsField.Id)));
                searchOptions.StartAt = Math.Min(searchOptions.StartAt + pages.ItemsPerPage, pages.TotalItems);
            } while (searchOptions.StartAt < pages.TotalItems);

            return(result);
        }