private void PublishError(Message request, PublisherSocket ioPub, IErrorResult error)
        {
            // Write to Stderr first -- then write the ExecuteError
            var     errorMessage = new StderrContent(error.Message);
            Message message      = new Message(MessageType.Stream, errorMessage, request.Header)
            {
                Identifiers = request.Identifiers
            };

            this._logger.LogInformation(string.Format("Sending message to IOPub {0}", JsonConvert.SerializeObject(message)));
            ioPub.SendMessage(message);


            var executeReply = new ExecuteErrorPublishContent()
            {
                ExecutionCount = _executionCount,
                EName          = error.Name,
                EValue         = error.Message,
                Traceback      = error.StackTrace
            };

            message = new Message(MessageType.Error, executeReply, request.Header)
            {
                Identifiers = request.Identifiers
            };
            this._logger.LogInformation(string.Format("Sending message to IOPub {0}", JsonConvert.SerializeObject(message)));
            ioPub.SendMessage(message);
        }
Example #2
0
        private void SendErrorToIOPub(Message message, PublisherSocket ioPub, IErrorResult error)
        {
            var executeReply = new ExecuteReplyError()
            {
                ExecutionCount = executionCount,
                EName          = error.Name,
                EValue         = error.Message,
                Traceback      = error.StackTrace
            };
            Message executeReplyMessage = new Message(MessageTypeValues.Error, JsonConvert.SerializeObject(executeReply), message.Header)
            {
                Identifiers = message.Identifiers
            };

            this.messageSender.Send(executeReplyMessage, ioPub);
            this.logger.LogInformation(string.Format("Sending message to IOPub {0}", JsonConvert.SerializeObject(executeReplyMessage)));

            var errorMessage = new StderrMessage()
            {
                Text = error.Message
            };

            Message stderrMessage = new Message(MessageTypeValues.Stream, JsonConvert.SerializeObject(errorMessage), message.Header)
            {
                Identifiers = message.Identifiers
            };

            this.messageSender.Send(stderrMessage, ioPub);
            this.logger.LogInformation(string.Format("Sending message to IOPub {0}", JsonConvert.SerializeObject(stderrMessage)));
        }
 public static bool HasErrors(this IErrorResult errorResult)
 {
     if (errorResult == null)
     {
         throw new ArgumentNullException(nameof(errorResult));
     }
     return(errorResult.ErrorMessage != null || errorResult.Exception != null);
 }
Example #4
0
        public async Task CollectException(IErrorResult errorResult)
        {
            using (FlashTunaDbContext db = new FlashTunaDbContext())
            {
                await db.ErrorResults.AddAsync(errorResult as ErrorResult);

                await db.SaveChangesAsync();
            }
        }
Example #5
0
        /// <summary>
        /// Обработать функцию, вернуть результирующий ответ или ошибку исключения
        /// </summary>
        public static IResultError ResultErrorTry(Action action, IErrorResult error)
        {
            try
            {
                action.Invoke();
            }
            catch (Exception ex)
            {
                return(new Models.Implementations.Result.ResultError(error.AppendException(ex)));
            }

            return(new Models.Implementations.Result.ResultError());
        }
Example #6
0
        /// <summary>
        /// Обработать функцию, вернуть результирующий ответ с коллекцией или ошибку исключения
        /// </summary>
        public static IResultCollection <TValue> ResultCollectionTry <TValue>(Func <IEnumerable <TValue> > func,
                                                                              IErrorResult error)
        {
            IEnumerable <TValue> funcCollectionResult;

            try
            {
                funcCollectionResult = func.Invoke();
            }
            catch (Exception ex)
            {
                return(new ResultCollection <TValue>(error.AppendException(ex)));
            }

            return(new ResultCollection <TValue>(funcCollectionResult));
        }
Example #7
0
 /// <summary>
 /// Создать асинхронный результирующий ответ с ошибкой
 /// </summary>
 public static Task <IResultError> CreateTaskResultError(IErrorResult error) =>
 Task.FromResult((IResultError) new ResultError(error));
