A Client for the GitHub API v3. You can read more about the api here: http://developer.github.com.
Inheritance: IGitHubClient
        public async Task<bool> DeployProject()
        {
            await LoadProjectSettings();
            var credentials = new Credentials(settings.GetString(OAuthTokenKey));
            var client = new GitHubClient(new ProductHeaderValue("Kerbal Space Program for Visual Studio"))
            {
                Credentials = credentials
            };
            var name = "";
            var versionName = "";
            await threadHandler.AsyncPump.RunAsync(async () =>
            {
                using (var readLock = await projectLockService.ReadLockAsync())
                {
                    var msBuildProject = await readLock.GetProjectAsync(await project.GetSuggestedConfiguredProjectAsync());
                    name = msBuildProject.GetPropertyValue("Name");
                    versionName = msBuildProject.GetProperty(nameof(VersionNamePattern)).EvaluatedValue;
                }
            });
            var tag = new NewTag
            {
                Message = $"Release {versionName} of {name}",
                Tag = versionName,
                Type = TaggedType.Commit,
                Tagger = new Committer(settings.GetString(UsernameKey), "", DateTimeOffset.UtcNow)
            };

            return false;
        }
示例#2
0
 /// <summary>
 /// Creates a pull request 
 /// </summary>
 static async Task SubmitPullRequest(GitHubClient github, string branchName)
 {
     await github.PullRequest.Create(REMOTE_USER, REPO_NAME,
         new NewPullRequest("Merge master into future", head: $"{MY_USER}:{branchName}", baseRef: "future") {
             Body = "this is the pull request body text"
         });
 }
示例#3
0
        public async Task<string> CreateGist(string contents)
        {
            try
            {
                string password = Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER", "gitPassword", "invalid").ToString();
                var credentials = new Octokit.Credentials("*****@*****.**", password);

                var connection = new Connection(new ProductHeaderValue("Whatever"))
                {
                    Credentials = credentials
                };
                var github = new GitHubClient(connection);
                var newGist = new NewGist()
                {
                    Description = "Generated by SnippetVS",
                    Public = false,
                };
                newGist.Files.Add("fragment.cs", contents);
                var gist = github.Gist.Create(newGist).Result;
                return gist.HtmlUrl;
            }
            catch (Exception ex)
            {
                var x = ex;
            }
            return String.Empty;
        }
示例#4
0
        /// <summary>
        /// Creates a pull request 
        /// </summary>
        static async Task SubmitPullRequest(GitHubClient github, string remoteUser, string myUser, string repoName, 
                                            string newBranchName, string fromBranch, string intoBranch)
        {
            await github.PullRequest.Create(remoteUser, repoName,
                new NewPullRequest($"Merge {fromBranch} into {intoBranch}", head: $"{myUser}:{newBranchName}", baseRef: intoBranch) {
                    Body = $@"
This is an automatically generated pull request from {fromBranch} into {intoBranch}.

@dotnet/roslyn-infrastructure:

```bash
git remote add roslyn-bot ""https://github.com/roslyn-bot/roslyn.git""
git fetch roslyn-bot
git checkout {newBranchName}
git reset --hard upstream/{intoBranch}
git merge upstream/{fromBranch}
# Fix merge conflicts
git commit
git push roslyn-bot {newBranchName} --force
```

Once the merge can be made and all the tests pass, you are free to merge the pull request.

".Trim()
                });
        }
示例#5
0
    async Task PublishRelease(string owner, string repo, string token, string tag, string description, string artifactPath, bool prerelease)
    {
        var tokenAuth    = new Octokit.Credentials(token);
        var githubClient = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("vc-build"))
        {
            Credentials = tokenAuth
        };
        var newRelease = new Octokit.NewRelease(tag)
        {
            Name       = tag,
            Prerelease = prerelease,
            Draft      = false,
            Body       = description
        };
        var release = await githubClient.Repository.Release.Create(owner, repo, newRelease);

        using (var artifactStream = File.OpenRead(artifactPath))
        {
            var assetUpload = new Octokit.ReleaseAssetUpload()
            {
                FileName    = Path.GetFileName(artifactPath),
                ContentType = "application/zip",
                RawData     = artifactStream
            };
            var asset = await githubClient.Repository.Release.UploadAsset(release, assetUpload);
        }
    }
        public async Task CreatesANewPrivateRepository()
        {
            var github = new GitHubClient(new ProductHeaderValue("OctokitTests"))
            {
                Credentials = Helper.Credentials
            };
            var repoName = Helper.MakeNameWithTimestamp("private-repo");

            var createdRepository = await github.Repository.Create(new NewRepository
            {
                Name = repoName,
                Private = true
            });

            try
            {
                Assert.True(createdRepository.Private);
                var repository = await github.Repository.Get(Helper.UserName, repoName);
                Assert.True(repository.Private);
            }
            finally
            {
                Helper.DeleteRepo(createdRepository);
            }
        }
示例#7
0
		public async Task when_updating_issue_then_can_assign_non_existent_label()
		{
			var label = Guid.NewGuid().ToString();
            var github = new GitHubClient(
                new ProductHeaderValue("kzu-client"), new InMemoryCredentialStore(credentials));

			var update = new IssueUpdate
            {
                State = ItemState.Open,
            };
			update.AddLabel(label);

            await github.Issue.Update("kzu", "sandbox", 56, update);

			var issue = await github.Issue.Get("kzu", "sandbox", 56);

			Assert.True(issue.Labels.Any(l => l.Name == label));

			var labels = await github.Issue.Labels.GetForRepository("kzu", "sandbox");
			foreach (var l in labels.Select(l => l.Name)) {
				Guid g;
				if (Guid.TryParse(l, out g))
					await github.Issue.Labels.Delete("kzu", "sandbox", l);
			}
		}
