Ejemplo n.º 1
0
 internal PullRequestItemViewModel(PullRequestModel pullRequest, Action gotoAction)
 {
     Title       = pullRequest.Title ?? "No Title";
     Avatar      = new GitHubAvatar(pullRequest.User.AvatarUrl);
     Details     = string.Format("#{0} opened {1} by {2}", pullRequest.Number, pullRequest.CreatedAt.UtcDateTime.Humanize(), pullRequest.User.Login);
     GoToCommand = ReactiveCommand.Create().WithSubscription(_ => gotoAction());
 }
Ejemplo n.º 2
0
        IRepositoryHost CreateRepositoryHost()
        {
            var result       = Substitute.For <IRepositoryHost>();
            var modelService = Substitute.For <IModelService>();
            var bitmapSource = Observable.Empty <BitmapImage>();

            var pullRequest = new PullRequestModel(
                1,
                "PR1",
                new Account("foo", true, false, 1, 0, bitmapSource),
                DateTimeOffset.MinValue);

            pullRequest.Assignee = new Account("foo", true, false, 1, 0, bitmapSource);

            var pullRequestCollection = Substitute.For <ITrackingCollection <IPullRequestModel> >();

            pullRequestCollection[0].Returns(pullRequest);

            modelService.GetPullRequests(
                Arg.Any <ILocalRepositoryModel>(),
                Arg.Any <ITrackingCollection <IPullRequestModel> >())
            .Returns(pullRequestCollection);
            result.ModelService.Returns(modelService);

            return(result);
        }
