Beispiel #1
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;
        }
    public async Task CanCreateEditAndDeleteAGist()
    {
        var newGist = new NewGist { Description = "my new gist", Public = true };

        newGist.Files.Add("myGistTestFile.cs", "new GistsClient(connection).Create();");

        var createdGist = await _fixture.Create(newGist);

        Assert.NotNull(createdGist);
        Assert.Equal(newGist.Description, createdGist.Description);
        Assert.Equal(newGist.Public, createdGist.Public);

        var gistUpdate = new GistUpdate { Description = "my newly updated gist" };
        var gistFileUpdate = new GistFileUpdate
        {
            NewFileName = "myNewGistTestFile.cs",
            Content = "new GistsClient(connection).Edit();"
        };

        gistUpdate.Files.Add("myGistTestFile.cs", gistFileUpdate);

        var updatedGist = await _fixture.Edit(createdGist.Id, gistUpdate);

        Assert.NotNull(updatedGist);
        Assert.Equal(updatedGist.Description, gistUpdate.Description);

        await _fixture.Delete(createdGist.Id);
    }
Beispiel #3
0
        protected override async System.Threading.Tasks.Task<Gist> SaveGist()
        {
            var newGist = new NewGist { Description = Description ?? string.Empty, Public = IsPublic };

            foreach (var file in Files)
                newGist.Files[file.Name.Trim()] = file.Content;

            using (_alertDialogFactory.Activate("Creating Gist..."))
                return await _sessionService.GitHubClient.Gist.Create(newGist);
        }
        private void debug_gist(NewGist gist)
        {
            if (!_configuration.IsDebugMode) return;

            var gistFilesLocation = _fileSystem.combine_paths(_fileSystem.get_temp_path(), ApplicationParameters.Name, "Gist_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_ffff"));
            this.Log().Info(() => "Generating gist files for gist '{0}' at '{1}'.".format_with(gist.Description.escape_curly_braces(), gistFilesLocation));
            _fileSystem.create_directory_if_not_exists(gistFilesLocation);
            _fileSystem.write_file(_fileSystem.combine_paths(gistFilesLocation, "description.txt"), gist.Description, Encoding.UTF8);

            foreach (var file in gist.Files)
            {
                _fileSystem.write_file(_fileSystem.combine_paths(gistFilesLocation, file.Key), file.Value, Encoding.UTF8);
            }
        }
        /// <summary>
        /// Creates a new gist
        /// </summary>
        /// <remarks>
        /// http://developer.github.com/v3/gists/#create-a-gist
        /// </remarks>
        /// <param name="newGist">The new gist to create</param>
        public Task<Gist> Create(NewGist newGist)
        {
            Ensure.ArgumentNotNull(newGist, "newGist");

            //Required to create anonymous object to match signature of files hash.  
            // Allowing the serializer to handle Dictionary<string,NewGistFile> 
            // will fail to match.
            var filesAsJsonObject = new JsonObject();
            foreach(var kvp in newGist.Files)
            {
                filesAsJsonObject.Add(kvp.Key, new { Content = kvp.Value });
            }

            var gist = new { 
                Description = newGist.Description,
                Public = newGist.Public,
                Files = filesAsJsonObject 
            };

            return ApiConnection.Post<Gist>(ApiUrls.Gist(), gist);
        }