示例#8
0
        public async Task MakePullRequest()
        {
            _client = new GitHubClient(new ProductHeaderValue(_options.SourceUser));
            _client.Credentials = new Credentials(_options.AuthToken);
            var remoteIntoBranch = await GetShaFromBranch(_options.DestinationUser, _options.RepoName, _options.SourceBranch);
            var newBranchPrefix = $"merge-{_options.SourceBranch}-into-{_options.DestinationBranch}";
            if (!_options.Force && await DoesOpenPrAlreadyExist(newBranchPrefix))
            {
                Console.WriteLine("Existing merge PRs exist; aboring creation.  Use `--force` option to override.");
                return;
            }

            var newBranchName = await MakePrBranch(_options.SourceUser, _options.RepoName, remoteIntoBranch, newBranchPrefix);
            var pullRequest = await SubmitPullRequest(newBranchName);

            // pullRequest could be null if we are running in debug mode.
            // Only write the comment if the pull request can be automatically merged.
            if ((pullRequest?.Mergeable).HasValue && pullRequest.Mergeable.Value)
            {
                // The reason for this delay is twofold:
                //
                // * Github has a bug in which it can "create" a pull request without that pull request
                //   being able to be commented on for a short period of time.
                // * The Jenkins "comment watcher" has a bug whereby any comment posted shortly after
                //   pull-request creation is ignored.
                //
                // Thus, this delay sidesteps both of those bugs by asking for a VSI test 30 seconds after 
                // the creation of the PR.  Ugly, yes; but the only *real* way to sidestep this would be to 
                // 1) Fix github, 2) Fix jenkins, and while those might be lofty goals, they are not in the 
                // scope of this PR.
                await Task.Delay(TimeSpan.FromSeconds(30.0));
                await _client.Issue.Comment.Create(_options.DestinationUser, _options.RepoName, pullRequest.Number, "@dotnet-bot test vsi please");
            }
            return;
        }
示例#9
0
        public async Task ProcessSingleBuildThatFails()
        {
            var cache = new TestBlobCache();
            var client = new GitHubClient(new ProductHeaderValue("Peasant"));
            var stdout = new Subject<string>();
            var allLines = stdout.CreateCollection();

            var fixture = new BuildQueue(client, cache);
            var result = default(int);
            bool shouldDie = true;

            try {
                // NB: This build fails because NuGet package restore wasn't set 
                // up properly, so MSBuild is missing a ton of assemblies
                result = await fixture.ProcessSingleBuild(new BuildQueueItem() {
                    BuildId = 1,
                    BuildScriptUrl = TestBuild.BuildScriptUrl,
                    RepoUrl = TestBuild.RepoUrl,
                    SHA1 = TestBuild.FailingBecauseOfMsbuildSHA1,
                }, stdout);
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                shouldDie = false;
            }

            var output = allLines.Aggregate(new StringBuilder(), (acc, x) => { acc.AppendLine(x); return acc; }).ToString();
            Console.WriteLine(output);

            Assert.False(shouldDie);
        }
示例#10
0
        public GitHubClient CreateGitHubClient()
        {
            var creds = new Credentials(Username, Password);
            var github = new GitHubClient(new ProductHeaderValue("ReleaseNotesCompiler")) { Credentials = creds };

            return github;
        }
        public IHttpActionResult ProcessHook(IssueCommentEvent commentEvent)
        {
            _baseUrl = commentEvent.Repository.Url.Scheme + "://" + commentEvent.Repository.Url.Host;
            _owner = commentEvent.Repository.Owner.Login;
            _repoName = commentEvent.Repository.Name;

            var creds = new InMemoryCredentialStore(new Credentials("derp", ApiKey));
            var headerVal = new ProductHeaderValue("GitHooks");
            _github = new GitHubClient(headerVal, creds, new Uri(_baseUrl));

            if (CheckComment(commentEvent.Comment.Body))
            {
                var branchName = GetBranchNameFromComment(commentEvent.Comment.Body);

                try
                {
                    var pullRequest = GetPullRequest(branchName, commentEvent.Issue.Number, commentEvent.Issue.Title);
                    var merge = MergePullRequest(pullRequest, commentEvent.Issue.Number, branchName, true);
                    DeleteBranch(merge, branchName, commentEvent.Issue.Number, pullRequest.Number);
                    LeaveSuccessfulMergeComment(commentEvent.Issue.Number, pullRequest.Number, branchName);
                }
                catch (RobotFallDownException e)
                {
                    return BadRequest();
                }
            }

            return Ok();
        }
示例#12
0
 /// <summary>
 /// Constructs a class for talking to GitHub
 /// </summary>
 /// <param name="organization">The organization you are interested in</param>
 /// <param name="repository">The repository within an organization</param>
 public GitHubApi(string organization, string repository)
 {
     _organization = organization;
     _repository = repository;
     _github = new GitHubClient(new ProductHeaderValue("Alteridem.GetChangeset"));
     _github.Credentials = new Credentials(Secrets.TOKEN);
 }
示例#13
0
 private static GitHubClient CreateClient()
 {
     var token = ConfigurationManager.AppSettings["github-token"];
     var client = new GitHubClient(new ProductHeaderValue("jbug-dash-app"));
     client.Credentials = new Credentials(token);
     return client;
 }
