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
        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
            }
        }
예제 #3
0
파일: Program.cs 프로젝트: NuGet/Entropy
        static void Main(string[] args)
        {
            if (Parser.Default.ParseArguments(args, options))
            {
                // consume Options instance properties
                if (options.Verbose)
                {
                    Console.WriteLine(options.Organization);
                    Console.WriteLine(options.Repo);
                    Console.WriteLine(options.Milestone);
                }
                else
                {
                    Console.WriteLine("working ...");
                }
            }
            else
            {
                Console.WriteLine(options.GetUsage());
            }

            var tokenAuth = new Credentials(options.GitHubToken);
            client.Credentials = tokenAuth;
            GetChangelog();
            Console.ReadLine();
        }
예제 #4
0
        public GitHubClient CreateGitHubClient()
        {
            var creds = new Credentials(Username, Password);
            var github = new GitHubClient(new ProductHeaderValue("ReleaseNotesCompiler")) { Credentials = creds };

            return github;
        }
예제 #5
0
    public string Submit()
    {
        string strReturn      = "";
        var    client         = new GitHubClient(new ProductHeaderValue("ArkansasRepeaterCouncil-site"));
        string githubUsername = System.Configuration.ConfigurationManager.AppSettings["githubUsername"];
        string githubPassword = System.Configuration.ConfigurationManager.AppSettings["githubPassword"];
        var    basicAuth      = new Octokit.Credentials(githubUsername, githubPassword);

        client.Credentials = basicAuth;
        var newIssue = new NewIssue(this.title);

        newIssue.Body = this.body;
        Task <Octokit.Issue> issue = client.Issue.Create("ArkansasRepeaterCouncil", "website", newIssue);

        issue.Wait(15000);

        try
        {
            strReturn = issue.Result.HtmlUrl;
        }
        catch (Exception)
        {
            strReturn = "";
        }


        return(strReturn);
    }
예제 #6
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;
            }
        }
예제 #7
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;
        }
예제 #8
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;
        }