Beispiel #6
0
        /// <summary>
        /// Creates a new gist
        /// </summary>
        /// <remarks>
        /// http://developer.github.com/v3/gists/#create-a-gist
        /// </remarks>
        /// <param name="newGist">The new gist to create</param>
        public Task <Gist> Create(NewGist newGist)
        {
            Ensure.ArgumentNotNull(newGist, "newGist");

            //Required to create anonymous object to match signature of files hash.
            // Allowing the serializer to handle Dictionary<string,NewGistFile>
            // will fail to match.
            var filesAsJsonObject = new JsonObject();

            foreach (var kvp in newGist.Files)
            {
                filesAsJsonObject.Add(kvp.Key, new { Content = kvp.Value });
            }

            var gist = new {
                Description = newGist.Description,
                Public      = newGist.Public,
                Files       = filesAsJsonObject
            };

            return(ApiConnection.Post <Gist>(ApiUrls.Gist(), gist));
        }
        IObservable<Gist> OnCreateGist(object unused)
        {
            var newGist = new NewGist
            {
                Description = Description,
                Public = !IsPrivate
            };

            newGist.Files.Add(FileName, SelectedText);

            return gistPublishService.PublishGist(apiClient, newGist)
                .Do(_ => usageTracker.IncrementCreateGistCount().Forget())
                .Catch<Gist, Exception>(ex =>
                {
                    if (!ex.IsCriticalException())
                    {
                        log.Error(ex);
                        var error = StandardUserErrors.GetUserFriendlyErrorMessage(ex, ErrorType.GistCreateFailed);
                        notificationService.ShowError(error);
                    }
                    return Observable.Return<Gist>(null);
                });
        }
        public async Task<Uri> create_gist(string description, bool isPublic, IList<PackageTestLog> logs)
        {
            this.Log().Debug(() => "Creating gist with description '{0}'.".format_with(description.escape_curly_braces()));

            var gitHubClient = this.create_git_hub_client();

            var gist = new NewGist
            {
                Description = description,
                Public = isPublic
            };

            foreach (var log in logs)
            {
                gist.Files.Add(log.Name, log.Contents);
            }

            debug_gist(gist);

            var createdGist = await gitHubClient.Gist.Create(gist); //.ConfigureAwait(continueOnCapturedContext:false);

            return new Uri(createdGist.HtmlUrl);
        }
 /// <summary>
 /// Publishes a gist to GitHub.
 /// </summary>
 /// <param name="apiClient">The client to use to post to GitHub.</param>
 /// <param name="gist">The new gist to post.</param>
 /// <returns>The created gist.</returns>
 public IObservable<Gist> PublishGist(IApiClient apiClient, NewGist gist)
 {
     return Observable.Defer(() => apiClient.CreateGist(gist));
 }
    public async Task CanListGists()
    {
        // Time is tricky between local and remote, be lenient
        var startTime = DateTimeOffset.Now.Subtract(TimeSpan.FromHours(1));
        var newGist = new NewGist { Description = "my new gist", Public = true };

        newGist.Files.Add("myGistTestFile.cs", "new GistsClient(connection).Create();");

        var createdGist = await _fixture.Create(newGist);

        // Test get all Gists
        var gists = await _fixture.GetAll();
        Assert.NotNull(gists);

        // Test get all Gists since startTime
        gists = await _fixture.GetAll(startTime);

        Assert.NotNull(gists);
        Assert.True(gists.Count > 0);

        // Make sure we can successfully request gists for another user
        await _fixture.GetAllForUser("FakeHaacked");
        await _fixture.GetAllForUser("FakeHaacked", startTime);

        // Test starred gists
        await _fixture.Star(createdGist.Id);
        var starredGists = await _fixture.GetAllStarred();

        Assert.NotNull(starredGists);
        Assert.True(starredGists.Any(x => x.Id == createdGist.Id));

        var starredGistsSinceStartTime = await _fixture.GetAllStarred(startTime);
        Assert.NotNull(starredGistsSinceStartTime);
        Assert.True(starredGistsSinceStartTime.Any(x => x.Id == createdGist.Id));

        await _fixture.Delete(createdGist.Id);
    }
        public void PostsToTheCorrectUrl()
        {
            var connection = Substitute.For<IApiConnection>();
            var client = new GistsClient(connection);

            var newGist = new NewGist();
            newGist.Description = "my new gist";
            newGist.Public = true;

            newGist.Files.Add("myGistTestFile.cs", "new GistsClient(connection).Create();");
            
            client.Create(newGist);

            connection.Received().Post<Gist>(Arg.Is<Uri>(u => u.ToString() == "gists"), Arg.Any<object>());
        }