示例#14
0
        private static void CreateIssueTrackers(IRepository repository, GitReleaseNotesArguments arguments)
        {
            _issueTrackers = new Dictionary<IssueTracker, IIssueTracker>
            {
                {
                    IssueTracker.GitHub,
                    new GitHubIssueTracker(repository, () =>
                    {
                        var gitHubClient = new GitHubClient(new ProductHeaderValue("GitReleaseNotes"));
                        if (arguments.Token != null)
                        {
                            gitHubClient.Credentials = new Credentials(arguments.Token);
                        }

                        return gitHubClient;
                    }, new Log(), arguments)
                },
                {
                    IssueTracker.Jira,
                    new JiraIssueTracker(new JiraApi(), arguments)
                },
                {
                    IssueTracker.YouTrack,
                    new YouTrackIssueTracker(new YouTrackApi(), arguments)
                }
            };
        }
        private async void HandleLoadStarted(object sender, EventArgs e)
        {
            if (webView.Request.Url.AbsoluteString.StartsWith("http://youhaveissues.azurewebsites.net"))
            {
                webView.StopLoading();

                var parameters = webView.Request.Url.Query.Split('&');
                Task<OauthToken> authTokenTask = null;
                foreach (var param in parameters)
                {
                    var parts = param.Split('=');
                    if (parts[0] == "code")
                    {
                        var code = parts[1];
                        authTokenTask = unauthenticatedClient.Oauth.CreateAccessToken(
                            new OauthTokenRequest(config.ClientID, config.ClientSecret, code));
                        break;
                    }
                }

                if (authTokenTask != null)
                {
                    var token = await authTokenTask;
                    var client = new GitHubClient(new ProductHeaderValue("YouHaveIssues"));
                    client.Credentials = new Credentials(token.AccessToken);
                    DismissViewController(animated: true, completionHandler: null);
                    AccountAuthenticated(this, new GitHubClientEventArgs(client));
                }
            }
        }
        public async Task CreatesANewPublicRepository()
        {
            var github = new GitHubClient(new ProductHeaderValue("OctokitTests"))
            {
                Credentials = Helper.Credentials
            };
            var repoName = Helper.MakeNameWithTimestamp("public-repo");

            var createdRepository = await github.Repository.Create(new NewRepository { Name = repoName });
                
            try
            {
                var cloneUrl = string.Format("https://github.com/{0}/{1}.git", Helper.UserName, repoName);
                Assert.Equal(repoName, createdRepository.Name);
                Assert.False(createdRepository.Private);
                Assert.Equal(cloneUrl, createdRepository.CloneUrl);
                var repository = await github.Repository.Get(Helper.UserName, repoName);
                Assert.Equal(repoName, repository.Name);
                Assert.Null(repository.Description);
                Assert.False(repository.Private);
                Assert.True(repository.HasDownloads);
                Assert.True(repository.HasIssues);
                Assert.True(repository.HasWiki);
                Assert.Null(repository.Homepage);
            }
            finally
            {
                Helper.DeleteRepo(createdRepository);
            }
        }
示例#17
0
        public async Task when_processing_issue_with_declared_plus_label_then_applies_it_with_plus()
        {
            var github = new GitHubClient(new ProductHeaderValue("kzu-client"), new InMemoryCredentialStore(credentials));
            var repository = await github.Repository.Get("kzu", "sandbox");
            var user = await github.User.Current();

            var issue = await github.Issue.Create(
                "kzu", "sandbox", new NewIssue("Auto-labeling to +doc"));

            var labeler = new OctoIssuerJob(github, new IOctoIssuer[] { new AutoLabel(github) });

            await labeler.ProcessAsync(new Octokit.Events.IssuesEvent
            {
                Action = IssuesEvent.IssueAction.Opened,
                Issue = issue,
                Repository = repository,
                Sender = user,
            });

            var updated = await github.Issue.Get("kzu", "sandbox", issue.Number);

            Assert.Equal("Auto-labeling to", updated.Title);
            Assert.True(updated.Labels.Any(l => l.Name == "+Doc"));

            await github.Issue.Update("kzu", "sandbox", issue.Number, new IssueUpdate { State = ItemState.Closed });
        }
        public async Task<ActionResult> Index(string idea, string description)
        {
            if (idea == "" || idea == null)
            {
                ViewBag.Message = "Enter an idea yo!";
                ViewBag.ImgUrl = "homerSad.jpg";
                return View();
            }

            try
            {
                var client = new GitHubClient(new ProductHeaderValue("Nommer-Idea-Lodger"));
                client.Credentials = new Credentials(Environment.GetEnvironmentVariable("GithubKey"));

                var newIdea = new NewIssue(idea) { Body = description };
                newIdea.Labels.Add("idea");

                await client.Issue.Create("NickBrooks", "Nommer-Roadmap", newIdea);

                ViewBag.Message = "You're an ideas man!";
                ViewBag.ImgUrl = "homerHappy.jpg";
            }
            catch (Exception ex)
            {
                ViewBag.ImgUrl = "homerSad.jpg";
                ViewBag.Message = ex.ToString();
            }

            return View();
        }
示例#19
0
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            // NB: GrossHackAlertTiem™:
            //
            // Monotouch appears to not load assemblies when you request them
            // via Type.GetType, unlike every other platform (even
            // Xamarin.Android). So, we've got to manually do what RxUI and
            // Akavache would normally do for us
            var r = new ModernDependencyResolver();
            (new ReactiveUI.Registrations()).Register((f,t) => r.Register(f, t));
            (new ReactiveUI.Cocoa.Registrations()).Register((f,t) => r.Register(f, t));
            (new ReactiveUI.Mobile.Registrations()).Register((f,t) => r.Register(f, t));
            (new Akavache.Registrations()).Register(r.Register);
            (new Akavache.Mobile.Registrations()).Register(r.Register);
            (new Akavache.Sqlite3.Registrations()).Register(r.Register);
            RxApp.DependencyResolver = r;

            window = new UIWindow(UIScreen.MainScreen.Bounds);

            var client = new GitHubClient(new System.Net.Http.Headers.ProductHeaderValue("RxUISample", "0.1"));
            client.Credentials = new Credentials("paulcbetts", GiveMeAToken.DoIt());
            r.RegisterConstant(client.Notification, typeof(INotificationsClient));

            viewController = new NotificationsListViewController();
            window.RootViewController = viewController;
            window.MakeKeyAndVisible();

            return true;
        }
示例#20
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                throw new Exception("Missing github API token argument");
            }
            var token = args[0];
            github = new GitHubClient(new ProductHeaderValue("Jackett"));
            github.Credentials = new Credentials(token);

            localVersion = GetJackettVersion();
            /*var latestReleaseVersion = LatestGithubRelease().Result;
            if (localVersion <= latestReleaseVersion)
            {
                Console.WriteLine("Latest Github release is {0}, will not upload local version {1}", latestReleaseVersion, localVersion);
                return;
            }*/

            Console.WriteLine("Zipping release build for Windows " + localVersion);
            ZippingReleaseBuildWindows();

            Console.WriteLine("Zipping release build for Mono " + localVersion);
            ZippingReleaseBuildMono();

            UploadRelease().Wait();
        }