예제 #9
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);
        }
    }
        protected override void OnHandleIntent(Intent intent)
        {
            if (!CrossConnectivity.Current.IsConnected)
            {
                return;
            }
            try
            {
                var client = new GitHubClient(new ProductHeaderValue("gitit"));

                if (CrossSecureStorage.Current.HasKey("OAuthToken"))
                {
                    _passwordCredential = new Credentials(CrossSecureStorage.Current.GetValue("OAuthToken"));
                    client.Credentials  = new Credentials(_passwordCredential.Password);
                    var notificationRequest = new NotificationsRequest
                    {
                        Since =
                            DateTimeOffset.Now.Subtract(new TimeSpan(1, 0, 0, 0))
                    };

                    var serverNotifications = client.Activity.Notifications.GetAllForCurrent(notificationRequest).Result;
                    if (serverNotifications.Count <= 0)
                    {
                        return;
                    }

                    var latestUpdatedAt = DateTime.Parse(serverNotifications[0].UpdatedAt);
                    IEnumerable <Octokit.Notification> notifications = new List <Notification>(0);

                    var prefs       = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
                    var prefsEditor = prefs.Edit();
                    if (prefs.Contains(_lastShowedNotificationKey))
                    {
                        var localUpdatedAt = DateTime.Parse(prefs.GetString(_lastShowedNotificationKey, "null"));
                        notifications = from notification in serverNotifications
                                        where latestUpdatedAt > localUpdatedAt
                                        select notification;
                    }
                    prefsEditor.PutString(_lastShowedNotificationKey, latestUpdatedAt.ToString());
                    prefsEditor.Apply();
                    foreach (var notification in notifications)
                    {
                        _title = $"{notification.Subject.Title}";
                        _text  =
                            $"in {notification.Repository.FullName} ({Convert.ToDateTime(notification.UpdatedAt).Humanize()})";

                        var builder = new NotificationCompat.Builder(this)
                                      .SetSmallIcon(Resource.Drawable.ic_stat_newstorelogo_scale_400)
                                      .SetContentTitle(_title)
                                      .SetContentText(_text);

                        var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
                        notificationManager.Notify(1, builder.Build());
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
예제 #11
0
		public GitHubWorker(CommandLineOptions options)
		{
			_options = options;

			var credentials = new Credentials(_options.GitHubAccessToken);
			var connection = new Connection(new ProductHeaderValue("CodeplexIssueMigrator")) { Credentials = credentials };
			_gitHubClient = new GitHubClient(connection);
		}
예제 #12
0
파일: Program.cs 프로젝트: muratg/ghfixer
        public static GitHubClient GetGitHubClient(GHCredentials ghcreds)
        {
            var basicAuth = new Credentials(ghcreds.Username, ghcreds.Password);
            var github = new GitHubClient(new ProductHeaderValue("muratg.ghfixer"));
            github.Credentials = basicAuth;

            return github;
        }
예제 #13
0
 public GithubPoller(IEnumerable<Project> projects, string user,
     string password)
 {
     var creds = new Credentials(user, password);
     var credsStore = new InMemoryCredentialStore(creds);
     this.github = new GitHubClient(new ProductHeaderValue("BuildSharp"),
         credsStore);
     this.projects = projects;
 }
예제 #14
0
        public Syncer(
            Credentials defaultCredentials,
            IWebProxy proxy = null,
            Action<LogEntry> loggerCallback = null)
        {
            logCallBack = loggerCallback ?? NullLogger;

            gw = new GitHubGateway(defaultCredentials, proxy, logCallBack);
        }
예제 #15
0
        public GitHubWrapper(string personalAccessToken)
        {
            if (string.IsNullOrEmpty(personalAccessToken))
            {
                throw new ArgumentNullException(personalAccessToken);
            }

            this.client = new GitHubClient(new ProductHeaderValue("mikeparker-testapp"));
            var authToken = new Credentials(personalAccessToken); // ask user to enter this from ui
            this.client.Credentials = authToken;
        }
예제 #16
0
        public GithubTileBuilder(GitHubApiConfig config)
        {
            _config = config;

            if (IsValid)
            {
                var credentials = new Credentials(config.Token);
                var credentialStore = new InMemoryCredentialStore(credentials);
                _client = new GitHubClient(new ProductHeaderValue("HomepageTile"), credentialStore);
            }
        }
예제 #17
0
            public static string Get_User_Repositories(string user, string app_name, string token)
            {
                var client = new GitHubClient(new ProductHeaderValue(app_name));

                if (!String.IsNullOrEmpty(token))
                {
                    var tokenAuth = new Octokit.Credentials(token);
                    client.Credentials = tokenAuth;
                }
                return(JsonConvert.SerializeObject(client.Repository.GetAllForUser(user).Result));
            }
예제 #18
0
        public void try_ocktokit()
        {
            var basicAuth = new Credentials("jeremydmiller", "FAKE");

            var exporter = new GitHubExporter(basicAuth, AppDomain.CurrentDomain.BaseDirectory.ParentDirectory().ParentDirectory().AppendPath("GitHub"));

            //exporter.Export("darthfubumvc", "HtmlTags");
            //exporter.Export("darthfubumvc", "FubuCore");
            //exporter.Export("darthfubumvc", "Bottles");
            //exporter.Export("darthfubumvc", "FubuMVC");
            //exporter.Export("structuremap", "structuremap");
            //exporter.Export("storyteller", "storyteller");
        }
예제 #19
0
        private GitHubClient create_git_hub_client()
        {
            // assume that these values will be correctly set
            Credentials credentials;
            if (!string.IsNullOrWhiteSpace(_configuration.GitHubToken)) credentials = new Credentials(_configuration.GitHubToken);
            else credentials = new Credentials(_configuration.GitHubUserName, _configuration.GitHubPassword);

            var gitHubClient = new GitHubClient(new ProductHeaderValue("ChocolateyPackageVerifier"))
            {
                Credentials = credentials
            };
            return gitHubClient;
        }
        public async Task CheckPullRequest()
        {
            var client    = new GitHubClient(new ProductHeaderValue("GithubAutoUpdatePR"));
            var tokenAuth = new Octokit.Credentials(_account.Token);

            client.Credentials = tokenAuth;

            var username = _account.UserName;

            var userAllReps = await client.Repository.GetAllForCurrent();

            foreach (var repository in userAllReps)
            {
                if (_account.IncludeRepository.Count != 0)
                {
                    if (!_account.IncludeRepository.Contains(repository.Name))
                    {
                        continue;
                    }
                }

                var fullGetRep = await client.Repository.Get(repository.Id);

                var parent = fullGetRep.Parent;
                if (parent == null)
                {
                    continue;
                }

                var parentUser = parent.Owner.Login;
                var parentName = parent.Name;


                var currRepPrs = await client.PullRequest.GetAllForRepository(parentUser, parentName,
                                                                              new PullRequestRequest { State = ItemStateFilter.Open }, ApiOptions.None);


                var currUserOpenPrs = currRepPrs.Where(w => w.User.Login == username).ToList();

                if (currUserOpenPrs.Count > 0)
                {
                    Pull(fullGetRep);
                }

                foreach (var pr in currUserOpenPrs)
                {
                    PullAndRebaseAndPush(pr);
                }
            }
        }
예제 #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped <GitHubClient>(sp =>
            {
                var TokenAuth      = new Octokit.Credentials(Configuration["GitHubAccessToken"]);
                var client         = new GitHubClient(new ProductHeaderValue("pdms-metrix"));
                client.Credentials = TokenAuth;

                return(client);
            });

            services.AddSingleton <Splitio.Services.Client.Interfaces.ISplitClient>(getSplitClient());
        }
예제 #22
0
        public static GitHubClient Create(Uri domain, Credentials credentials)
        {
            // Decorate the HttpClient
            //IHttpClient httpClient = new HttpClientAdapter();
            //httpClient = new OctokitCacheClient(httpClient);
            var client = new HttpClientAdapter(CreateMessageHandler);
            var httpClient = new OctokitNetworkClient(client, Locator.Current.GetService<INetworkActivityService>());

            var connection = new Connection(
                new ProductHeaderValue("CodeHub"),
                domain,
                new InMemoryCredentialStore(credentials),
                httpClient,
                new SimpleJsonSerializer());
            return new GitHubClient(connection);
        }
예제 #23
0
        private async Task<IEnumerable<IFile>> ReadAsync()
        {
            List<GitHubFile> files = new List<GitHubFile>();

            var client = new GitHubClient(new ProductHeaderValue(_project));
            var basicAuth = new Credentials(_user, _password);
            client.Credentials = basicAuth;

            var commits = (await client.Repository.Commits.GetAll(_owner, _project)).ToList();

            foreach (var item in commits)
            {
                var commit = await client.Repository.Commits.Get(_owner, _project, item.Sha);

                foreach (var fileItem in commit.Files) 
                {
                    GitHubFile file = files.FirstOrDefault(x => x.Path == fileItem.Filename);
                    if (file == null)
                    {
                        file = new GitHubFile()
                            {
                                Sha = fileItem.Sha,
                                Path = fileItem.Filename,
                                RawDataUrl = fileItem.RawUrl,
                            };

                        files.Add(file);
                    }

                    file.Changes.Add( new Change
                        {
                            AddedLines = fileItem.Additions,
                            DeletedLines = fileItem.Deletions,
                            TotalChanges = fileItem.Changes,
                            ChangeType = fileItem.Status,
                            Date = commit.Commit.Committer.Date
                        });

                }
            }

            files.ForEach(x => x.Date = x.Changes.Min(y => y.Date).Date);

            return files.Cast<IFile>();
        }
예제 #24
0
파일: Program.cs 프로젝트: jaredpar/random
        internal static async Task Go()
        { 
            var items = File.ReadAllText(@"c:\users\jaredpar\jenkins.txt").Trim().Split(':');
            var credentials = new Credentials(items[1]);
            var client = new GitHubClient(new ProductHeaderValue("jaredpar-api-test"));
            client.Connection.Credentials = credentials;

            var request = new RepositoryIssueRequest();
            request.Labels.Add("Area-Compilers");
            request.State = ItemState.Open;
            request.Milestone = "4";

            var issues = await client.Issue.GetAllForRepository("dotnet", "roslyn", request);
            foreach (var issue in issues)
            {
                var name = issue.User.Name ?? "unassigned";
                Console.WriteLine(issue.Url);
            }
        }
        public void CreatePullRequest(string pullRequestTitle)
        {
            // we will need to use octokit for this
            Console.WriteLine($"Sending pull request for {_changesBranch.FriendlyName} -> {_baseBranch.FriendlyName}");

            var githubCredentials = new Octokit.Credentials(_credentials.Username, _credentials.Password);

            var client = new GitHubClient(new ProductHeaderValue("MassPullRequest"))
            {
                Credentials = githubCredentials
            };

            // octokit can only get a repo by owner + name, so we need to chop up the url
            var urlParts = _repositoryUrl.AbsolutePath.Split("/").Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
            var repoName = urlParts.Last();
            var owner    = urlParts[urlParts.Count - 2];

            var pr = new NewPullRequest(pullRequestTitle, _changesBranch.FriendlyName, _baseBranch.FriendlyName);

            client.PullRequest.Create(owner, repoName, pr).Wait();
        }
예제 #26
0
        static async void MainAsync(string[] args)
        {
            const String File = "FILENAME";
            const String repoOwner = "REPO OWNER";
            const String repo = "REPOSITORY";
            const string GitToken = "TOKEN";
            Dictionary<string,string> UserMapping = new Dictionary<string, string> {
                {"JohnDorian", "jDorian"},
                {"BobKelso", "bKelso"},
                {"ElliotReid","eReid"}                
            }; 
            XDocument xdoc = XDocument.Load(File);
            var Git = new GitHubClient(new ProductHeaderValue("JiraImporter"));
            var TokenAuth = new Credentials(GitToken);
            Git.Credentials = TokenAuth;
             
            var items = from p in xdoc.Descendants("item") select p;
            foreach(var i in items)
            {
                Console.WriteLine("Item: " + i.Descendants("summary").First().Value);
                var Issue = new NewIssue(i.Descendants("summary").First().Value);
                Issue.Body = i.Descendants("description").First().Value;                
                Issue.Assignee = UserMapping[i.Descendants("assignee").First().Attribute("username").Value];
                var itask = Git.Issue.Create(repoOwner, repo, Issue);
                var issue = await itask;

                if (i.Descendants("resolution").First().Value == "Done")
                {
                    var issueUpdate = issue.ToUpdate();
                    issueUpdate.State = ItemState.Closed;
                    await Git.Issue.Update(repoOwner, repo, issue.Number, issueUpdate);
                }
                if(i.Descendants("comments").Count()>0)
                    foreach(var comment in i.Descendants("comments").First().Descendants("comment"))
                    {
                        var ctask = Git.Issue.Comment.Create(repoOwner, repo, issue.Number, UserMapping[comment.Attribute("author").Value] + " commented: " + comment.Value);                    
                        var createdComment = await ctask;
                    }                
           }
        }
예제 #27
0
파일: Program.cs 프로젝트: k2moz/First
        static void Main(string[] args)
        {
            #region  Инициализируемся (Асинхронно)
            Console.WriteLine("Идет подключение и парсинг...");
            var github = new GitHubClient(new ProductHeaderValue("MyApp"));
            var basicAuth = new Credentials("k2moz", "89511922779aA"); //Здесь указан мой пароль
            github.Credentials = basicAuth;
            #endregion

            #region Собираем все теги в репозитории (Асинхронно)
            var allTagsTask = github.Repository.GetAllTags("k2moz", "preact");
            var tags = allTagsTask.Result;
            Console.WriteLine("Данные о тегах были получены...");
            #endregion
           
            #region Собираем все коммиты привязанные к тегам (Асинхронно)
            List<GitTagsEx> list = new List<GitTagsEx>();
            foreach (var item in tags)
            {
                var commitTask = github.Repository.Commits.Get("k2moz", "preact", item.Commit.Sha);
                var commit = commitTask.Result;
                list.Add(new GitTagsEx
                {
                    Tag=item.Name,
                    Date=commit.Commit.Author.Date.ToString("R")
                });
            }
            #endregion
            #region Сериализуем и записываем в файл (Синхронно)
            XmlSerializer serializer = new XmlSerializer(typeof(List<GitTagsEx>));
            using (var stream = new FileStream("Ser.xml", System.IO.FileMode.OpenOrCreate))
            {
                Console.WriteLine("Данные сформированы, началась запись в файл");
                    serializer.Serialize(stream, list);
                Console.WriteLine("Данные сохранены");
            }
            #endregion
            //Задержка
            Console.ReadKey();
        }
예제 #28
0
        public async Task SetSessionAccount(GitHubAccount account)
        {
            if (account == null)
            {
                Account = null;
                Client = null;
                GitHubClient = null;
                return;
            }

            try
            {
                var domain = account.Domain ?? Client.DefaultApi;
                var credentials = new Credentials(account.OAuth);
                var oldClient = Client.BasicOAuth(account.OAuth, domain);
                var newClient = OctokitClientFactory.Create(new Uri(domain), credentials);

                var userInfo = await newClient.User.Current();
                account.Name = userInfo.Name;
                account.Email = userInfo.Email;
                account.AvatarUrl = userInfo.AvatarUrl;
                await _accountsRepository.Update(account);

                // Set all the good stuff.
                Client = oldClient;
                GitHubClient = newClient;
                Account = account;

                // Identify for the analytics service
                _analyticsService.Identify(Account.Username);
                _analyticsService.Track("login");
            }
            catch
            {
                Account = null;
                GitHubClient = null;
                Client = null;
                throw;
            }
        }
예제 #29
0
        public async Task PublishToGitAsync(string json)
        {
            var credentials = new Credentials(ConfigurationManager.AppSettings["github_access_token"]);
            var connection = new Connection(new ProductHeaderValue("aptitud.github.io"))
            {
                Credentials = credentials
            };

            var client = new GitHubClient(connection);

            var contents = await client.Repository.Content.GetAllContents("aptitud", "aptitud.github.io", "instagram.json");
            if (JsonIsSame(contents, json))
                return;

            string fileSha = contents.First().Sha;
            await client.Repository.Content.UpdateFile(
                "aptitud",
                "aptitud.github.io",
                "instagram.json",
                new UpdateFileRequest("Update", json, fileSha));

        }
예제 #30
0
            public static string Get_Basic_Info(string app_name, int repo_id, string token)
            {
                string result;

                try
                {
                    var client = new GitHubClient(new ProductHeaderValue(app_name));

                    if (!String.IsNullOrEmpty(token))
                    {
                        var tokenAuth = new Octokit.Credentials(token);
                        client.Credentials = tokenAuth;
                    }
                    Octokit.Repository repository = client.Repository.Get(repo_id).Result;
                    result = JsonConvert.SerializeObject(repository);
                }
                catch (Exception ex)
                {
                    Logger.Log_Error("AustinsFirstProject.Github_Api.Api.Rest_Api_V3.Repositories.Get_Basic_Info failed. Error Msg: " + ex.Message);
                    result = "";
                }
                return(result);
            }
예제 #31
0
            public static string Get_Commits(string app_name, string _owner, string _repo, string token)
            {
                string result;

                try
                {
                    var client = new GitHubClient(new ProductHeaderValue(app_name));

                    if (!String.IsNullOrEmpty(token))
                    {
                        var tokenAuth = new Octokit.Credentials(token);
                        client.Credentials = tokenAuth;
                    }
                    IReadOnlyList <Octokit.GitHubCommit> commits = client.Repository.Commit.GetAll(_owner, _repo).Result;
                    result = JsonConvert.SerializeObject(commits);
                }
                catch (Exception ex)
                {
                    Logger.Log_Error("AustinsFirstProject.Github_Api.Api.Rest_Api_V3.Repositories.Get_Commits failed. Error Msg: " + ex.Message);
                    result = "";
                }
                return(result);
            }
예제 #32
0
        /// <summary>
        /// Setting GitHub Status using Octokit
        /// </summary>
        /// <returns>
        ///     
        /// </returns>
        public async Task AssignPendingToCommit(JObject data)
        {
            var client = new GitHubClient(new ProductHeaderValue("CaptainHook"));

            var token = ConfigurationManager.AppSettings["github_token"];
            if (token != null)
            {
                var tokenAuth = new Credentials(token);
                client.Credentials = tokenAuth;

                var status = new NewCommitStatus
                {
                    State = CommitState.Pending,
                    Description = "This is a test status"
                };

                var repoOwner = data["repository"]["owner"]["login"].Value<string>();
                var repoName = data["repository"]["name"].Value<string>();
                var commitSha = data["pull_request"]["head"]["sha"].Value<string>();

                var result = await client.Repository.CommitStatus.Create(repoOwner, repoName, commitSha, status);
            }
        }
            public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser()
            {
                var newRepository = new NewRepository { Name = "aName" };
                var response = Substitute.For<IResponse>();
                response.StatusCode.Returns((HttpStatusCode)422);
                response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
                    + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
                    + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}");
                var credentials = new Credentials("haacked", "pwd");
                var connection = Substitute.For<IApiConnection>();
                connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
                connection.Connection.Credentials.Returns(credentials);
                connection.Post<Repository>(Args.Uri, newRepository)
                    .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
                var client = new RepositoriesClient(connection);

                var exception = await AssertEx.Throws<RepositoryExistsException>(
                    async () => await client.Create(newRepository));

                Assert.False(exception.OwnerIsOrganization);
                Assert.Null(exception.Owner);
                Assert.Equal("aName", exception.RepositoryName);
                Assert.Null(exception.ExistingRepositoryWebUrl);
            }
        public List<Commit>  GetCommitsBetweenTag_AndCommit(string tagName, string commitId)
        {
            var credentials = new Credentials(_settings.GithubToken);
            var connection = new Connection(new ProductHeaderValue(_settings.RepositoryName))
            {
                Credentials = credentials
            };

            var client = new GitHubClient(connection);
           
            var results = client.Repository.Commits.Compare(_settings.OrganisationName, _settings.RepositoryName, tagName, commitId);

            var result = results.GetAwaiter().GetResult();

            return result.Commits.Select(commit =>
            {
                var comm = new Commit();

                comm.Message = commit.Commit.Message;
                comm.Authour = commit.Author != null ? commit.Author.Login : "******";
                comm.CommitId = commit.Commit.Sha;
                return comm;
            }).ToList();
        }
예제 #35
0
 public GitHubExporter(Credentials gitHubCredentials, string exportPath)
 {
     _exportPath = exportPath;
     _client = new GitHubClient(new ProductHeaderValue("marten-testing")) {Credentials = gitHubCredentials};
 }
            public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded()
            {
                var newRepository = new NewRepository { Name = "aName", Private = true };
                var response = Substitute.For<IResponse>();
                response.StatusCode.Returns((HttpStatusCode)422);
                response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":"
                    + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository"","
                    + @"""code"":""custom"",""field"":""name"",""message"":"
                    + @"""name can't be private. You are over your quota.""}]}");
                var credentials = new Credentials("haacked", "pwd");
                var connection = Substitute.For<IApiConnection>();
                connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl);
                connection.Connection.Credentials.Returns(credentials);
                connection.Post<Repository>(Args.Uri, newRepository)
                    .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); });
                var client = new RepositoriesClient(connection);

                var exception = await AssertEx.Throws<PrivateRepositoryQuotaExceededException>(
                    async () => await client.Create(newRepository));

                Assert.NotNull(exception);
            }
