コード例 #1
0
        private int OnExecute(IConsole console)
        {
            var reporter = new ConsoleReporter(console);

            try
            {
                if (OutputPath == null)
                {
                    OutputPath = Environment.CurrentDirectory;
                }

                if (FileHelper.IsNarc(InputPath))
                {
                    NarcArchive.ExtractTppk(InputPath, OutputPath);
                }
                else
                {
                    TppkArchive.Extract(InputPath, OutputPath);
                }

                return(0);
            }
            catch (Exception e)
            {
                reporter.Error(e.Message);

                return(e.HResult);
            }
        }
コード例 #2
0
        private async Task Start()
        {
            var node = new EventStoreNode(new IPEndPoint(
                                              IPAddress.Loopback, 2113), "admin", "changeit");

            var scavenge = await node.FindLastScavenge();

            _reporter.Error(scavenge.Result);
        }
コード例 #3
0
        private static int ImportCertificate(CommandOption import, CommandOption password, ConsoleReporter reporter)
        {
            var manager = CertificateManager.Instance;

            try
            {
                var result = manager.ImportCertificate(import.Value(), password.Value());
                switch (result)
                {
                case ImportCertificateResult.Succeeded:
                    reporter.Output("The certificate was successfully imported.");
                    break;

                case ImportCertificateResult.CertificateFileMissing:
                    reporter.Error($"The certificate file '{import.Value()}' does not exist.");
                    return(MissingCertificateFile);

                case ImportCertificateResult.InvalidCertificate:
                    reporter.Error($"The provided certificate file '{import.Value()}' is not a valid PFX file or the password is incorrect.");
                    return(FailedToLoadCertificate);

                case ImportCertificateResult.NoDevelopmentHttpsCertificate:
                    reporter.Error($"The certificate at '{import.Value()}' is not a valid ASP.NET Core HTTPS development certificate.");
                    return(NoDevelopmentHttpsCertificate);

                case ImportCertificateResult.ExistingCertificatesPresent:
                    reporter.Error($"There are one or more ASP.NET Core HTTPS development certificates present in the environment. Remove them before importing the given certificate.");
                    return(ExistingCertificatesPresent);

                case ImportCertificateResult.ErrorSavingTheCertificateIntoTheCurrentUserPersonalStore:
                    reporter.Error("There was an error saving the HTTPS developer certificate to the current user personal certificate store.");
                    return(ErrorSavingTheCertificate);

                default:
                    break;
                }
            }
            catch (Exception)
            {
                return(ErrorImportingCertificate);
            }

            return(Success);
        }
コード例 #4
0
        private int OnExecute(IConsole console)
        {
            var reporter = new ConsoleReporter(console);

            try
            {
                var rootDirectory = new NarcArchiveRootDirectoryEntry(InputPath);
                NarcArchive.Create(rootDirectory, OutputPath, !NoFilenames);

                return(0);
            }
            catch (Exception e)
            {
                reporter.Error(e.Message);

                return(e.HResult);
            }
        }
コード例 #5
0
        private int OnExecute(IConsole console)
        {
            var reporter = new ConsoleReporter(console);

            try
            {
                var files = new List <string>();
                foreach (var file in InputPaths)
                {
                    if (Directory.Exists(file))
                    {
                        // This is a directory, add all the DDS files in it
                        files.AddRange(Directory.EnumerateFiles(file, "*.dds"));
                    }
                    else
                    {
                        // This is a file (or has wildcards), add all the files that match it
                        var directory = Path.GetDirectoryName(file);
                        if (directory == string.Empty)
                        {
                            directory = Environment.CurrentDirectory;
                        }
                        files.AddRange(Directory.EnumerateFiles(directory, Path.GetFileName(file)));
                    }
                }

                if (File.Exists(OutputPath) && FileHelper.IsNarc(OutputPath))
                {
                    NarcArchive.UpdateTppk(files, OutputPath);
                }
                else
                {
                    TppkArchive.Create(files, OutputPath);
                }

                return(0);
            }
            catch (Exception e)
            {
                reporter.Error(e.Message);

                return(e.HResult);
            }
        }
