static int Main(string[] args) { #if DEBUG if (args.Length == 0) { Main(new[] { "--path", @"E:\Notes\mpvlogs", "--start", DateTime.UnixEpoch.ToString(), "--end", DateTime.Now.ToString(), "--order", SortOrder.Duration.ToString() }); Main(new[] { "compare", "--path", @"E:\Notes\mpvlogs", }); Console.ReadLine(); return(0); } #endif var rootCommand = new RootCommand { new Option <string>( "--path", getDefaultValue: () => Directory.GetCurrentDirectory(), description: "Log directory"), new Option <DateTime>( new [] { "--start", "-s" }, () => DateTime.UnixEpoch.ToLocalTime(), "Start date filter"), new Option <DateTime>( new [] { "--end", "-e" }, () => DateTime.Now.ToLocalTime(), "End date filter"), new Option <SortOrder>( "--order", () => SortOrder.Duration, "Sort ordering") }; rootCommand.Description = "MPV Playlog analyser"; // Note that the parameters of the handler method are matched according to the names of the options rootCommand.Handler = CommandHandler.Create <string, DateTime, DateTime, SortOrder>(Analyse); var compareCommand = new Command("compare", "Retrieve the logs from file names in standard input"); var sourceOpt = new Option <string>( "--path", getDefaultValue: () => Directory.GetCurrentDirectory(), description: "Log directory" ); compareCommand.AddOption(sourceOpt); compareCommand.Handler = CommandHandler.Create <string>(Compare); rootCommand.AddCommand(compareCommand); // Parse the incoming args and invoke the handler return(rootCommand.InvokeAsync(args).Result); }
// Entrypoint. public static int Main(string[] args) { // *** PRELAUNCH CHECKS // Check that we are, in fact, running on Linux/WSL. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Console.WriteLine("genie: not executing on the Linux platform - how did we get here?"); return(EBADF); } if (!IsWsl()) { Console.WriteLine("genie: not executing under WSL - how did we get here?"); return(EBADF); } if (IsWsl1()) { Console.WriteLine("genie: systemd is not supported under WSL 1."); return(EPERM); } if (geteuid() != 0) { Console.WriteLine("genie: must execute as root - has the setuid bit gone astray?"); return(EPERM); } // Set up secure path. var securePath = Configuration["genie:secure-path"]; // Console.WriteLine ($"secure path: {securePath}"); Environment.SetEnvironmentVariable("PATH", securePath); // *** PARSE COMMAND-LINE // Create options. Option optVerbose = new Option("--verbose", "Display verbose progress messages"); optVerbose.AddAlias("-v"); optVerbose.Argument = new Argument <bool>(); optVerbose.Argument.SetDefaultValue(false); // Add them to the root command. var rootCommand = new RootCommand(); rootCommand.Description = "Handles transitions to the \"bottle\" namespace for systemd under WSL."; rootCommand.AddOption(optVerbose); rootCommand.Handler = CommandHandler.Create <bool>((Func <bool, int>)RootHandler); var cmdInitialize = new Command("--initialize"); cmdInitialize.AddAlias("-i"); cmdInitialize.Description = "Initialize the bottle (if necessary) only."; cmdInitialize.Handler = CommandHandler.Create <bool>((Func <bool, int>)InitializeHandler); rootCommand.Add(cmdInitialize); var cmdShell = new Command("--shell"); cmdShell.AddAlias("-s"); cmdShell.Description = "Initialize the bottle (if necessary), and run a shell in it."; cmdShell.Handler = CommandHandler.Create <bool>((Func <bool, int>)ShellHandler); rootCommand.Add(cmdShell); var argCmdLine = new Argument <string> (); argCmdLine.Description = "The command to execute within the bottle."; argCmdLine.Arity = ArgumentArity.OneOrMore; var cmdExec = new Command("--command"); cmdExec.AddAlias("-c"); cmdExec.AddArgument(argCmdLine); cmdExec.Description = "Initialize the bottle (if necessary), and run the specified command in it."; cmdExec.Handler = CommandHandler.Create <bool, List <string> >((Func <bool, List <string>, int>)ExecHandler); rootCommand.Add(cmdExec); var cmdShutdown = new Command("--shutdown"); cmdShutdown.AddAlias("-u"); cmdShutdown.Description = "Shut down systemd and exit the bottle."; cmdShutdown.Handler = CommandHandler.Create <bool>((Func <bool, int>)ShutdownHandler); rootCommand.Add(cmdShutdown); // Parse the arguments and invoke the handler. return(rootCommand.InvokeAsync(args).Result); }
static void Main(string[] args) { var startOption = new Option(new string[] { "--start", "-s" }, "Start time (earliest videos to download)") { Argument = new Argument <DateTime>("start", () => DateTime.MinValue), IsRequired = false }; var endOption = new Option(new string[] { "--end", "-e" }, "End time (latest videos to download)") { Argument = new Argument <DateTime>("end", () => DateTime.MaxValue), IsRequired = false }; var pathOption = new Option(new string[] { "--path" }, "Path to save videos to") { Argument = new Argument <string>("path", () => string.Empty), IsRequired = false }; var passwordOption = new Option(new string[] { "--password", "-p" }, "Ring account password") { Argument = new Argument <string>("password", () => string.Empty), IsRequired = false }; var userNameOption = new Option(new string[] { "--username", "-u" }, "Ring account username") { Argument = new Argument <string>("username", () => string.Empty), IsRequired = false }; var starredOption = new Option(new string[] { "--starred" }, "Flag to only download Starred videos") { Argument = new Argument <bool>("starred", () => false), IsRequired = false }; var maxcountOption = new Option(new string[] { "--maxcount", "-m" }, "Maximum number of videos to download") { Argument = new Argument <int>("maxcount", () => 1000), IsRequired = false }; RootCommand rootCommand = new RootCommand(description: "Simple command line tool to download videos from your Ring account"); var starCommand = new Command("starred", "Download only starred videos") { Handler = CommandHandler.Create <string, string, string, DateTime, DateTime, int>(GetStarredVideos) }; var allCommand = new Command("all", "Download all videos (starred and unstarred)") { Handler = CommandHandler.Create <string, string, string, DateTime, DateTime, int>(GetAllVideos) }; var snapshotCommand = new Command("snapshot", "Download only snapshot images") { Handler = CommandHandler.Create <string, string, string, DateTime, DateTime>(GetSnapshotImages) }; rootCommand.Add(starCommand); rootCommand.Add(allCommand); rootCommand.Add(snapshotCommand); starCommand.Add(userNameOption); starCommand.Add(passwordOption); starCommand.Add(pathOption); starCommand.Add(startOption); starCommand.Add(endOption); starCommand.Add(maxcountOption); allCommand.Add(userNameOption); allCommand.Add(passwordOption); allCommand.Add(pathOption); allCommand.Add(startOption); allCommand.Add(endOption); allCommand.Add(maxcountOption); snapshotCommand.Add(userNameOption); snapshotCommand.Add(passwordOption); snapshotCommand.Add(pathOption); snapshotCommand.Add(startOption); snapshotCommand.Add(endOption); var services = new ServiceCollection(); ConfigureServices(services, args); using (ServiceProvider serviceProvider = services.BuildServiceProvider()) { app = serviceProvider.GetService <RingVideoApplication>(); auth = Configuration.GetSection("Authentication").Get <Authentication>(); if (auth != null) { auth.Decrypt(); } else { auth = new Authentication(); } filter = Configuration.GetSection("Filter").Get <Filter>(); if (filter == null) { filter = new Filter(); } Task <int> val = rootCommand.InvokeAsync(args); val.Wait(); SaveSettings(Program.filter, Program.auth, val.Result); } }
public static async Task <int> Main(string[] args) { var optionFile = new Option(new[] { "--files", "-f" }, "The relative or absolute path to the input files") { Argument = new Argument <FileInfo[]>(defaultValue: () => null) }; var optionDirectory = new Option(new[] { "--directories", "-d" }, "The relative or absolute path to the input directories") { Argument = new Argument <DirectoryInfo[]>(defaultValue: () => null) }; var optionOutput = new Option(new[] { "--output", "-o" }, "The relative or absolute path to the output directory") { Argument = new Argument <DirectoryInfo>(defaultValue: () => null) }; var optionPattern = new Option(new[] { "--pattern", "-p" }, "The search string to match against the names of files in the input directory") { Argument = new Argument <string>(defaultValue: () => null) }; var optionFormat = new Option(new[] { "--format" }, "The output image format") { Argument = new Argument <string>(defaultValue: () => "png") }; var optionQuality = new Option(new[] { "--quality", "-q" }, "The output image quality") { Argument = new Argument <int>(defaultValue: () => 100) }; var optionBackground = new Option(new[] { "--background", "-b" }, "The output image background") { Argument = new Argument <string>(defaultValue: () => "#00000000") }; var optionScale = new Option(new[] { "--scale", "-s" }, "The output image horizontal and vertical scaling factor") { Argument = new Argument <float>(defaultValue: () => 1f) }; var optionScaleX = new Option(new[] { "--scaleX", "-sx" }, "The output image horizontal scaling factor") { Argument = new Argument <float>(defaultValue: () => 1f) }; var optionScaleY = new Option(new[] { "--scaleY", "-sy" }, "The output image vertical scaling factor") { Argument = new Argument <float>(defaultValue: () => 1f) }; var optionDebug = new Option(new[] { "--debug" }, "Write debug output to a file") { Argument = new Argument <bool>() }; var optionQuiet = new Option(new[] { "--quiet" }, "Set verbosity level to quiet") { Argument = new Argument <bool>() }; var optionLoadConfig = new Option(new[] { "--load-config", "-c" }, "The relative or absolute path to the config file") { Argument = new Argument <FileInfo>(defaultValue: () => null) }; var optionSaveConfig = new Option(new[] { "--save-config" }, "The relative or absolute path to the config file") { Argument = new Argument <FileInfo>(defaultValue: () => null) }; var rootCommand = new RootCommand() { Description = "Converts a svg file to an encoded bitmap image." }; rootCommand.AddOption(optionFile); rootCommand.AddOption(optionDirectory); rootCommand.AddOption(optionOutput); rootCommand.AddOption(optionPattern); rootCommand.AddOption(optionFormat); rootCommand.AddOption(optionQuality); rootCommand.AddOption(optionBackground); rootCommand.AddOption(optionScale); rootCommand.AddOption(optionScaleX); rootCommand.AddOption(optionScaleY); rootCommand.AddOption(optionDebug); rootCommand.AddOption(optionQuiet); rootCommand.AddOption(optionLoadConfig); rootCommand.AddOption(optionSaveConfig); rootCommand.Handler = CommandHandler.Create((ConverterSettings converterSettings, FileInfo loadConfig, FileInfo saveConfig) => { if (loadConfig != null) { var jsonSerializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, Converters = { new FileInfoJsonConverter(), new DirectoryInfoJsonConverter() } }; var json = File.ReadAllText(loadConfig.FullName); var loadedConverterSettings = JsonConvert.DeserializeObject <ConverterSettings>(json, jsonSerializerSettings); if (loadedConverterSettings != null) { Converter.Convert(loadedConverterSettings); } } else { if (saveConfig != null) { var jsonSerializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, Converters = { new FileInfoJsonConverter(), new DirectoryInfoJsonConverter() } }; string json = JsonConvert.SerializeObject(converterSettings, jsonSerializerSettings); File.WriteAllText(saveConfig.FullName, json); } Converter.Convert(converterSettings); } }); return(await rootCommand.InvokeAsync(args)); }
private static Task <int> Main(string[] args) { var configJsonOption = new Option <FileInfo?>("--config", "The config.json file."); configJsonOption.AddAlias("-c"); var input = new Argument <FileInfo>("Input file", "File to be extracted."); var outFile = new Option <FileInfo>("--output", "Path to write output file."); outFile.AddAlias("-o"); var outDirectory = new Option <DirectoryInfo>("--outdir", () => new DirectoryInfo("."), "Directory to write output."); outDirectory.AddAlias("--output"); outDirectory.AddAlias("-o"); var outJson = new Option <FileInfo?>("--json", "Path to write json file."); var outYaml = new Option <FileInfo?>("--yaml", "Path to write yaml file."); var outBinary = new Option <FileInfo?>("--binary", "Path to write binary file."); var outLipsync = new Option <FileInfo?>("--lipsync", "Path to write lipsync file."); var outVtt = new Option <FileInfo>("--vtt", "Path to write vtt file."); outVtt.AddAlias("--output"); outVtt.AddAlias("-o"); var imageType = new Option <Unity3dResource.ImageFormat>("--type", () => Unity3dResource.ImageFormat.Webp, "The image type to extract."); imageType.AddAlias("-t"); var intermediateFiles = new Option <bool>("--keep-intermediate", () => false, "Keep intermediate wav files."); intermediateFiles.AddAlias("-k"); var stepOption = new Option <bool>("--step", () => false, "Only check next version."); stepOption.AddAlias("-s"); var proxyOption = new Option <string?>("--proxy", "Proxy server to use."); var resourceVersion = new Command("resver", "Fetch latest resource version.") { configJsonOption, stepOption, proxyOption }; resourceVersion.SetHandler( (FileInfo? config, bool step, string?proxy) => GuessTruthVersion(config, step, proxy), configJsonOption, stepOption, proxyOption); var bundleVersion = new Command("bdlver", "Fetch latest bundle version.") { configJsonOption, stepOption, proxyOption }; bundleVersion.SetHandler( (FileInfo? config, bool step, string?proxy) => GuessBundleVersion(config, step, proxy), configJsonOption, stepOption, proxyOption); var fetch = new Command("fetch", "Fetch latest assets files.") { configJsonOption, outDirectory, stepOption, proxyOption, resourceVersion, bundleVersion }; fetch.SetHandler( (FileInfo? config, DirectoryInfo output, bool step, string?proxy) => DownloadManifests(config, output.FullName, step, proxy), configJsonOption, outDirectory, stepOption, proxyOption); var database = new Command("database", "Extract database file from unity3d.") { input, outFile }; database.SetHandler((FileInfo source, FileInfo dest) => DatabaseResource.ExtractMasterData(source, dest), input, outFile); var storyData = new Command("storydata", "Extract story data from unity3d.") { input, outJson, outYaml, outBinary, outLipsync }; storyData.SetHandler( (FileInfo source, FileInfo? json, FileInfo? yaml, FileInfo? binary, FileInfo? lipsync) => StoryResource.ExtractStoryData(source, json, yaml, binary, lipsync), input, outJson, outYaml, outBinary, outLipsync); var constText = new Command("consttext", "Extract const text from unity3d.") { input, outJson, outYaml }; constText.SetHandler((FileInfo source, FileInfo? json, FileInfo? yaml) => ConstTextResource.ExtractConstText(source, json, yaml), input, outJson, outYaml); var usm = new Command("usm", "Extract videos from usm.") { input, outDirectory, intermediateFiles }; usm.SetHandler( (FileInfo source, DirectoryInfo output, bool keepWav) => CriResource.ExtractUsmFinal(source, output, keepWav), input, outDirectory, intermediateFiles); var hca = new Command("hca", "Extract musics from hca.") { input, outFile }; hca.SetHandler((FileInfo source, FileInfo dest) => Audio.HcaToWav(source, dest), input, outFile); var adx = new Command("adx", "Extract musics from adx.") { input, outFile }; adx.SetHandler((FileInfo source, FileInfo dest) => Audio.AdxToWav(source, dest), input, outFile); var acb = new Command("acb", "Extract musics from acb.") { input, outDirectory }; acb.SetHandler((FileInfo source, DirectoryInfo output) => Audio.ExtractAcbCommand(source, output), input, outDirectory); var u3d = new Command("unity3d", "Extract all things in unity3d file.") { input, outDirectory, imageType }; u3d.SetHandler((FileInfo source, DirectoryInfo output, Unity3dResource.ImageFormat type) => Unity3dResource.ExtractUnity3dCommand(source, output, type), input, outDirectory, imageType); // TODO: do extract vtt according to MonoBehaviour var vtt = new Command("vtt", "Extract vtt from unity3d asset.") { input, outVtt }; vtt.SetHandler((FileInfo source, FileInfo dest) => VttResource.ExtractVtt(source, dest), input, outVtt); var extract = new Command("extract") { database, storyData, constText, usm, hca, adx, acb, u3d, vtt }; var rootCommand = new RootCommand("Redive Extractor\n" + "Download and extract assets from game Princess Connect! Re:Dive.") { fetch, extract }; return(rootCommand.InvokeAsync(args)); }
public void Kubernetes_Queue_SBMSource_Local_Secrets_Success(string runtimeFile, string secretsFile, string deployFile) { var prc = new ProcessHelper(); secretsFile = Path.GetFullPath(secretsFile); runtimeFile = Path.GetFullPath(runtimeFile); deployFile = Path.GetFullPath(deployFile); var overrideFile = Path.GetFullPath("TestConfig/databasetargets.cfg"); var sbmFileName = Path.GetFullPath("SimpleSelect.sbm"); if (!File.Exists(sbmFileName)) { File.WriteAllBytes(sbmFileName, Properties.Resources.SimpleSelect); } //get the size of the log file before we start int startingLine = TestHelper.LogFileCurrentLineCount(); RootCommand rootCommand = CommandLineBuilder.SetUp(); //Clear any exiting pods var result = prc.ExecuteProcess("kubectl", $"delete job sqlbuildmanager "); //Prep the build var args = new string[] { "k8s", "prep", "--secretsfile", secretsFile, "--runtimefile", runtimeFile, "--jobname", TestHelper.GetUniqueJobName("k8s"), "--packagename", sbmFileName }; var val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); //enqueue the topic messages args = new string[] { "k8s", "enqueue", "--secretsfile", secretsFile, "--runtimefile", runtimeFile, "--override", overrideFile }; val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); result = prc.ExecuteProcess("kubectl", $"apply -f {secretsFile}"); Assert.AreEqual(0, result); result = prc.ExecuteProcess("kubectl", $"apply -f {runtimeFile}"); Assert.AreEqual(0, result); result = prc.ExecuteProcess("kubectl", $"apply -f {deployFile}"); Assert.AreEqual(0, result); result = prc.ExecuteProcess("kubectl", $"get pods"); Assert.AreEqual(0, result); //monitor for completion args = new string[] { "k8s", "monitor", "--secretsfile", secretsFile, "--runtimefile", runtimeFile, "--override", overrideFile, "--unittest", "true" }; val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); }
// Entrypoint. public static int Main(string[] args) { // *** PRELAUNCH CHECKS // Check that we are, in fact, running on Linux/WSL. if (!PlatformChecks.IsLinux) { Console.WriteLine("genie: not executing on the Linux platform - how did we get here?"); return(EBADF); } if (PlatformChecks.IsWsl1) { Console.WriteLine("genie: systemd is not supported under WSL 1."); return(EPERM); } if (!PlatformChecks.IsWsl2) { Console.WriteLine("genie: not executing under WSL 2 - how did we get here?"); return(EBADF); } if (!UidChecks.IsEffectivelyRoot) { Console.WriteLine("genie: must execute as root - has the setuid bit gone astray?"); return(EPERM); } // Set up secure path, saving original if specified. if (Config.ClonePath) { originalPath = Environment.GetEnvironmentVariable("PATH"); } else { // TODO: Should reference system drive by letter originalPath = @"/mnt/c/Windows/System32"; } Environment.SetEnvironmentVariable("PATH", Config.SecurePath); // Stash original environment (specified variables only). clonedVariables = GenieConfig.DefaultVariables .Union(from DictionaryEntry de in Environment.GetEnvironmentVariables() where Config.CloneEnv.Contains(de.Key) select $"{de.Key}={de.Value}") .ToArray(); // Store the name of the real user. // TODO: replace this with something less hilariously insecure realUserName = Environment.GetEnvironmentVariable("LOGNAME"); // *** PARSE COMMAND-LINE // Create options. Option optVerbose = new Option("--verbose", "Display verbose progress messages"); optVerbose.AddAlias("-v"); optVerbose.Argument = new Argument <bool>(); optVerbose.Argument.SetDefaultValue(false); // Add them to the root command. var rootCommand = new RootCommand(); rootCommand.Description = "Handles transitions to the \"bottle\" namespace for systemd under WSL."; rootCommand.AddOption(optVerbose); rootCommand.Handler = CommandHandler.Create <bool>((Func <bool, int>)RootHandler); var cmdInitialize = new Command("--initialize"); cmdInitialize.AddAlias("-i"); cmdInitialize.Description = "Initialize the bottle (if necessary) only."; cmdInitialize.Handler = CommandHandler.Create <bool>((Func <bool, int>)InitializeHandler); rootCommand.Add(cmdInitialize); var cmdShell = new Command("--shell"); cmdShell.AddAlias("-s"); cmdShell.Description = "Initialize the bottle (if necessary), and run a shell in it."; cmdShell.Handler = CommandHandler.Create <bool>((Func <bool, int>)ShellHandler); rootCommand.Add(cmdShell); var cmdLogin = new Command("--login"); cmdLogin.AddAlias("-l"); cmdLogin.Description = "Initialize the bottle (if necessary), and open a logon prompt in it."; cmdLogin.Handler = CommandHandler.Create <bool>((Func <bool, int>)LoginHandler); rootCommand.Add(cmdLogin); var argCmdLine = new Argument <IEnumerable <string> > ("command"); argCmdLine.Description = "The command to execute within the bottle."; argCmdLine.Arity = ArgumentArity.OneOrMore; var cmdExec = new Command("--command"); cmdExec.AddAlias("-c"); cmdExec.AddArgument(argCmdLine); cmdExec.Description = "Initialize the bottle (if necessary), and run the specified command in it."; cmdExec.Handler = CommandHandler.Create <bool, IEnumerable <string> >((Func <bool, IEnumerable <string>, int>)ExecHandler); rootCommand.Add(cmdExec); var cmdShutdown = new Command("--shutdown"); cmdShutdown.AddAlias("-u"); cmdShutdown.Description = "Shut down systemd and exit the bottle."; cmdShutdown.Handler = CommandHandler.Create <bool>((Func <bool, int>)ShutdownHandler); rootCommand.Add(cmdShutdown); var cmdIsRunning = new Command("--is-running"); cmdIsRunning.AddAlias("-r"); cmdIsRunning.Description = "Check whether systemd is running in genie, or not."; cmdIsRunning.Handler = CommandHandler.Create <bool>((Func <bool, int>)IsRunningHandler); rootCommand.Add(cmdIsRunning); var cmdIsInside = new Command("--is-in-bottle"); cmdIsInside.AddAlias("-b"); cmdIsInside.Description = "Check whether currently executing within the genie bottle, or not."; cmdIsInside.Handler = CommandHandler.Create <bool>((Func <bool, int>)IsInsideHandler); rootCommand.Add(cmdIsInside); // Parse the arguments and invoke the handler. return(rootCommand.InvokeAsync(args).Result); }
internal static async Task <int> Main(string[] args) { // Create a root command with some options var rootCommand = new RootCommand { Description = "CosmosDb dotnet cli tool", }; // azure url var azureOption = new Option(new string[] { "--azure", "-a" }, "The Azure Key Vault") { Argument = new Argument <string>((SymbolResult result, out string value) => { value = result.Token.Value; return(true); }) }; rootCommand.AddOption(azureOption); // query option var queryOption = new Option(new string[] { "--query", "-q" }, "The query to be used for delete.") { Argument = new Argument <string>() }; rootCommand.AddOption(queryOption); // endpoint var endPointOption = new Option(new string[] { "--endpoint", "-e" }, "The CosmosDb endpoint.") { Argument = new Argument <Uri>() }; rootCommand.AddOption(endPointOption); var dbNameOption = new Option(new string[] { "--name", "-n" }, "The CosmosDb Name.") { Argument = new Argument <string>() }; rootCommand.AddOption(dbNameOption); var containerOption = new Option(new string[] { "--container", "-c" }, "The CosmosDb Container.") { Argument = new Argument <string>() }; rootCommand.AddOption(containerOption); var dbKeyOption = new Option(new string[] { "--key", "-k" }, "The CosmosDb Key.") { Argument = new Argument <string>() }; rootCommand.AddOption(dbKeyOption); var deleteCommand = new Command("del", "Deletes CosmosDb entities based on a query") { Handler = CommandHandler.Create <string, string, Uri, string, string, IConsole, CancellationToken>(async( azure, query, endpoint, name, key, console, cancellationToken) => { console.Out.WriteLine(azure); var hostingOptions = new HostingOptions { AzureVaultOptions = new AzureVaultOptionsEx { BaseUrl = azure }, Query = query, CosmosDbOptions = new CosmosDbOptions { DatabaseName = name, ContainerName = name, Endpoint = endpoint, AuthKey = key } }; return(await HostingExtensions.RunAync(args, hostingOptions, cancellationToken)); }) }; rootCommand.AddCommand(deleteCommand); return(await rootCommand.InvokeAsync(args)); }
private static async Task <int> Main(string[] args) { var pathToTemplates = Environment.GetEnvironmentVariable("SCAFFOLD_TEMPLATES"); var pathToPlugins = Environment.GetEnvironmentVariable("SCAFFOLD_PLUGINS"); if (string.IsNullOrEmpty(pathToTemplates)) { pathToTemplates = Path.Join(Environment.CurrentDirectory, "templates"); } if (string.IsNullOrEmpty(pathToPlugins)) { pathToPlugins = Path.Join(Environment.CurrentDirectory, "plugins"); } if (!new DirectoryInfo(pathToTemplates).Exists) { Console.WriteLine($"Directory '{pathToTemplates}' not found!"); Console.WriteLine($"Press any key to continue..."); Console.ReadKey(); return(0); } if (!new DirectoryInfo(pathToPlugins).Exists) { Console.WriteLine($"Directory '{pathToPlugins}' not found!"); Console.WriteLine($"Press any key to continue..."); Console.ReadKey(); return(0); } // Add services. Services is used to take needed class with certain interface _services.AddSingleton <ILoader, FileSystemLoader>(x => new FileSystemLoader(pathToTemplates, pathToPlugins)); _services.AddSingleton <IGenerator, LocalGenerator>(); _services.AddSingleton <ITemplater, RegexTemplater>(); _serviceProvider = _services.BuildServiceProvider(); // Next we creating console commands // This is root console command whith option -l var rootCommand = new RootCommand { new Option <bool>(new[] { "-l", "--list" }, "Displays the entire list of templates"), }; // Some argument need to be created outside '{...}'. This need for adding extra validation var templateArgument = new Argument <string>("template-name", "The template used to create the project when executing the command"); templateArgument.AddValidator(cr => { var loader = _serviceProvider.GetRequiredService <ILoader>(); var templateInfos = loader.GetAllLanguagesAndTemplateNames().ToList(); // check if we have such template if (!templateInfos.Select(x => x.Name).Contains(cr.Tokens[0].Value)) { return($"Sorry, but there is no '{cr.Tokens[0].Value}' template. To see entire list of templates please use 'scaffold -l'"); } return(null); }); var languageArgument = new Argument <string>("language", "The language of the template to create. Depends on the template"); languageArgument.AddValidator(cr => { var loader = _serviceProvider.GetRequiredService <ILoader>(); var templateInfos = loader.GetAllLanguagesAndTemplateNames().ToList(); // check if we have such language if (!templateInfos.Select(x => x.Language).Contains(cr.Tokens[0].Value)) { return($"Sorry, but there is no '{cr.Tokens[0].Value}' program language in template folder. To see entire list of templates please use 'scaffold -l'"); } return(null); }); // This is 'create' console command for creating project from template var createCommand = new Command("create", "Create a project using the specified template") { languageArgument, templateArgument, new Option <string>(new[] { "-n", "--name" }, "Sets the project name"), new Option <DirectoryInfo>(new[] { "-o", "--output" }, "Sets the location where the template will be created"), new Option <string>(new[] { "-v", "--version" }, "Sets the SDK version") { IsRequired = true }, new Option <bool>(new[] { "--git" }, "Adds Git support"), new Option <bool>(new[] { "--docker" }, "Adds Dockerfile support"), new Option <bool>(new[] { "-kn", "--kubernetes" }, "Adds Kubernetes support"), new Option <bool>(new[] { "-gi", "--gitignore" }, "Adds a file .gitignore"), new Option <bool>(new[] { "-di", "--dockerignore" }, "Adds a file .dockerignore"), new Option <bool>(new[] { "-rm", "--readme" }, "Adds a file README.md"), new Option <bool>(new[] { "-con", "--contributing" }, "Adds a file CONTRIBUTING.md"), new Option <bool>(new[] { "-li", "--license" }, "Adds a file LICENSE"), new Option <bool>(new[] { "-cop", "--codeofproduct" }, "Adds a file CODE_OF_PRODUCT.md"), new Option <bool>(new[] { "-ghw", "--githubworkflows" }, "Adds files for GitHub Workflows"), new Option <bool>(new[] { "-glci", "--gitlabci" }, "Adds files for GitLab CI"), }; // Method is used for processing create command createCommand.Handler = CommandHandler .Create <string, string, string, DirectoryInfo, string, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool, bool>(CreateCall); // Method is used for processing scaffold.exe call rootCommand.Handler = CommandHandler.Create <bool>(EmptyCall); // Adding createCommand to rootCommand rootCommand.AddCommand(createCommand); // If scaffold.exe calls without anything, need to show help if (args.Length == 0) { return(await rootCommand.InvokeAsync(new[] { "-h" })); } return(await rootCommand.InvokeAsync(args)); }
public static async Task <int> Main(params string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); RootCommand rootCommand = new RootCommand(description: "Create AWS CodeDeploy deployments") { TreatUnmatchedTokensAsErrors = false }; Option appOption = new Option( aliases: new string[] { "--application" } , description: "AWS CodeDeploy application name") { Argument = new Argument <string>(), Required = true }; rootCommand.AddOption(appOption); Option deployGroupOption = new Option( aliases: new string[] { "--deployment-group" } , description: "Deployment Group Name") { Argument = new Argument <string>(), Required = true }; rootCommand.AddOption(deployGroupOption); Option bucketOption = new Option( aliases: new string[] { "--s3-location" } , description: "S3 Revision Location s3://<bucket>/<key>") { Argument = new Argument <string>(), Required = true }; rootCommand.AddOption(bucketOption); Option localPathOption = new Option( aliases: new string[] { "--app-path" } , description: "Local application path to deploy. Default './'.") { Name = "app-path", Argument = new Argument <string>() }; rootCommand.AddOption(localPathOption); Option regionOption = new Option( aliases: new string[] { "--region" } , description: "AWS Region e.g. us-east-1") { Argument = new Argument <string>() }; rootCommand.AddOption(regionOption); Command statusCommand = new Command("status", description: "Get Deployment Status") { TreatUnmatchedTokensAsErrors = true }; Option deploymentOption = new Option( aliases: new string[] { "--deployment-id" } , description: "Deployment Id") { Argument = new Argument <string>(), Required = true }; statusCommand.AddOption(deploymentOption); statusCommand.AddOption(regionOption); statusCommand.Handler = CommandHandler.Create <string, string>(GetDeploymentStatus); rootCommand.AddCommand(statusCommand); rootCommand.Handler = CommandHandler.Create <string, string, string, string, string>(Deploy); return(await rootCommand.InvokeAsync(args)); }
public static Task Main(string[] args) { RootCommand rootCommand = RootCommandConfiguration.GenerateCommand(Run); return(rootCommand.InvokeAsync(args)); }
public void ACI_Queue_SBMSource_KeyVault_Secrets_Success(string settingsFile, string imageTag, int containerCount, int concurrency, ConcurrencyType concurrencyType) { settingsFile = Path.GetFullPath(settingsFile); var overrideFile = Path.GetFullPath("TestConfig/databasetargets.cfg"); var sbmFileName = Path.GetFullPath("SimpleSelect.sbm"); if (!File.Exists(sbmFileName)) { File.WriteAllBytes(sbmFileName, Properties.Resources.SimpleSelect); } //get the size of the log file before we start int startingLine = TestHelper.LogFileCurrentLineCount(); RootCommand rootCommand = CommandLineBuilder.SetUp(); string jobName = TestHelper.GetUniqueJobName("aci"); string outputFile = Path.Combine(Directory.GetCurrentDirectory(), jobName + ".json"); //Prep the build var args = new string[] { "aci", "prep", "--settingsfile", settingsFile, "--tag", imageTag, "--jobname", jobName, "--packagename", sbmFileName, "--outputfile", outputFile, "--containercount", containerCount.ToString(), "--concurrencytype", concurrencyType.ToString(), "--concurrency", concurrency.ToString() }; var val = rootCommand.InvokeAsync(args); val.Wait(); int result = val.Result; Assert.AreEqual(0, result); //enqueue the topic messages args = new string[] { "aci", "enqueue", "--settingsfile", settingsFile, "--jobname", jobName, "--concurrencytype", concurrencyType.ToString(), "--override", overrideFile }; val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); //monitor for completion args = new string[] { "aci", "deploy", "--settingsfile", settingsFile, "--templatefile", outputFile, "--override", overrideFile, "--unittest", "true", "--monitor", "true" }; val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); }
public void ACI_Queue_DacpacSource_ForceApplyCustom_eyVault_Secrets_Success(string settingsFile, string imageTag, int containerCount, int concurrency, ConcurrencyType concurrencyType) { settingsFile = Path.GetFullPath(settingsFile); var overrideFile = Path.GetFullPath("TestConfig/databasetargets.cfg"); int removeCount = 1; string server, database; var overrideFileContents = File.ReadAllLines(overrideFile).ToList(); string firstOverride = overrideFileContents.First(); (server, database) = DatabaseHelper.ExtractServerAndDbFromLine(firstOverride); string server2, database2; string thirdOverride = overrideFileContents.ElementAt(2); (server2, database2) = DatabaseHelper.ExtractServerAndDbFromLine(thirdOverride); string minusFirst = Path.GetFullPath("TestConfig/minusFirst.cfg"); File.WriteAllLines(minusFirst, DatabaseHelper.ModifyTargetList(overrideFileContents, removeCount)); //Get the creds locally from the K8s file var secretsFile = Path.GetFullPath("TestConfig/secrets.yaml"); var ymlD = new ydn.Deserializer(); var obj = ymlD.Deserialize <dynamic>(File.ReadAllText(secretsFile)); var pw = Encoding.UTF8.GetString(Convert.FromBase64String(obj["data"]["Password"])); var un = Encoding.UTF8.GetString(Convert.FromBase64String(obj["data"]["UserName"])); var cmdLine = new CommandLineArgs() { UserName = un, Password = pw }; DatabaseHelper.CreateRandomTable(cmdLine, new List <string>() { firstOverride, thirdOverride }); string dacpacName = DatabaseHelper.CreateDacpac(cmdLine, server, database); //get the size of the log file before we start int startingLine = TestHelper.LogFileCurrentLineCount(); RootCommand rootCommand = CommandLineBuilder.SetUp(); string jobName = TestHelper.GetUniqueJobName("aci"); string outputFile = Path.Combine(Directory.GetCurrentDirectory(), jobName + ".json"); //Prep the build var args = new string[] { "aci", "prep", "--settingsfile", settingsFile, "--tag", imageTag, "--jobname", jobName, "--platinumdacpac", dacpacName, "--outputfile", outputFile, "--containercount", containerCount.ToString(), "--concurrencytype", concurrencyType.ToString(), "--concurrency", concurrency.ToString(), "--override", minusFirst }; var val = rootCommand.InvokeAsync(args); val.Wait(); int result = val.Result; Assert.AreEqual(0, result); //Create another table in the first that will be applied when the custom DACPAC is created DatabaseHelper.CreateRandomTable(cmdLine, firstOverride); //enqueue the topic messages args = new string[] { "aci", "enqueue", "--settingsfile", settingsFile, "--jobname", jobName, "--concurrencytype", concurrencyType.ToString(), "--override", minusFirst }; val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); //monitor for completion args = new string[] { "aci", "deploy", "--settingsfile", settingsFile, "--templatefile", outputFile, "--override", minusFirst, "--unittest", "true", "--monitor", "true", "--stream", "true" }; val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); var logFileContents = TestHelper.ReleventLogFileContents(startingLine); Assert.IsTrue(logFileContents.Contains("Committed - With Custom Dacpac"), "A custom DACPAC should have been required for a database"); }
static async Task Main(string[] args) { Console.WriteLine(@" CCCCCCCCCCCCC CCC::::::::::::C ###### ###### CC:::::::::::::::C #::::# #::::# C:::::CCCCCCCC::::C #::::# #::::# C:::::C CCCCCC######::::######::::###### C:::::C #::::::::::::::::::::::::# C:::::C ######::::######::::###### C:::::C #::::# #::::# C:::::C #::::# #::::# C:::::C ######::::######::::###### C:::::C #::::::::::::::::::::::::# C:::::C CCCCCC######::::######::::###### C:::::CCCCCCCC::::C #::::# #::::# CC:::::::::::::::C #::::# #::::# CCC::::::::::::C ###### ###### CCCCCCCCCCCCC "); var logLevelSwitch = new LoggingLevelSwitch { MinimumLevel = LogEventLevel.Information }; var loggerConfiguration = new LoggerConfiguration() .MinimumLevel.ControlledBy(logLevelSwitch) .WriteTo.Console(); var rootCommand = new RootCommand { new Option <string?>(new[] { "--token", "-t" }, () => null, "Set output to be verbose"), new Option <bool>("--split-channels", () => true, "Generates split JSON files for each channel in guild"), new Option <bool>("--combine", () => true, "Generates one JSON file at the end of the process, with all messages from all channels"), new Option <string?>("--output", () => "output", "Generates one JSON file at the end of the process, with all messages from all channels"), new Option <bool>("--verbose", () => false, "Set output to be verbose"), new Option <string?>("--log-file", () => null, "Path to log file"), }; rootCommand.Description = "CSharp Discord Metrics CLI"; rootCommand.Handler = CommandHandler.Create <string?, bool, bool, string?, bool, string?>(async(token, splitChannels, combine, output, verbose, logFile) => { if (verbose) { logLevelSwitch.MinimumLevel = LogEventLevel.Debug; } if (!string.IsNullOrWhiteSpace(logFile)) { loggerConfiguration .WriteTo.File(logFile !); } Log.Logger = loggerConfiguration.CreateLogger(); while (string.IsNullOrWhiteSpace(token)) { Log.Warning("Discord token not provided, please provide a token now to use for authentication, find a token at: https://discord.com/developers/applications"); token = Console.ReadLine(); } while (string.IsNullOrWhiteSpace(output)) { Log.Warning("Output path for JSON files not provided or doesn't exist, please provide a path now"); output = Console.ReadLine(); } if (!Directory.Exists(output)) { Directory.CreateDirectory(output); } Log.Debug("Starting Discord metrics CLI with provided options"); await Run(token !, output !, splitChannels, combine); }); await rootCommand.InvokeAsync(args); }
static int Main(string[] args) { Option[] opts = { new Option("--ek", "encryption key") { Argument = new Argument <string>() }, new Option("--vk", "validation key") { Argument = new Argument <string>() }, new Option("--msg", "base64 encoded message to encrypt/decrypt") { Argument = new Argument <string>() }, new Option("--alg", "encryption algorithm") { Argument = new Argument <string>(defaultValue: () => "3DES") }, new Option("--hash", "hashing algorithm") { Argument = new Argument <string>(defaultValue: () => "SHA1") }, new Option("--url", "public URL") { Argument = new Argument <string>(defaultValue: () => "/dnn/Default") }, }; var rootCmd = new RootCommand(); var encryptCmd = new Command("encrypt"); encryptCmd.Description = "encrypt a ViewState (for exploitation)"; Array.ForEach(opts, opt => encryptCmd.AddOption(opt)); rootCmd.AddCommand(encryptCmd); var decryptCmd = new Command("decrypt"); decryptCmd.Description = "decrypt a ViewState (verify keys / algs)"; Array.ForEach(opts, opt => decryptCmd.AddOption(opt)); rootCmd.AddCommand(decryptCmd); ICryptoService GetCrypto(string ek, string vk, string alg, string hash, string url) { string type = url.TrimStart('/').Replace('/', '_').ToUpper() + "_ASPX"; string dir = "/" + url.TrimStart('/').Split('/')[0].ToUpper(); Purpose purpose = new Purpose("WebForms.HiddenFieldPageStatePersister.ClientState", new string[] { "TemplateSourceDirectory: " + dir, "Type: " + type, } ); IMasterKeyProvider mkp = new FakeMasterKeyProvider(ek, vk); ICryptoAlgorithmFactory caf = new FakeCryptoAlgorithmFactory(alg, hash); CryptographicKey dek = purpose.GetDerivedEncryptionKey(mkp, SP800_108.DeriveKey); CryptographicKey dvk = purpose.GetDerivedValidationKey(mkp, SP800_108.DeriveKey); return(new NetFXCryptoService(caf, dek, dvk)); } void Encrypt(string ek, string vk, string msg, string alg, string hash, string url) { var cs = GetCrypto(ek, vk, alg, hash, url); byte[] payload = System.Convert.FromBase64String(msg); byte[] data = cs.Protect(payload); Console.WriteLine(System.Convert.ToBase64String(data)); } void Decrypt(string ek, string vk, string msg, string alg, string hash, string url) { var cs = GetCrypto(ek, vk, alg, hash, url); byte[] payload = System.Convert.FromBase64String(msg); byte[] data = cs.Unprotect(payload); Console.WriteLine(System.Text.Encoding.Default.GetString(data)); } encryptCmd.Handler = CommandHandler.Create <string, string, string, string, string, string>(Encrypt); decryptCmd.Handler = CommandHandler.Create <string, string, string, string, string, string>(Decrypt); return(rootCmd.InvokeAsync(args).Result); }
static async Task Main(string[] args) { TransformationLogging.LoggerFactory = LoggerFactory.Create(builder => { builder.AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) .AddFilter("Microsoft.Health.Fhir.Transformation", LogLevel.Information) .AddConsole(); }); System.Net.ServicePointManager.DefaultConnectionLimit = 10 * 1024; ILogger logger = TransformationLogging.CreateLogger <Program>(); var rootCommand = new RootCommand(); var generateSchemaCommand = new Command("generate-schema") { new Option <string>("--clientId"), new Option <string>("--tenantId"), new Option <string>("--adlsAccount"), new Option <string>("--cdmFileSystem"), new Option <string>("--configurationContainer", getDefaultValue: () => "config"), new Option <string>("--clientSecret"), new Option <int>("--maxDepth", getDefaultValue: () => 3) }; generateSchemaCommand.Handler = CommandHandler.Create <string, string, string, string, string, string, int>( async(clientId, tenantId, adlsAccount, cdmFileSystem, configurationContainer, clientSecret, maxDepth) => { logger.LogInformation("Start to generate CDM schema."); ClientSecretCredential credential = GetClientSecretCredential(tenantId, clientId, clientSecret); StorageDefinitionLoader configLoader = new StorageDefinitionLoader(GetStorageServiceEndpoint(adlsAccount), configurationContainer, credential, maxDepth); TabularMappingDefinition[] mappings = configLoader.Load(); AdlsCsvSink sink = new AdlsCsvSink(adlsAccount, cdmFileSystem, credential); await sink.InitAsync(); await sink.CreateFileSystemClientIfNotExistAsync(); CdmCorpusDefinition defination = InitAdlscdmCorpusDefinition(adlsAccount, "/" + cdmFileSystem, tenantId, clientId, clientSecret); CdmSchemaGenerator cdmSchemaGenerator = new CdmSchemaGenerator(defination); List <string> entities = await cdmSchemaGenerator.InitializeCdmFolderAsync(mappings, "adls"); WriteActivityOutputs(entities); logger.LogInformation("Generate CDM schema completed."); }); rootCommand.AddCommand(generateSchemaCommand); var transformDataCommand = new Command("transform-data") { new Option <string>("--clientId"), new Option <string>("--tenantId"), new Option <string>("--adlsAccount"), new Option <string>("--cdmFileSystem"), new Option <string>("--inputBlobUri"), new Option <string>("--configurationContainer"), new Option <string>("--clientSecret"), new Option <string>("--operationId"), new Option <string>("--maxDepth"), }; Func <string, string, string, string, string, string, string, string, int, Task> transformDataAction = async(clientId, tenantId, adlsAccount, cdmFileSystem, inputBlobUri, configurationContainer, operationId, clientSecret, maxDepth) => { logger.LogInformation("Start to transform data."); ClientSecretCredential credential = GetClientSecretCredential(tenantId, clientId, clientSecret); StorageDefinitionLoader configLoader = new StorageDefinitionLoader(GetStorageServiceEndpoint(adlsAccount), configurationContainer, credential, maxDepth); TabularMappingDefinition[] mappings = configLoader.Load(); Uri inputUri = new Uri(inputBlobUri); ISource source = new StorageBlobNdjsonSource(inputUri, credential) { ConcurrentCount = Environment.ProcessorCount * 2 }; string fileName = Path.GetFileNameWithoutExtension(inputUri.AbsolutePath); AdlsCsvSink sink = new AdlsCsvSink(adlsAccount, cdmFileSystem, credential) { CsvFilePath = (string tableName) => { return($"data/Local{tableName}/partition-data-{tableName}-{fileName}-{operationId}.csv"); }, ConcurrentCount = Environment.ProcessorCount * 2 }; TransformationExecutor executor = new TransformationExecutor(source, sink, mappings, new BasicFhirElementTabularTransformer()); executor.ConcurrentCount = Environment.ProcessorCount * 2; IProgress <(int, int)> progressHandler = new Progress <(int, int)>(progress => { if (progress.Item1 % 100 == 0 || progress.Item2 % 100 == 0) { logger.LogInformation($"({progress.Item1} loaded, {progress.Item2} transformed) to CDM folder. {DateTime.UtcNow.ToLongTimeString()}"); } }); await executor.ExecuteAsync(progressHandler); logger.LogInformation("Transform data complete."); }; transformDataCommand.Handler = HandlerDescriptor.FromDelegate(transformDataAction).GetCommandHandler(); rootCommand.AddCommand(transformDataCommand); await rootCommand.InvokeAsync(args); }
public void Kubernetes_Queue_DacpacSource_ForceApplyCustom_KeyVault_Secrets_Success(string runtimeFile, string secretsFile, string secretsProviderFile, string podIdentityFile, string deployFile) { var prc = new ProcessHelper(); secretsProviderFile = Path.GetFullPath(secretsProviderFile); podIdentityFile = Path.GetFullPath(podIdentityFile); runtimeFile = Path.GetFullPath(runtimeFile); deployFile = Path.GetFullPath(deployFile); secretsFile = Path.GetFullPath(secretsFile); var overrideFile = Path.GetFullPath("TestConfig/databasetargets.cfg"); int removeCount = 1; string server, database; var overrideFileContents = File.ReadAllLines(overrideFile).ToList(); string firstOverride = overrideFileContents.First(); (server, database) = DatabaseHelper.ExtractServerAndDbFromLine(firstOverride); string server2, database2; string thirdOverride = overrideFileContents.ElementAt(2); (server2, database2) = DatabaseHelper.ExtractServerAndDbFromLine(thirdOverride); string minusFirst = Path.GetFullPath("TestConfig/minusFirst.cfg"); File.WriteAllLines(minusFirst, DatabaseHelper.ModifyTargetList(overrideFileContents, removeCount)); var ymlD = new ydn.Deserializer(); var obj = ymlD.Deserialize <dynamic>(File.ReadAllText(secretsFile)); var pw = Encoding.UTF8.GetString(Convert.FromBase64String(obj["data"]["Password"])); var un = Encoding.UTF8.GetString(Convert.FromBase64String(obj["data"]["UserName"])); var cmdLine = new CommandLineArgs() { UserName = un, Password = pw }; DatabaseHelper.CreateRandomTable(cmdLine, new List <string>() { firstOverride, thirdOverride }); string dacpacName = DatabaseHelper.CreateDacpac(cmdLine, server, database); //get the size of the log file before we start int startingLine = TestHelper.LogFileCurrentLineCount(); RootCommand rootCommand = CommandLineBuilder.SetUp(); //Clear any exiting pods var result = prc.ExecuteProcess("kubectl", $"delete job sqlbuildmanager "); //Prep the build var args = new string[] { "k8s", "prep", "--secretsfile", secretsFile, "--runtimefile", runtimeFile, "--jobname", TestHelper.GetUniqueJobName("k8s-kv"), "--platinumdacpac", dacpacName, "--override", minusFirst }; var val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); //Create another table in the first that will be applied when the custom DACPAC is created DatabaseHelper.CreateRandomTable(cmdLine, firstOverride); //enqueue the topic messages args = new string[] { "k8s", "enqueue", "--secretsfile", secretsFile, "--runtimefile", runtimeFile, "--override", minusFirst }; val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); result = prc.ExecuteProcess("kubectl", $"apply -f {secretsProviderFile}"); Assert.AreEqual(0, result, "Failed to apply secrets provider file"); result = prc.ExecuteProcess("kubectl", $"apply -f {podIdentityFile}"); Assert.AreEqual(0, result, "Failed to apply pod identity file"); result = prc.ExecuteProcess("kubectl", $"apply -f {runtimeFile}"); Assert.AreEqual(0, result, "Failed to apply runtime file"); result = prc.ExecuteProcess("kubectl", $"apply -f {deployFile}"); Assert.AreEqual(0, result, "Failed to apply deploy file"); result = prc.ExecuteProcess("kubectl", $"get pods"); Assert.AreEqual(0, result); //monitor for completion args = new string[] { "k8s", "monitor", "--secretsfile", secretsFile, "--runtimefile", runtimeFile, "--override", minusFirst, "--unittest", "true", "--stream", "true" }; val = rootCommand.InvokeAsync(args); val.Wait(); result = val.Result; Assert.AreEqual(0, result); var logFileContents = TestHelper.ReleventLogFileContents(startingLine); Assert.IsTrue(logFileContents.Contains("Committed - With Custom Dacpac"), "A custom DACPAC should have been required for a database"); }
public static async Task <int> Main(string[] args) { var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddJsonFile("settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); IConfiguration configuration = configBuilder.Build(); var rootCommand = new RootCommand { new Option <string>( "--messageType", getDefaultValue: () => "CalculateMessage", description: "The type of message to send. Valid values are QuitMessage and CalculateMessage. If not supplied this will defualt to CalculateMessage"), new Option <string>( "--dllName", description: "The name of the DLL from which you wish to execute a function (DLL will be downloaded from blob storage)"), new Option <string>( "--functionName", description: "the name of the function your wish to execute"), new Option <string>( "--functionType", description: "The type of function you wish to execute. Valid values are IntFunction or StringFunction. If you specify IntFunction you will need to supply a parameter which will be parsed as an integer"), new Option <string>( "--parameters", getDefaultValue: () => null, description: "A comma separated string of Int parameters. Must be supplied for IntFunction calls, ignored for StringFunctions. "), }; rootCommand.Description = "This command will generate a single calculation request based on the supplied input parameters, and will generate a calculation request message. " + "This will be placed on the configured service bus queue, which will then be picked up by the DLLStuff service and the requested calculation performed. " + "Finally, the results will be written to the blob storage container specified in configuration. You can see the results in a blob called <requestid>.json. " + "Request Id is written to the console on completion of the command."; try { rootCommand.Handler = CommandHandler.Create <string, string, string, string, string>(async(messageType, dllName, functionName, functionType, parameters) => { try { if (string.IsNullOrEmpty(messageType)) { throw new Exception($"--messageType {messageType} must be provided"); } if ((messageType.ToLower() != "quitmessage") && (messageType.ToLower() != "calculatemessage")) { throw new Exception($"--messageType {messageType} is invalid. Valid values are QuitMessage and CalculateMessage"); } Console.WriteLine($"The value for --messageType is: {messageType}"); if (string.IsNullOrEmpty(dllName)) { throw new Exception($"--dllName {dllName} must be provided"); } Console.WriteLine($"The value for --dllName is: {dllName}"); if (string.IsNullOrEmpty(functionName)) { throw new Exception($"--functionName {functionName} must be provided"); } Console.WriteLine($"The value for --functionName is: {functionName}"); if (string.IsNullOrEmpty(functionType)) { throw new Exception($"--functionType {functionType} must be provided"); } if ((functionType.ToLower() != "intfunction") && (functionType.ToLower() != "stringfunction")) { throw new Exception($"--messageType {messageType} is invalid. Valid values are IntFunction and StringFunction"); } Console.WriteLine($"The value for --functionType is: {functionType}"); if (functionType.ToLower() == "intfunction") { if (string.IsNullOrEmpty(parameters)) { throw new Exception($"--parameters {parameters} must be provided when --functionType is {functionType}"); } } Console.WriteLine($"The value for --parameters is: {parameters}"); string serviceBusConnectionString = ""; string serviceBusQueueName = ""; string storageConnectionString = ""; string containerName = ""; try { storageConnectionString = configuration["StorageConnectionString"]; serviceBusConnectionString = configuration["ServiceBusConnectionString"]; serviceBusQueueName = configuration["ServiceBusQueueName"]; containerName = configuration["ContainerName"]; } catch (Exception e) { Console.WriteLine($"Exception caught while accessing configuration: {e.Message}"); return; } queueClient = new QueueClient(serviceBusConnectionString, serviceBusQueueName); var crm = new CalculationRequestMessage(); crm.RequestId = Guid.NewGuid().ToString(); crm.ContainerName = containerName; if (messageType.ToLower() == "quitmessage") { crm.MessageType = MessageType.QuitMessage; } else { crm.MessageType = MessageType.CalculateMessage; crm.DllName = dllName; crm.FunctionName = functionName; if (functionType.ToLower() == "stringfunction") { crm.FunctionType = FunctionType.StringFunction; } else { crm.FunctionType = FunctionType.IntFunction; crm.Parameters = parameters.Split(','); } } var body = JsonConvert.SerializeObject(crm).ToString(); var message = new Message(Encoding.UTF8.GetBytes(body)); Console.WriteLine($"Sending message: {body}"); await queueClient.SendAsync(message); await queueClient.CloseAsync(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Done. Your request id was {crm.RequestId}"); } catch (Exception e) { Console.WriteLine(e.Message); } } ); } catch (Exception e) { Console.WriteLine(e.Message); return(-1); } return(rootCommand.InvokeAsync(args).Result); }
public static int Main(string[] args, Action <DILevel> initStartup, Action initUIApp, Action initCef) { if (args.Length == 0) { args = new[] { "-h" } } ; // https://docs.microsoft.com/zh-cn/archive/msdn-magazine/2019/march/net-parse-the-command-line-with-system-commandline var rootCommand = new RootCommand("命令行工具(Command Line Tools/CLT)"); #if DEBUG // -clt debug -args 730 var debug = new Command("debug", "调试"); debug.AddOption(new Option <string>("-args", () => "", "测试参数")); debug.Handler = CommandHandler.Create((string args) => // 参数名与类型要与 Option 中一致! { //Console.WriteLine("-clt debug -args " + args); // OutputType WinExe 导致控制台输入不会显示,只能附加一个新的控制台窗口显示内容,不合适 // 如果能取消 管理员权限要求,改为运行时管理员权限, // 则可尝试通过 Windows Terminal 或直接 Host 进行命令行模式 initStartup(DILevel.MainProcess); initCef(); initUIApp(); }); rootCommand.AddCommand(debug); #endif // -clt devtools var devtools = new Command("devtools"); devtools.Handler = CommandHandler.Create(() => { var appInstance = new ApplicationInstance(); if (!appInstance.IsFirst) { return; } IsMainProcess = true; IsCLTProcess = false; AppHelper.EnableDevtools = true; initStartup(DILevel.MainProcess); initCef(); initUIApp(); }); rootCommand.AddCommand(devtools); // -clt c -silence var common = new Command("c", "common"); common.AddOption(new Option <bool>("-silence", "静默启动(不弹窗口)")); common.Handler = CommandHandler.Create((bool silence) => { var appInstance = new ApplicationInstance(); if (!appInstance.IsFirst) { return; } IsMainProcess = true; IsCLTProcess = false; initStartup(DILevel.MainProcess); initCef(); IsMinimize = silence; initUIApp(); }); rootCommand.AddCommand(common); // -clt app -id 632360 var unlock_achievement = new Command("app", "打开成就解锁窗口"); unlock_achievement.AddOption(new Option <int>("-id", "指定一个Steam游戏Id")); unlock_achievement.AddOption(new Option <bool>("-silence", "静默启动(不弹窗口)")); unlock_achievement.Handler = CommandHandler.Create((int id, bool silence) => { if (id <= 0) { return; } initStartup(DILevel.GUI | DILevel.Steam | DILevel.HttpClientFactory); IWindowService.Instance.InitUnlockAchievement(id); IsMinimize = silence; initUIApp(); }); rootCommand.AddCommand(unlock_achievement); var r = rootCommand.InvokeAsync(args).Result; return(r); } }
/// <summary> /// The main entry point of the program. /// </summary> /// <param name="args">The string array of the command line arguments.</param> /// <returns>The int, defining the exit code of this console application.</returns> public static int Main(string[] args) { // configure logging Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console( outputTemplate: "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}", theme: AnsiConsoleTheme.Code) .CreateLogger(); // configure base services ConfigureServices(Services); // collect plugins via mef var commandAssemblies = new List <Assembly>(); var configuration = new ContainerConfiguration(); var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var baseDirectoryFiles = Directory.EnumerateFiles(baseDirectory, "*.Commands.*.dll", SearchOption.AllDirectories); foreach (var file in baseDirectoryFiles) { try { var assembly = Assembly.LoadFrom(file); configuration.WithAssembly(assembly); commandAssemblies.Add(assembly); } catch (ReflectionTypeLoadException ex) { Log.Error(ex, "An unexpected error occured while loading command assemblies."); } catch (BadImageFormatException ex) { Log.Error(ex, "An unexpected error occured while loading command assemblies."); } } // manage services and other injections var compositeHost = configuration.CreateContainer(); var cliAdapters = compositeHost.GetExports <IPenshellCLIAdapter>(); var adapterRootCommands = new List <Command>(); foreach (var cliAdapter in cliAdapters) { cliAdapter.ConfigureServices(Services); } // build di container ServiceProvider = Services.BuildServiceProvider(); // create commands via di container foreach (var cliAdapter in cliAdapters) { adapterRootCommands.AddRange(cliAdapter.CreateCommands(ServiceProvider)); } // build command structure var rootCommand = new RootCommand("Welcome to the penshell cli."); foreach (var adapterRootCommand in adapterRootCommands) { rootCommand.AddCommand(adapterRootCommand); } // register command for later usage Registry.Register(rootCommand); // Parse the incoming args and invoke the handler return(rootCommand.InvokeAsync(args).Result); }
static async Task <int> Main(string[] args) { var buildCommand = new Command("build") { new Option <string>(new string[] { "--name", "-n" }, "Name of the package") { IsRequired = true }, new Option <string>(new string[] { "--version", "-v" }, "Version of the package"), new Option <FileInfo>(new string[] { "--output", "-o" }, "Filename of the output package"), new Option <SqlServerVersion>(new string[] { "--sqlServerVersion", "-sv" }, () => SqlServerVersion.Sql150, description: "Target version of the model"), new Option <FileInfo>(new string[] { "--inputfile", "-i" }, "Text file listing all input files"), new Option <string[]>(new string[] { "--reference", "-r" }, "Reference(s) to include"), new Option <FileInfo>(new string[] { "--predeploy" }, "Filename of optional pre-deployment script"), new Option <FileInfo>(new string[] { "--postdeploy" }, "Filename of optional post-deployment script"), new Option <FileInfo>(new string[] { "--refactorlog" }, "Filename of optional refactor log script"), new Option <string[]>(new string[] { "--buildproperty", "-bp" }, "Build properties to be set on the model"), new Option <string[]>(new string[] { "--deployproperty", "-dp" }, "Deploy properties to be set for the create script"), new Option <string[]>(new string[] { "--sqlcmdvar", "-sc" }, "SqlCmdVariable(s) to include"), new Option <bool>(new string[] { "--warnaserror" }, "Treat T-SQL Warnings As Errors"), new Option <bool>(new string[] { "--generatecreatescript", "-gcs" }, "Generate create script for package"), new Option <bool>(new string[] { "--includecompositeobjects", "-ico" }, "Include referenced, external elements that also compose the source model"), new Option <string>(new string[] { "--targetdatabasename", "-tdn" }, "Name of the database to use in the generated create script"), new Option <string>(new string[] { "--suppresswarnings", "-spw" }, "Warning(s) to suppress"), new Option <FileInfo>(new string[] { "--suppresswarningslistfile", "-spl" }, "Filename for warning(s) to suppress for particular files"), #if DEBUG new Option <bool>(new string[] { "--debug" }, "Waits for a debugger to attach") #endif }; buildCommand.Handler = CommandHandler.Create <BuildOptions>(BuildDacpac); var collectIncludesCommand = new Command("collect-includes") { new Option <FileInfo>(new string[] { "--predeploy" }, "Filename of optional pre-deployment script"), new Option <FileInfo>(new string[] { "--postdeploy" }, "Filename of optional post-deployment script"), #if DEBUG new Option <bool>(new string[] { "--debug" }, "Waits for a debugger to attach") #endif }; collectIncludesCommand.Handler = CommandHandler.Create <InspectOptions>(InspectIncludes); var deployCommand = new Command("deploy") { new Option <FileInfo>(new string[] { "--input", "-i" }, "Path to the .dacpac package to deploy"), new Option <string>(new string[] { "--targetServerName", "-tsn" }, "Name of the server to deploy the package to"), new Option <int>(new string[] { "--targetPort", "-tprt" }, "Port number to connect on (leave blank for default)"), new Option <string>(new string[] { "--targetDatabaseName", "-tdn" }, "Name of the database to deploy the package to"), new Option <string>(new string[] { "--targetUser", "-tu" }, "Username used to connect to the target server, using SQL Server authentication"), new Option <string>(new string[] { "--targetPassword", "-tp" }, "Password used to connect to the target server, using SQL Server authentication"), new Option <string[]>(new string[] { "--property", "-p" }, "Properties used to control the deployment"), new Option <string[]>(new string[] { "--sqlcmdvar", "-sc" }, "SqlCmdVariable(s) and their associated values, separated by an equals sign."), new Option <bool>(new string[] { "--runScriptsFromReferences", "-sff" }, "Whether to run pre- and postdeployment scripts from references"), #if DEBUG new Option <bool>(new string[] { "--debug" }, "Waits for a debugger to attach") #endif }; deployCommand.Handler = CommandHandler.Create <DeployOptions>(DeployDacpac); var rootCommand = new RootCommand { buildCommand, collectIncludesCommand, deployCommand }; rootCommand.Description = "Command line tool for generating a SQL Server Data-Tier Application Framework package (dacpac)"; return(await rootCommand.InvokeAsync(args)); }
private static async Task <int> Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; SetExecutionEnvironment(); var preambleWriter = new ConsoleInteractiveServiceImpl(diagnosticLoggingEnabled: false); preambleWriter.WriteLine("AWS .NET deployment tool for deploying .NET Core applications to AWS."); preambleWriter.WriteLine("Project Home: https://github.com/aws/aws-dotnet-deploy"); preambleWriter.WriteLine(string.Empty); // Name is important to set here to show correctly in the CLI usage help. // Either dotnet-aws or dotnet aws works from the CLI. System.Commandline's help system does not like having a space with dotnet aws. var rootCommand = new RootCommand { Name = "dotnet-aws", Description = "The AWS .NET deployment tool for deploying .NET applications on AWS." }; var deployCommand = new Command( "deploy", "Inspect, build, and deploy the .NET project to AWS using the recommended AWS service.") { _optionProfile, _optionRegion, _optionProjectPath, _optionDiagnosticLogging }; deployCommand.Handler = CommandHandler.Create <string, string, string, bool, bool>(async(profile, region, projectPath, saveCdkProject, diagnostics) => { var toolInteractiveService = new ConsoleInteractiveServiceImpl(diagnostics); try { var orchestratorInteractiveService = new ConsoleOrchestratorLogger(toolInteractiveService); var previousSettings = PreviousDeploymentSettings.ReadSettings(projectPath, null); var awsUtilities = new AWSUtilities(toolInteractiveService); var awsCredentials = await awsUtilities.ResolveAWSCredentials(profile, previousSettings.Profile); var awsRegion = awsUtilities.ResolveAWSRegion(region, previousSettings.Region); var commandLineWrapper = new CommandLineWrapper( orchestratorInteractiveService, awsCredentials, awsRegion); var directoryManager = new DirectoryManager(); var fileManager = new FileManager(); var packageJsonGenerator = new PackageJsonGenerator( typeof(PackageJsonGenerator).Assembly .ReadEmbeddedFile(PackageJsonGenerator.TemplateIdentifier)); var npmPackageInitializer = new NPMPackageInitializer(commandLineWrapper, packageJsonGenerator, fileManager, directoryManager); var cdkInstaller = new CDKInstaller(commandLineWrapper); var cdkManager = new CDKManager(cdkInstaller, npmPackageInitializer); var systemCapabilityEvaluator = new SystemCapabilityEvaluator(commandLineWrapper, cdkManager); var systemCapabilities = systemCapabilityEvaluator.Evaluate(); var stsClient = new AmazonSecurityTokenServiceClient(awsCredentials); var callerIdentity = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest()); var session = new OrchestratorSession { AWSProfileName = profile, AWSCredentials = awsCredentials, AWSRegion = awsRegion, AWSAccountId = callerIdentity.Account, ProjectPath = projectPath, ProjectDirectory = projectPath, SystemCapabilities = systemCapabilities, CdkManager = cdkManager }; var awsResourceQueryer = new AWSResourceQueryer(new DefaultAWSClientFactory()); var zipFileManager = new ZipFileManager(commandLineWrapper); var deploy = new DeployCommand( toolInteractiveService, orchestratorInteractiveService, new CdkProjectHandler(orchestratorInteractiveService, commandLineWrapper), new DeploymentBundleHandler(session, commandLineWrapper, awsResourceQueryer, orchestratorInteractiveService, directoryManager, zipFileManager), awsResourceQueryer, session); await deploy.ExecuteAsync(saveCdkProject); return(CommandReturnCodes.SUCCESS); } catch (Exception e) when(e.IsAWSDeploymentExpectedException()) { // helpful error message should have already been presented to the user, // bail out with an non-zero return code. return(CommandReturnCodes.USER_ERROR); } catch (Exception e) { // This is a bug toolInteractiveService.WriteErrorLine( "Unhandled exception. This is a bug. Please copy the stack trace below and file a bug at https://github.com/aws/aws-dotnet-deploy. " + e.PrettyPrint()); return(CommandReturnCodes.UNHANDLED_EXCEPTION); } }); rootCommand.Add(deployCommand); var listCommand = new Command("list-deployments", "List existing deployments.") { _optionProfile, _optionRegion, _optionProjectPath, _optionDiagnosticLogging }; listCommand.Handler = CommandHandler.Create <string, string, string, bool>(async(profile, region, projectPath, diagnostics) => { var toolInteractiveService = new ConsoleInteractiveServiceImpl(diagnostics); var orchestratorInteractiveService = new ConsoleOrchestratorLogger(toolInteractiveService); var awsUtilities = new AWSUtilities(toolInteractiveService); var previousSettings = PreviousDeploymentSettings.ReadSettings(projectPath, null); var awsCredentials = await awsUtilities.ResolveAWSCredentials(profile, previousSettings.Profile); var awsRegion = awsUtilities.ResolveAWSRegion(region, previousSettings.Region); var stsClient = new AmazonSecurityTokenServiceClient(awsCredentials); var callerIdentity = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest()); var session = new OrchestratorSession { AWSProfileName = profile, AWSCredentials = awsCredentials, AWSRegion = awsRegion, AWSAccountId = callerIdentity.Account, ProjectPath = projectPath, ProjectDirectory = projectPath }; var commandLineWrapper = new CommandLineWrapper( orchestratorInteractiveService, awsCredentials, awsRegion); var awsResourceQueryer = new AWSResourceQueryer(new DefaultAWSClientFactory()); var directoryManager = new DirectoryManager(); var zipFileManager = new ZipFileManager(commandLineWrapper); await new ListDeploymentsCommand(toolInteractiveService, new ConsoleOrchestratorLogger(toolInteractiveService), new CdkProjectHandler(orchestratorInteractiveService, commandLineWrapper), new DeploymentBundleHandler(session, commandLineWrapper, awsResourceQueryer, orchestratorInteractiveService, directoryManager, zipFileManager), awsResourceQueryer, session).ExecuteAsync(); }); rootCommand.Add(listCommand); var deleteCommand = new Command("delete-deployment", "Delete an existing deployment.") { _optionProfile, _optionRegion, _optionProjectPath, _optionDiagnosticLogging, new Argument("deployment-name") }; deleteCommand.Handler = CommandHandler.Create <string, string, string, string, bool>(async(profile, region, projectPath, deploymentName, diagnostics) => { var toolInteractiveService = new ConsoleInteractiveServiceImpl(diagnostics); var awsUtilities = new AWSUtilities(toolInteractiveService); var previousSettings = PreviousDeploymentSettings.ReadSettings(projectPath, null); var awsCredentials = await awsUtilities.ResolveAWSCredentials(profile, previousSettings.Profile); var awsRegion = awsUtilities.ResolveAWSRegion(region, previousSettings.Region); var session = new OrchestratorSession { AWSProfileName = profile, AWSCredentials = awsCredentials, AWSRegion = awsRegion, }; await new DeleteDeploymentCommand(new DefaultAWSClientFactory(), toolInteractiveService, session).ExecuteAsync(deploymentName); return(CommandReturnCodes.SUCCESS); }); rootCommand.Add(deleteCommand); // if user didn't specify a command, default to help if (args.Length == 0) { args = new string[] { "-h" }; } return(await rootCommand.InvokeAsync(args)); }
private static async Task <int> Main(string[] args) { CursorVisible = false; #region Application Banner var(left, top) = GetCursorPosition(); WriteLine(string.Join(string.Empty, Banner.Hello .Select(s => s.ToString().Pastel("EE977F").PastelBg("FFFFC5")))); SetCursorPosition(left + 12, top + 2); Write("HttpDoom, flyover"); SetCursorPosition(left + 12, top + 3); Write("to your horizon."); SetCursorPosition(0, top + 5); WriteLine(" v0.4".Pastel("EE977F")); WriteLine(); #endregion #region Command Line Argument Parsing var commands = new RootCommand { new Option <bool>(new[] { "--debug", "-d" }) { Description = "Print debugging information" }, new Option <bool>(new[] { "--follow-redirect", "-f" }) { Description = "HTTP client follow any automatic redirects (default is false)" }, new Option <bool>(new[] { "--max-redirects", "-m" }) { Description = "Max automatic redirect depth when is enable (default is 3)" }, new Option <bool>(new[] { "--screenshot", "-s" }) { Description = "Take screenshots from the alive host with ChromeDriver (default is false)" }, new Option <bool>(new[] { "--screenshot-resolution", "-r" }) { Description = "Set screenshot resolution (default is 1366x768)" }, new Option <bool>(new[] { "--capture-favicon", "-f" }) { Description = "Download the application favicon" }, new Option <string[]>(new[] { "--headers", "-h" }) { Description = "Set default headers to every request (default is just a random User-Agent)" }, new Option <int>(new[] { "--http-timeout", "-t" }) { Description = "Timeout in milliseconds for HTTP requests (default is 5000)" }, new Option <int>(new[] { "--threads", "-T" }) { Description = $"Number of concurrent threads (default is {Environment.ProcessorCount})" }, new Option <string>(new[] { "--output-directory", "-o" }) { Description = "Path to save the output directory" }, new Option <int[]>(new[] { "--ports", "-p" }) { Description = "Set of ports to check (default is 80, 443, 8080 and 8433)" }, new Option <string>(new[] { "--proxy", "-P" }) { Description = "Proxy to use for HTTP requests" }, new Option <string>(new[] { "--word-list", "-w" }) { Description = "List of hosts to flyover against", IsRequired = true } }; commands.Description = "HttpDoom is a tool for response-based inspection of websites across a large " + "amount of hosts for quickly gaining an overview of HTTP-based attack surface."; #endregion commands.Handler = CommandHandler.Create <Options>(async options => await Router(options)); CursorVisible = true; return(await commands.InvokeAsync(args)); }
/// <summary> /// Main entry-point for this sample application. /// </summary> /// <param name="args">An array of command-line argument strings.</param> /// <returns> /// An asynchronous result that yields exit-code for the process - 0 for success, else an error code. /// </returns> static async Task <int> Main(string[] args) { var rootCommand = new RootCommand("Device Update for IoT Hub client library for .NET sample"); rootCommand.AddOption(new Option("--tenant", "AAD tenant id") { Argument = new Argument <string>(() => Environment.GetEnvironmentVariable("DEVICEUPDATE_TENANT_ID")), IsRequired = true }); rootCommand.AddOption(new Option("--client", "AAD client id") { Argument = new Argument <string>(() => Environment.GetEnvironmentVariable("DEVICEUPDATE_CLIENT_ID")), IsRequired = true }); rootCommand.AddOption(new Option("--clientSecret", "AAD client secret") { Argument = new Argument <string>(() => Environment.GetEnvironmentVariable("DEVICEUPDATE_CLIENT_SECRET")), IsRequired = true }); rootCommand.AddOption(new Option("--accountEndpoint", "ADU account endpoint") { Argument = new Argument <string>(() => Environment.GetEnvironmentVariable("DEVICEUPDATE_ACCOUNT_ENDPOINT")), IsRequired = true }); rootCommand.AddOption(new Option("--instance", "ADU instance id") { Argument = new Argument <string>(() => Environment.GetEnvironmentVariable("DEVICEUPDATE_INSTANCE_ID")), IsRequired = true }); rootCommand.AddOption(new Option("--connectionString", "Azure Storage account connection string") { Argument = new Argument <string>(() => $"DefaultEndpointsProtocol=https;AccountName={Environment.GetEnvironmentVariable("DEVICEUPDATE_STORAGE_NAME")};AccountKey={Environment.GetEnvironmentVariable("DEVICEUPDATE_STORAGE_KEY")};EndpointSuffix=core.windows.net"), IsRequired = true }); rootCommand.AddOption(new Option("--device", "Registered ADU simulator device id") { Argument = new Argument <string>(), IsRequired = true }); rootCommand.AddOption(new Option("--deviceTag", "IoT Hub device tag") { Argument = new Argument <string>(), IsRequired = true }); rootCommand.AddOption(new Option("--delete", "Delete update when finished") { Argument = new Argument <bool>(), IsRequired = false }); rootCommand.Handler = CommandHandler.Create <Arguments>(async(Arguments arguments) => { Console.WriteLine("Device Update for IoT Hub client library for .NET sample"); Console.WriteLine(); // Sample runner that will exercise the following: // * publish new update // * retrieve the newly imported update // * create deployment/device group // * check that device group contains devices that can be updated with our new update // * create deployment for our device group to deploy our new update // * check device and wait until the new update is installed there // * check that device group contains *NO* devices that can be updated with our new update // * delete the update // * retrieve the deleted update and check that we get 404 (NotFound) await new Sample( arguments.Tenant, arguments.Client, arguments.ClientSecret, arguments.AccountEndpoint, arguments.Instance, arguments.ConnectionString, arguments.Device, arguments.DeviceTag, arguments.Delete) .RunAsync(); ConsoleEx.WriteLine(ConsoleColor.Green, "Finished."); return(0); }); return(await rootCommand.InvokeAsync(args)); }
private static Task Main(string[] args) { var botTokenOption = new Option <string?>("--bot-token", "Telegram bot token."); var enableCommandsModuleOption = new Option <bool?>("--enable-commands-mod", "Whether to enable the commands module."); var enableStatsModuleOption = new Option <bool?>("--enable-stats-mod", "Whether to enable the stats module."); var enablePersonalCommandsOption = new Option <bool?>("--enable-personal-commands", "Whether to enable personal commands."); var enableCommonCommandsOption = new Option <bool?>("--enable-common-commands", "Whether to enable common commands."); var enableDiceCommandsOption = new Option <bool?>("--enable-dice-commands", "Whether to enable dice commands."); var enableConsentNotNeededCommandsOption = new Option <bool?>("--enable-consent-not-needed-commands", "Whether to enable consent not needed commands."); var enableNonVeganCommandsOption = new Option <bool?>("--enable-non-vegan-commands", "Whether to enable non-vegan commands."); var enableLawEnforcementCommandsOption = new Option <bool?>("--enable-law-enforcement-commands", "Whether to enable law enforcement commands."); var enablePublicServicesCommandsOption = new Option <bool?>("--enable-public-services-commands", "Whether to enable public services commands."); var enableChineseCommandsOption = new Option <bool?>("--enable-chinese-commands", "Whether to enable Chinese commands."); var enableChineseTasksCommandsOption = new Option <bool?>("--enable-chinese-tasks-commands", "Whether to enable Chinese tasks commands."); var enableSystemdCommandsOption = new Option <bool?>("--enable-systemd-commands", "Whether to enable systemd commands."); var enableGrassStatsOption = new Option <bool?>("--enable-grass-stats", "Whether to enable grass stats."); var enableCommandStatsOption = new Option <bool?>("--enable-command-stats", "Whether to enable command stats."); var enableMessageCounterOption = new Option <bool?>("--enable-message-counter", "Whether to enable message counter."); var configGetCommand = new Command("get", "Print config."); var configSetCommand = new Command("set", "Change config.") { botTokenOption, enableCommandsModuleOption, enableStatsModuleOption, enablePersonalCommandsOption, enableCommonCommandsOption, enableDiceCommandsOption, enableConsentNotNeededCommandsOption, enableNonVeganCommandsOption, enableLawEnforcementCommandsOption, enablePublicServicesCommandsOption, enableChineseCommandsOption, enableChineseTasksCommandsOption, enableSystemdCommandsOption, enableGrassStatsOption, enableCommandStatsOption, enableMessageCounterOption, }; var configSetBinder = new ConfigSetBinder( botTokenOption, enableCommandsModuleOption, enableStatsModuleOption, enablePersonalCommandsOption, enableCommonCommandsOption, enableDiceCommandsOption, enableConsentNotNeededCommandsOption, enableNonVeganCommandsOption, enableLawEnforcementCommandsOption, enablePublicServicesCommandsOption, enableChineseCommandsOption, enableChineseTasksCommandsOption, enableSystemdCommandsOption, enableGrassStatsOption, enableCommandStatsOption, enableMessageCounterOption); configGetCommand.SetHandler <CancellationToken>(ConfigCommand.Get); configSetCommand.SetHandler <ConfigChangeSet, CancellationToken>(ConfigCommand.Set, configSetBinder); var configCommand = new Command("config", "Print or change config.") { configGetCommand, configSetCommand, }; var rootCommand = new RootCommand("A stupid and annoying chatbot for your group chats.") { configCommand, }; rootCommand.AddOption(botTokenOption); rootCommand.SetHandler <string?, CancellationToken>(BotRunner.RunBot, botTokenOption); Console.OutputEncoding = Encoding.UTF8; return(rootCommand.InvokeAsync(args)); }
public static async Task <int> Main(params string[] args) { IsPlatformSupported(); var validOutputs = Enum.GetNames(typeof(OutputFormat)).Select(format => format.ToLower()).ToArray(); var validCollectors = Assembly.GetExecutingAssembly().GetTypes() .Where(type => type.IsSubclassOf(CollectorsBaseClass)) .Select(collector => collector.Name) .ToArray(); var rootCommand = new RootCommand { new Option <bool>(new[] { "-v", "--verbose" }, "Verbose output"), new Option <bool>(new[] { "-d", "--debug" }, "Debug output (implies verbose)"), new Option <bool>(new[] { "-nc", "--no-color" }, "No colored output"), new Option <string>(new[] { "-o", "--output" }, () => "table", "Output format") { Name = "outputFormatString", Arity = ArgumentArity.ExactlyOne }.FromAmong(validOutputs), new Option <string[]>(new[] { "-c", "--collectors" }, "Collectors to run") { Name = "collectorsSelected", Arity = ArgumentArity.OneOrMore }.FromAmong(validCollectors) }; rootCommand.Handler = CommandHandler.Create <bool, bool, bool, string, string[]>( (verbose, debug, noColor, outputFormatString, collectorsSelected) => { VerboseOutput = verbose; DebugOutput = debug; if (DebugOutput) { VerboseOutput = true; } var colorOutput = !noColor; if (colorOutput) { ResetConsoleColor(); } Enum.TryParse(outputFormatString, true, out OutputFormat outputFormat); var collectors = new List <Collector>(); collectorsSelected = collectorsSelected.Length != 0 ? collectorsSelected : validCollectors; // Ensure order of execution is deterministic var collectorsToRun = collectorsSelected .Where(collector => !CollectorsSortExclusions.Contains(collector)) .OrderBy(collector => collector).ToList(); // SystemInfo collector should be first if (collectorsSelected.Contains("SystemInfo")) { collectorsToRun.Insert(0, "SystemInfo"); } foreach (var collectorName in collectorsToRun) { var collectorType = Type.GetType($"{CollectorsNamespace}.{collectorName}"); Debug.Assert(collectorType != null, nameof(collectorType) + " != null"); try { collectors.Add((Collector)Activator.CreateInstance(collectorType)); } catch (TargetInvocationException ex) { WriteConsoleError( $"{collectorName} collector failed to initialize: {ex.InnerException?.Message}"); } } if (outputFormat == OutputFormat.Json) { /* * The serialization and immediate deserialization provides a copy of the * underlying collector metadata. Definitely not at all efficient, but it * works and and we're not dealing with any large JSON data structures. */ var collectorsData = new ExpandoObject(); foreach (var collector in collectors) { ((IDictionary <string, object>)collectorsData)[collector.JsonName] = JsonConvert.DeserializeObject(collector.ConvertToJson()); } var collectorsJson = JsonConvert.SerializeObject(collectorsData, Formatting.Indented); Console.WriteLine(collectorsJson); return; } var consoleFirstOutput = true; Enum.TryParse(outputFormatString, true, out ConsoleOutputStyle consoleOutputStyle); foreach (var collector in collectors) { if (!consoleFirstOutput && outputFormat == OutputFormat.Raw) { Console.WriteLine(); } collector.ConsoleColorOutput = colorOutput; collector.WriteConsole(consoleOutputStyle); consoleFirstOutput = false; } if (outputFormat == OutputFormat.Table) { Console.WriteLine(new string('-', 119)); } }); return(await rootCommand.InvokeAsync(args).ConfigureAwait(false)); }
static int Main(string[] args) { /// /// Create a root command with the required options. /// var rootCommand = new RootCommand(Strings.rootCmdDescription) { new Option <string>( new string[] { "--connection-string", "-cs" }, Strings.csDescription) { IsRequired = true }, new Option <Mode>( new string[] { "--mode", "-m" }, getDefaultValue: () => Mode.Export, description: Strings.modeDescription), new Option <DirectoryInfo>( new string[] { "--export-folder", "-ef" }, Strings.efDescription).ExistingOnly(), new Option <FileInfo>( new string[] { "--import-file", "-if" }, Strings.ifDescription).ExistingOnly(), new Option <string>( new string[] { "--locale-id", "-lcid" }, Strings.lcidDescription), new Option <bool>( new string[] { "--fallback-mode", "-fm" }, Strings.fallbackDescription), new Option <string>( new string[] { "--key-prefix", "-kp" }, Strings.keyPrefixDescription) }; // Note that the parameters of the handler method are matched according to the names of the options rootCommand.Handler = CommandHandler.Create <string, Mode, DirectoryInfo, FileInfo, string, bool, string>((connectionString, mode, exportFolder, importFile, localeId, fallbackMode, keyPrefix) => { try { DataModel model = DataModel.Connect(connectionString); model.InitializeLanguages(); switch (mode) { case Mode.Export: case Mode.ExportResx: Export(mode, model, exportFolder, localeId, keyPrefix); break; case Mode.Import: Import(model, importFile, false, fallbackMode); break; case Mode.Overwrite: Import(model, importFile, true, fallbackMode); break; default: break; } } catch (Exception ex) { Console.Error.WriteLine($"{ex}"); } }); // Parse the incoming args and invoke the handler return(rootCommand.InvokeAsync(args).Result); }
public static int Main(params string[] args) { ServicePointManager.DefaultConnectionLimit = 2048; ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => { return(true); }; var rootCommand = new RootCommand { new Argument <string>( "url", description: "视频地址 或 av|bv|BV|ep|ss"), new Option <bool>( new string[] { "--use-tv-api", "-tv" }, "使用TV端解析模式"), new Option <bool>( new string[] { "--only-hevc", "-hevc" }, "下载hevc编码"), new Option <bool>( new string[] { "--only-show-info", "-info" }, "仅解析不下载"), new Option <bool>( new string[] { "--hide-streams", "-hs" }, "不要显示所有可用音视频流"), new Option <bool>( new string[] { "--interactive", "-ia" }, "交互式选择清晰度"), new Option <bool>( new string[] { "--multi-thread", "-mt" }, "使用多线程下载"), new Option <string>( new string[] { "--select-page", "-p" }, "选择指定分p或分p范围"), /*new Option<bool>( * new string[]{ "--audio-only" ,"-vn"}, * "仅下载音频"), * new Option<bool>( * new string[]{ "--video-only" ,"-an"}, * "仅下载视频"),*/ new Option <bool>( new string[] { "--debug" }, "输出调试日志"), new Option <string>( new string[] { "--cookie", "-c" }, "设置字符串cookie用以下载网页接口的会员内容"), new Option <string>( new string[] { "--access-token", "-a" }, "设置access_token用以下载TV接口的会员内容") }; Command loginCommand = new Command( "login", "通过APP扫描二维码以登录您的WEB账号"); rootCommand.AddCommand(loginCommand); Command loginTVCommand = new Command( "logintv", "通过APP扫描二维码以登录您的TV账号"); rootCommand.AddCommand(loginTVCommand); rootCommand.Description = "BBDown是一个免费且便捷高效的哔哩哔哩下载/解析软件."; rootCommand.TreatUnmatchedTokensAsErrors = true; //WEB登录 loginCommand.Handler = CommandHandler.Create(delegate { try { Log("获取登录地址..."); string loginUrl = "https://passport.bilibili.com/qrcode/getLoginUrl"; string url = JObject.Parse(GetWebSource(loginUrl))["data"]["url"].ToString(); string oauthKey = GetQueryString("oauthKey", url); //Log(oauthKey); //Log(url); bool flag = false; Log("生成二维码..."); QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData); Bitmap qrCodeImage = qrCode.GetGraphic(7); qrCodeImage.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png); Log("生成二维码成功:qrcode.png, 请打开并扫描"); while (true) { Thread.Sleep(1000); string w = GetLoginStatus(oauthKey); string data = JObject.Parse(w)["data"].ToString(); if (data == "-2") { LogColor("二维码已过期, 请重新执行登录指令."); break; } else if (data == "-4") //等待扫码 { continue; } else if (data == "-5") //等待确认 { if (!flag) { Log("扫码成功, 请确认..."); flag = !flag; } } else { string cc = JObject.Parse(w)["data"]["url"].ToString(); Log("登录成功: SESSDATA=" + GetQueryString("SESSDATA", cc)); //导出cookie File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "BBDown.data"), "SESSDATA=" + GetQueryString("SESSDATA", cc)); File.Delete("qrcode.png"); break; } } } catch (Exception e) { LogError(e.Message); } }); //TV登录 loginTVCommand.Handler = CommandHandler.Create(delegate { try { string loginUrl = "https://passport.snm0516.aisee.tv/x/passport-tv-login/qrcode/auth_code"; string pollUrl = "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll"; var parms = GetTVLoginParms(); Log("获取登录地址..."); WebClient webClient = new WebClient(); byte[] responseArray = webClient.UploadValues(loginUrl, parms); string web = Encoding.UTF8.GetString(responseArray); string url = JObject.Parse(web)["data"]["url"].ToString(); string authCode = JObject.Parse(web)["data"]["auth_code"].ToString(); Log("生成二维码..."); QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData); Bitmap qrCodeImage = qrCode.GetGraphic(7); qrCodeImage.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png); Log("生成二维码成功:qrcode.png, 请打开并扫描"); parms.Set("auth_code", authCode); parms.Set("ts", GetTimeStamp(true)); parms.Remove("sign"); parms.Add("sign", GetSign(ToQueryString(parms))); while (true) { Thread.Sleep(1000); responseArray = webClient.UploadValues(pollUrl, parms); web = Encoding.UTF8.GetString(responseArray); string code = JObject.Parse(web)["code"].ToString(); if (code == "86038") { LogColor("二维码已过期, 请重新执行登录指令."); break; } else if (code == "86039") //等待扫码 { continue; } else { string cc = JObject.Parse(web)["data"]["access_token"].ToString(); Log("登录成功: AccessToken=" + cc); //导出cookie File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "BBDownTV.data"), "access_token=" + cc); File.Delete("qrcode.png"); break; } } } catch (Exception e) { LogError(e.Message); } }); rootCommand.Handler = CommandHandler.Create <MyOption>(async(myOption) => { await DoWorkAsync(myOption); }); return(rootCommand.InvokeAsync(args).Result); }
static int Main(string[] args) { Option methodOption = new Option <SolvingMethod>( new string[] { "--method", "-m" }, getDefaultValue: () => SolvingMethod.Sequential, description: "The method used to solve the nonogram" ); Option methodsOption = new Option <SolvingMethod[]>( new string[] { "--methods", "-mx" }, getDefaultValue: () => new[] { SolvingMethod.Sequential, SolvingMethod.Parallel }, description: "The methods used to benchmark the nonogram" ); Option sourceOption = new Option <PuzzleSource>( new string[] { "--source", "-s" }, getDefaultValue: () => PuzzleSource.WebPBN, description: "The source of the puzzle to be solved" ); Option idOption = new Option <int>( new string[] { "--id" }, getDefaultValue: () => 0, description: "The id of the puzzle to be solved" ); Option idSetOption = new Option <string>( new string[] { "--idSet", "-ix" }, getDefaultValue: () => "4", description: "The set of puzzle ids to benchmark (comma delimited)" ); Option trialsOption = new Option <int>( new string[] { "--trials", "-t" }, getDefaultValue: () => 5, description: "The number of trials to time per benchmark" ); Option timeoutOption = new Option <int>( new string[] { "--timeout", "-to" }, getDefaultValue: () => 10000, description: "The maximum number of milliseconds to wait for a solution" ); Option directoryOption = new Option <DirectoryInfo>( new string[] { "--directory", "-d" }, getDefaultValue: () => new DirectoryInfo(@"./"), description: "The working root directory for all I/O" ); Option verboseOption = new Option <bool>( new string[] { "--verbose", "-v" }, getDefaultValue: () => false, description: "Make program report all processes" ); Option threadsOption = new Option <int>( new string[] { "--threads", "-t" }, getDefaultValue: () => 2, description: "Sets number of threads to use for parallel solvers" ); // Root command RootCommand rootCommand = new RootCommand(); rootCommand.AddGlobalOption(directoryOption); rootCommand.AddGlobalOption(verboseOption); rootCommand.AddGlobalOption(timeoutOption); rootCommand.AddGlobalOption(sourceOption); // Solve command Command solveCommand = new Command("solve"); solveCommand.AddOption(methodOption); solveCommand.AddOption(idOption); solveCommand.AddOption(threadsOption); solveCommand.Handler = CommandHandler.Create <PuzzleSource, SolvingMethod, DirectoryInfo, int, int, int, bool>(Solve); // Play command Command playCommand = new Command("play"); playCommand.AddOption(idOption); playCommand.Handler = CommandHandler.Create <PuzzleSource, DirectoryInfo, int, bool>(Play); Command benchmarkCommand = new Command("benchmark"); benchmarkCommand.AddOption(methodsOption); benchmarkCommand.AddOption(idSetOption); benchmarkCommand.AddOption(trialsOption); benchmarkCommand.Handler = CommandHandler.Create <PuzzleSource, SolvingMethod[], DirectoryInfo, string, int, int, bool>(Benchmark); rootCommand.AddCommand(benchmarkCommand); rootCommand.AddCommand(solveCommand); rootCommand.AddCommand(playCommand); return(rootCommand.InvokeAsync(args).Result); }
static int Main(string[] args) { #if DEBUG Console.WriteLine("Program was called with : [{0}]", string.Join(", ", args)); #endif #region generator var generatorCommand = new Command("generate", description: "Maze generator") { new Option <int>( "--width", getDefaultValue: () => 10, description: "Width of the maze" ), new Option <int>( "--height", getDefaultValue: () => 10, description: "Height of the maze" ), new Option <int>( "--cell-size", getDefaultValue: () => 10, "Size of the cells of the maze" ), new Option <int>( "--seed", getDefaultValue: () => - 1, "Seed for the maze" ), new Option <bool>( "--write-maze", getDefaultValue: () => true, description: "Output the generated bitmap. Default is true" ), new Option <FileInfo>( new string[] { "--output", "-o" }, getDefaultValue: () => null, description: "Output file for the maze" ), new Option <bool>( "--write-json", getDefaultValue: () => false, description: "Output the generated json maze representation. False by default" ), new Option <FileInfo>( new string[] { "--json-output", "-j" }, getDefaultValue: () => null, description: "Output file for the generated json maze representation" ) }; generatorCommand.Handler = CommandHandler.Create <GeneratorArgs>((args) => { #if DEBUG Console.WriteLine(args.ToString()); #endif var date = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss"); if (args.WriteMaze && args.Output == null) { args.Output = new FileInfo($"maze-{date}.png"); } if (args.WriteJson && args.JsonOutput == null) { args.JsonOutput = new FileInfo($"maze-{date}.json"); } var maze = args.Seed switch { -1 => new PrimsMazeGenerator(args.Width, args.Height).GenerateMaze(), _ => new PrimsMazeGenerator(args.Seed, args.Width, args.Height).GenerateMaze() }; maze.CellSize = args.CellSize; if (args.WriteMaze) { maze.GenerateBitmap().Save(args.Output.FullName); } if (args.WriteJson) { File.WriteAllText(args.JsonOutput.FullName, JsonConvert.SerializeObject(maze, Formatting.Indented)); } }); #endregion #region explore var exploreCommand = new Command("explore", "Maze explorer") { new Option <int>( "--width", getDefaultValue: () => 10, description: "Width of the maze" ), new Option <int>( "--height", getDefaultValue: () => 10, description: "Height of the maze" ), new Option <int>( "--cell-size", getDefaultValue: () => 10, "Size of the cells of the maze" ), new Option <int>( "--seed", getDefaultValue: () => - 1, "Seed for the maze" ), new Option <int>( "--delay", getDefaultValue: () => 100, description: "Delay for the frame of the gif animation" ), new Option <FileInfo>( new string[] { "--output", "-o" }, getDefaultValue: () => null, description: "Output file for the explore animation" ), new Option <bool>( "--write-json", getDefaultValue: () => false, description: "Output the generated json maze representation. False by default" ), new Option <FileInfo>( new string[] { "--json-output", "-j" }, getDefaultValue: () => null, description: "Output file for the generated json maze representation" ), new Option <bool>( "--write-maze", getDefaultValue: () => false, description: "Write the generated maze." ), new Option <FileInfo>( "--maze-output", getDefaultValue: () => null, description: "Output file for the maze" ) }; exploreCommand.Handler = CommandHandler.Create <ExplorerArgs>((args) => { #if DEBUG Console.WriteLine(args.ToString()); #endif var date = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss"); if (args.Output == null) { args.Output = new FileInfo($"maze-{date}.gif"); } if (args.WriteMaze && args.MazeOutput == null) { args.MazeOutput = new FileInfo($"maze-{date}.png"); } if (args.WriteJson && args.JsonOutput == null) { args.JsonOutput = new FileInfo($"maze-{date}.json"); } var maze = args.Seed switch { -1 => new PrimsMazeGenerator(args.Width, args.Height).GenerateMaze(), _ => new PrimsMazeGenerator(args.Seed, args.Width, args.Height).GenerateMaze() }; maze.CellSize = args.CellSize; if (args.WriteMaze) { maze.GenerateBitmap().Save(args.MazeOutput.FullName); } if (args.WriteJson) { File.WriteAllText(args.JsonOutput.FullName, JsonConvert.SerializeObject(maze, Formatting.Indented)); } maze.Explorers.Add(new LeftHandExplorer { ColorPen = Pens.Red, }); maze.Explorers.Add(new RightHandExplorer { ColorPen = Pens.Blue }); maze.FullExplore(args.Output.FullName, args.Delay); #if DEBUG foreach (var ex in maze.Explorers) { Console.WriteLine("{0} : {1}", ex.GetType(), JsonConvert.SerializeObject(ex, Formatting.Indented)); } #endif }); #endregion var statCommand = new Command("stats", description: "Run stat programm") { new Option <int>( "--iter", getDefaultValue: () => 100, description: "Number of maze created for each size of maze" ), new Option <FileInfo>( new string[] { "--output", "-o" }, getDefaultValue: () => null, description: "Output file for statistiques" ) }; statCommand.Handler = CommandHandler.Create <int, FileInfo>((iter, output) => { #if DEBUG Console.WriteLine("Stats : {{ Iter : {0}, Output : {1} }}", iter, output?.FullName ?? "null"); #endif StatsProgram.DoStat(iter, output); }); var rootCommand = new RootCommand { statCommand, generatorCommand, exploreCommand }; return(rootCommand.InvokeAsync(args).Result); }