示例#21
0
        public async Task Sync()
        {
            var github = new GitHubClient(new ProductHeaderValue("Jackett"));
            var releases = await github.Release.GetAll("zone117x", "Jackett");

            if (releases.Count > 0)
            {
                using (var db = new LiteDatabase(GetDBPath()))
                {
                    var releaseCollection = db.GetCollection<Release>("Releases");
                    releaseCollection.Drop();
                    releaseCollection.EnsureIndex(x => x.When);

                    foreach (var release in releases)
                    {
                        releaseCollection.Insert(new Release()
                        {
                            When = release.PublishedAt.Value.DateTime,
                            Description = release.Body,
                            Title = release.Name,
                            Url = release.HtmlUrl,
                            Version = release.TagName
                        });
                    }
                }
            }
        }
        public async Task CreatesARepositoryWithoutDownloads()
        {
            var github = new GitHubClient(new ProductHeaderValue("OctokitTests"))
            {
                Credentials = Helper.Credentials
            };
            var repoName = Helper.MakeNameWithTimestamp("repo-without-downloads");

            var createdRepository = await github.Repository.Create(new NewRepository
            {
                Name = repoName,
                HasDownloads = false
            });

            try
            {
                Assert.False(createdRepository.HasDownloads);
                var repository = await github.Repository.Get(Helper.UserName, repoName);
                Assert.False(repository.HasDownloads);
            }
            finally
            {
                Helper.DeleteRepo(createdRepository);
            }
        }
示例#23
0
 public GitHubRepository(string appName, string token)
 {
     _gitHubClient = new GitHubClient(new ProductHeaderValue(appName))
     {
         Credentials = new Credentials(token)
     };
 }
示例#24
0
 public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context)
 {
     GitHubClient github = new GitHubClient(new ProductHeaderValue("Wyam"), _url ?? GitHubClient.GitHubApiUrl);
     if (_credentials != null)
     {
         github.Credentials = _credentials;
     }
     return inputs.AsParallel().Select(input =>
     {
         ConcurrentDictionary<string, object> results = new ConcurrentDictionary<string, object>();
         foreach (KeyValuePair<string, Func<IDocument, IExecutionContext, GitHubClient, object>> request in _requests.AsParallel())
         {
             Trace.Verbose("Submitting {0} GitHub request for {1}", request.Key, input.Source);
             try
             {
                 results[request.Key] = request.Value(input, context, github);
             }
             catch (Exception ex)
             {
                 Trace.Warning("Exception while submitting {0} GitHub request for {1}: {2}", request.Key, input.Source, ex.ToString());
             }
         }
         return context.GetDocument(input, results);
     });
 }
示例#25
0
        private static async Task<string> createGistAsync(string snippet)
        {
            try
            {
                var token = Options.SavedOptions.Instance.TokenValue;
                if (String.IsNullOrWhiteSpace(token))
                {
                    StatusBar.ShowStatus("Please provide GitHub access token in Tools > Options > Gistify");
                    return String.Empty;
                }
                var credentials = new Octokit.Credentials(token);

                var connection = new Connection(new ProductHeaderValue("Whatever"))
                {
                    Credentials = credentials
                };
                var github = new GitHubClient(connection);
                var newGist = new NewGist()
                {
                    Description = "Generated by Code Connect's Gistify",
                    Public = false,
                };
                newGist.Files.Add("fragment.cs", snippet);
                var gist = await github.Gist.Create(newGist).ConfigureAwait(false);
                return gist.HtmlUrl;
            }
            catch (Exception)
            {
                StatusBar.ShowStatus("Gistify ran into a problem creating the gist.");
                return String.Empty;
            }
        }
 private void CreateClient()
 {
     if (_client == null)
     {
         _client = new GitHubClient(new ProductHeaderValue("XMLDiff"));
     }
 }