Example #8
0
        public async Task OnMoveButtonClick(UIMouseEventArgs e)
        {
            IssueMoveStates = new List <IssueMoveState>();

            try
            {
                MoveInProgress = true;

                // Check From/To are valid
                // TODO: Is this needed? Would we be here if it wasn't valid?

                // Create destination labels
                if (ShouldCreateDestinationLabels)
                {
                    var createLabelState = new IssueMoveState {
                        Description = "Creating labels"
                    };
                    IssueMoveStates.Add(createLabelState);
                    NotifyStateChanged();

                    if (OriginalIssueMoveData.Labels.Any())
                    {
                        IErrorResult labelCreateResultError = null;
                        try
                        {
                            var labelCreateResult = await Http.PostJsonAsync <LabelCreateResult>($"/api/createlabels/{DestinationRepoMoveData.Owner}/{DestinationRepoMoveData.Repo}", new LabelCreateRequest { Labels = OriginalIssueMoveData.Labels, });

                            if (labelCreateResult.HasErrors())
                            {
                                labelCreateResultError = labelCreateResult;
                            }
                            AddJsonLog(labelCreateResult);
                        }
                        catch (Exception ex)
                        {
                            labelCreateResultError = new ErrorResult {
                                Exception = ex,
                            };
                        }

                        if (labelCreateResultError != null)
                        {
                            AddJsonLog(new ErrorLogEntry
                            {
                                Description = "Error calling 'createlabels'",
                                ErrorResult = labelCreateResultError,
                            });

                            createLabelState.Result  = "Error! (skipping)";
                            createLabelState.Success = false;
                            NotifyStateChanged();

                            // No need to abort if this failed because it's optional, so continue to next step
                        }
                        else
                        {
                            createLabelState.Result  = "Done!";
                            createLabelState.Success = true;
                            NotifyStateChanged();
                        }
                    }
                    else
                    {
                        createLabelState.Result  = "Skipped (no labels on issue)";
                        createLabelState.Success = true;
                        NotifyStateChanged();
                    }
                }

                // Create destination milestone
                if (ShouldCreateDestinationMilestone)
                {
                    var createMilestoneState = new IssueMoveState {
                        Description = "Creating milestone"
                    };
                    IssueMoveStates.Add(createMilestoneState);
                    NotifyStateChanged();

                    if (!string.IsNullOrEmpty(OriginalIssueMoveData.Milestone))
                    {
                        IErrorResult milestoneCreateResultError = null;
                        try
                        {
                            var milestoneCreateResult = await Http.PostJsonAsync <MilestoneCreateResult>($"/api/createmilestone/{DestinationRepoMoveData.Owner}/{DestinationRepoMoveData.Repo}", new MilestoneCreateRequest { Milestone = OriginalIssueMoveData.Milestone, });

                            if (milestoneCreateResult.HasErrors())
                            {
                                milestoneCreateResultError = milestoneCreateResult;
                            }
                            AddJsonLog(milestoneCreateResult);
                        }
                        catch (Exception ex)
                        {
                            milestoneCreateResultError = new ErrorResult {
                                Exception = ex,
                            };
                        }

                        if (milestoneCreateResultError != null)
                        {
                            AddJsonLog(new ErrorLogEntry
                            {
                                Description = "Error calling 'createmilestone'",
                                ErrorResult = milestoneCreateResultError,
                            });

                            createMilestoneState.Result  = "Error! (skipping)";
                            createMilestoneState.Success = false;
                            NotifyStateChanged();

                            // No need to abort if this failed because it's optional, so continue to next step
                        }
                        else
                        {
                            createMilestoneState.Result  = "Done!";
                            createMilestoneState.Success = true;
                            NotifyStateChanged();
                        }
                    }
                    else
                    {
                        createMilestoneState.Result  = "Skipped (no milestone on issue)";
                        createMilestoneState.Success = true;
                        NotifyStateChanged();
                    }
                }

                // Create destination issue
                var moveIssueState = new IssueMoveState {
                    Description = "Moving issue"
                };
                IssueMoveStates.Add(moveIssueState);
                NotifyStateChanged();

                var destinationIssueNumber  = -1;
                var destinationIssueHtmlUrl = string.Empty;

                IErrorResult issueMoveResultError = null;
                try
                {
                    var issueMoveResult = await Http.PostJsonAsync <IssueMoveResult>($"/api/moveissue/{DestinationRepoMoveData.Owner}/{DestinationRepoMoveData.Repo}",
                                                                                     new IssueMoveRequest
                    {
                        Title     = OriginalIssueMoveData.Title,
                        Body      = GetDestinationBody(OriginalIssueMoveData),
                        Assignees = OriginalIssueMoveData.Assignees,
                        Milestone = ShouldCreateDestinationMilestone ? OriginalIssueMoveData.Milestone : null,
                        Labels    = ShouldCreateDestinationLabels ? OriginalIssueMoveData.Labels.Select(l => l.Text).ToArray() : null,
                    });

                    if (issueMoveResult.HasErrors())
                    {
                        issueMoveResultError = issueMoveResult;
                    }
                    AddJsonLog(issueMoveResult);

                    destinationIssueNumber  = issueMoveResult.IssueNumber;
                    destinationIssueHtmlUrl = issueMoveResult.HtmlUrl;
                }
                catch (Exception ex)
                {
                    issueMoveResultError = new ErrorResult {
                        Exception = ex,
                    };
                }

                if (issueMoveResultError != null)
                {
                    AddJsonLog(new ErrorLogEntry
                    {
                        Description = "Error calling 'moveissue'",
                        ErrorResult = issueMoveResultError,
                    });

                    moveIssueState.Result  = "Error!";
                    moveIssueState.Success = false;

                    IssueMoveStates.Add(new IssueMoveState
                    {
                        StateType   = IssueMoveStateType.FatalError,
                        ErrorResult = issueMoveResultError,
                        Description = "Fatal error",
                    });
                    return;
                }

                moveIssueState.Result  = "Done!";
                moveIssueState.Success = true;


                // Create destination comments
                var moveCommentState = new IssueMoveState {
                    Description = "Moving comments"
                };
                IssueMoveStates.Add(moveCommentState);
                NotifyStateChanged();

                if (OriginalIssueMoveData.Comments.Any())
                {
                    for (var i = 0; i < OriginalIssueMoveData.Comments.Count; i++)
                    {
                        var commentData = OriginalIssueMoveData.Comments[i];

                        IErrorResult commentMoveResultError = null;
                        try
                        {
                            var commentMoveResult = await Http.PostJsonAsync <CommentMoveResult>($"/api/movecomment/{DestinationRepoMoveData.Owner}/{DestinationRepoMoveData.Repo}",
                                                                                                 new CommentMoveRequest
                            {
                                IssueNumber = destinationIssueNumber,
                                Text        = GetDestinationComment(commentData.Author, commentData.Text, commentData.Date),
                            });

                            if (commentMoveResult.HasErrors())
                            {
                                commentMoveResultError = commentMoveResult;
                            }
                            moveCommentState.Description = $"Moving comment {i + 1}/{OriginalIssueMoveData.Comments.Count}";
                            AddJsonLog(commentMoveResult);
                        }
                        catch (Exception ex)
                        {
                            commentMoveResultError = new ErrorResult {
                                Exception = ex,
                            };
                        }

                        if (commentMoveResultError != null)
                        {
                            AddJsonLog(new ErrorLogEntry
                            {
                                Description = $"Error calling 'movecomment' for comment #{i + 1}",
                                ErrorResult = commentMoveResultError,
                            });

                            moveCommentState.Result  = "Error!";
                            moveCommentState.Success = false;

                            IssueMoveStates.Add(new IssueMoveState
                            {
                                StateType   = IssueMoveStateType.FatalError,
                                ErrorResult = commentMoveResultError,
                                Description = "Fatal error",
                            });
                            return;
                        }

                        NotifyStateChanged();
                    }

                    moveCommentState.Result  = "Done!";
                    moveCommentState.Success = true;
                }
                else
                {
                    moveCommentState.Result  = "Skipped (no comments)";
                    moveCommentState.Success = true;
                    NotifyStateChanged();
                }

                // Add old issue close message
                var addCloseCommentState = new IssueMoveState {
                    Description = "Adding comment to original issue"
                };
                IssueMoveStates.Add(addCloseCommentState);
                NotifyStateChanged();

                IErrorResult closeCommentResultError = null;
                try
                {
                    var issueCloseCommentResult = await Http.PostJsonAsync <IssueCloseCommentResult>($"/api/closeissuecomment/{OriginalIssueMoveData.RepoOwner}/{OriginalIssueMoveData.RepoName}",
                                                                                                     new IssueCloseCommentRequest
                    {
                        IssueNumber = OriginalIssueMoveData.Number,
                        Comment     = $"This issue was moved to {DestinationRepoMoveData.Owner}/{DestinationRepoMoveData.Repo}#{destinationIssueNumber}",
                    });

                    if (issueCloseCommentResult.HasErrors())
                    {
                        closeCommentResultError = issueCloseCommentResult;
                    }
                    AddJsonLog(issueCloseCommentResult);
                }
                catch (Exception ex)
                {
                    closeCommentResultError = new ErrorResult {
                        Exception = ex,
                    };
                }

                if (closeCommentResultError != null)
                {
                    AddJsonLog(new ErrorLogEntry
                    {
                        Description = $"Error calling 'closeissuecomment'",
                        ErrorResult = closeCommentResultError,
                    });

                    addCloseCommentState.Result  = "Error!";
                    addCloseCommentState.Success = false;

                    IssueMoveStates.Add(new IssueMoveState
                    {
                        StateType   = IssueMoveStateType.FatalError,
                        ErrorResult = closeCommentResultError,
                        Description = "Fatal error",
                    });
                    return;
                }

                addCloseCommentState.Result  = "Done!";
                addCloseCommentState.Success = true;

                // Lock old issue
                if (ShouldLockOriginalIssue)
                {
                    var lockIssueState = new IssueMoveState {
                        Description = "Locking original issue"
                    };
                    IssueMoveStates.Add(lockIssueState);
                    NotifyStateChanged();

                    IErrorResult lockIssueResultError = null;
                    try
                    {
                        var issueLockResult = await Http.PostJsonAsync <IssueLockResult>($"/api/lockissue/{OriginalIssueMoveData.RepoOwner}/{OriginalIssueMoveData.RepoName}",
                                                                                         new IssueLockRequest
                        {
                            IssueNumber = OriginalIssueMoveData.Number,
                        });

                        if (issueLockResult.HasErrors())
                        {
                            lockIssueResultError = issueLockResult;
                        }
                        AddJsonLog(issueLockResult);
                    }
                    catch (Exception ex)
                    {
                        lockIssueResultError = new ErrorResult {
                            Exception = ex,
                        };
                    }

                    if (lockIssueResultError != null)
                    {
                        AddJsonLog(new ErrorLogEntry
                        {
                            Description = $"Error calling 'lockissue'",
                            ErrorResult = lockIssueResultError,
                        });

                        lockIssueState.Result  = "Error! (skipping)";
                        lockIssueState.Success = false;
                        NotifyStateChanged();

                        // No need to abort if this failed because it's optional, so continue to next step
                    }
                    else
                    {
                        lockIssueState.Result  = "Done!";
                        lockIssueState.Success = true;
                        NotifyStateChanged();
                    }
                }

                // Close old issue
                var closeIssueState = new IssueMoveState {
                    Description = "Closing original issue"
                };
                IssueMoveStates.Add(closeIssueState);
                NotifyStateChanged();

                IErrorResult closeIssueResultError = null;
                try
                {
                    var issueCloseResult = await Http.PostJsonAsync <IssueCloseResult>($"/api/closeissue/{OriginalIssueMoveData.RepoOwner}/{OriginalIssueMoveData.RepoName}",
                                                                                       new IssueCloseRequest
                    {
                        IssueNumber = OriginalIssueMoveData.Number,
                    });

                    if (issueCloseResult.HasErrors())
                    {
                        closeIssueResultError = issueCloseResult;
                    }
                    AddJsonLog(issueCloseResult);
                }
                catch (Exception ex)
                {
                    closeIssueResultError = new ErrorResult {
                        Exception = ex,
                    };
                }

                if (closeIssueResultError != null)
                {
                    AddJsonLog(new ErrorLogEntry
                    {
                        Description = $"Error calling 'closeissue'",
                        ErrorResult = closeIssueResultError,
                    });

                    closeIssueState.Result  = "Error!";
                    closeIssueState.Success = false;

                    IssueMoveStates.Add(new IssueMoveState
                    {
                        StateType   = IssueMoveStateType.FatalError,
                        ErrorResult = closeIssueResultError,
                        Description = "Fatal error",
                    });
                    return;
                }

                closeIssueState.Result  = "Done!";
                closeIssueState.Success = true;
                NotifyStateChanged();


                IssueMoveStates.Add(new IssueMoveState
                {
                    StateType   = IssueMoveStateType.LinkResult,
                    Description = $"Moved to new issue #{destinationIssueNumber}",
                    Link        = destinationIssueHtmlUrl,
                });


                // Reset states
                MoveInProgress = false;
            }
            catch (Exception ex)
            {
                var overallErrorResult = new ErrorResult {
                    Exception = ex,
                };
                AddJsonLog(new ErrorLogEntry
                {
                    Description = "Unknown error during move operation",
                    ErrorResult = overallErrorResult,
                });

                var outerState = new IssueMoveState {
                    Description = "Error"
                };
                outerState.Result  = "Unknown error during move operation";
                outerState.Success = false;
                IssueMoveStates.Add(outerState);

                IssueMoveStates.Add(new IssueMoveState
                {
                    StateType   = IssueMoveStateType.FatalError,
                    ErrorResult = overallErrorResult,
                    Description = "Fatal error",
                });
            }
        }
 /// <summary>
 /// Преобразовать значение в результирующий ответ с проверкой на нуль
 /// </summary>
 public static IResultValue <TValue> ToResultValueNullCheck <TValue>(this TValue? @this, IErrorResult errorNull)
     where TValue : struct =>
 @this != null
         ? new ResultValue <TValue>((TValue)@this)
 : new ResultValue <TValue>(errorNull);
 public static IActionResult ToActionResult(this IErrorResult result) => result?.Code switch
 {
Example #11
0
 public ResultValue(IErrorResult error)
     : this(error.AsEnumerable())
 {
 }
 /// <summary>
 /// Связать результирующий ответ со значением со связыванием с обработкой функции при положительном условии
 /// </summary>
 public static IResultCollection <TValueOut> ResultCollectionBindTryOk <TValueIn, TValueOut>(this IResultCollection <TValueIn> @this,
                                                                                             Func <IReadOnlyCollection <TValueIn>, IResultCollection <TValueOut> > func,
                                                                                             IErrorResult error) =>
 @this.ResultCollectionBindOk(value => ResultCollectionBindTry(() => func.Invoke(value), error));
 /// <summary>
 /// Результирующий ответ со значением с обработкой функции при положительном условии
 /// </summary>
 public static IResultValue <TValueOut> ResultValueTryOk <TValueIn, TValueOut>(this IResultValue <TValueIn> @this,
                                                                               Func <TValueIn, TValueOut> func, IErrorResult error) =>
 @this.ResultValueBindOk(value => ResultValueTry(() => func.Invoke(value), error));
 /// <summary>
 /// Обработать асинхронную функцию, вернуть результирующий ответ со значением или ошибку исключения
 /// </summary>
 public static async Task <IResultCollection <TValue> > ResultCollectionTryAsync <TValue>(Func <Task <List <TValue> > > func,
                                                                                          IErrorResult error) =>
 await ResultCollectionTryAsync(async() => (IEnumerable <TValue>) await func.Invoke(), error);
Example #15
0
        /// <summary>
        /// Обработать асинхронную функцию, вернуть результирующий ответ со значением или ошибку исключения
        /// </summary>
        public static async Task <IResultValue <TValue> > ResultValueTryAsync <TValue>(Func <Task <TValue> > func, IErrorResult error)
        {
            TValue funcResult;

            try
            {
                funcResult = await func.Invoke();
            }
            catch (Exception ex)
            {
                return(new ResultValue <TValue>(error.AppendException(ex)));
            }

            return(new ResultValue <TValue>(funcResult));
        }
 /// <summary>
 /// Создать асинхронный результирующий ответ с коллекцией и ошибкой
 /// </summary>
 public static Task <IResultCollection <TValue> > CreateTaskResultCollectionError <TValue>(IErrorResult error)
     where TValue : notnull =>
 Task.FromResult((IResultCollection <TValue>) new ResultCollection <TValue>(error));
 public ErrorResultException(IErrorResult errorResult) : base(GetErrorMessage(errorResult))
 {
     ErrorResult = errorResult ?? throw new ArgumentNullException(nameof(errorResult));
 }
 private static string GetErrorMessage(IErrorResult errorResult)
 => errorResult is null
     ? string.Empty
     : string.Join(", ", errorResult.Errors ?? new List <ResultError>());
 /// <summary>
 /// Связать результирующий ответ со значением с обработкой функции при положительном условии для задачи-объекта
 /// </summary>
 public static async Task <IResultValue <TValueOut> > ResultValueTryOkTaskAsync <TValueIn, TValueOut>(this Task <IResultValue <TValueIn> > @this,
                                                                                                      Func <TValueIn, TValueOut> func, IErrorResult error) =>
 await @this.
 ResultValueBindOkTaskAsync(value => ResultValueTry(() => func.Invoke(value), error));
Example #20
0
 /// <summary>
 /// Создать асинхронный результирующий ответ с ошибкой
 /// </summary>
 public static async Task <IResultError> CreateTaskResultErrorAsync(IErrorResult error) =>
 await Task.FromResult((IResultError) new ResultError(error));
        /// <summary>
        /// Обработать функцию, вернуть результирующий ответ со значением или ошибку исключения
        /// </summary>
        public static IResultValue <TValue> ResultValueTry <TValue>(Func <TValue> func, IErrorResult error)
        {
            TValue funcResult;

            try
            {
                funcResult = func.Invoke();
            }
            catch (Exception ex)
            {
                return(new ResultValue <TValue>(error.AppendException(ex)));
            }

            return(new ResultValue <TValue>(funcResult));
        }
 /// <summary>
 /// Преобразовать значение в результирующий ответ коллекции с проверкой на нуль
 /// </summary>
 public static IResultCollection <TValue> ToResultCollectionNullCheck <TValue>(this IEnumerable <TValue?>? @this,
                                                                               IErrorResult errorNull)
     where TValue : class =>
 @this != null
         ? @this.Select(value => value.ToResultValueNullCheck(errorNull)).
 ToResultCollection()
 : new ResultCollection <TValue>(errorNull);
 /// <summary>
 /// Создать асинхронный результирующий ответ со значением и ошибкой
 /// </summary>
 public static async Task <IResultValue <TValue> > CreateTaskResultValueErrorAsync <TValue>(IErrorResult error)
     where TValue : notnull =>
 await Task.FromResult((IResultValue <TValue>) new ResultValue <TValue>(error));
Example #24
0
 public ResultCollection(IErrorResult error)
     : this(error.AsEnumerable())
 {
 }
 public static Exception ToException(this IErrorResult result)
 => new ErrorResultException(result);
Example #26
0
 /// <summary>
 /// Преобразовать значение в результирующий ответ с проверкой на нуль для задачи-объекта
 /// </summary>
 public static async Task <IResultValue <TValue> > ToResultValueNullCheckTaskAsync <TValue>(this Task <TValue?> @this, IErrorResult errorNull)
     where TValue : struct =>
 await @this.
 MapTaskAsync(awaitedThis => awaitedThis.ToResultValueNullCheck(errorNull));
 /// <summary>
 /// Связать результирующий ответ с коллекцией с обработкой функции при положительном условии для задачи-объекта
 /// </summary>
 public static async Task <IResultCollection <TValueOut> > ResultCollectionTryOkTaskAsync <TValueIn, TValueOut>(this Task <IResultCollection <TValueIn> > @this,
                                                                                                                Func <IReadOnlyCollection <TValueIn>, IEnumerable <TValueOut> > func,
                                                                                                                IErrorResult error) =>
 await @this.
 ResultCollectionBindOkTaskAsync(value => ResultCollectionTry(() => func.Invoke(value), error));
Example #28
0
        public async Task OnFromInputBlur()
        {
            if (string.IsNullOrEmpty(FromValue))
            {
                FromProgressBarText   = "";
                FromProgressBarStyle  = ProgressBarStyle.None;
                OriginalIssueMoveData = null;
                return;
            }

            FromProgressBarText  = "Looking for issue...";
            FromProgressBarStyle = ProgressBarStyle.InProgress;
            NotifyStateChanged();

            var val = FromValue;

            // If pattern is not in required format 'owner/repo#123', try to normalize
            if (!IsValidIssueFormat(val))
            {
                FromValue = NormalizeIssueFormat(val);
            }

            val = FromValue;

            // If pattern is STILL not in required format 'owner/repo#123', abort
            if (!IsValidIssueFormat(val))
            {
                // TODO: Set validation error somehow?
                FromProgressBarText  = "Invalid issue format";
                FromProgressBarStyle = ProgressBarStyle.Error;
                return;
            }

            var shortNameParts  = val.Split('/', '#');
            var fromOwner       = shortNameParts[0];
            var fromRepo        = shortNameParts[1];
            var fromIssueNumber = shortNameParts[2];

            IssueQueryInProgress = true;
            NotifyStateChanged();

            IErrorResult getMoveDataError = null;

            try
            {
                OriginalIssueMoveData = await Http.GetJsonAsync <IssueMoveData>($"/api/getmovedata/{fromOwner}/{fromRepo}/{fromIssueNumber}");

                if (OriginalIssueMoveData.HasErrors())
                {
                    getMoveDataError = OriginalIssueMoveData;
                }
            }
            catch (Exception ex)
            {
                getMoveDataError = new ErrorResult {
                    Exception = ex,
                };
            }

            if (getMoveDataError != null)
            {
                OriginalIssueMoveData = null;
                AddJsonLog(new ErrorLogEntry
                {
                    Description = "Error calling 'getmovedata'",
                    ErrorResult = getMoveDataError,
                });
                IssueQueryInProgress = false;

                FromProgressBarText  = $"Error!";
                FromProgressBarStyle = ProgressBarStyle.Error;
                return;
            }

            AddJsonLog(OriginalIssueMoveData);
            IssueQueryInProgress = false;

            if (OriginalIssueMoveData.IsPullRequest)
            {
                FromProgressBarText  = $"Found #{OriginalIssueMoveData.Number}, but it's a pull request";
                FromProgressBarStyle = ProgressBarStyle.Error;
            }
            else if (OriginalIssueMoveData.State == IssueState.Closed)
            {
                FromProgressBarText  = $"Found #{OriginalIssueMoveData.Number}, but it's closed";
                FromProgressBarStyle = ProgressBarStyle.Error;
            }
            else
            {
                FromProgressBarText  = $"Found issue #{OriginalIssueMoveData.Number}";
                FromProgressBarStyle = ProgressBarStyle.Success;
            }
        }
        /// <summary>
        /// Обработать асинхронную функцию, вернуть результирующий ответ со значением или ошибку исключения
        /// </summary>
        public static async Task <IResultError> ResultErrorTryAsync(Func <Task> action, IErrorResult error)
        {
            try
            {
                await action.Invoke();
            }
            catch (Exception ex)
            {
                return(new Models.Implementations.Result.ResultError(error.AppendException(ex)));
            }

            return(new Models.Implementations.Result.ResultError());
        }
Example #30
0
        public async Task OnToInputBlur()
        {
            if (string.IsNullOrEmpty(ToValue))
            {
                ToProgressBarText       = "";
                ToProgressBarStyle      = ProgressBarStyle.None;
                DestinationRepoMoveData = null;
                return;
            }

            ToProgressBarText  = "Looking for repo...";
            ToProgressBarStyle = ProgressBarStyle.InProgress;
            NotifyStateChanged();

            var val = ToValue;

            // If pattern is not in required format 'owner/repo', try to normalize
            if (!IsValidRepoFormat(val))
            {
                ToValue = NormalizeRepoFormat(val);
            }

            val = ToValue;

            // If pattern is STILL not in required format 'owner/repo', abort
            if (!IsValidRepoFormat(val))
            {
                // TODO: Set validation error somehow?
                ToProgressBarText  = "Invalid repo format";
                ToProgressBarStyle = ProgressBarStyle.Error;
                return;
            }

            var shortNameParts = val.Split('/');
            var toOwner        = shortNameParts[0];
            var toRepo         = shortNameParts[1];

            ToRepoQueryInProgress = true;
            NotifyStateChanged();

            IErrorResult getRepoDataError = null;

            try
            {
                DestinationRepoMoveData = await Http.GetJsonAsync <RepoMoveData>($"/api/getrepodata/{toOwner}/{toRepo}");

                if (DestinationRepoMoveData.HasErrors())
                {
                    getRepoDataError = DestinationRepoMoveData;
                }
            }
            catch (Exception ex)
            {
                getRepoDataError = new ErrorResult {
                    Exception = ex,
                };
            }

            if (getRepoDataError != null)
            {
                DestinationRepoMoveData = null;
                AddJsonLog(new ErrorLogEntry
                {
                    Description = "Error calling 'getrepodata'",
                    ErrorResult = getRepoDataError,
                });
                ToRepoQueryInProgress = false;

                ToProgressBarText  = $"Error!";
                ToProgressBarStyle = ProgressBarStyle.Error;
                return;
            }

            AddJsonLog(DestinationRepoMoveData);
            ToRepoQueryInProgress = false;

            ToProgressBarText  = $"Found repo, {DestinationRepoMoveData.OpenIssueCount} open issue(s)";
            ToProgressBarStyle = ProgressBarStyle.Success;
        }