Ejemplo n.º 3
0
 internal PullRequestItemViewModel(PullRequestModel pullRequest, Action gotoAction)
 {
     Title       = pullRequest.Title ?? "No Title";
     ImageUrl    = pullRequest.User.AvatarUrl;
     Details     = string.Format("#{0} opened {1} by {2}", pullRequest.Number, pullRequest.CreatedAt.ToDaysAgo(), pullRequest.User.Login);
     GoToCommand = ReactiveCommand.Create().WithSubscription(_ => gotoAction());
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Генерирует модели с пулл-реквестами по выбранному проекту
        /// </summary>
        /// <param name="key">ключ проекта</param>
        /// <param name="start">номер первого пулл-реквеста</param>
        /// <param name="limit">количество возвращаемых пулл-реквестов</param>
        /// <returns>список моделей пулл-реквестов</returns>
        public static List <PullRequestModel> GetPullRequest(string key, int start, int limit)
        {
            List <PullRequestModel> output = new List <PullRequestModel>();
            string  slug = GetSlug(key);
            JObject o    = ApiRequestGet(string.Format("rest/api/1.0/projects/{0}/repos/{1}/pull-requests?state=ALL&start={2}&limit={3}", key, slug, start, limit));

            if (o["values"] == null)
            {
                return(output);
            }
            foreach (var pul in o["values"])
            {
                PullRequestModel p = new PullRequestModel(key, slug);
                p.Author = new UserModel()
                {
                    Name  = pul["author"]["user"]["displayName"].Value <string>(),
                    Email = pul["author"]["user"]["emailAddress"].Value <string>(),
                    Slug  = pul["author"]["user"]["slug"].Value <string>(),
                };
                p.PullRequestUrl    = pul["links"]["self"].First["href"].Value <string>();
                p.PullRequestNumber = pul["id"].Value <string>();
                p.PullRequestTitle  = pul["title"].Value <string>();
                p.PullRequestDate   = ConvertUnixDT(pul["createdDate"].Value <long>()).ToString("dd.MM.yyyy HH:mm:ss");
                p.Description       = pul["description"] == null ? string.Empty : pul["description"].Value <string>();
                output.Add(p);
            }
            return(output);
        }
Ejemplo n.º 5
0
        public PullRequestReviewAuthoringViewModelDesigner()
        {
            PullRequestModel = new PullRequestModel(
                419,
                "Fix a ton of potential crashers, odd code and redundant calls in ModelService",
                new AccountDesigner {
                Login = "******", IsUser = true
            },
                DateTimeOffset.Now - TimeSpan.FromDays(2));

            Files = new PullRequestFilesViewModelDesigner();

            FileComments = new[]
            {
                new PullRequestReviewFileCommentViewModelDesigner
                {
                    Body         = @"These should probably be properties. Most likely they should be readonly properties. I know that makes creating instances of these not look as nice as using property initializers when constructing an instance, but if these properties should never be mutated after construction, then it guides future consumers to the right behavior.

However, if you're two-way binding these properties to a UI, then ignore the readonly part and make them properties. But in that case they should probably be reactive properties (or implement INPC).",
                    RelativePath = "src/GitHub.Exports.Reactive/ViewModels/IPullRequestListViewModel.cs",
                },
                new PullRequestReviewFileCommentViewModelDesigner
                {
                    Body         = "While I have no problems with naming a variable ass I think we should probably avoid swear words in case Microsoft runs their Policheck tool against this code.",
                    RelativePath = "src/GitHub.App/ViewModels/PullRequestListViewModel.cs",
                },
            };
        }
Ejemplo n.º 6
0
 internal PullRequestItemViewModel(PullRequestModel pullRequest) 
 {
     var user = pullRequest.User ?? new BasicUserModel();
     Title = pullRequest.Title ?? "No Title";
     Avatar = new GitHubAvatar(user.AvatarUrl);
     Details = string.Format("#{0} opened {1} by {2}", pullRequest.Number, pullRequest.CreatedAt.UtcDateTime.Humanize(), user.Login);
     GoToCommand = ReactiveCommand.Create();
 }
Ejemplo n.º 7
0
    public void ComparisonNotEquals(int id1, int ms1, int id2, int ms2)
    {
        PullRequestModel left  = new PullRequestModel(id1, "", Substitute.For <IAccount>(), Substitute.For <IAccount>(), Now, Now + TimeSpan.FromMilliseconds(ms1));
        PullRequestModel right = new PullRequestModel(id2, "", Substitute.For <IAccount>(), Substitute.For <IAccount>(), Now, Now + TimeSpan.FromMilliseconds(ms2));

        Assert.False(left == right);
        Assert.True(left != right);
    }
        public async Task InitializeAsync_Creates_Reviews()
        {
            var author = Substitute.For <IAccount>();

            author.Login.Returns(AuthorLogin);

            var anotherAuthor = Substitute.For <IAccount>();

            anotherAuthor.Login.Returns("SomeoneElse");

            var pullRequest = new PullRequestModel(5, "PR title", author, DateTimeOffset.Now)
            {
                Reviews = new[]
                {
                    new PullRequestReviewModel
                    {
                        User  = author,
                        State = PullRequestReviewState.Approved,
                    },
                    new PullRequestReviewModel
                    {
                        User  = author,
                        State = PullRequestReviewState.ChangesRequested,
                    },
                    new PullRequestReviewModel
                    {
                        User  = anotherAuthor,
                        State = PullRequestReviewState.Approved,
                    },
                    new PullRequestReviewModel
                    {
                        User  = author,
                        State = PullRequestReviewState.Dismissed,
                    },
                    new PullRequestReviewModel
                    {
                        User  = author,
                        State = PullRequestReviewState.Pending,
                    },
                },
                ReviewComments = new IPullRequestReviewCommentModel[0],
            };

            var modelSerivce = Substitute.For <IModelService>();

            modelSerivce.GetUser(AuthorLogin).Returns(Observable.Return(author));
            modelSerivce.GetPullRequest("owner", "repo", 5).Returns(Observable.Return(pullRequest));

            var user   = Substitute.For <IAccount>();
            var target = CreateTarget(
                modelServiceFactory: CreateFactory(modelSerivce));

            await Initialize(target);

            // Should load reviews by the correct author which are not Pending.
            Assert.That(target.Reviews, Has.Count.EqualTo(3));
        }
 public void ComparisonEquals()
 {
     PullRequestModel left = new PullRequestModel(1, "", Substitute.For<IAccount>(), Now, Now + TimeSpan.FromMilliseconds(1));
     PullRequestModel right = new PullRequestModel(1, "", Substitute.For<IAccount>(), Now, Now + TimeSpan.FromMilliseconds(1));
     Assert.True(left == right);
     Assert.False(left != right);
     Assert.False(left > right);
     Assert.False(left < right);
 }
 public void ComparisonNullLowerThan()
 {
     PullRequestModel left = null;
     PullRequestModel right = new PullRequestModel(0, "", Substitute.For<IAccount>(), Now, Now);
     Assert.False(left == right);
     Assert.True(left != right);
     Assert.False(left > right);
     Assert.True(left < right);
 }
Ejemplo n.º 11
0
    public void ComparisonNullEqualsNull()
    {
        PullRequestModel left  = null;
        PullRequestModel right = null;

        Assert.True(left == right);
        Assert.False(left != right);
        Assert.False(left > right);
        Assert.False(left < right);
    }
Ejemplo n.º 12
0
    public void ComparisonNullLowerThan()
    {
        PullRequestModel left  = null;
        PullRequestModel right = new PullRequestModel(0, "", Substitute.For <IAccount>(), Substitute.For <IAccount>(), Now, Now);

        Assert.False(left == right);
        Assert.True(left != right);
        Assert.False(left > right);
        Assert.True(left < right);
    }
Ejemplo n.º 13
0
    public void ComparisonEquals()
    {
        PullRequestModel left  = new PullRequestModel(1, "", Substitute.For <IAccount>(), Substitute.For <IAccount>(), Now, Now + TimeSpan.FromMilliseconds(1));
        PullRequestModel right = new PullRequestModel(1, "", Substitute.For <IAccount>(), Substitute.For <IAccount>(), Now, Now + TimeSpan.FromMilliseconds(1));

        Assert.False(left == right);
        Assert.True(left != right);
        Assert.False(left > right);
        Assert.False(left < right);
    }
Ejemplo n.º 14
0
 private ReviewModel CreateNewReview(PullRequestModel prModel)
 {
     return(new ReviewModel()
     {
         Author = prModel.Author,
         CreationDate = DateTime.Now,
         Name = prModel.PackageName,
         IsClosed = false,
         FilterType = ReviewType.PullRequest,
         ReviewId = IdHelper.GenerateId()
     });
 }
Ejemplo n.º 15
0
        private async Task <bool> IsPullRequestEligibleForCleanup(PullRequestModel prModel)
        {
            var repoInfo = prModel.RepoName.Split("/");
            var issue    = await _githubClient.Issue.Get(repoInfo[0], repoInfo[1], prModel.PullRequestNumber);

            // Close review created for pull request if pull request was closed more than _pullRequestCleanupDays days ago
            if (issue.ClosedAt != null)
            {
                return(issue.ClosedAt?.AddDays(_pullRequestCleanupDays) < DateTimeOffset.Now);
            }
            return(false);
        }
        public PullRequestReviewViewModelDesigner()
        {
            PullRequestModel = new PullRequestModel(
                419,
                "Fix a ton of potential crashers, odd code and redundant calls in ModelService",
                new AccountDesigner {
                Login = "******", IsUser = true
            },
                DateTimeOffset.Now - TimeSpan.FromDays(2));

            Model = new PullRequestReviewModel
            {
                SubmittedAt = DateTimeOffset.Now - TimeSpan.FromDays(1),
                User        = new AccountDesigner {
                    Login = "******", IsUser = true
                },
            };

            Body = @"Just a few comments. I don't feel too strongly about them though.

Otherwise, very nice work here! ✨";

            StateDisplay = "approved";

            FileComments = new[]
            {
                new PullRequestReviewFileCommentViewModelDesigner
                {
                    Body         = @"These should probably be properties. Most likely they should be readonly properties. I know that makes creating instances of these not look as nice as using property initializers when constructing an instance, but if these properties should never be mutated after construction, then it guides future consumers to the right behavior.

However, if you're two-way binding these properties to a UI, then ignore the readonly part and make them properties. But in that case they should probably be reactive properties (or implement INPC).",
                    RelativePath = "src/GitHub.Exports.Reactive/ViewModels/IPullRequestListViewModel.cs",
                },
                new PullRequestReviewFileCommentViewModelDesigner
                {
                    Body         = "While I have no problems with naming a variable ass I think we should probably avoid swear words in case Microsoft runs their Policheck tool against this code.",
                    RelativePath = "src/GitHub.App/ViewModels/PullRequestListViewModel.cs",
                },
            };

            OutdatedFileComments = new[]
            {
                new PullRequestReviewFileCommentViewModelDesigner
                {
                    Body         = @"So this is just casting a mutable list to an IReadOnlyList which can be cast back to List. I know we probably won't do that, but I'm thinking of the next person to come along. The safe thing to do is to wrap List with a ReadOnlyList. We have an extension method ToReadOnlyList for observables. Wouldn't be hard to write one for IEnumerable.",
                    RelativePath = "src/GitHub.Exports.Reactive/ViewModels/IPullRequestListViewModel.cs",
                },
            };
        }
Ejemplo n.º 17
0
        public static PullRequestModel PullPayments(QueryPullAPIModel request, string ConsumerKey, string ConsumerSecret)
        {
            //var serializer = new JavaScriptSerializer();
            string         serializedBodyRequest = JsonConvert.SerializeObject(request);
            HttpWebRequest httpRequest           = (HttpWebRequest)WebRequest.Create(CONSTANTS.PullAPIQuery);

            httpRequest.ContentType = "application/json";
            httpRequest.Method      = "POST";
            httpRequest.Headers.Add("Authorization", "Bearer " + PullAPIHttp.GetAuthen(ConsumerKey, ConsumerSecret));
            using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                streamWriter.Write(serializedBodyRequest);
                streamWriter.Flush();
                streamWriter.Close();
            }
            try
            {
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                var             result       = "";
                using (var responseStream = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = responseStream.ReadToEnd();
                }
                PullRequestModel resp = JsonConvert.DeserializeObject <PullRequestModel>(result);
                Console.WriteLine("" + request.ShortCode + "    " + resp.ResponseCode + "   " + resp.ResponseMessage);
                if (resp == null)
                {
                    Console.WriteLine("An error has occurred");
                }
                if (resp.ResponseCode == "1000")
                {
                    PullAPISQL.ProcessPulledPayments(resp, request.ShortCode);
                    PullAPISQL.UpdateTillFetch(request, resp.Response[0].Count);
                }
                else
                {
                    PullAPISQL.UpdateTillFetch(request, 0);
                }

                Console.WriteLine(resp.ToString());
                return(resp);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                //  Console.ReadLine();
                return(null);
            }
        }
        public async Task First_Review_Is_Expanded()
        {
            var author = Substitute.For <IAccount>();

            author.Login.Returns(AuthorLogin);

            var anotherAuthor = Substitute.For <IAccount>();

            author.Login.Returns("SomeoneElse");

            var pullRequest = new PullRequestModel(5, "PR title", author, DateTimeOffset.Now)
            {
                Reviews = new[]
                {
                    new PullRequestReviewModel
                    {
                        User  = author,
                        State = PullRequestReviewState.Approved,
                    },
                    new PullRequestReviewModel
                    {
                        User  = author,
                        State = PullRequestReviewState.ChangesRequested,
                    },
                    new PullRequestReviewModel
                    {
                        User  = author,
                        State = PullRequestReviewState.Dismissed,
                    },
                },
                ReviewComments = new IPullRequestReviewCommentModel[0],
            };

            var modelSerivce = Substitute.For <IModelService>();

            modelSerivce.GetUser(AuthorLogin).Returns(Observable.Return(author));
            modelSerivce.GetPullRequest("owner", "repo", 5).Returns(Observable.Return(pullRequest));

            var user   = Substitute.For <IAccount>();
            var target = CreateTarget(
                modelServiceFactory: CreateFactory(modelSerivce));

            await Initialize(target);

            Assert.That(target.Reviews[0].IsExpanded, Is.True);
            Assert.That(target.Reviews[1].IsExpanded, Is.False);
            Assert.That(target.Reviews[2].IsExpanded, Is.False);
        }