示例#27
0
        public GitHubClient CreateWithOAuth(string productHeaderValue, string username, string oAuthToken)
        {
            var client = new GitHubClient(new ProductHeaderValue(productHeaderValue));
            client.Credentials = new Credentials(username, oAuthToken);

            return client;
        }
 private static async Task<IEnumerable<Repository>> GetMissingStars(GitHubClient client)
 {
     var currentUser = await client.User.Current();
     var repos = (await client.Repository.GetAllForCurrent()).Where(a => !a.Private).ToList();
     var stars = await client.Activity.Starring.GetAllForCurrent();
     return repos.Where(a => !stars.Any(b => string.Equals(a.Owner.Name, b.Owner.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(a.FullName, b.FullName, StringComparison.OrdinalIgnoreCase)));
 }
 public GitHubTeamService(string clientToken)
 {
     Client = new GitHubClient(new ProductHeaderValue("dePested"))
     {
         Credentials = new Credentials(clientToken)
     };
 }
示例#30
0
        public List<Developer> page(int page = 1, int size = 40)
        {
            var credentials = new Octokit.Credentials(ConfigurationManager.AppSettings["user_git"], ConfigurationManager.AppSettings["pass_git"]);
            Octokit.Connection connection = new Connection(new ProductHeaderValue("DevStore"));
            Octokit.ApiConnection apiConn = new ApiConnection(connection);
            Octokit.SearchUsersRequest search = new SearchUsersRequest("a");
            search.AccountType = AccountSearchType.User;
            search.PerPage = size;
            search.Page = page;
            Octokit.UsersClient userCliente = new UsersClient(apiConn);
            Octokit.SearchClient searchUserService = new SearchClient(apiConn);
            SearchUsersResult usersResult = searchUserService.SearchUsers(search).Result;
            Octokit.GitHubClient gitClient = new GitHubClient(connection);
            Octokit.UsersClient userClient = new UsersClient(apiConn);
            List<Developer> developers = (from userGit in usersResult.Items
                                          select new Developer
                                          {
                                              User = userGit.Login,
                                              UrlAvatar = userGit.AvatarUrl.ToString(),
                                              TotalRepo = userGit.PublicRepos,
                                              TotalFollowers = userGit.Followers,
                                              Price = ((userGit.PublicRepos * pesoTotalRepository) + (userGit.Followers * pesoTotalFollowers)) / (pesoTotalRepository + pesoTotalFollowers)
                                          }).ToList();

            return developers;
        }
示例#31
0
        public static async Task<bool> CheckForUpdate()
        {
            var client = new GitHubClient(new ProductHeaderValue("auto-updater"));

            var tokenAuth = new Credentials("token"); // NOTE: not real token
            client.Credentials = tokenAuth;

            var request = client.Release.GetAll("kdolan", "AutoUpdater");
            var releases = await request;
            var latest = releases[0];

            var remoteVersion = latest.TagName;
            var currentVersion = FileVersionInfo.GetVersionInfo("Updater.exe"); //Get the version of this file. Set in AssemblyInfo.cs. Look for ProductInformationVersion

            if (remoteVersion != currentVersion.ProductVersion) //If the remote version does not equal the current version then download the remote version
            {
                //Download Release.zip here
                var response =
                    await
                        client.Connection.Get<object>(new Uri(latest.Url), new Dictionary<string, string>(),
                            "application/octet-stream");
                //Then call to PerformUpdate to apply the update
                return true;
            }
            else
            {
                return false; //No Update needed
            }
        }
示例#32
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (User != null && Organization != null && Options != null)
            {
                var userValue         = User.GetValue(dc.State);
                var organizationValue = Organization.GetValue(dc.State);
                var optionsValue      = Options.GetValue(dc.State);
                return(await gitHubClient.Activity.Events.GetAllForAnOrganization(userValue, organizationValue, optionsValue).ConfigureAwait(false));
            }
            if (User != null && Organization != null)
            {
                var userValue         = User.GetValue(dc.State);
                var organizationValue = Organization.GetValue(dc.State);
                return(await gitHubClient.Activity.Events.GetAllForAnOrganization(userValue, organizationValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [user,organization] arguments missing for GitHubClient.Activity.Events.GetAllForAnOrganization");
        }
示例#33
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Options != null)
            {
                var ownerValue   = Owner.GetValue(dc.State);
                var nameValue    = Name.GetValue(dc.State);
                var optionsValue = Options.GetValue(dc.State);
                return(await gitHubClient.Activity.Events.GetAllForRepositoryNetwork(ownerValue, nameValue, optionsValue).ConfigureAwait(false));
            }
            if (Owner != null && Name != null)
            {
                var ownerValue = Owner.GetValue(dc.State);
                var nameValue  = Name.GetValue(dc.State);
                return(await gitHubClient.Activity.Events.GetAllForRepositoryNetwork(ownerValue, nameValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [owner,name] arguments missing for GitHubClient.Activity.Events.GetAllForRepositoryNetwork");
        }
示例#34
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && HookId != null)
            {
                var ownerValue  = Owner.GetValue(dc.State);
                var nameValue   = Name.GetValue(dc.State);
                var hookIdValue = HookId.GetValue(dc.State);
                return(gitHubClient.Repository.Hooks.Test(ownerValue, nameValue, (Int32)hookIdValue));
            }
            if (RepositoryId != null && HookId != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var hookIdValue       = HookId.GetValue(dc.State);
                return(gitHubClient.Repository.Hooks.Test((Int64)repositoryIdValue, (Int32)hookIdValue));
            }

            throw new ArgumentNullException("Required [hookId] arguments missing for GitHubClient.Repository.Hooks.Test");
        }
示例#35
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && LabelName != null)
            {
                var ownerValue     = Owner.GetValue(dc.State);
                var nameValue      = Name.GetValue(dc.State);
                var labelNameValue = LabelName.GetValue(dc.State);
                return(gitHubClient.Issue.Labels.Delete(ownerValue, nameValue, labelNameValue));
            }
            if (RepositoryId != null && LabelName != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var labelNameValue    = LabelName.GetValue(dc.State);
                return(gitHubClient.Issue.Labels.Delete((Int64)repositoryIdValue, labelNameValue));
            }

            throw new ArgumentNullException("Required [labelName] arguments missing for GitHubClient.Issue.Labels.Delete");
        }
示例#36
0
        private async Task <Release> GetReleases()
        {
            var client  = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("MkvMasivo"));
            var release = await client.Repository.Release.GetLatest("Hosfix", "MkvMasivo");

            if (release != null && !String.IsNullOrEmpty(release.TagName))
            {
                if (!release.TagName.Equals(fileVersion.FileVersion))
                {
                    if (MessageBox.Show("Se ha encontrado la versión " + release.TagName + ". ¿Desea que se le abra un enlace de descarga?", "Nueva versión", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        Process.Start(release.Assets[0].BrowserDownloadUrl);
                        Close();
                    }
                }
            }
            return(release);
        }