Beispiel #12
0
 public IObservable<Gist> CreateGist(NewGist newGist)
 {
     return gitHubClient.Gist.Create(newGist);
 }
        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;
            }
        }
Beispiel #14
0
        public static int Main(string[] args)
        {
            var config = LoadConfig();

            if (args.Length == 0)
            {
                Usage();
                return -1;
            }

            foreach (var s in args)
            {
                switch (s)
                {
                    case "/?":
                    case "-?":
                    case "-help":
                    case "--help":
                        Usage();
                        return -1;
                }
            }

            var isPublic = config.IsPublic;
            var anonymous = string.IsNullOrEmpty(config.GitHubAccessToken);
            string description = null;
            IReadOnlyList<string> lprunArgs = new string[0];

            for (var i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                    case "--private":
                        isPublic = false;
                        continue;
                    case "--public":
                        isPublic = true;
                        continue;
                    case "--anonymous":
                        anonymous = true;
                        continue;
                    case "--description":
                    case "-d":
                        try
                        {
                            description = args[++i];
                        }
                        catch (IndexOutOfRangeException)
                        {
                            Console.WriteLine("Invalid --description argument");
                            return -1;
                        }
                        continue;
                }

                lprunArgs = new ArraySegment<string>(args, i, args.Length - i);
                break;
            }

            string format = null;
            string queryFileName = null;
            foreach (var s in lprunArgs)
            {
                if (s.StartsWith("-format=", StringComparison.OrdinalIgnoreCase))
                    format = s.Substring(8, s.Length - 8);
                else if (!s.StartsWith("-"))
                {
                    queryFileName = s;
                    break;
                }
            }

            var lprunArgsStr = string.Join(" ",
                lprunArgs.Select(x => string.Concat(
                    "\"",
                    x.Replace("\\", "\\\\").Replace("\"", "\\\""),
                    "\"")));

            if (format == null)
            {
                format = config.Format;
                lprunArgsStr = string.Format("-format={0} {1}", format, lprunArgsStr);
            }

            Console.WriteLine("Running lprun...");

            string stdout;
            using (var p = Process.Start(new ProcessStartInfo(config.LprunPath, lprunArgsStr)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                WorkingDirectory = Environment.CurrentDirectory,
                RedirectStandardOutput = true
            }))
            {
                Contract.Assume(p != null);
                stdout = p.StandardOutput.ReadToEnd();
                p.WaitForExit();

                if (p.ExitCode != 0)
                {
                    Console.WriteLine(stdout);
                    Console.WriteLine("lprun failed");
                    return p.ExitCode;
                }
            }

            Contract.Assume(queryFileName != null, nameof(queryFileName) + " is a valid file name because lprun succeeded");

            Console.WriteLine("Uploading...");

            var queryFileContent = File.ReadAllText(queryFileName);
            var query = LinqPadQuery.Parse(queryFileContent);

            var newGist = new NewGist()
            {
                Description = description,
                Public = isPublic
            };

            var forBlocksorg = isPublic && format.Equals("html", StringComparison.OrdinalIgnoreCase);

            newGist.Files.Add(Path.GetFileName(queryFileName), queryFileContent);
            newGist.Files.Add("source" + GetSourceExtension(query.Kind), query.Source);
            newGist.Files.Add(
                forBlocksorg ? "index.html" : ("result" + GetResultExtension(format)),
                stdout);

            var client = new GitHubClient(userAgent);
            if (!anonymous)
                client.Credentials = new Credentials(config.GitHubAccessToken);

            var gist = client.Gist.Create(newGist).GetAwaiter().GetResult();

            Console.WriteLine();
            Console.WriteLine(gist.HtmlUrl);

            if (forBlocksorg)
                Console.WriteLine("http://bl.ocks.org/{0}/{1}", gist.Owner?.Login ?? "anonymous", gist.Id);

            return 0;
        }