Ejemplo n.º 19
0
        private async Task AssertPullRequestCreatorPermission(PullRequestModel prModel)
        {
            var orgs = await _githubClient.Organization.GetAllForUser(prModel.Author);

            var orgNames = orgs.Select(o => o.Login);
            var result   = await _authorizationService.AuthorizeAsync(
                null,
                orgNames,
                new[] { PullRequestPermissionRequirement.Instance });

            if (!result.Succeeded)
            {
                _telemetryClient.TrackTrace($"API change detection permission failed for user {prModel.Author}.");
                throw new AuthorizationFailedException();
            }
        }
Ejemplo n.º 20
0
        private async Task ClosePullRequestReview(PullRequestModel pullRequestModel)
        {
            if (pullRequestModel.ReviewId != null)
            {
                var review = await _reviewsRepository.GetReviewAsync(pullRequestModel.ReviewId);

                if (review != null)
                {
                    review.IsClosed = true;
                    await _reviewsRepository.UpsertReviewAsync(review);
                }
            }

            pullRequestModel.IsOpen = false;
            await _pullRequestsRepository.UpsertPullRequestAsync(pullRequestModel);
        }
        public async Task Orders_Reviews_Descending()
        {
            var author = Substitute.For <IAccount>();

            author.Login.Returns(AuthorLogin);

            var pullRequest = new PullRequestModel(5, "PR title", author, DateTimeOffset.Now)
            {
                Reviews = new[]
                {
                    new PullRequestReviewModel
                    {
                        User        = author,
                        State       = PullRequestReviewState.Approved,
                        SubmittedAt = DateTimeOffset.Now - TimeSpan.FromDays(2),
                    },
                    new PullRequestReviewModel
                    {
                        User        = author,
                        State       = PullRequestReviewState.ChangesRequested,
                        SubmittedAt = DateTimeOffset.Now - TimeSpan.FromDays(3),
                    },
                    new PullRequestReviewModel
                    {
                        User        = author,
                        State       = PullRequestReviewState.Dismissed,
                        SubmittedAt = DateTimeOffset.Now - TimeSpan.FromDays(1),
                    },
                },
                ReviewComments = new IPullRequestReviewCommentModel[0],
            };

            var modelSerivce = Substitute.For <IModelService>();

            modelSerivce.GetUser(AuthorLogin).Returns(Observable.Return(author));
            modelSerivce.GetPullRequest("owner", "repo", 5).Returns(Observable.Return(pullRequest));

            var user   = Substitute.For <IAccount>();
            var target = CreateTarget(
                modelServiceFactory: CreateFactory(modelSerivce));

            await Initialize(target);

            Assert.That(
                target.Reviews.Select(x => x.Model.SubmittedAt),
                Is.EqualTo(target.Reviews.Select(x => x.Model.SubmittedAt).OrderByDescending(x => x)));
        }
        static PullRequestModel CreatePullRequest(
            string authorLogin = "******",
            params IPullRequestReviewModel[] reviews)
        {
            var author = Substitute.For <IAccount>();

            author.Login.Returns(authorLogin);

            var result = new PullRequestModel(
                5,
                "Pull Request",
                author,
                DateTimeOffset.Now);

            result.Reviews = reviews.ToList();
            return(result);
        }