示例#37
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Number != null)
            {
                var ownerValue  = Owner.GetValue(dc.State);
                var nameValue   = Name.GetValue(dc.State);
                var numberValue = Number.GetValue(dc.State);
                return(await gitHubClient.PullRequest.Get(ownerValue, nameValue, (Int32)numberValue).ConfigureAwait(false));
            }
            if (RepositoryId != null && Number != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var numberValue       = Number.GetValue(dc.State);
                return(await gitHubClient.PullRequest.Get((Int64)repositoryIdValue, (Int32)numberValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [number] arguments missing for GitHubClient.PullRequest.Get");
        }
示例#38
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && NewSubscription != null)
            {
                var ownerValue           = Owner.GetValue(dc.State);
                var nameValue            = Name.GetValue(dc.State);
                var newSubscriptionValue = NewSubscription.GetValue(dc.State);
                return(await gitHubClient.Activity.Watching.WatchRepo(ownerValue, nameValue, newSubscriptionValue).ConfigureAwait(false));
            }
            if (RepositoryId != null && NewSubscription != null)
            {
                var repositoryIdValue    = RepositoryId.GetValue(dc.State);
                var newSubscriptionValue = NewSubscription.GetValue(dc.State);
                return(await gitHubClient.Activity.Watching.WatchRepo((Int64)repositoryIdValue, newSubscriptionValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [newSubscription] arguments missing for GitHubClient.Activity.Watching.WatchRepo");
        }
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Branch != null)
            {
                var ownerValue  = Owner.GetValue(dc.State);
                var nameValue   = Name.GetValue(dc.State);
                var branchValue = Branch.GetValue(dc.State);
                return(await gitHubClient.Repository.Branch.GetAllProtectedBranchUserRestrictions(ownerValue, nameValue, branchValue).ConfigureAwait(false));
            }
            if (RepositoryId != null && Branch != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var branchValue       = Branch.GetValue(dc.State);
                return(await gitHubClient.Repository.Branch.GetAllProtectedBranchUserRestrictions((Int64)repositoryIdValue, branchValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [branch] arguments missing for GitHubClient.Repository.Branch.GetAllProtectedBranchUserRestrictions");
        }
        public static bool CheckCredentials(string user, string password, string token)
        {
            var client = new Octokit.GitHubClient(new ProductHeaderValue(AppName))
            {
                Credentials = string.IsNullOrEmpty(token) ? new Credentials(user, password) : new Credentials(token)
            };

            try
            {
                var repositoryContents = client.Repository.Content.GetAllContents(RepositoryOwner, Repository).Result;
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }
示例#41
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Preferences != null)
            {
                var ownerValue       = Owner.GetValue(dc.State);
                var nameValue        = Name.GetValue(dc.State);
                var preferencesValue = Preferences.GetValue(dc.State);
                return(await gitHubClient.Check.Suite.UpdatePreferences(ownerValue, nameValue, preferencesValue).ConfigureAwait(false));
            }
            if (RepositoryId != null && Preferences != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var preferencesValue  = Preferences.GetValue(dc.State);
                return(await gitHubClient.Check.Suite.UpdatePreferences((Int64)repositoryIdValue, preferencesValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [preferences] arguments missing for GitHubClient.Check.Suite.UpdatePreferences");
        }
示例#42
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Number != null && Users != null)
            {
                var ownerValue  = Owner.GetValue(dc.State);
                var nameValue   = Name.GetValue(dc.State);
                var numberValue = Number.GetValue(dc.State);
                var usersValue  = Users.GetValue(dc.State);
                return(gitHubClient.Repository.PullRequest.ReviewRequest.Delete(ownerValue, nameValue, (Int32)numberValue, usersValue));
            }
            if (RepositoryId != null && Number != null && Users != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var numberValue       = Number.GetValue(dc.State);
                var usersValue        = Users.GetValue(dc.State);
                return(gitHubClient.Repository.PullRequest.ReviewRequest.Delete((Int64)repositoryIdValue, (Int32)numberValue, usersValue));
            }

            throw new ArgumentNullException("Required [number,users] arguments missing for GitHubClient.Repository.PullRequest.ReviewRequest.Delete");
        }
示例#43
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Base != null && Head != null)
            {
                var ownerValue = Owner.GetValue(dc.State);
                var nameValue  = Name.GetValue(dc.State);
                var baseValue  = Base.GetValue(dc.State);
                var headValue  = Head.GetValue(dc.State);
                return(await gitHubClient.Repository.Commit.Compare(ownerValue, nameValue, baseValue, headValue).ConfigureAwait(false));
            }
            if (RepositoryId != null && Base != null && Head != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var baseValue         = Base.GetValue(dc.State);
                var headValue         = Head.GetValue(dc.State);
                return(await gitHubClient.Repository.Commit.Compare((Int64)repositoryIdValue, baseValue, headValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [base,head] arguments missing for GitHubClient.Repository.Commit.Compare");
        }
示例#44
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Sha != null && NewCommitComment != null)
            {
                var ownerValue            = Owner.GetValue(dc.State);
                var nameValue             = Name.GetValue(dc.State);
                var shaValue              = Sha.GetValue(dc.State);
                var newCommitCommentValue = NewCommitComment.GetValue(dc.State);
                return(await gitHubClient.Repository.Comment.Create(ownerValue, nameValue, shaValue, newCommitCommentValue).ConfigureAwait(false));
            }
            if (RepositoryId != null && Sha != null && NewCommitComment != null)
            {
                var repositoryIdValue     = RepositoryId.GetValue(dc.State);
                var shaValue              = Sha.GetValue(dc.State);
                var newCommitCommentValue = NewCommitComment.GetValue(dc.State);
                return(await gitHubClient.Repository.Comment.Create((Int64)repositoryIdValue, shaValue, newCommitCommentValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [sha,newCommitComment] arguments missing for GitHubClient.Repository.Comment.Create");
        }
示例#45
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Path != null && Request != null)
            {
                var ownerValue   = Owner.GetValue(dc.State);
                var nameValue    = Name.GetValue(dc.State);
                var pathValue    = Path.GetValue(dc.State);
                var requestValue = Request.GetValue(dc.State);
                return(gitHubClient.Repository.Content.DeleteFile(ownerValue, nameValue, pathValue, requestValue));
            }
            if (RepositoryId != null && Path != null && Request != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var pathValue         = Path.GetValue(dc.State);
                var requestValue      = Request.GetValue(dc.State);
                return(gitHubClient.Repository.Content.DeleteFile((Int64)repositoryIdValue, pathValue, requestValue));
            }

            throw new ArgumentNullException("Required [path,request] arguments missing for GitHubClient.Repository.Content.DeleteFile");
        }
示例#46
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Id != null && Organization != null && RepoName != null && Permission != null)
            {
                var idValue           = Id.GetValue(dc.State);
                var organizationValue = Organization.GetValue(dc.State);
                var repoNameValue     = RepoName.GetValue(dc.State);
                var permissionValue   = Permission.GetValue(dc.State);
                return(await gitHubClient.Organization.Team.AddRepository((Int32)idValue, organizationValue, repoNameValue, permissionValue).ConfigureAwait(false));
            }
            if (Id != null && Organization != null && RepoName != null)
            {
                var idValue           = Id.GetValue(dc.State);
                var organizationValue = Organization.GetValue(dc.State);
                var repoNameValue     = RepoName.GetValue(dc.State);
                return(await gitHubClient.Organization.Team.AddRepository((Int32)idValue, organizationValue, repoNameValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [id,organization,repoName] arguments missing for GitHubClient.Organization.Team.AddRepository");
        }
示例#47
0
        public static async Task <bool> Authorize(string username, string password)
        {
            var githubClient = new Octokit.GitHubClient(new ProductHeaderValue("AppyLinks"));

            githubClient.Credentials = new Octokit.Credentials(username, password);

            var authenticationResult = await githubClient.Authorization.GetOrCreateApplicationAuthentication(
                "b205f79f35a8b9a48674",
                Secret.GithubApiSecret(),
                new Octokit.NewAuthorization()
            {
                Note = "AppyLinksInitial", Scopes = new[] { "gist" }
            }
                );

            var authToken = authenticationResult.Token;

            LocalSettings.GithubAuthorizationToken = authToken;

            return(true);
        }
示例#48
0
        public async Task<string> GetTokenForInstallationAsync(long installationId)
        {
            if (TryGetCachedToken(installationId, out AccessToken cachedToken))
            {
                _logger.LogInformation($"Cached token obtained for GitHub installation {installationId}. Expires at {cachedToken.ExpiresAt}.");
                return cachedToken.Token;
            }

            return await _retry.RetryAsync(
                async () =>
                {
                    string jwt = _tokens.GetAppToken();
                    var appClient = new Octokit.GitHubClient(_gitHubClientOptions.Value.ProductHeader) { Credentials = new Credentials(jwt, AuthenticationType.Bearer) };
                    AccessToken token = await appClient.GitHubApps.CreateInstallationToken(installationId);
                    _logger.LogInformation($"New token obtained for GitHub installation {installationId}. Expires at {token.ExpiresAt}.");
                    UpdateTokenCache(installationId, token);
                    return token.Token;
                },
                ex => _logger.LogError(ex, $"Failed to get a github token for installation id {installationId}, retrying"),
                ex => ex is ApiException && ((ApiException)ex).StatusCode == HttpStatusCode.InternalServerError);
        }
示例#49
0
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddEnvironmentVariables()
                         .AddCommandLine(args)
                         .AddUserSecrets <Program>()
                         .Build();

            var secrets  = config.GetSection("SECRETS");
            var userName = secrets?["GITHUB_USERNAME"];
            var password = secrets?["GITHUB_PASSWORD"];

            var loadedIssues = LoadIssues(@"c:\Users\MarkJunker\Downloads\quickgraph\issues\").ToList();

            var credentialStore = new Octokit.Internal.InMemoryCredentialStore(new Credentials(userName, password));
            var client          = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("codeplex-issue-import", "0.0.1"), credentialStore);

            _throttler = new GitHubRequestThrottler(client);

            var repository = await client.Repository.Get("FubarDevelopment", "QuickGraph");

            var labels = loadedIssues.Select(x => x.issue.WorkItem.AffectedComponent)
                         .Where(x => !string.IsNullOrEmpty(x?.Name))
                         .Distinct(new CodePlexComponentComparer());

            await ImportComponentLabelsAsync(client, repository, labels);

            var priorities = loadedIssues.Select(x => x.issue.WorkItem.Priority)
                             .Where(x => !string.IsNullOrEmpty(x?.Name))
                             .Distinct(new CodePlexPriorityComparer());

            await ImportPriorityLabelsAsync(client, repository, priorities);

            var closeReasons = loadedIssues.Select(x => x.issue.WorkItem.ReasonClosed)
                               .Where(x => !string.IsNullOrEmpty(x?.Name))
                               .Select(x => x.Name)
                               .Distinct();

            await ImportIssuesAsync(client, repository, loadedIssues);
        }
示例#50
0
        public static async Task <int> CreateNewIssueAsync(
            string repositoryUrl,
            string issueTitle,
            string issueDescription,
            string personalAccessToken)
        {
            (string owner, string repoName) = ParseRepoUri(repositoryUrl);

            Octokit.GitHubClient client    = new Octokit.GitHubClient(new ProductHeaderValue("assets-publisher"));
            Credentials          tokenAuth = new Credentials(personalAccessToken);

            client.Credentials = tokenAuth;

            NewIssue issueToBeCreated = new NewIssue(issueTitle)
            {
                Body = issueDescription
            };

            Issue createdIssue = await client.Issue.Create(owner, repoName, issueToBeCreated);

            return(createdIssue.Number);
        }
        public GitCommitResult CommitFile(string mdFile, string commitMessage)
        {
            IReadOnlyList <RepositoryContent> repositoryContents = null;

            Octokit.GitHubClient client = null;
            var result = CheckCredentials(ref client, ref repositoryContents);

            if (result.Status != GitCommitStatus.Success)
            {
                return(result);
            }

            var filename          = Path.GetFileName(mdFile);
            var content           = File.ReadAllText(mdFile);
            var repositoryContent = repositoryContents.FirstOrDefault(x => x.Name.Equals(filename));

            if (repositoryContent == null)
            {
                // Create file
                var createChangeSet = client.Repository.Content.CreateFile(
                    RepositoryOwner,
                    Repository,
                    filename,
                    new CreateFileRequest(commitMessage, content)).Result;
            }
            else
            {
                // Update file
                var updateChangeSet = client.Repository.Content.UpdateFile(
                    RepositoryOwner,
                    Repository,
                    filename,
                    new UpdateFileRequest(commitMessage, content, repositoryContent.Sha)).Result;
            }

            return(new GitCommitResult {
                Status = GitCommitStatus.Success
            });
        }
        private async Task UpdateComment(long repositoryId, int commentId, string existingCommentBody, string sentimentMessage)
        {
            var ghe = Environment.GetEnvironmentVariable("GITHUB_ENTERPRISE_URL", EnvironmentVariableTarget.Process);

            if (string.IsNullOrEmpty(ghe))
            {
                throw new ArgumentNullException("ghe", "Please set environment variable GITHUB_ENTERPRISE_URL");
            }

            var client = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("sentiment-test-bot", "0.1.0"), new Uri(ghe));

            var personalAccessToken = Environment.GetEnvironmentVariable("GITHUB_PERSONAL_ACCESS_TOKEN", EnvironmentVariableTarget.Process);

            if (string.IsNullOrEmpty(personalAccessToken))
            {
                throw new ArgumentNullException("personalAccessToken", "Please set environment variable GITHUB_PERSONAL_ACCESS_TOKEN");
            }

            client.Credentials = new Credentials(personalAccessToken);

            await client.Issue.Comment.Update(repositoryId, commentId, $"{existingCommentBody}\n\n_Sentiment Bot Says: {sentimentMessage}_");
        }
示例#53
0
 /// <inheritdoc/>
 protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
 {
     if (Request != null && Options != null)
     {
         var requestValue = Request.GetValue(dc.State);
         var optionsValue = Options.GetValue(dc.State);
         return(await gitHubClient.Issue.GetAllForOwnedAndMemberRepositories(requestValue, optionsValue).ConfigureAwait(false));
     }
     if (Options != null)
     {
         var optionsValue = Options.GetValue(dc.State);
         return(await gitHubClient.Issue.GetAllForOwnedAndMemberRepositories(optionsValue).ConfigureAwait(false));
     }
     if (Request != null)
     {
         var requestValue = Request.GetValue(dc.State);
         return(await gitHubClient.Issue.GetAllForOwnedAndMemberRepositories(requestValue).ConfigureAwait(false));
     }
     else
     {
         return(await gitHubClient.Issue.GetAllForOwnedAndMemberRepositories().ConfigureAwait(false));
     }
 }
示例#54
0
 /// <inheritdoc/>
 protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
 {
     if (Request != null && Options != null)
     {
         var requestValue = Request.GetValue(dc.State);
         var optionsValue = Options.GetValue(dc.State);
         return(await gitHubClient.Activity.Starring.GetAllForCurrent(requestValue, optionsValue).ConfigureAwait(false));
     }
     if (Options != null)
     {
         var optionsValue = Options.GetValue(dc.State);
         return(await gitHubClient.Activity.Starring.GetAllForCurrent(optionsValue).ConfigureAwait(false));
     }
     if (Request != null)
     {
         var requestValue = Request.GetValue(dc.State);
         return(await gitHubClient.Activity.Starring.GetAllForCurrent(requestValue).ConfigureAwait(false));
     }
     else
     {
         return(await gitHubClient.Activity.Starring.GetAllForCurrent().ConfigureAwait(false));
     }
 }
示例#55
0
 /// <inheritdoc/>
 protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
 {
     if (Since != null && Options != null)
     {
         var sinceValue   = Since.GetValue(dc.State);
         var optionsValue = Options.GetValue(dc.State);
         return(await gitHubClient.Gist.GetAllStarred(sinceValue, optionsValue).ConfigureAwait(false));
     }
     if (Options != null)
     {
         var optionsValue = Options.GetValue(dc.State);
         return(await gitHubClient.Gist.GetAllStarred(optionsValue).ConfigureAwait(false));
     }
     if (Since != null)
     {
         var sinceValue = Since.GetValue(dc.State);
         return(await gitHubClient.Gist.GetAllStarred(sinceValue).ConfigureAwait(false));
     }
     else
     {
         return(await gitHubClient.Gist.GetAllStarred().ConfigureAwait(false));
     }
 }
        private GitCommitResult CheckCredentials(ref Octokit.GitHubClient client, ref IReadOnlyList <RepositoryContent> repositoryContents)
        {
            if (!CheckLoginData())
            {
                return new GitCommitResult {
                           Status = GitCommitStatus.AuthMissing
                }
            }
            ;

            client = new Octokit.GitHubClient(new ProductHeaderValue(AppName))
            {
                Credentials = string.IsNullOrEmpty(_settings.Token) ? new Credentials(_settings.User, _settings.Password) : new Credentials(_settings.Token)
            };

            try
            {
                repositoryContents = client.Repository.Content.GetAllContents(RepositoryOwner, Repository).Result;
            }
            catch (Exception e)
            {
                if (e.InnerException != null && e.InnerException.GetType() == typeof(AuthorizationException))
                {
                    return(new GitCommitResult {
                        Status = GitCommitStatus.AuthFailed
                    });
                }

                return(new GitCommitResult {
                    Status = GitCommitStatus.Error, ErrorMsg = e.Message
                });
            }

            return(new GitCommitResult {
                Status = GitCommitStatus.Success
            });
        }
示例#57
0
        public static async Task <IEnumerable <Link> > GetLinks()
        {
            var githubClient = new Octokit.GitHubClient(new ProductHeaderValue("AppyLinks"));

            githubClient.Credentials = new Octokit.Credentials(LocalSettings.GithubAuthorizationToken);

            var allGists = await githubClient.Gist.GetAll();

            var appyLinksGist = allGists.Where(gist => String.Equals(gist.Description, "AppyLinks", StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (appyLinksGist == null)
            {
                throw new KeyNotFoundException("Could not find gist.");
            }

            //parse gist for links
            //TODO: support multiple files, and split by file so user can group
            var appyLinksGistFull = await githubClient.Gist.Get(appyLinksGist.Id);

            var content = appyLinksGistFull.Files.Select(file => file.Value.Content).FirstOrDefault();

            if (content == null)
            {
                throw new KeyNotFoundException("Could not find any files in gist.");
            }

            //parse
            var rawLinks = content.Split(new[] { Environment.NewLine + Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            Debug.WriteLine("Found " + rawLinks.Length + " raw links.");
            var links = rawLinks.Select(rawLink => rawLink.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                        .Select(StringPairToLink).Where(item => item != null);

            Debug.WriteLine("Parsed to " + links.Count() + " links.");

            return(links);
        }
示例#58
0
        public static async Task <int> CreateNewIssueAsync(
            string repositoryUrl,
            string issueTitle,
            string issueDescription,
            string personalAccessToken,
            int?milestone = null,
            IEnumerable <string> labels    = null,
            IEnumerable <string> assignees = null)
        {
            (string owner, string repoName) = ParseRepoUri(repositoryUrl);

            Octokit.GitHubClient client    = new Octokit.GitHubClient(new ProductHeaderValue("assets-publisher"));
            Credentials          tokenAuth = new Credentials(personalAccessToken);

            client.Credentials = tokenAuth;

            NewIssue issueToBeCreated = new NewIssue(issueTitle)
            {
                Body      = issueDescription,
                Milestone = milestone
            };

            if (labels is not null)
            {
                issueToBeCreated.Labels.AddRange(labels);
            }

            if (assignees is not null)
            {
                issueToBeCreated.Assignees.AddRange(assignees);
            }

            Issue createdIssue = await client.Issue.Create(owner, repoName, issueToBeCreated);

            return(createdIssue.Number);
        }
 public GitHubClient(IGitHubOptions options)
 {
     octoClient   = new OctoClient(ProductHeader);
     this.options = options;
     LoadCredentials();
 }
示例#60
0
 /// <inheritdoc/>
 protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await gitHubClient.Enterprise.AdminStats.GetStatisticsPages().ConfigureAwait(false));
 }