コード例 #6
0
        public static int Main(string[] args)
        {
            var console = PhysicalConsole.Singleton;
            var app     = new CommandLineApplication <Root>(console, Environment.CurrentDirectory);

            app.Conventions.UseDefaultConventions().UseConstructorInjection(SetUpDi());
            ConfigureHelp(app);

            try
            {
                return(app.Execute(args));
            }
            catch (CommandParsingException ex)
            {
                var reporter = new ConsoleReporter(console);
                reporter.Error($"{ex.Message}{Environment.NewLine}");
                ex.Command.ShowHelp();
                return(1);
            }
        }
コード例 #7
0
        private int OnExecute(IConsole console)
        {
            var reporter = new ConsoleReporter(console);

            try
            {
                if (OutputPath == null)
                {
                    OutputPath = Environment.CurrentDirectory;
                }

                NarcArchive.Extract(InputPath, OutputPath, IgnoreFilenames, justPrint);

                return(0);
            }
            catch (Exception e)
            {
                reporter.Error(e.Message);

                return(e.HResult);
            }
        }
コード例 #8
0
        public void WritesToStandardStreams()
        {
            var testConsole = new TestConsole();
            var reporter    = new ConsoleReporter(testConsole, verbose: true, quiet: false);

            // stdout
            reporter.Verbose("verbose");
            Assert.Equal("verbose" + EOL, testConsole.GetOutput());
            testConsole.Clear();

            reporter.Output("out");
            Assert.Equal("out" + EOL, testConsole.GetOutput());
            testConsole.Clear();

            reporter.Warn("warn");
            Assert.Equal("warn" + EOL, testConsole.GetOutput());
            testConsole.Clear();

            // stderr
            reporter.Error("error");
            Assert.Equal("error" + EOL, testConsole.GetError());
            testConsole.Clear();
        }
コード例 #9
0
    public static int Main(string[] args)
    {
        if (args.Contains("--debug"))
        {
            Console.WriteLine("Press any key to continue...");
            _ = Console.ReadKey();
            var newArgs = new List <string>(args);
            newArgs.Remove("--debug");
            args = newArgs.ToArray();
        }

        try
        {
            var app = new CommandLineApplication
            {
                Name = "dotnet dev-certs"
            };

            app.Command("https", c =>
            {
                var exportPath = c.Option("-ep|--export-path",
                                          "Full path to the exported certificate",
                                          CommandOptionType.SingleValue);

                var password = c.Option("-p|--password",
                                        "Password to use when exporting the certificate with the private key into a pfx file or to encrypt the Pem exported key",
                                        CommandOptionType.SingleValue);

                // We want to force generating a key without a password to not be an accident.
                var noPassword = c.Option("-np|--no-password",
                                          "Explicitly request that you don't use a password for the key when exporting a certificate to a PEM format",
                                          CommandOptionType.NoValue);

                var check = c.Option(
                    "-c|--check",
                    "Check for the existence of the certificate but do not perform any action",
                    CommandOptionType.NoValue);

                var clean = c.Option(
                    "--clean",
                    "Cleans all HTTPS development certificates from the machine.",
                    CommandOptionType.NoValue);

                var import = c.Option(
                    "-i|--import",
                    "Imports the provided HTTPS development certificate into the machine. All other HTTPS developer certificates will be cleared out",
                    CommandOptionType.SingleValue);

                var format = c.Option(
                    "--format",
                    "Export the certificate in the given format. Valid values are Pfx and Pem. Pfx is the default.",
                    CommandOptionType.SingleValue);

                CommandOption trust = null;
                trust = c.Option("-t|--trust",
                                 "Trust the certificate on the current platform. When combined with the --check option, validates that the certificate is trusted.",
                                 CommandOptionType.NoValue);

                var verbose = c.Option("-v|--verbose",
                                       "Display more debug information.",
                                       CommandOptionType.NoValue);

                var quiet = c.Option("-q|--quiet",
                                     "Display warnings and errors only.",
                                     CommandOptionType.NoValue);

                c.HelpOption("-h|--help");

                c.OnExecute(() =>
                {
                    var reporter = new ConsoleReporter(PhysicalConsole.Singleton, verbose.HasValue(), quiet.HasValue());

                    if (verbose.HasValue())
                    {
                        var listener = new ReporterEventListener(reporter);
                        listener.EnableEvents(CertificateManager.Log, System.Diagnostics.Tracing.EventLevel.Verbose);
                    }

                    if (clean.HasValue())
                    {
                        if (exportPath.HasValue() || trust?.HasValue() == true || format.HasValue() || noPassword.HasValue() || check.HasValue() ||
                            (!import.HasValue() && password.HasValue()) ||
                            (import.HasValue() && !password.HasValue()))
                        {
                            reporter.Error(InvalidUsageErrorMessage);
                            return(CriticalError);
                        }
                    }

                    if (check.HasValue())
                    {
                        if (exportPath.HasValue() || password.HasValue() || noPassword.HasValue() || clean.HasValue() || format.HasValue() || import.HasValue())
                        {
                            reporter.Error(InvalidUsageErrorMessage);
                            return(CriticalError);
                        }
                    }

                    if (!clean.HasValue() && !check.HasValue())
                    {
                        if (password.HasValue() && noPassword.HasValue())
                        {
                            reporter.Error(InvalidUsageErrorMessage);
                            return(CriticalError);
                        }

                        if (noPassword.HasValue() && !(format.HasValue() && string.Equals(format.Value(), "PEM", StringComparison.OrdinalIgnoreCase)))
                        {
                            reporter.Error(InvalidUsageErrorMessage);
                            return(CriticalError);
                        }

                        if (import.HasValue())
                        {
                            reporter.Error(InvalidUsageErrorMessage);
                            return(CriticalError);
                        }
                    }

                    if (check.HasValue())
                    {
                        return(CheckHttpsCertificate(trust, reporter));
                    }

                    if (clean.HasValue())
                    {
                        var clean = CleanHttpsCertificates(reporter);
                        if (clean != Success || !import.HasValue())
                        {
                            return(clean);
                        }

                        return(ImportCertificate(import, password, reporter));
                    }

                    return(EnsureHttpsCertificate(exportPath, password, noPassword, trust, format, reporter));
                });
            });

            app.HelpOption("-h|--help");

            app.OnExecute(() =>
            {
                app.ShowHelp();
                return(Success);
            });

            return(app.Execute(args));
        }
        catch
        {
            return(CriticalError);
        }
    }