Ejemplo n.º 23
0
        public PullRequestDetailViewModelDesigner()
        {
            var repoPath = @"C:\Repo";

            Model = new PullRequestModel(419,
                                         "Error handling/bubbling from viewmodels to views to viewhosts",
                                         new AccountDesigner {
                Login = "******", IsUser = true
            },
                                         DateTime.Now.Subtract(TimeSpan.FromDays(3)))
            {
                State       = PullRequestStateEnum.Open,
                CommitCount = 9,
            };

            SourceBranchDisplayName = "shana/error-handling-a-ridiculously-long-branch-name-because-why-not";
            TargetBranchDisplayName = "master-is-always-stable";
            Body = @"Adds a way to surface errors from the view model to the view so that view hosts can get to them.

ViewModels are responsible for handling the UI on the view they control, but they shouldn't be handling UI for things outside of the view. In this case, we're showing errors in VS outside the view, and that should be handled by the section that is hosting the view.

This requires that errors be propagated from the viewmodel to the view and from there to the host via the IView interface, since hosts don't usually know what they're hosting.

![An image](https://cloud.githubusercontent.com/assets/1174461/18882991/5dd35648-8496-11e6-8735-82c3a182e8b4.png)";

            var gitHubDir       = new PullRequestDirectoryNode("GitHub");
            var modelsDir       = new PullRequestDirectoryNode("Models");
            var repositoriesDir = new PullRequestDirectoryNode("Repositories");
            var itrackingBranch = new PullRequestFileNode(repoPath, @"GitHub\Models\ITrackingBranch.cs", "abc", PullRequestFileStatus.Modified, null);
            var oldBranchModel  = new PullRequestFileNode(repoPath, @"GitHub\Models\OldBranchModel.cs", "abc", PullRequestFileStatus.Removed, null);
            var concurrentRepositoryConnection = new PullRequestFileNode(repoPath, @"GitHub\Repositories\ConcurrentRepositoryConnection.cs", "abc", PullRequestFileStatus.Added, "add");

            repositoriesDir.Files.Add(concurrentRepositoryConnection);
            modelsDir.Directories.Add(repositoriesDir);
            modelsDir.Files.Add(itrackingBranch);
            modelsDir.Files.Add(oldBranchModel);
            gitHubDir.Directories.Add(modelsDir);

            ChangedFilesTree = new ReactiveList <IPullRequestChangeNode>();
            ChangedFilesTree.Add(gitHubDir);

            ChangedFilesList = new ReactiveList <IPullRequestFileNode>();
            ChangedFilesList.Add(concurrentRepositoryConnection);
            ChangedFilesList.Add(itrackingBranch);
            ChangedFilesList.Add(oldBranchModel);
        }
Ejemplo n.º 24
0
        private async Task <ReviewRevisionModel> CreateBaselineRevision(
            CodeFile baselineCodeFile,
            MemoryStream baseLineStream,
            PullRequestModel prModel,
            string fileName)
        {
            var newRevision = new ReviewRevisionModel()
            {
                Author = prModel.Author,
                Label  = $"Baseline for PR {prModel.PullRequestNumber}"
            };
            var reviewCodeFileModel = await _reviewManager.CreateReviewCodeFileModel(newRevision.RevisionId, baseLineStream, baselineCodeFile);

            reviewCodeFileModel.FileName = fileName;
            newRevision.Files.Add(reviewCodeFileModel);
            return(newRevision);
        }
Ejemplo n.º 25
0
        public static void ProcessPulledPayments(PullRequestModel payments, string ShortCode)
        {
            foreach (var payment in payments.Response[0])
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(CONSTANTS.DBConn))
                    {
                        connection.Open();
                        string sql = "IF NOT EXISTS(SELECT * FROM protobase.dbo.MpesaC2BPayments where TransID=@TransID) BEGIN INSERT INTO protobase.[dbo].[MpesaC2BPayments] ([TransactionType] ,[TransID] ,[TransTime] ,[TransAmount],[BusinessShortCode] ,[MSISDN] ,[FirstName] ,[MiddleName] ,[LastName] ,[OrgAccountBalance],[UsageBalance],[AddedBy])" +
                                     "VALUES(@TransactionType ,@TransID ,@TransTime ,@TransAmount,@BusinessShortCode ,@MSISDN ,@FirstName ,@MiddleName ,@LastName ,@OrgAccountBalance,@TransAmount,@AddedBy)  END";
                        SqlCommand command = new SqlCommand(sql, connection);
                        command.CommandType = CommandType.Text;

                        command.Parameters.AddWithValue("@TransactionType", payment.transactiontype);
                        command.Parameters.AddWithValue("@TransID", payment.transactionId);
                        command.Parameters.AddWithValue("@TransTime", payment.trxDate);
                        command.Parameters.AddWithValue("@TransAmount", payment.amount);
                        command.Parameters.AddWithValue("@BillRefNumber", payment.billreference ?? "");
                        command.Parameters.AddWithValue("@InvoiceNumber", "");
                        command.Parameters.AddWithValue("@BusinessShortCode", ShortCode);
                        command.Parameters.AddWithValue("@MSISDN", payment.msisdn);
                        command.Parameters.AddWithValue("@FirstName", "");
                        command.Parameters.AddWithValue("@MiddleName", "");
                        command.Parameters.AddWithValue("@LastName", "");

                        command.Parameters.AddWithValue("@OrgAccountBalance", 0);
                        command.Parameters.AddWithValue("@AddedBy", "PullAPI");
                        command.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    //ErrorLogger.FailedC2BLogs(json);
                    //ErrorLogger.ProtoKopaLogging(ex.Message, "B2CPayment", "AddingPayment");
                    try
                    {
                        //transaction.Rollback();
                    }
                    catch (Exception ex2)
                    {
                        //ErrorLogger.ProtoKopaLogging(ex2.Message, "B2CPayment", "AddingPayment");
                    }
                }
            }
        }
        public PullRequestDetailViewModelDesigner()
        {
            var repoPath = @"C:\Repo";

            Model = new PullRequestModel(419, 
                "Error handling/bubbling from viewmodels to views to viewhosts",
                 new AccountDesigner { Login = "******", IsUser = true },
                 DateTime.Now.Subtract(TimeSpan.FromDays(3)))
            {
                State = PullRequestStateEnum.Open,
                CommitCount = 9,
            };

            SourceBranchDisplayName = "shana/error-handling";
            TargetBranchDisplayName = "master";
            Body = @"Adds a way to surface errors from the view model to the view so that view hosts can get to them.

ViewModels are responsible for handling the UI on the view they control, but they shouldn't be handling UI for things outside of the view. In this case, we're showing errors in VS outside the view, and that should be handled by the section that is hosting the view.

This requires that errors be propagated from the viewmodel to the view and from there to the host via the IView interface, since hosts don't usually know what they're hosting.

![An image](https://cloud.githubusercontent.com/assets/1174461/18882991/5dd35648-8496-11e6-8735-82c3a182e8b4.png)";

            var gitHubDir = new PullRequestDirectoryNode("GitHub");
            var modelsDir = new PullRequestDirectoryNode("Models");
            var repositoriesDir = new PullRequestDirectoryNode("Repositories");
            var itrackingBranch = new PullRequestFileNode(repoPath, @"GitHub\Models\ITrackingBranch.cs", PullRequestFileStatus.Modified);
            var oldBranchModel = new PullRequestFileNode(repoPath, @"GitHub\Models\OldBranchModel.cs", PullRequestFileStatus.Removed);
            var concurrentRepositoryConnection = new PullRequestFileNode(repoPath, @"GitHub\Repositories\ConcurrentRepositoryConnection.cs", PullRequestFileStatus.Added);

            repositoriesDir.Files.Add(concurrentRepositoryConnection);
            modelsDir.Directories.Add(repositoriesDir);
            modelsDir.Files.Add(itrackingBranch);
            modelsDir.Files.Add(oldBranchModel);
            gitHubDir.Directories.Add(modelsDir);

            ChangedFilesTree = new ReactiveList<IPullRequestChangeNode>();
            ChangedFilesTree.Add(gitHubDir);

            ChangedFilesList = new ReactiveList<IPullRequestFileNode>();
            ChangedFilesList.Add(concurrentRepositoryConnection);
            ChangedFilesList.Add(itrackingBranch);
            ChangedFilesList.Add(oldBranchModel);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Обогащает пулл-реквест активностью
        /// </summary>
        /// <param name="pullrequest">пулл-реквест</param>
        /// <param name="key">ключ проекта</param>
        static void GetPullRequestActivities(PullRequestModel pullrequest, string key)
        {
            pullrequest.Actives = new List <ActivitiesModel>();
            string  slug = GetSlug(key);
            JObject o    = ApiRequestGet(string.Format("rest/api/1.0/projects/{1}/repos/{2}/pull-requests/{0}/activities", pullrequest.PullRequestNumber, key, slug));

            foreach (var act in o["values"])
            {
                ActivitiesModel a = new ActivitiesModel(key, slug);
                a.Author = new UserModel()
                {
                    Name = act["user"]["displayName"].Value <string>(), Email = act["user"]["emailAddress"].Value <string>(), Slug = act["user"]["slug"].Value <string>()
                };
                a.Action      = act["action"].Value <string>();
                a.Description = act["comment"] != null ? act["comment"]["text"].Value <string>() : act["commit"] != null ? act["commit"]["message"].Value <string>() : string.Empty;
                a.Date        = ConvertUnixDT(act["createdDate"].Value <long>()).ToString("dd.MM.yyyy HH:mm:ss");
                pullrequest.Actives.Add(a);
            }
        }
Ejemplo n.º 28
0
        private async Task AssertPullRequestCreatorPermission(PullRequestModel prModel)
        {
            // White list bot accounts to create API reviews from PR automatically
            if (!_allowedListBotAccounts.Contains(prModel.Author))
            {
                var orgs = await _githubClient.Organization.GetAllForUser(prModel.Author);

                var orgNames = orgs.Select(o => o.Login);
                var result   = await _authorizationService.AuthorizeAsync(
                    null,
                    orgNames,
                    new[] { PullRequestPermissionRequirement.Instance });

                if (!result.Succeeded)
                {
                    _telemetryClient.TrackTrace($"API change detection permission failed for user {prModel.Author}.");
                    throw new AuthorizationFailedException();
                }
            }
        }
Ejemplo n.º 29
0
        private async Task <PullRequestModel> GetPullRequestModel(int prNumber, string repoName, string packageName, string originalFile, string language)
        {
            var pullRequestModel = await _pullRequestsRepository.GetPullRequestAsync(prNumber, repoName, packageName, language);

            if (pullRequestModel == null)
            {
                string[] repoInfo    = repoName.Split("/");
                var      pullRequest = await _githubClient.PullRequest.Get(repoInfo[0], repoInfo[1], prNumber);

                pullRequestModel = new PullRequestModel()
                {
                    RepoName          = repoName,
                    PullRequestNumber = prNumber,
                    FilePath          = originalFile,
                    Author            = pullRequest.User.Login,
                    PackageName       = packageName,
                    Language          = language
                };
            }
            return(pullRequestModel);
        }
        static PullRequestModel CreatePullRequest(
            string authorLogin = "******",
            IEnumerable <IPullRequestReviewModel> reviews = null,
            IEnumerable <IPullRequestReviewCommentModel> reviewComments = null)
        {
            reviews        = reviews ?? new IPullRequestReviewModel[0];
            reviewComments = reviewComments ?? new IPullRequestReviewCommentModel[0];

            var author = Substitute.For <IAccount>();

            author.Login.Returns(authorLogin);

            var result = new PullRequestModel(
                5,
                "Pull Request",
                author,
                DateTimeOffset.Now);

            result.Reviews        = reviews.ToList();
            result.ReviewComments = reviewComments.ToList();
            return(result);
        }
Ejemplo n.º 31
0
    protected IEnumerable <object> ExtractValues(PullRequestModel pr, IEnumerable <PullRequestCommentModel> comments)
    {
        yield return(pr.Id);

        yield return(pr.RepositoryName);

        yield return(pr.Title);

        yield return(pr.Description);

        yield return(pr.CreationDate);

        yield return(pr.ClosedDate);

        yield return(pr.Duration);

        yield return(pr.CreatedBy);

        yield return(pr.ReviewerAsString);

        yield return(comments.Count());
    }
        IRepositoryHost CreateRepositoryHost()
        {
            var result = Substitute.For<IRepositoryHost>();
            var modelService = Substitute.For<IModelService>();
            var bitmapSource = Observable.Empty<BitmapImage>();

            var pullRequest = new PullRequestModel(
                1,
                "PR1",
                new Account("foo", true, false, 1, 0, bitmapSource),
                DateTimeOffset.MinValue);
            pullRequest.Assignee = new Account("foo", true, false, 1, 0, bitmapSource);

            var pullRequestCollection = Substitute.For<ITrackingCollection<IPullRequestModel>>();
            pullRequestCollection[0].Returns(pullRequest);

            modelService.GetPullRequests(
                Arg.Any<ILocalRepositoryModel>(),
                Arg.Any<ITrackingCollection<IPullRequestModel>>())
               .Returns(pullRequestCollection);
            result.ModelService.Returns(modelService);

            return result;
        }
Ejemplo n.º 33
0
 public PullRequestElement(PullRequestModel model, Action action)
 {
     _model  = model;
     _action = action;
     _avatar = new Avatar(_model.Author?.Links?.Avatar?.Href);
 }
Ejemplo n.º 34
0
 public async Task UpsertPullRequestAsync(PullRequestModel pullRequestModel)
 {
     await _pullRequestsContainer.UpsertItemAsync(pullRequestModel, new PartitionKey(pullRequestModel.PullRequestNumber));
 }
Ejemplo n.º 35
0
 public PullRequestElement(PullRequestModel model, Action action)
 {
     _model  = model;
     _action = action;
 }
 public void ComparisonNotEquals(int id1, int ms1, int id2, int ms2)
 {
     PullRequestModel left = new PullRequestModel(id1, "", Substitute.For<IAccount>(), Now, Now + TimeSpan.FromMilliseconds(ms1));
     PullRequestModel right = new PullRequestModel(id2, "", Substitute.For<IAccount>(), Now, Now + TimeSpan.FromMilliseconds(ms2));
     Assert.False(left == right);
     Assert.True(left != right);
 }
Ejemplo n.º 37
0
 public PullRequestElement(PullRequestModel model, Action action)
 {
     _model = model;
     _action = action;
 }