public SourceWatcherService(IHostingEnvironment env, IConfiguration configuration, IInvokerCacheService invokerCacheService, IGistCacheService gistCacheService, ISearchService searchService)
        {
            SourceWatcherType watcherType;

            if (env.IsProduction())
            {
                string watcherTypeRegistryValue = Registry.GetValue(RegistryConstants.SourceWatcherRegistryPath, RegistryConstants.WatcherTypeKey, 0).ToString();
                if (!Enum.TryParse <SourceWatcherType>(watcherTypeRegistryValue, out watcherType))
                {
                    throw new NotSupportedException($"Source Watcher Type : {watcherTypeRegistryValue} not supported.");
                }
            }
            else
            {
                watcherType = Enum.Parse <SourceWatcherType>(configuration[$"SourceWatcher:{RegistryConstants.WatcherTypeKey}"]);
            }

            switch (watcherType)
            {
            case SourceWatcherType.LocalFileSystem:
                _watcher = new LocalFileSystemWatcher(env, configuration, invokerCacheService, gistCacheService);
                break;

            case SourceWatcherType.Github:
                IGithubClient githubClient = new GithubClient(env, configuration);
                _watcher = new GitHubWatcher(env, configuration, invokerCacheService, gistCacheService, githubClient, searchService);
                break;

            default:
                throw new NotSupportedException("Source Watcher Type not supported");
            }
        }