예제 #37
0
파일: GitHub.cs 프로젝트: ibebbs/Wyam
 /// <summary>
 /// Creates a connection to the GitHub API with OAuth authentication.
 /// </summary>
 /// <param name="token">The token to use.</param>
 public GitHub(string token)
 {
     _credentials = new Credentials(token);
 }
예제 #38
0
파일: GitHub.cs 프로젝트: ibebbs/Wyam
 /// <summary>
 /// Creates a connection to the GitHub API with basic authenticated access.
 /// </summary>
 /// <param name="username">The username to use.</param>
 /// <param name="password">The password to use.</param>
 public GitHub(string username, string password)
 {
     _credentials = new Credentials(username, password);
 }
예제 #39
0
 public ReturnTheDamnCredentialsStore(Credentials creds)
 {
     this.creds = creds;
 }
예제 #40
0
        static async Task MainAsync(string[] args)
        {
            var client = new GitHubClient(new ProductHeaderValue("GitHubClient"));

            // NOTE: not real credentials
            var basicAuth = new Octokit.Credentials("MyGitHubLogin", "MyGitHubPassword");

            client.Credentials = basicAuth;

            //////////////////////////////////////////////
            //
            //  Git Hub Users Api
            //
            //////////////////////////////////////////////

            var user = await client.User.Get("scarlin90");

            Console.WriteLine("GitHub Users API");
            PrintPropertyAndValue(nameof(user.AvatarUrl), user.AvatarUrl);
            PrintPropertyAndValue(nameof(user.Bio), user.Bio);
            PrintPropertyAndValue(nameof(user.Blog), user.Blog);
            PrintPropertyAndValue(nameof(user.Collaborators), user.Collaborators);
            PrintPropertyAndValue(nameof(user.Company), user.Company);
            PrintPropertyAndValue(nameof(user.CreatedAt), user.CreatedAt);
            PrintPropertyAndValue(nameof(user.DiskUsage), user.DiskUsage);
            PrintPropertyAndValue(nameof(user.Email), user.Email);
            PrintPropertyAndValue(nameof(user.Followers), user.Followers);
            PrintPropertyAndValue(nameof(user.Following), user.Following);
            PrintPropertyAndValue(nameof(user.Hireable), user.Hireable);
            PrintPropertyAndValue(nameof(user.HtmlUrl), user.HtmlUrl);
            PrintPropertyAndValue(nameof(user.Id), user.Id);
            PrintPropertyAndValue(nameof(user.LdapDistinguishedName), user.LdapDistinguishedName);
            PrintPropertyAndValue(nameof(user.Location), user.Location);
            PrintPropertyAndValue(nameof(user.Login), user.Login);
            PrintPropertyAndValue(nameof(user.Name), user.Name);
            PrintPropertyAndValue(nameof(user.OwnedPrivateRepos), user.OwnedPrivateRepos);
            PrintPropertyAndValue(nameof(user.Permissions), user.Permissions);
            PrintPropertyAndValue(nameof(user.Plan), user.Plan);
            PrintPropertyAndValue(nameof(user.PrivateGists), user.PrivateGists);
            PrintPropertyAndValue(nameof(user.PublicGists), user.PublicGists);
            PrintPropertyAndValue(nameof(user.PublicRepos), user.PublicRepos);
            PrintPropertyAndValue(nameof(user.SiteAdmin), user.SiteAdmin);
            PrintPropertyAndValue(nameof(user.Suspended), user.Suspended);
            PrintPropertyAndValue(nameof(user.SuspendedAt), user.SuspendedAt);
            PrintPropertyAndValue(nameof(user.TotalPrivateRepos), user.TotalPrivateRepos);
            PrintPropertyAndValue(nameof(user.Type), user.Type);
            PrintPropertyAndValue(nameof(user.Url), user.Url);


            //////////////////////////////////////////////
            //
            //  Git Hub Issues Api
            //
            //////////////////////////////////////////////

            var issues = await client.Issue.GetAllForCurrent();


            foreach (var issue in issues)
            {
                PrintPropertyAndValue(nameof(issue.Title), issue.Title);
            }

            //try
            //{
            //    var iss = await client.Issue.Create("scarlin90", "WebHookMonitor", new NewIssue("Automated Issue"));
            //}
            //catch(Exception ex)
            //{
            //    await client.Issue.Update("scarlin90", "WebHookMonitor", 2, new IssueUpdate
            //    {
            //        State = ItemState.Closed
            //    });
            //}
        }