コード例 #10
0
ファイル: Program.cs プロジェクト: zzekikaya/AspNetCore
        public static int Main(string[] args)
        {
            try
            {
                var app = new CommandLineApplication
                {
                    Name = "dotnet dev-certs"
                };

                app.Command("https", c =>
                {
                    var exportPath = c.Option("-ep|--export-path",
                                              "Full path to the exported certificate",
                                              CommandOptionType.SingleValue);

                    var password = c.Option("-p|--password",
                                            "Password to use when exporting the certificate with the private key into a pfx file",
                                            CommandOptionType.SingleValue);

                    var check = c.Option(
                        "-c|--check",
                        "Check for the existence of the certificate but do not perform any action",
                        CommandOptionType.NoValue);

                    var clean = c.Option(
                        "--clean",
                        "Cleans all HTTPS development certificates from the machine.",
                        CommandOptionType.NoValue);

                    CommandOption trust = null;
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    {
                        trust = c.Option("-t|--trust",
                                         "Trust the certificate on the current platform",
                                         CommandOptionType.NoValue);
                    }

                    var verbose = c.Option("-v|--verbose",
                                           "Display more debug information.",
                                           CommandOptionType.NoValue);

                    var quiet = c.Option("-q|--quiet",
                                         "Display warnings and errors only.",
                                         CommandOptionType.NoValue);

                    c.HelpOption("-h|--help");

                    c.OnExecute(() =>
                    {
                        var reporter = new ConsoleReporter(PhysicalConsole.Singleton, verbose.HasValue(), quiet.HasValue());
                        if ((clean.HasValue() && (exportPath.HasValue() || password.HasValue() || trust?.HasValue() == true)) ||
                            (check.HasValue() && (exportPath.HasValue() || password.HasValue() || clean.HasValue())))
                        {
                            reporter.Error(@"Incompatible set of flags. Sample usages
'dotnet dev-certs https --clean'
'dotnet dev-certs https --check --trust'
'dotnet dev-certs https -ep ./certificate.pfx -p password --trust'");
                        }

                        if (check.HasValue())
                        {
                            return(CheckHttpsCertificate(trust, reporter));
                        }

                        if (clean.HasValue())
                        {
                            return(CleanHttpsCertificates(reporter));
                        }

                        return(EnsureHttpsCertificate(exportPath, password, trust, reporter));
                    });
                });

                app.HelpOption("-h|--help");

                app.OnExecute(() =>
                {
                    app.ShowHelp();
                    return(Success);
                });

                return(app.Execute(args));
            }
            catch
            {
                return(CriticalError);
            }
        }
コード例 #11
0
        public async Task <int> TryRunAsync(string[] args)
        {
            CommandLineOptions options;

            try
            {
                options = CommandLineOptions.Parse(args, this.console);
            }
            catch (CommandParsingException ex)
            {
                new ConsoleReporter(this.console).Warn(ex.Message);
                return(1);
            }

            if (options == null)
            {
                return(1);
            }

            if (options.Help.HasValue())
            {
                return(2);
            }

            if (options.Command == null)
            {
                return(3);
            }

            var repository = new CommandDataRepository(this.provider);

            if (options.Command is LoginCommand.Reset)
            {
                await options.Command.ExecuteAsync(new CommandContext(this.console, null, null, null, repository)).ConfigureAwait(false);

                return(0);
            }

            var data = repository.GetCommandData() ??
                       new CommandData
            {
                Authority  = LoginCommand.DefaultAuthority,
                ServiceUrl = LoginCommand.DefaultService,
            };

            var authority = data.Authority;
            var service   = data.ServiceUrl;

            if (options.Command is LoginCommand loginCommand)
            {
                authority = loginCommand.Authority;
                service   = loginCommand.ServiceUrl;
            }
            else
            {
                this.console.WriteLine("Executing command against ");
                this.console.ForegroundColor = ConsoleColor.White;
                this.console.WriteLine($"Authority: {authority}");
                this.console.WriteLine($"Service Url: {service}");
                this.console.ResetColor();
                this.console.WriteLine("...");
            }

            var discoveryResponse = default(DiscoveryResponse);

            using (var discoveryClient = new DiscoveryClient(authority))
            {
                discoveryResponse = await discoveryClient.GetAsync().ConfigureAwait(false);

                if (discoveryResponse.IsError)
                {
                    await this.console.Error.WriteLineAsync(discoveryResponse.Error).ConfigureAwait(false);

                    return(500);
                }
            }

            var api = default(Api);

            using (var client = new HttpClient())
            {
                try
                {
                    using (var response = client.GetAsync(new Uri($"{service}/platform")).GetAwaiter().GetResult())
                    {
                        response.EnsureSuccessStatusCode();
                        api = JsonConvert.DeserializeObject <Api>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
                    }
                }
                catch (HttpRequestException)
                {
                    await this.console.Error.WriteLineAsync($"Unable to connect to service: {service}.").ConfigureAwait(false);

                    return(500);
                }

                if (api == null)
                {
                    await this.console.Error.WriteLineAsync($"Invalid response from: {service}.").ConfigureAwait(false);

                    return(500);
                }
            }

            using (var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "donut_console"))
                using (var refreshTokenHandler = new RefreshTokenHandler(tokenClient, data.RefreshToken, data.AccessToken))
                    using (var usersClient = new UsersHttpClient(service, refreshTokenHandler))
                        using (var assetAccountsClient = new AssetAccountsHttpClient(service, refreshTokenHandler))
                        {
                            refreshTokenHandler.TokenRefreshed += (sender, e) =>
                            {
                                repository.SetCommandData(
                                    new CommandData
                                {
                                    Authority    = authority,
                                    AccessToken  = e.AccessToken,
                                    RefreshToken = e.RefreshToken,
                                    ServiceUrl   = service,
                                });
                            };

                            var reporter = new ConsoleReporter(this.console, options.Verbose.HasValue(), false);
                            var context  = new CommandContext(this.console, reporter, usersClient, assetAccountsClient, repository);

                            try
                            {
                                await options.Command.ExecuteAsync(context).ConfigureAwait(false);
                            }
                            catch (Exception ex)
                            {
                                reporter.Error(ex.Message);
                                return(500);
                            }
                            finally
                            {
                                this.console.ResetColor();
                            }

                            return(0);
                        }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: LykkeCorp/ironclad-custom
        public async Task <int> TryRunAsync(string[] args)
        {
            CommandLineOptions options;

            try
            {
                options = CommandLineOptions.Parse(args, this.console);
            }
            catch (CommandParsingException ex)
            {
                new ConsoleReporter(this.console).Warn(ex.Message);
                return(1);
            }

            if (options == null)
            {
                return(1);
            }

            if (options.Help.HasValue())
            {
                return(2);
            }

            if (options.Command == null)
            {
                return(3);
            }

            var repository = new CommandDataRepository(this.provider);

            if (options.Command is LoginCommand.Reset)
            {
                await options.Command.ExecuteAsync(new CommandContext(this.console, null, null, null, null, null, null, repository)).ConfigureAwait(false);

                return(0);
            }

            var data = repository.GetCommandData() ??
                       new CommandData
            {
                Authority = LoginCommand.ProductionAuthority,
            };

            var authority = data.Authority;

            if (options.Command is LoginCommand loginCommand)
            {
                authority = loginCommand.Authority;
            }
            else
            {
                this.console.Write("Executing command against ");
                this.console.ForegroundColor = ConsoleColor.White;
                this.console.Write(authority);
                this.console.ResetColor();
                this.console.WriteLine("...");
            }

            var discoveryResponse = default(DiscoveryResponse);

            using (var discoveryClient = new DiscoveryClient(authority))
            {
                discoveryResponse = await discoveryClient.GetAsync().ConfigureAwait(false);

                if (discoveryResponse.IsError)
                {
                    await this.console.Error.WriteLineAsync(discoveryResponse.Error).ConfigureAwait(false);

                    return(500);
                }
            }

            using (var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "auth_console"))
                using (var refreshTokenHandler = new RefreshTokenHandler(tokenClient, data.RefreshToken, data.AccessToken))
                    using (var clientsClient = new ClientsHttpClient(authority, refreshTokenHandler))
                        using (var apiResourcesClient = new ApiResourcesHttpClient(authority, refreshTokenHandler))
                            using (var identityResourcesClient = new IdentityResourcesHttpClient(authority, refreshTokenHandler))
                                using (var rolesClient = new RolesHttpClient(authority, refreshTokenHandler))
                                    using (var usersClient = new UsersHttpClient(authority, refreshTokenHandler))
                                    {
                                        refreshTokenHandler.TokenRefreshed += (sender, e) =>
                                        {
                                            repository.SetCommandData(
                                                new CommandData
                                            {
                                                Authority    = authority,
                                                AccessToken  = e.AccessToken,
                                                RefreshToken = e.RefreshToken,
                                            });
                                        };

                                        var reporter = new ConsoleReporter(this.console, options.Verbose.HasValue(), false);
                                        var context  = new CommandContext(this.console, reporter, clientsClient, apiResourcesClient, identityResourcesClient, rolesClient, usersClient, repository);

                                        try
                                        {
                                            await options.Command.ExecuteAsync(context).ConfigureAwait(false);
                                        }
                                        catch (Exception ex)
                                        {
                                            reporter.Error(ex.Message);
                                            return(500);
                                        }
                                        finally
                                        {
                                            this.console.ResetColor();
                                        }

                                        return(0);
                                    }
        }