Exemplo n.º 2
0
        public async Task ShouldNotCreateIssue(string repoUrl, string branch, string method, string arguments, DateTime errorOccurredAt, bool success)
        {
            // Not testing SubscriptionUpdateHistoryEntry since this is always "no" for them.
            RepositoryBranchUpdateHistoryEntry repositoryBranchUpdate =
                new RepositoryBranchUpdateHistoryEntry
            {
                Repository = repoUrl,
                Branch     = branch,
                Method     = method,
                Timestamp  = errorOccurredAt,
                Arguments  = arguments,
                Success    = success
            };
            Repository repository = new Repository();

            GithubClient.Setup(x => x.Repository.Get(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(repository);
            Maestro.Data.Models.Subscription subscription = new Maestro.Data.Models.Subscription();
            Context.Subscriptions.Add(subscription);
            Context.SaveChanges();
            Mock <Issue> issue = new Mock <Issue>();

            GithubClient.Setup(x => x.Issue.Create(It.IsAny <long>(), It.IsAny <NewIssue>())).ReturnsAsync(issue.Object);
            Context.RepoBranchUpdateInMemory = new List <RepositoryBranchUpdateHistoryEntry>
            {
                repositoryBranchUpdate
            };
            DependencyUpdateErrorProcessor errorProcessor =
                ActivatorUtilities.CreateInstance <DependencyUpdateErrorProcessor>(Scope.ServiceProvider,
                                                                                   Context);
            await errorProcessor.ProcessDependencyUpdateErrorsAsync();

            GithubClient.Verify(x => x.Issue.Create(It.IsAny <long>(), It.IsAny <NewIssue>()), Times.Never);
        }
Exemplo n.º 3
0
        public object Post(AddGithubSSHKeyToCurrentUser request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            WebGithubProfile result;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/github/sshkey POST"));

                GithubProfile user    = GithubProfile.FromId(context, context.UserId);
                UserTep       userTep = UserTep.FromId(context, context.UserId);
                userTep.LoadSSHPubKey();
                user.PublicSSHKey = userTep.SshPubKey;
                GithubClient githubClient = new GithubClient(context);
                if (!user.IsAuthorizationTokenValid())
                {
                    throw new UnauthorizedAccessException("Invalid token");
                }
                if (user.PublicSSHKey == null)
                {
                    throw new UnauthorizedAccessException("No available public ssh key");
                }
                githubClient.AddSshKey("Terradue ssh key", user.PublicSSHKey, user.Name, user.Token);
                context.LogDebug(this, string.Format("User {0} added Terradue ssh key to his github account", userTep.Username));
                result = new WebGithubProfile(user);
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(result);
        }
Exemplo n.º 4
0
        public async Task TestGetRepos()
        {
            const string reposResp = "[{\"id\": 221949625," +
                                     "\"name\": \"Jija\"," +
                                     "\"html_url\": \"https://github.com/7Nikita/Jija\"," +
                                     "\"owner\": {" +
                                     "\"login\": \"7Nikita\"," +
                                     "\"avatar_url\": \"https://avatars1.githubusercontent.com/u/20500960?v=4\"," +
                                     "\"html_url\": \"https://github.com/7Nikita\"" +
                                     "}}" +
                                     "]";

            _server.Given(Request.Create()
                          .WithPath("/user/repos")
                          .UsingGet()
                          )
            .RespondWith(Response.Create()
                         .WithStatusCode(250)
                         .WithBody(reposResp)
                         );

            _client = new GithubClient(_config, _httpClient)
            {
                Token = "testToken", ApiUrl = _server.Urls[0]
            };

            var reposInfo = await _client.GetRepos();

            Assert.AreEqual(1, reposInfo.Count);
        }
Exemplo n.º 5
0
        public async Task TestGetUserInfo()
        {
            const string userResp = "{" +
                                    "\"login\": \"7Nikita\"," +
                                    "\"avatar_url\": \"https://avatars1.githubusercontent.com/u/20500960?v=4\"," +
                                    "\"html_url\": \"https://github.com/7Nikita\"," +
                                    "\"bio\": null" +
                                    "}";

            _server.Given(Request.Create()
                          .WithPath("/user")
                          .UsingGet()
                          )
            .RespondWith(Response.Create()
                         .WithStatusCode(250)
                         .WithBody(userResp)
                         );

            _client = new GithubClient(_config, _httpClient)
            {
                Token = "testToken", ApiUrl = _server.Urls[0]
            };
            var userInfo = await _client.GetUserInfo();

            Assert.AreEqual("7Nikita", userInfo.login);
            Assert.AreEqual("https://github.com/7Nikita", userInfo.html_url);
        }
Exemplo n.º 6
0
            private static async Task CheckMissedBuildsBetween(DiscordClient discordClient, DiscordChannel compatChannel, string?previousUpdatePr, string?latestUpdatePr, CancellationToken cancellationToken)
            {
                if (!int.TryParse(previousUpdatePr, out var oldestPr) ||
                    !int.TryParse(latestUpdatePr, out var newestPr))
                {
                    return;
                }

                var mergedPrs = await GithubClient.GetClosedPrsAsync(cancellationToken).ConfigureAwait(false); // this will cache 30 latest PRs

                var newestPrCommit = await GithubClient.GetPrInfoAsync(newestPr, cancellationToken).ConfigureAwait(false);

                var oldestPrCommit = await GithubClient.GetPrInfoAsync(oldestPr, cancellationToken).ConfigureAwait(false);

                if (newestPrCommit?.MergedAt == null || oldestPrCommit?.MergedAt == null)
                {
                    return;
                }

                mergedPrs = mergedPrs?.Where(pri => pri.MergedAt.HasValue)
                            .OrderBy(pri => pri.MergedAt !.Value)
                            .SkipWhile(pri => pri.Number != oldestPr)
                            .Skip(1)
                            .TakeWhile(pri => pri.Number != newestPr)
                            .ToList();
                if (mergedPrs is null or {
                    Count : 0
                })
        public async Task CreateIssue()
        {
            RepositoryBranchUpdateHistoryEntry firstError =
                new RepositoryBranchUpdateHistoryEntry
            {
                Repository   = RepoUrl,
                Branch       = BranchOne,
                Method       = "ProcessPendingUpdatesAsync",
                Timestamp    = new DateTime(2200, 1, 1),
                Arguments    = "[Error Message]",
                Success      = false,
                ErrorMessage = "Error Message",
                Action       = "Creating new issue"
            };

            RepositoryBranchUpdateHistoryEntry secondError =
                new RepositoryBranchUpdateHistoryEntry
            {
                Repository   = RepoUrl,
                Branch       = BranchTwo,
                Method       = "ProcessPendingUpdatesAsync",
                Timestamp    = new DateTime(2200, 1, 1),
                Arguments    = "[Arguments]",
                Success      = false,
                ErrorMessage = "ProcessPendingUpdatesAsync error",
                Action       = "Create another issue"
            };

            Context.RepoBranchUpdateInMemory = new List <RepositoryBranchUpdateHistoryEntry>
            {
                firstError, secondError
            };

            Repository repository = new Repository();

            GithubClient.Setup(x => x.Repository.Get(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(repository);
            Mock <Octokit.Issue> issue    = new Mock <Issue>();
            List <NewIssue>      newIssue = new List <NewIssue>();

            GithubClient.Setup(x => x.Issue.Create(It.IsAny <long>(), Capture.In(newIssue))).ReturnsAsync(issue.Object);
            DependencyUpdateErrorProcessor errorProcessor =
                ActivatorUtilities.CreateInstance <DependencyUpdateErrorProcessor>(Scope.ServiceProvider,
                                                                                   Context);
            await errorProcessor.ProcessDependencyUpdateErrorsAsync();

            Assert.Equal(2, newIssue.Count);
            Assert.Equal("DependencyUpdateError", newIssue[0].Labels[0]);
            Assert.Contains(RepoUrl, newIssue[0].Title);
            Assert.Contains(BranchOne, newIssue[0].Body);
            Assert.Contains("ProcessPendingUpdatesAsync", newIssue[0].Body);
            Assert.Contains("1/1/2200 12:00:00 AM", newIssue[0].Body);
            Assert.Contains(RepoUrl, newIssue[0].Body);
            Assert.Equal("DependencyUpdateError", newIssue[1].Labels[0]);
            Assert.Contains(RepoUrl, newIssue[1].Title);
            Assert.Contains(BranchTwo, newIssue[1].Body);
            Assert.Contains("ProcessPendingUpdatesAsync error", newIssue[1].Body);
            Assert.Contains("1/1/2200 12:00:00 AM", newIssue[1].Body);
            Assert.Contains(RepoUrl, newIssue[1].Body);
        }
Exemplo n.º 8
0
        public void GithubClient_GetRepositories_CredentialsFail()
        {
            var helper = new Mock <IWebsiteRequestHelper>();
            //helper.Setup(a => a.GetStringResponse(null, null, null))

            var client = new GithubClient(helper.Object);

            client.GetRepositories();
        }
Exemplo n.º 9
0
        public async Task <bool> Check()
        {
            var client = new GithubClient(Application.ProductName);

            _repository = await client.GetRepositoryAsync("https://api.github.com/repositories/283887091/releases/latest");

            return(new Version(_repository.TagName.Substring(1)) // Remove 'v' from version string
                   .CompareTo(new Version(Application.ProductVersion)) > 0);
        }
        public void SetUp()
        {
            var guard = new GuardService();

            Client     = new GithubClient();
            Converter  = new ContentConverterService(new ConverterTemplates(), guard);
            ApiService = new RestApiService(Client, Converter);
            AuthenticationController = new AuthenticationController(new AuthenticationService(ApiService, Converter));
            RepositoryController     = new RepositoryController(AuthenticationController, new RepositoryService(ApiService, Converter, guard));
        }
        public void GithubClient_SearchRepositories_FormsCorrectUrl()
        {
            // Arrange
            const int    expectedCount = 3;
            const string expectedUrl   =
                "https://api.github.com/search/repositories?q=tetris in:name+language:assembly&sort=stars&order=asc";

            var mockRest = new Mock <IRestClient>();

            mockRest.Setup(rc => rc.Get <GithubResponse>(expectedUrl)).Returns(
                new GithubResponse()
            {
                TotalCount = 3,
                Items      = new List <GithubRepository>()
                {
                    new GithubRepository()
                    {
                        Name     = "Tetris #1",
                        Url      = "Tetris #1",
                        Stars    = 0,
                        FullName = "Tetris #1",
                        Id       = 1,
                        Language = "Assembly"
                    },
                    new GithubRepository()
                    {
                        Name     = "Tetris #2",
                        Url      = "Tetris #2",
                        Stars    = 1,
                        FullName = "Tetris #2",
                        Id       = 2,
                        Language = "Assembly"
                    },
                    new GithubRepository()
                    {
                        Name     = "Tetris #3",
                        Url      = "Tetris #3",
                        Stars    = 2,
                        FullName = "Tetris #3",
                        Id       = 3,
                        Language = "Assembly"
                    }
                }
            }
                );

            var client = new GithubClient(mockRest.Object);

            // Act
            var result = client.SearchRepositories("q=tetris in:name+language:assembly&sort=stars&order=asc");

            // Assert
            Assert.IsNotNull(result, "Result should not be null!");
            Assert.AreEqual(expectedCount, result.Count(), "Result count should be equal to 3!");
        }
Exemplo n.º 12
0
        private static async Task ProcessRepositories(GithubClient github)
        {
            var response = await github.GetData();

            // var data = await response.Content.ReadAsAsync<JObject>();
            var data = await response.Content.ReadAsStringAsync();

            var repositories = JsonConvert.DeserializeObject <IEnumerable <Repo> >(data);

            PrintRepositories(repositories);
        }
Exemplo n.º 13
0
        public async Task Test_API_GetRepositories()
        {
            var authToken = _configuration["githubAuthToken"];

            var client = new GithubClient(new GithubClientOptions(authToken));

            var result = await client.GetUserRepos("ThatBlokeCalledJay");

            Assert.IsTrue(result.Success, "Request was successful.");
            Assert.IsTrue(result.Content.Repositories.Count > 0, "Found repositories.");
        }
Exemplo n.º 14
0
        public async Task GetCodeFromGitHubFile(string filename = "", bool isFromPublic = false)
        {
            var sw = new Stopwatch();

            sw.Start();
            string code = isFromPublic ? await UpdateFromPublicRepo() : await GithubClient.CodeFromGithub(filename);

            sw.Stop();
            Console.WriteLine($"GitHub file content retrieved in {sw.ElapsedMilliseconds}ms \r\n Returned: {code}");
            await UpdateCodeSnippet(code);
        }
Exemplo n.º 15
0
        public async Task Should_Add_User_To_Cache()
        {
            var handlerMock = GetHandlerMock();
            var httpClient  = new GithubClient(handlerMock.Object);
            var cache       = new MemoryCache("cache");
            var userService = new UserService(new UserRepository(cache, httpClient));

            await userService.GetUser("test");

            Assert.IsTrue(cache.Contains("test"));
        }
Exemplo n.º 16
0
        private async Task Submit()
        {
            var codeFile = await GithubClient.CodeFromPublicRepo(FormModel.GithubName, FormModel.RepoName,
                                                                 FormModel.FilePath);

            var parameters = new ModalDialogParameters
            {
                { "FileCode", codeFile }
            };

            ModalService.Close(true, parameters);
        }
Exemplo n.º 17
0
        public void GithubClient_GetRepositories_JsonFormatFail()
        {
            var helper = new Mock <IWebsiteRequestHelper>();

            helper.Setup(a => a.GetStringResponse("azurecoder", "adghjsueu374", "blah"))
            .Returns(JsonResponseIncorrect);
            var client = new GithubClient(helper.Object)
            {
                Username = "******",
                Password = "******"
            };
            var list = client.GetRepositories("blah");
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post")]
            HttpRequest request,
            ILogger logger)
        {
            logger.LogInformation("Initialize called.");

            try
            {
                var configuration = new Configuration.Configuration();
                var fileParser    = new FileParser();

                // Get all the files from GitHub
                var githubClient = new GithubClient(
                    new HttpClient(),
                    configuration.GithubRepositoryName,
                    configuration.GithubRepositoryOwner,
                    configuration.GithubAccessToken);
                var githubService = new Services.GithubService(githubClient, fileParser);
                var codeFiles     = await githubService.GetCodeFilesAsync();

                // Persist all code sample files
                var connectionString   = configuration.RepositoryConnectionString;
                var codeFileRepository = await CodeFileRepositoryProvider.CreateCodeFileRepositoryInstance(connectionString);

                var fragmentsToUpsert = new List <CodeFragment>();

                foreach (var codeFile in codeFiles)
                {
                    await codeFileRepository.StoreAsync(codeFile);

                    fragmentsToUpsert.AddRange(codeFile.CodeFragments);
                }

                // Store code fragment event
                var eventDataRepository = await EventDataRepository.CreateInstance(connectionString);

                await new EventDataService(eventDataRepository)
                .SaveCodeFragmentEventAsync(FunctionMode.Initialize, fragmentsToUpsert);

                return(new OkObjectResult("Initialized."));
            }
            catch (Exception exception)
            {
                // This try-catch is required for correct logging of exceptions in Azure
                var message = $"Exception: {exception.Message}\nStack: {exception.StackTrace}";

                throw new GithubServiceException(message);
            }
        }
Exemplo n.º 19
0
        public async Task CanGetUserAsyncFromGithubClientApi(string username, string fullName)
        {
            // Arrange
            var _client = new HttpClient();

            _client.BaseAddress = new Uri("https://api.github.com");
            _client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Yolo", "0.1.0"));
            var _githubClient = new GithubClient(_client);

            // Act
            var response = await _githubClient.GetUserAsync(username);

            // Assert
            Assert.Equal(response.Name, fullName);
        }
Exemplo n.º 20
0
        public void GithubClient_GetRepositories_List()
        {
            var helper = new Mock <IWebsiteRequestHelper>();

            helper.Setup(a => a.GetStringResponse("azurecoder", "adghjsueu374", "blah"))
            .Returns(JsonResponseCorrect);
            var client = new GithubClient(helper.Object)
            {
                Username = "******",
                Password = "******"
            };
            var list = client.GetRepositories("blah");

            list.Count.Should().Be(5);
            list["b"].Should().Be("a");
        }
Exemplo n.º 21
0
        public async Task TestGetOauthToken()
        {
            const string oauthResp = "{ \"access_token\": \"31ccdad924fb247281124be8691955a85054d833\" }";

            _server.Given(Request.Create()
                          .WithPath("/")
                          .UsingPost()
                          )
            .RespondWith(Response.Create()
                         .WithStatusCode(250)
                         .WithBody(oauthResp)
                         );

            _client = new GithubClient(_config, _httpClient)
            {
                OauthUrl = _server.Urls[0]
            };

            var oauthToken = await _client.GetOauthToken("sampleToken");

            Assert.AreEqual("31ccdad924fb247281124be8691955a85054d833", oauthToken.access_token);
        }
Exemplo n.º 22
0
        public async void GetUserByLogin_InputNonExisting_ReturnNull()
        {
            var configuration     = new HttpConfiguration();
            var clientHandlerStub = new DelegatingHandlerStub((request, cancellationToken) =>
            {
                request.SetConfiguration(configuration);
                var response = request.CreateResponse(
                    HttpStatusCode.NotFound,
                    ""
                    );
                return(Task.FromResult(response));
            });
            var client = new HttpClient(clientHandlerStub);

            client.BaseAddress = new Uri("https://api.github.com/");

            var githubClient = new GithubClient(client);

            var githubUser = await githubClient.GetUserByLogin("asdafdsf");

            Assert.Null(githubUser);
        }
        public async Task Test_ParseErrorData()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When(HttpMethod.Get, "https://test.com/users/TestUser/repos")
            .Respond(HttpStatusCode.BadRequest, (m) => new StringContent(JsonConvert.SerializeObject(CreateError()), Encoding.UTF8, "application/json"));

            var httpClient = new HttpClient(mockHttp)
            {
                BaseAddress = new Uri("https://test.com")
            };

            var clientOptions = new GithubClientOptions(httpClient);

            var client = new GithubClient(clientOptions);

            var result = await client.GetUserRepos("TestUser");

            Assert.IsFalse(result.Success, "Is failed response.");
            Assert.AreEqual(HttpStatusCode.BadRequest, result.ResponseCode);
            Assert.AreEqual("https://docs.com", result.DocumentationUrl);
            Assert.AreEqual("Naughty Robot", result.Message);
        }
        public async Task Test_ParseResponseData()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When(HttpMethod.Get, "https://test.com/users/TestUser/repos")
            .Respond("application/json", JsonConvert.SerializeObject(CreateRepoList()));

            var httpClient = new HttpClient(mockHttp)
            {
                BaseAddress = new Uri("https://test.com")
            };

            var clientOptions = new GithubClientOptions(httpClient);

            var client = new GithubClient(clientOptions);

            var result = await client.GetUserRepos("TestUser");

            Assert.IsTrue(result.Success, "Is success response.");
            Assert.AreEqual(HttpStatusCode.OK, result.ResponseCode);

            Assert.AreEqual(1, result.Content.Repositories.Count, "A single test repo was returned.");
        }
Exemplo n.º 25
0
        public async Task Should_Go_To_Api_If_Not_Cached()
        {
            var handlerMock = GetHandlerMock();
            var httpClient  = new GithubClient(handlerMock.Object);
            var userService = new UserService(new UserRepository(new MemoryCache("cache"), httpClient));


            var result = await userService.GetUser("test");


            var expectedUri1 = new Uri("https://api.github.com/users/test");
            var expectedUri2 = new Uri("https://api.github.com/users/test/repos");

            handlerMock.Protected().Verify(
                "SendAsync",
                Times.Exactly(2),
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Get &&
                                               (req.RequestUri == expectedUri1 || req.RequestUri == expectedUri2)
                                               ),
                ItExpr.IsAny <CancellationToken>()
                );
        }
Exemplo n.º 26
0
        public void UpdateCheck()
        {
            try
            {
                var update = GithubClient.GetNewRelease(BoxartConfig.Repository, BoxartConfig.Version);

                if (update != null)
                {
                    var result = MessageBox.Show(update.UpdateText,
                                                 "A new update is available!",
                                                 MessageBoxButtons.YesNo,
                                                 MessageBoxIcon.Information);

                    if (result == DialogResult.Yes)
                    {
                        OSHelper.OpenBrowser(BoxartConfig.RepositoryReleasesUrl);
                    }
                }
            }
            catch (Exception e)
            {
                Log($"An error occured while looking for updates. {e.Message}");
            }
        }
Exemplo n.º 27
0
        public async Task ShouldCreateIssue(string repoUrl, string branch, string method, string arguments, DateTime errorOccurredAt, bool success)
        {
            // Not testing SubscriptionUpdateHistoryEntry since this is always "yes" for them.
            RepositoryBranchUpdateHistoryEntry repositoryBranchUpdate =
                new RepositoryBranchUpdateHistoryEntry
            {
                Repository = repoUrl,
                Branch     = branch,
                Method     = method,
                Timestamp  = errorOccurredAt,
                Arguments  = arguments,
                Success    = success
            };
            Repository repository = new Repository();

            GithubClient.Setup(x => x.Repository.Get(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(repository);
            Mock <Maestro.Data.Models.Subscription> subscription = new Mock <Maestro.Data.Models.Subscription>();

            subscription.Object.Id = Guid.Parse(SubscriptionId);
            Context.Subscriptions.Add(subscription.Object);
            Context.SaveChanges();
            Mock <Issue> issue = new Mock <Issue>();

            //Shared mocks works for Xunit as it creates a separate file for each test, but for Nunit there will be a conflict.
            //We need to take care of this if we port to Nunit in future.
            GithubClient.Setup(x => x.Issue.Create(It.IsAny <long>(), It.IsAny <NewIssue>())).ReturnsAsync(issue.Object);
            Context.RepoBranchUpdateInMemory = new List <RepositoryBranchUpdateHistoryEntry> {
                repositoryBranchUpdate
            };
            DependencyUpdateErrorProcessor errorProcessor =
                ActivatorUtilities.CreateInstance <DependencyUpdateErrorProcessor>(Scope.ServiceProvider,
                                                                                   Context);
            await errorProcessor.ProcessDependencyUpdateErrorsAsync();

            GithubClient.Verify(x => x.Issue.Create(It.IsAny <long>(), It.IsAny <NewIssue>()), Times.Once);
        }
Exemplo n.º 28
0
 // The 'typed client' is now available from the service provider
 public async Task <JObject> Example2([FromServices] GithubClient client)
 {
     return(await client.GetIndexAsync());
 }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post")]
            HttpRequest request,
            ILogger logger)
        {
            logger.LogInformation("Update called.");

            try
            {
                var configuration = new Configuration.Configuration();
                var fileParser    = new FileParser();

                // Get all the files from GitHub
                var githubClient = new GithubClient(
                    new HttpClient(),
                    configuration.GithubRepositoryName,
                    configuration.GithubRepositoryOwner,
                    configuration.GithubAccessToken);
                var githubService = new Services.GithubService(githubClient, fileParser);

                // Read Webhook message from GitHub
                WebhookMessage webhookMessage;
                using (var streamReader = new StreamReader(request.Body, Encoding.UTF8))
                {
                    var requestBody = streamReader.ReadToEnd();
                    webhookMessage = JsonConvert.DeserializeObject <WebhookMessage>(requestBody);
                }

                // Get paths to added/modified/deleted files
                var parser = new WebhookParser();
                var(addedFiles, modifiedFiles, removedFiles) = parser.ExtractFiles(webhookMessage);

                var connectionString   = configuration.RepositoryConnectionString;
                var codeFileRepository = await CodeFileRepositoryProvider.CreateCodeFileRepositoryInstance(connectionString);

                var fileProcessor = new FileProcessor(githubService, codeFileRepository);

                var addedFragmentsFromNewFiles = await fileProcessor.ProcessAddedFiles(addedFiles);

                var(addedFragmentsFromModifiedFiles, modifiedFragments, removedFragmentsFromModifiedFiles) =
                    await fileProcessor.ProcessModifiedFiles(modifiedFiles, logger);

                var removedFragmentsFromDeletedFiles = await fileProcessor.ProcessRemovedFiles(removedFiles);

                var allAddedFragments = addedFragmentsFromNewFiles
                                        .Concat(addedFragmentsFromModifiedFiles);
                var allRemovedFragments = removedFragmentsFromModifiedFiles
                                          .Concat(removedFragmentsFromDeletedFiles);

                // Store code fragment event
                var eventDataRepository = await EventDataRepository.CreateInstance(connectionString);

                await new EventDataService(eventDataRepository)
                .SaveCodeFragmentEventAsync(
                    FunctionMode.Update,
                    allAddedFragments,
                    modifiedFragments,
                    allRemovedFragments
                    );

                return(new OkObjectResult("Updated."));
            }
            catch (Exception exception)
            {
                // This try-catch is required for correct logging of exceptions in Azure
                var message = $"Exception: {exception.Message}\nStack: {exception.StackTrace}";

                throw new GithubServiceException(message);
            }
        }
Exemplo n.º 30
0
 public void initialize()
 {
     this.client = new GithubClient();
     client.Authenticate(this.userName, this.password);
 }
Exemplo n.º 31
0
        internal override void ExecuteCommand()
        {
            if (Git && GitHub)
            {
                throw new Exception("Please run the command with either -Git or -GitHub options. Not both.");
            }

            if (Git)
            {
                PublishingUsername = GetPublishingUser();
            }

            WebSpaces webspaceList = null;

            InvokeInOperationContext(() => { webspaceList = RetryCall(s => Channel.GetWebSpacesWithCache(s)); });
            if (webspaceList.Count == 0)
            {
                // If location is still empty or null, give portal instructions.
                string error = string.Format(Resources.PortalInstructions, Name);
                throw new Exception(!Git
                    ? error
                    : string.Format("{0}\n{1}", error, Resources.PortalInstructionsGit));
            }

            WebSpace webspace = null;
            if (string.IsNullOrEmpty(Location))
            {
                // If no location was provided as a parameter, try to default it
                webspace = webspaceList.FirstOrDefault();
                if (webspace == null)
                {
                    // Use east us
                    webspace = new WebSpace
                    {
                        Name = "eastuswebspace",
                        GeoRegion = "East US",
                        Subscription = CurrentSubscription.SubscriptionId,
                        Plan = "VirtualDedicatedPlan"
                    };
                }
            }
            else
            {
                // Find the webspace that corresponds to the georegion
                webspace = webspaceList.FirstOrDefault(w => w.GeoRegion.Equals(Location, StringComparison.OrdinalIgnoreCase));
                if (webspace == null)
                {
                    // If no webspace corresponding to the georegion was found, attempt to create it
                    webspace = new WebSpace
                    {
                        Name = Regex.Replace(Location.ToLower(), " ", "") + "webspace",
                        GeoRegion = Location,
                        Subscription = CurrentSubscription.SubscriptionId,
                        Plan = "VirtualDedicatedPlan"
                    };
                }
            }

            SiteWithWebSpace website = new SiteWithWebSpace
            {
                Name = Name,
                HostNames = new[] { Name + General.AzureWebsiteHostNameSuffix },
                WebSpace = webspace.Name,
                WebSpaceToCreate = webspace
            };

            if (!string.IsNullOrEmpty(Hostname))
            {
                List<string> newHostNames = new List<string>(website.HostNames);
                newHostNames.Add(Hostname);
                website.HostNames = newHostNames.ToArray();
            }

            try
            {
                InvokeInOperationContext(() => RetryCall(s => Channel.CreateSite(s, webspace.Name, website)));

                // If operation succeeded try to update cache with new webspace if that's the case
                if (webspaceList.FirstOrDefault(ws => ws.Name.Equals(webspace.Name)) == null)
                {
                    Cache.AddWebSpace(CurrentSubscription.SubscriptionId, webspace);
                }

                Cache.AddSite(CurrentSubscription.SubscriptionId, website);
            }
            catch (ProtocolException ex)
            {
                // Handle site creating indepently so that cmdlet is idempotent.
                string message = ProcessException(ex, false);
                if (message.Equals(string.Format(Resources.WebsiteAlreadyExistsReplacement,
                                                 Name)) && (Git || GitHub))
                {
                    WriteWarning(message);
                }
                else
                {
                    SafeWriteError(new Exception(message));
                }
            }

            if (Git || GitHub)
            {
                try
                {
                    Directory.SetCurrentDirectory(SessionState.Path.CurrentFileSystemLocation.Path);
                }
                catch (Exception)
                {
                    // Do nothing if session state is not present
                }

                LinkedRevisionControl linkedRevisionControl = null;
                if (Git)
                {
                    linkedRevisionControl = new GitClient(this);
                }
                else if (GitHub)
                {
                    linkedRevisionControl = new GithubClient(this, GithubCredentials, GithubRepository);
                }

                linkedRevisionControl.Init();

                CopyIisNodeWhenServerJsPresent();
                UpdateLocalConfigWithSiteName(Name, webspace.Name);

                InitializeRemoteRepo(webspace.Name, Name);

                Site updatedWebsite = RetryCall(s => Channel.GetSite(s, webspace.Name, Name, "repositoryuri,publishingpassword,publishingusername"));
                if (Git)
                {
                    AddRemoteToLocalGitRepo(updatedWebsite);
                }

                linkedRevisionControl.Deploy(updatedWebsite);
                linkedRevisionControl.Dispose();
            }
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            ConsoleEx.WriteGreenLine(BoxartConfig.Credits);
            Console.WriteLine();

            var config = new BoxartConfig();

            try
            {
                config.Load();
            }
            catch { Console.WriteLine("Could not load TwilightBoxart.ini - using defaults."); }

            if (!config.DisableUpdates)
            {
                try
                {
                    var update = GithubClient.GetNewRelease(BoxartConfig.Repository, BoxartConfig.Version);

                    if (update != null)
                    {
                        ConsoleEx.WriteGreenLine(update.UpdateText);

                        if (ConsoleEx.YesNoMenu())
                        {
                            OSHelper.OpenBrowser(BoxartConfig.RepositoryReleasesUrl);
                        }

                        Console.WriteLine();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Could not check for updates: {e.Message}");
                }
            }

            if (string.IsNullOrEmpty(config.SdRoot))
            {
                var allDrives = new List <DriveInfo>();
                try
                {
                    allDrives = DriveInfo.GetDrives().Where(c => c.DriveType == DriveType.Removable).ToList();
                }
                catch { }

                var choice = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                if (allDrives.Count > 0)
                {
                    var choices = allDrives.Select(c => c.Name).ToList();
                    choices.Add("Current Directory");
                    var i = ConsoleEx.MenuIndex("Select your SD location: ", true, choices.ToArray());
                    if (i != choices.Count - 1)
                    {
                        choice = allDrives[i].RootDirectory.FullName;
                    }
                }
                else
                {
                    Console.WriteLine("No settings or drives found. Using current directory.");
                }

                config.SdRoot = choice;
            }

            var boxArtPath = config.GetCorrectBoxartPath();

            ConsoleEx.WriteGreenLine("Loaded settings:");
            Console.WriteLine("SDRoot / Roms location: \t" + config.SdRoot);
            Console.WriteLine("BoxArt location: \t\t" + boxArtPath);
            Console.WriteLine();
            if (!ConsoleEx.YesNoMenu("Is this OK?"))
            {
                Console.WriteLine("Please edit TwilightBoxart.ini or insert your SD card and try again.");
                return;
            }
            Console.WriteLine();

            var progress = new Progress <string>(Console.WriteLine);
            var crawler  = new BoxartCrawler(progress);

            config.BoxartPath   = boxArtPath;
            config.SettingsPath = config.GetCorrectSettingsIniPath();
            crawler.DownloadArt(config).Wait();
        }
Exemplo n.º 33
0
 static ConsoleMain()
 {
     _client = new GithubClient();
 }
Exemplo n.º 34
0
 public void SetUp()
 {
     Client = new GithubClient();
 }