예제 #41
0
        static async Task getContributorsAsync(AppData data)
        {
            if (data.Owner == "N/A" || data.RepoName == "N/A") // Something went wrong or not Github Repo.
            {
                Console.WriteLine("Not a Github repo.");
                data.Authors = "N/A";
                finalList.Add(data);
                return;
            }

            //  This starts a GitHubClient. Not sure why I have to pass my username like that.. said so on Library Doc.
            var client = new Octokit.GitHubClient(new ProductHeaderValue("ytrehorn"));

            // OAuth Token authentification. Necessary to have more than 60 requests/h. With token 5000 per hour.
            var tokenAuth = new Octokit.Credentials("60a58f7387e72c630f2fc0e073a86a595ce78efb"); // NOTE: Token for "ytrehorn". Please don't abuse :)

            client.Credentials = tokenAuth;                                                      // Save token into current client session.

            // Read Only List of all the contributors.
            IReadOnlyList <RepositoryContributor> contributorList;

            try // Tries to read Contributors. If repo doesn't exist or no contributors available, will throw an exception.
            {
                contributorList = await client.Repository.GetAllContributors(data.Owner, data.RepoName);
            }
            catch (Exception e) // Catch exception and log it in data.Authors. This will then show in the output.
            {
                data.Authors = "Error: " + e.Message + ".";
                finalList.Add(data);
                dataAsStringList.Add(data.ID + "; " + data.Owner + "; " + data.RepoName + "; " + data.Authors);
                return;
            }


            try // Try making a combined author string. try/catch for safety, not sure if necessary..
            {
                string combinedAuthors = "";
                int    counter         = 1;
                foreach (RepositoryContributor x in contributorList)
                {
                    if (counter == contributorList.Count)
                    {
                        combinedAuthors += x.Login;
                    }
                    else
                    {
                        combinedAuthors += x.Login + " ,";
                    }

                    counter++;
                }

                data.Authors = combinedAuthors;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error in " + data.RepoName + ": " + e.Message);
                data.Authors = "N/A";
            }

            // Add to List<Data>. Isn't really used but maybe useful for other people instead of just a .txt file.
            finalList.Add(data);
            // Add all variables of data to one string. Using ";" as .csv delimiter.
            dataAsStringList.Add(data.ID + "; " + data.Owner + "; " + data.RepoName + "; " + data.Authors);
        }
예제 #42
0
 public GitHubUtils(string credentialType, string userName, string password, ILogger logger)
 {
     _logger           = logger;
     _gitCredential    = GetGitCredentials(credentialType, userName, password);
     _gitHubCredential = GetGitHubCredentials(credentialType, userName, password);
 }