コード例 #13
0
        private async Task <int> OnExecuteAsync()
        {
            var reporter = new ConsoleReporter(PhysicalConsole.Singleton)
            {
                IsVerbose = Verbose
            };

            var installDir = string.IsNullOrEmpty(OutputDirectory)
                ? Path.Combine(Directory.GetCurrentDirectory(), "packages")
                : Path.GetFullPath(OutputDirectory);

            var       tempFilePath = Path.Combine(AppContext.BaseDirectory, "projectThatNeverExists.csproj");
            ISettings settings     = Settings.LoadDefaultSettings(tempFilePath);

            VersionRange versionRange;

            if (!string.IsNullOrEmpty(Version))
            {
                if (!VersionRange.TryParse(Version, out versionRange))
                {
                    reporter.Error($"Invalid nuget version '{Version}'");
                    return(1);
                }
            }
            else
            {
                versionRange = Prerelease
                    ? VersionRange.AllFloating
                    : VersionRange.AllStableFloating;
            }

            var logger = new ConsoleNuGetLogger(reporter);

            var results = await RestoreRunnerEx.RunWithoutCommit(tempFilePath,
                                                                 installDir,
                                                                 PackageId,
                                                                 versionRange,
                                                                 settings,
                                                                 Sources,
                                                                 logger);

            var success = false;

            foreach (var result in results)
            {
                if (result.Result.Success)
                {
                    var installedVersion = result.Result.LockFile.Libraries.FirstOrDefault(l => string.Equals(PackageId, l.Name, StringComparison.OrdinalIgnoreCase));
                    if (installedVersion != null)
                    {
                        var path = installedVersion.Path;
                        reporter.Output($"Installed {installedVersion.Name} {installedVersion.Version}");
                        foreach (var file in installedVersion.Files)
                        {
                            reporter.Verbose("Package file: " + file);
                        }
                        success = true;
                        break;
                    }
                }
                else
                {
                    foreach (var unresolved in result.Result.GetAllUnresolved())
                    {
                        reporter.Warn($"Could not find a package {unresolved.Name} in the version range {unresolved.VersionRange}");
                    }
                }
            }

            if (success)
            {
                reporter.Output("Installation succeeded");
                return(0);
            }

            reporter.Error("Installation failed");

            return(success ? 1 : 0);
        }
