/// <summary> /// Create and delete resource grouop /// </summary> /// <param name="context"></param> /// <param name="options"></param> /// <returns></returns> private static async Task TestVmCreateDeleteCreate(IComponentContext context, CliOptions options) { var manager = context.Resolve <IResourceGroupFactory>(); var name = options.GetValueOrDefault("-n", "--name", StringEx.CreateUnique(9, "test")); Console.WriteLine("Creating resource group...."); using (var resourceGroup = await manager.CreateAsync(true)) { Console.WriteLine("Resource group created."); var vms = context.Resolve <IVirtualMachineFactory>(); Console.WriteLine("Creating virtual machine..."); var vm = await vms.CreateAsync(resourceGroup, name); Console.WriteLine("Virtual machine created."); Console.WriteLine("Deleting virtual machine..."); await vm.DeleteAsync(); Console.WriteLine("Virtual machine deleted."); Console.WriteLine("Recreating virtual machine..."); vm = await vms.CreateAsync(resourceGroup, name); Console.WriteLine("Virtual machine created."); } Console.WriteLine("Resource group deleted."); }
static async Task OutputTypes(CliOptions options, List <NgType> types) { var directoryPath = Path.Combine(options.OutputDirectory, "models"); Directory.CreateDirectory(directoryPath); string indexTs = ""; foreach (var type in types) { if (type.Name == "JsonElement" || type.Name == "JsonValueKind") { continue; } System.IO.File.WriteAllText( Path.Combine(directoryPath, type.Name + ".ts"), type.ToString() ); indexTs += $"export * from './{type.Name}';\r\n"; } indexTs = indexTs.Replace("\t", " "); System.IO.File.WriteAllText(Path.Combine(directoryPath, "index.ts"), indexTs); }
static async Task Main(CliOptions options) { Console.WriteLine("Start"); await ClearOutput(options.OutputDirectory); try { Console.Write("Load Swagger JSON...\t"); var swaggerDoc = await OpenApiDocument.FromUrlAsync(options.URL); Console.WriteLine("OK"); switch (SchemaType = swaggerDoc.SchemaType) { case SchemaType.Swagger2: Console.WriteLine("SchemaType: Swagger2"); break; case SchemaType.OpenApi3: Console.WriteLine("SchemaType: OpenApi3"); break; default: Console.WriteLine("SchemaType: Unsupported"); break; } Console.Write("Analysis Models...\t"); var types = await LoadTypes(swaggerDoc); Console.WriteLine("OK"); Console.Write("Analysis Services...\t"); var services = await LoadServices(swaggerDoc, types); Console.WriteLine("OK"); Console.Write("Output Models...\t"); await OutputTypes(options, types); Console.WriteLine("OK"); Console.Write("Output Services...\t"); await OutputServices(options, services); Console.WriteLine("OK"); Console.Write("Output Module...\t"); await OutputModule(options, Path.Combine(options.OutputDirectory, FirstCharToLower(options.ModuleName) + ".module.ts"), options.ModuleName, services); await OutputModuleIndexTs(options, Path.Combine(options.OutputDirectory, "index.ts"), options.ModuleName); Console.WriteLine("OK"); } catch { Console.WriteLine("ERROR"); } Console.WriteLine("Finish"); }
public void CliOptionsParameterMissingTest() { var ex = Assert.Throws <ArgumentException>(() => _options = new CliOptions(new[] { "-a:app" })); Assert.That(ex.Message, Is.EqualTo("Required parameter missing.")); Assert.That(_options, Is.Null); }
/// <summary> /// Create and delete resource grouop /// </summary> /// <param name="context"></param> /// <param name="options"></param> /// <returns></returns> private static async Task TestIoTHubCreateDeleteCreate(IComponentContext context, CliOptions options) { var manager = context.Resolve <IResourceGroupFactory>(); var name = options.GetValueOrDefault("-n", "--name", StringEx.CreateUnique(9, "test")); Console.WriteLine("Creating resource group...."); using (var resourceGroup = await manager.CreateAsync(true)) { Console.WriteLine("Resource group created."); var hubs = context.Resolve <IIoTHubFactory>(); Console.WriteLine("Creating iothub..."); var hub = await hubs.CreateAsync(resourceGroup, name); Console.WriteLine("iothub created."); Console.WriteLine("Deleting iothub..."); await hub.DeleteAsync(); Console.WriteLine("iothub deleted."); Console.WriteLine("Recreating iothub..."); hub = await hubs.CreateAsync(resourceGroup, name); Console.WriteLine("iothub created."); } Console.WriteLine("Resource group deleted."); }
public void CliOptionsWithoutParameterTest() { var ex = Assert.Throws <ArgumentNullException>(() => _options = new CliOptions(null)); Assert.That(ex.Message.Substring(0, 21), Is.EqualTo("Value cannot be null.")); Assert.That(_options, Is.Null); }
private static int OnParse(GlobalOptions globals, CliOptions _) { var bootstrapper = new MicroserviceHostBootstrapper(() => new MongoDbPopulatorHost(globals)); int ret = bootstrapper.Main(); return(ret); }
/// <summary> /// Parses the command line arguments fed to <see cref="MlosAgentServer.Main" />. /// Displays help output and forces a program exit upon errors. /// </summary> /// <param name="args">The input arguments to parse.</param> /// <returns></returns> internal static CliOptions ParseArgs(string[] args) { CliOptions result = null; using var cliOptsParser = new Parser(with => with.HelpWriter = null); var cliOptsParseResult = cliOptsParser.ParseArguments <CliOptions>(args); cliOptsParseResult .WithParsed(parsedOptions => { if (parsedOptions.ExtraArgs.Any()) { ShowUsageHelp(cliOptsParseResult, msg: "ERROR: Unknown arguments: " + string.Join(" ", parsedOptions.ExtraArgs.Any())); } result = parsedOptions; }) .WithNotParsed(errors => { // Handle command line parsing errors. // ShowUsageHelp( cliOptsParseResult, errors: errors, msg: "Failed to parse command line options."); }); return(result); }
public static async Task <Result <string> > Run(CliOptions options) { return(await LeetCodeApi.GetAllProblems() .Map(problems => SelectProblem(options, problems)) .Map(LeetCodeApi.GetProblemData) .Map(data => CreateProject(options.TestFramework, data))); }
/// <summary> /// Converts the pattern expression into a collection of descriptions /// of parameters. /// </summary> /// <param name="pOptions">Parser options to use.</param> /// <param name="pHelpProvider"></param> /// <param name="pPattern">A string containing the syntax pattern for the application's argument.</param> /// <returns>A collection of descriptions.</returns> public static List <Description> Create(CliOptions pOptions, iHelpProvider pHelpProvider, string pPattern) { string[] strings = pPattern.Split(' '); return((from str in strings where !string.IsNullOrWhiteSpace(str) select Parse(pOptions, pHelpProvider, str)).ToList()); }
/// <summary> /// Run gremlin from file input line by line /// </summary> public static async Task RunGremlinFileAsync(CliOptions options) { var graph = await GetGraphAsync(options); using (var gremlinClient = graph.OpenGremlinClient()) { var lines = await File.ReadAllLinesAsync( options.GetValueOrDefault("-f", "--file", "gremlin.txt")); foreach (var gremlin in lines) { Console.WriteLine($"\"{gremlin}\" ..."); var feed = gremlinClient.Submit <dynamic>(gremlin); try { var results = await feed.AllAsync(); var array = results.ToArray(); for (var i = 0; i < array.Length; i++) { Console.WriteLine($"[{i + 1}]\t{array[i]}"); } Console.WriteLine($" ... {array.Length} item(s) returned."); } catch (Exception e) { Console.WriteLine(e); } } } }
private static void Main(string[] args) { Parser.Default.ParseArguments <CliOptions>(args).WithParsed(options => { _options = options; var watcher = new FileSystemWatcher(options.WorkingDirectory) { Filter = "*.cs", IncludeSubdirectories = true }; watcher.Changed += OnWatcherTriggered; watcher.Created += OnWatcherTriggered; watcher.Deleted += OnWatcherTriggered; watcher.Renamed += OnWatcherTriggered; watcher.EnableRaisingEvents = true; }); Compile(); Console.WriteLine("Press ESC to stop."); while (Console.ReadKey(true).Key != ConsoleKey.Escape) { } Console.WriteLine("Program closed."); }
public static bool TryParse(string[] args, out CliOptions options) { var port = _defaultPort; var verbose = false; foreach (var arg in args) { switch (arg) { case "-v": case "--verbose": verbose = true; continue; default: if (int.TryParse(arg, out port)) { continue; } options = null; return(false); } } options = new CliOptions(port, verbose); return(true); }
/// <summary> /// Login /// </summary> /// <param name="shellFactory"></param> /// <param name="options"></param> /// <returns></returns> private static async Task <ISecureShell> LoginAsync(IShellFactory shellFactory, CliOptions options) { var user = options.GetValueOrDefault <string>("-u", "--user", null); var pw = options.GetValueOrDefault <string>("-p", "--password", null); while (string.IsNullOrEmpty(user)) { Console.WriteLine("User:"******"Password:"******"-t", "--timeout", -1))) { return(await shellFactory.OpenSecureShellAsync( options.GetValue <string>("-h", "--host"), options.GetValueOrDefault("-p", "--port", 22), creds, cts.Token)); } }
private static void ConfigureLogging(IServiceCollection services, CliOptions options, ConfigurationFile configuration) { services.AddLogging(x => { x.ClearProviders(); var filters = new Dictionary <string, LogLevel[]>(); if (configuration.Logging?.TryGetValue("EventLog") is LoggingTargetConfiguration eventLogConfig) { var target = eventLogConfig.Target?.Split('/'); x.AddEventLog(new EventLogSettings() { MachineName = target?.TryGetAt(0, null, str => !string.IsNullOrEmpty(str) && str != "."), LogName = target?.TryGetAt(1, null, str => !string.IsNullOrEmpty(str) && str != "."), SourceName = target?.TryGetAt(2, null, str => !string.IsNullOrEmpty(str) && str != "."), }); filters.Add(typeof(EventLogLoggerProvider).FullName, eventLogConfig.Levels); } if (configuration.Logging?.TryGetValue("Console") is LoggingTargetConfiguration consoleLogConfig) { x.AddConsole((consoleLoggerOptions) => consoleLoggerOptions.IncludeScopes = true); filters.Add(typeof(ConsoleLoggerProvider).FullName, consoleLogConfig.Levels); } x.AddFilter((t, c, l) => { return(filters.TryGetValue(t)?.Contains(l) == true); }); }); }
public void CliOptionsInvalidParameterTest() { var ex = Assert.Throws <ArgumentException>(() => _options = new CliOptions(new[] { "-x:wrong" })); Assert.That(ex.Message, Is.EqualTo("Invalid parameter.")); Assert.That(_options, Is.Null); }
/// <summary> /// Print result /// </summary> private void PrintResult <T>(CliOptions options, T status) { Console.WriteLine("=================="); Console.WriteLine(JsonConvert.SerializeObject(status, options.GetValueOrDefault("-F", "--format", Formatting.Indented))); Console.WriteLine("=================="); }
public void Init(InstDeclController controller) { _controller = controller; _cli = CliOptions.GetInstance(); _nl = Environment.NewLine; _externFncs = new List <string>(); if (CliOptions.Arch.Arch == System.Reflection.ProcessorArchitecture.Amd64) { byteWidth = 1; shortWidth = 2; intWidth = 4; longWidth = 8; longlongWidth = 16; bitMode = 64; } else if (CliOptions.Arch.Arch == System.Reflection.ProcessorArchitecture.X86) { byteWidth = 1; shortWidth = 2; intWidth = 4; longWidth = 8; longlongWidth = 16; bitMode = 32; } }
private static int OnParse(GlobalOptions globals, CliOptions opts) { var bootstrapper = new MicroserviceHostBootstrapper(() => new DicomRelationalMapperHost(globals)); int ret = bootstrapper.Main(); return(ret); }
/// <summary> /// Console entry point /// </summary> /// <param name="args"></param> public static void Main(string[] args) { var command = (args.Length > 0) ? args[0].ToLowerInvariant() : null; var options = new CliOptions(args, 2); try { switch (command) { case "dump": DumpCollectionAsync(options).Wait(); break; case "-?": case "-h": case "--help": case "help": PrintHelp(); break; default: throw new ArgumentException($"Unknown command {command}."); } } catch (ArgumentException e) { Console.WriteLine(e.Message); PrintHelp(); } catch (Exception e) { Console.WriteLine("=================="); Console.WriteLine(e); Console.WriteLine("=================="); } }
private static void RunCli(CliOptions options) { if (StringExt.IsNullOrWhiteSpace(options.Game.Value)) { Console.WriteLine($"Empty game specified. Exiting..."); } var userDataAccessor = new UserDataAccessor(); var game = userDataAccessor.GetFirstGameWithName(options.Game.Value); if (StringExt.IsNullOrWhiteSpace(game.DOSEXEPath)) { game = userDataAccessor.GetGameWithMainExecutable(options.Game.Value); } if (options.Setup.IsProvided) { if (options.Verbose.IsProvided) { Console.WriteLine($"Running '{game.Name}''s setup executable: {game.SetupEXEPath}..."); } game.RunSetup(userDataAccessor.GetUserData()); } else { if (options.Verbose.IsProvided) { Console.WriteLine($"Running the game named '{game.Name}' via the main executable at {game.DOSEXEPath}..."); } game.Run(userDataAccessor.GetUserData()); } }
/// <summary> /// <para> **** Please be aware! MCWrapper.CLI has only been tested and configured to function in a Windows environment. ****</para> /// <para> **** We are working on a Linux client for version 2.0.0, current version is 1.0.0 ****</para> /// /// Use this method to add MultiChain Command Line Interface (CLI) services to an application's service container. /// /// <para> /// Be aware a MultiChain blockchain network must be installed and configured externally from this application. /// However, consumers using the MCWrapper.CLI ForgeClient are able to create, start, and stop Hot and Cold node /// wallet types directly from an application. /// </para> /// <para> /// The MultiChain library and installation instructions are availabale at https://multichain.com for consumers not using the MCWrapper.CLI ForgeClient /// </para> /// <para> /// This method automatically loads the CliOptions and RuntimeParamOptions from the /// local environment's variable store. CliOptions and RuntimeParamOptions are implemented in such a way /// that during instantiation the local environment's variable store /// is automatically parsed for available parameter values. In our opinion this is the best and most secure /// method to implement MCWrapper within an application. /// Set each environment's variables and let MCWrapper lazy load all the values. Easy peasy! /// </para> /// </summary> /// <param name="services">Service container</param> /// <returns></returns> public static IServiceCollection AddMultiChainCoreCliServices(this IServiceCollection services) { var cliOptions = new CliOptions(true); var runtimeOptions = new RuntimeParamOptions(true); // detect misconfiguration early in pipeline if (string.IsNullOrEmpty(cliOptions.ChainAdminAddress)) { throw new ArgumentNullException($"{nameof(cliOptions.ChainAdminAddress)} is required and cannot be empty or null"); } if (string.IsNullOrEmpty(cliOptions.ChainBurnAddress)) { throw new ArgumentNullException($"{nameof(cliOptions.ChainBurnAddress)} is required and cannot be empty or null"); } if (string.IsNullOrEmpty(cliOptions.ChainName)) { throw new ArgumentNullException($"{nameof(cliOptions.ChainName)} is required and cannot be empty or null"); } // load Options from the local environment variable store services.Configure <CliOptions>(config => { config.ChainDefaultColdNodeLocation = cliOptions.ChainDefaultColdNodeLocation; config.ChainDefaultLocation = cliOptions.ChainDefaultLocation; config.ChainBinaryLocation = cliOptions.ChainBinaryLocation; config.ChainAdminAddress = cliOptions.ChainAdminAddress; config.ChainBurnAddress = cliOptions.ChainBurnAddress; config.ChainName = cliOptions.ChainName; }) .Configure <RuntimeParamOptions>(config => { config.MiningRequiresPeers = runtimeOptions.MiningRequiresPeers; config.LockAdminMineRounds = runtimeOptions.LockAdminMineRounds; config.MaxQueryScanItems = runtimeOptions.MaxQueryScanItems; config.HideKnownOpDrops = runtimeOptions.HideKnownOpDrops; config.MineEmptyRounds = runtimeOptions.MineEmptyRounds; config.MiningTurnOver = runtimeOptions.MiningTurnOver; config.HandshakeLocal = runtimeOptions.HandshakeLocal; config.AutoSubscribe = runtimeOptions.AutoSubscribe; config.MaxShownData = runtimeOptions.MaxShownData; config.LockBlock = runtimeOptions.LockBlock; config.BanTx = runtimeOptions.BanTx; }); // command line interface clients and client factory services.AddTransient <IMultiChainCliGeneral, MultiChainCliGeneralClient>() .AddTransient <IMultiChainCliGenerate, MultiChainCliGenerateClient>() .AddTransient <IMultiChainCliOffChain, MultiChainCliOffChainClient>() .AddTransient <IMultiChainCliControl, MultiChainCliControlClient>() .AddTransient <IMultiChainCliNetwork, MultiChainCliNetworkClient>() .AddTransient <IMultiChainCliUtility, MultiChainCliUtilityClient>() .AddTransient <IMultiChainCliWallet, MultiChainCliWalletClient>() .AddTransient <IMultiChainCliMining, MultiChainCliMiningClient>() .AddTransient <IMultiChainCliRaw, MultiChainCliRawClient>() .AddTransient <IMultiChainCliForge, MultiChainCliForgeClient>() .AddTransient <IMultiChainCliClientFactory, MultiChainCliClientFactory>(); return(services); }
/// <summary> /// Run command /// </summary> /// <param name="shell"></param> /// <param name="options"></param> /// <returns></returns> private static async Task ExecuteCommandAsync(ISecureShell shell, CliOptions options) { var str = await shell.ExecuteCommandAsync( options.GetValue <string>("-c", "--command")); PrintResult(options, str); }
/// <summary> /// Download folder /// </summary> /// <param name="shell"></param> /// <param name="options"></param> /// <returns></returns> private static async Task DownloadFolderAsync(ISecureShell shell, CliOptions options) { var from = options.GetValue <string>("-f", "--from"); var path = options.GetValue <string>("-p", "--path"); await shell.DownloadFolderAsync(path, from, options.GetValueOrDefault("-h", "--home", true)); }
private static void AssertNamed(CliOptions pOptions, string pPattern) { Description desc = DescriptionFactory.Parse(pOptions, new MockHelpProvider(), pPattern); Assert.AreEqual(eROLE.NAMED, desc.Role); AssertTypes(pOptions, pPattern); }
/// <summary> /// Upload folder /// </summary> /// <param name="shell"></param> /// <param name="options"></param> /// <returns></returns> private static async Task UploadFolderAsync(ISecureShell shell, CliOptions options) { var to = options.GetValue <string>("-t", "--to"); var from = options.GetValue <string>("-p", "--path"); await UploadFolderAsync(shell, options, to, from); }
private static void AssertMultiple(CliOptions pOptions, string pPattern) { Description desc = DescriptionFactory.Parse(pOptions, new MockHelpProvider(), pPattern); Assert.AreEqual(eMULTIPLICITY.MULTIPLE, desc.Multiplicity); AssertOptional(pOptions, "[" + pPattern + "]"); }
public void FilesExist() { CliOptions.GetInstance().Refresh(new string[] { "--src=" + helloPath + ".kcc" }); Utils.CallSystem("kcc", "--src=" + helloPath); Assert.IsTrue(File.Exists(helloPath + ".kcc"), $"{helloPath}.kcc not found"); Assert.IsTrue(File.Exists(helloPath + ".s"), $"{helloPath}.s not found"); Assert.IsTrue(File.Exists(helloPath + ".exe") || File.Exists(helloPath), $"{helloPath}(.exe) not found"); }
/// <summary> /// Upload file /// </summary> /// <param name="shell"></param> /// <param name="options"></param> /// <param name="to"></param> /// <param name="from"></param> /// <param name="file"></param> /// <returns></returns> private static async Task UploadFileAsync(ISecureShell shell, CliOptions options, string to, string from, string file) { var buffer = await File.ReadAllBytesAsync(Path.Combine(from, file)); await shell.UploadAsync(buffer, file, to, options.GetValueOrDefault("-h", "--home", true), options.GetValueOrDefault <string>("-m", "--mode", null)); }
/// <summary> /// Get collection interface /// </summary> /// <param name="options"></param> /// <returns></returns> private static async Task <IGraph> GetGraphAsync(CliOptions options) { var database = await GetDatabaseAsync(options); var coll = await database.OpenContainerAsync( options.GetValueOrDefault("-c", "--collection", "default")); return(coll.AsGraph()); }
/// <summary> /// Constructor /// </summary> /// <param name="pOptions">The parser options</param> /// <param name="pOutput">The output handler</param> /// <param name="pUsageNamed">True to list named parameters in the "usage" description.</param> public OutputHelp(CliOptions pOptions, iOutputStream pOutput, bool pUsageNamed = false) { _options = pOptions; _output = pOutput; _usageNamed = pUsageNamed; }
public void CliOptionsInvalidParameterTest() { var ex = Assert.Throws<ArgumentException>(() => _options = new CliOptions(new[] { "-x:wrong"})); Assert.That(ex.Message, Is.EqualTo("Invalid parameter.")); Assert.That(_options, Is.Null); }
public void CliOptionsParameterMissingTest() { var ex = Assert.Throws<ArgumentException>(() => _options = new CliOptions(new[] { "-a:app" })); Assert.That(ex.Message, Is.EqualTo("Required parameter missing.")); Assert.That(_options, Is.Null); }
/// <summary> /// Initializes this class /// </summary> public OutputMessages(CliOptions pOptions, iOutputStream pOutput) { _options = pOptions; _output = pOutput; }
public void CliOptionsWithoutParameterTest() { var ex = Assert.Throws<ArgumentNullException>(() => _options = new CliOptions(null)); Assert.That(ex.Message, Is.EqualTo("Value cannot be null.\r\nParameter name: args")); Assert.That(_options, Is.Null); }