コード例 #14
0
        private int OnExecute(IConsole console)
        {
            var reporter = new ConsoleReporter(console);

            try
            {
                // Strip end slash
                if (BaseDirectory[BaseDirectory.Length - 1] == Path.DirectorySeparatorChar || BaseDirectory[BaseDirectory.Length - 1] == Path.AltDirectorySeparatorChar)
                {
                    BaseDirectory = BaseDirectory.Substring(0, BaseDirectory.Length - 1);
                }

                List <NarcArchiveEntry> narcObjects = new List <NarcArchiveEntry>();
                // Initialize with base directory and passed files
                narcObjects.Add(new NarcArchiveRootDirectoryEntry
                {
                    Name   = Path.GetFileName(BaseDirectory),
                    Path   = BaseDirectory,
                    Parent = null,
                });
                for (int i = 0; i < InputFiles.Length; ++i)
                {
                    narcObjects.Add(new NarcArchiveFileEntry
                    {
                        Name      = Path.GetFileName(getFakePath(InputFiles[i])),
                        Path      = getRealPath(InputFiles[i]),
                        Directory = null,
                    });
                }
                // Add missing directories and assign parents. Skip base directory.
                for (int i = 1; i < narcObjects.Count; ++i)
                {
                    string _cachedParent;

                    if (i < InputFiles.Length + 1) // Use fake paths if it's a passed file
                    {
                        _cachedParent = Path.GetDirectoryName(getFakePath(InputFiles[i - 1]));
                    }
                    else
                    {
                        _cachedParent = Path.GetDirectoryName(narcObjects[i].Path);
                    }

                    NarcArchiveDirectoryEntry _possibleParent = (NarcArchiveDirectoryEntry)narcObjects.FirstOrDefault(o => o.Path == _cachedParent);
                    if (_possibleParent == null)
                    {
                        _possibleParent = new NarcArchiveDirectoryEntry
                        {
                            Name   = Path.GetFileName(_cachedParent),
                            Path   = _cachedParent,
                            Parent = null,
                        };
                        narcObjects.Add(_possibleParent);
                    }
                    _possibleParent.Entries.Add(narcObjects[i]);
                    if (narcObjects[i] is NarcArchiveDirectoryEntry _currentFolder)
                    {
                        _currentFolder.Parent = _possibleParent;
                    }
                    else if (narcObjects[i] is NarcArchiveFileEntry _currentFile)
                    {
                        _currentFile.Directory = _possibleParent;
                    }
                }

                NarcArchive.Create((NarcArchiveRootDirectoryEntry)narcObjects[0], OutputPath, !NoFilenames);
                return(0);
            }
            catch (Exception e)
            {
                reporter.Error(e.Message);

                return(e.HResult);
            }
        }