public static async System.Threading.Tasks.Task ASyncMain(string[] args) { FluentCommandLineParser <BitCLIV1Args> commandLineParser = new FluentCommandLineParser <BitCLIV1Args>(); commandLineParser.Setup(arg => arg.Action) .As('a', "action") .Required() .WithDescription($"Action to perform. {nameof(BitCLIV1Action.Clean)} || {nameof(BitCLIV1Action.Generate)} || {nameof(BitCLIV1Action.Validate)}. Required"); commandLineParser.Setup(arg => arg.SolutionPath) .As('p', "path") .Required() .WithDescription("Path to solution file. Required."); commandLineParser.SetupHelp("?", "help") .Callback(helpText => Console.WriteLine(helpText)); ICommandLineParserResult result = commandLineParser.Parse(args); if (result.HasErrors == true) { Console.WriteLine(result.ErrorText); } else { BitCLIV1Args typedArgs = commandLineParser.Object; typedArgs.SolutionPath = Path.Combine(Environment.CurrentDirectory, typedArgs.SolutionPath); } }
private static CommandLineArgs ParseCommandLineArguments(string[] args) { var commandLineParser = new FluentCommandLineParser <CommandLineArgs>(); commandLineParser .Setup(arg => arg.Iterations) .As('i', "iterations") .SetDefault(DefaultIterations) .WithDescription("The number of simulation iterations."); commandLineParser.SetupHelp("?", "help") .Callback(text => Console.WriteLine(text)); ICommandLineParserResult result = commandLineParser.Parse(args); if (result.HelpCalled) { Environment.Exit(0); } if (result.HasErrors) { Environment.Exit(1); } return(commandLineParser.Object); }
public static CommandLineParsingResult <TBuildType> Parse(string[] args, bool isCaseSensitive = false) { var parser = new FluentCommandLineParser <TBuildType>(); parser.IsCaseSensitive = isCaseSensitive; TBuildType options; ICommandLineParserResult result = parser.Parse <TBuildType>(args, out options, ShortOptions, LongOptions, Description, Required, Default); IEnumerable <string> invalidMutuallyExclusiveSets; IEnumerable <string> invalidMutuallyExclusiveSetsByDefaultValues; bool isValidMutuallyExclusiveSets = ValidateMutuallyExclusiveSets(options, result.UnMatchedOptions, out invalidMutuallyExclusiveSets, out invalidMutuallyExclusiveSetsByDefaultValues); return(new CommandLineParsingResult <TBuildType>() { Options = options, EmptyArgs = result.EmptyArgs, HasErrors = result.HasErrors, ErrorText = result.ErrorText, HelpCalled = result.HelpCalled, HasMutuallyExclusiveSetErrors = !isValidMutuallyExclusiveSets, InvalidMutuallyExclusiveSets = invalidMutuallyExclusiveSets, InvalidMutuallyExclusiveSetsByDefaultValues = invalidMutuallyExclusiveSetsByDefaultValues, ParserResult = result }); }
static void Main(string[] args) { // create a generic parser for the ApplicationArguments type var p = new FluentCommandLineParser <ApplicationArguments>(); p.Setup(arg => arg.BackstoriesInputFileName) .As('b', "backstories") // define the short and long option name .Required() // using the standard fluent Api to declare this Option as required. .WithDescription("Backstories input file path"); p.Setup(arg => arg.StoriesPerIssue) .As('n', "number") // define the short and long option name .Required() // using the standard fluent Api to declare this Option as required. .WithDescription("Number of stories per issue"); p.Setup(arg => arg.IssuesOutputFileName) .As('o', "output") .Required() .WithDescription("Issue headers output file path"); ICommandLineParserResult result = p.Parse(args); if (result.HasErrors) { Console.WriteLine(result.ErrorText); return; } XDocument document = XDocument.Parse(File.ReadAllText(p.Object.BackstoriesInputFileName)); string[] issueHeaders = GenerateIssueHeaders(document, p.Object.StoriesPerIssue); File.WriteAllLines(p.Object.IssuesOutputFileName, issueHeaders); }
public void Ensure_Example_Works_As_Expected() { const int expectedRecordId = 10; const string expectedValue = "Mr. Smith"; const bool expectedSilentMode = true; const bool expectedSwitchA = true; const bool expectedSwitchB = true; const bool expectedSwitchC = false; var args = new[] { "-r", expectedRecordId.ToString(CultureInfo.InvariantCulture), "-v", "\"Mr. Smith\"", "--silent", "-ab", "-c-" }; var recordId = 0; string newValue = null; var inSilentMode = false; var switchA = false; var switchB = false; var switchC = true; var parser = CreateFluentParser(); parser.Setup <bool>('a') .Callback(value => switchA = value); parser.Setup <bool>('b') .Callback(value => switchB = value); parser.Setup <bool>('c') .Callback(value => switchC = value); // create a new Option using a short and long name parser.Setup <int>('r', "record") .WithDescription("The record id to update (required)") .Callback(record => recordId = record) // use callback to assign the record value to the local RecordID property .Required(); // fail if this Option is not provided in the arguments parser.Setup <bool>("silent") .WithDescription("Execute the update in silent mode without feedback (default is false)") .Callback(silent => inSilentMode = silent) .SetDefault(false); // explicitly set the default value to use if this Option is not specified in the arguments parser.Setup <string>('v', "value") .WithDescription("The new value for the record (required)") // used when help is requested e.g -? or --help .Callback(value => newValue = value) .Required(); // do the work ICommandLineParserResult result = parser.Parse(args); Assert.IsFalse(result.HasErrors); Assert.IsFalse(result.Errors.Any()); Assert.AreEqual(expectedRecordId, recordId); Assert.AreEqual(expectedValue, newValue); Assert.AreEqual(expectedSilentMode, inSilentMode); Assert.AreEqual(expectedSwitchA, switchA); Assert.AreEqual(expectedSwitchB, switchB); Assert.AreEqual(expectedSwitchC, switchC); }
private static bool ShouldTerminate(ICommandLineParserResult result) { if (result.HasErrors) { Console.Error.WriteLine(result.ErrorText); } return(result.HasErrors || result.HelpCalled); }
static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var parser = new FluentCommandLineParser <AppArguments>(); parser.Setup(x => x.FilePath) .As('f', "filepath") .WithDescription("Excel file path") .Required(); ICommandLineParserResult result = parser.Parse(args); if (result.HasErrors) { var errorList = new List <string>(); foreach (var formattedError in result.Errors.Select(error => $"{error}: '{error.Option.Description}'")) { errorList.Add(formattedError); logger.Error(formattedError); } RunErrorDialog(errorList); return; } var registrations = from type in Assembly.GetExecutingAssembly().GetExportedTypes() where type.GetInterfaces().Any(x => x.Namespace != null && x.Namespace.StartsWith("Rawr")) where type.Namespace != null && !type.Namespace.StartsWith("BitterMinion") select new { Service = type.GetInterfaces().First(), Implementation = type }; var container = new Container(); foreach (var reg in registrations) { container.Register(reg.Service, reg.Implementation, Lifestyle.Transient); } container.Register <IFileSystem, FileSystem>(); container.Verify(); // This is to resolve the following exceptions: "System.Runtime.InteropServices.COMException // (0x80028018): Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))" Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); var launcher = container.GetInstance <IFileLauncher>(); try { launcher.Launch(parser.Object.FilePath); } catch (Exception exception) { logger.Error(exception.InnerException, exception.Message); RunErrorDialog(exception.Message); } }
private static CommandLineArgs ParseCommandLineArguments(string[] args) { var commandLineParser = new FluentCommandLineParser <CommandLineArgs>(); commandLineParser .Setup(arg => arg.OverviewPath) .As('o', "overview") .WithDescription("Add new sample overviews to the database."); commandLineParser .Setup(arg => arg.PetrographyPath) .As('p', "petrography") .WithDescription("Add new petrography data."); commandLineParser .Setup(arg => arg.GrainSizePath) .As('g', "grainSize") .WithDescription("Add new grain size data."); commandLineParser .Setup(arg => arg.XrdMineralogyPath) .As('x', "xrdMineralogy") .WithDescription("Add new xrd mineralogy data."); commandLineParser .Setup(arg => arg.XrfMainElementsPath) .As('a', "xrfMainElements") .WithDescription("Add new xrf main elements data."); commandLineParser .Setup(arg => arg.XrfMinorElementsPath) .As('i', "xrfMinorElements") .WithDescription("Add new xrf minor elements data."); commandLineParser.SetupHelp("?", "help") .Callback(text => Console.WriteLine(text)); ICommandLineParserResult result = commandLineParser.Parse(args); if (result.HelpCalled) { Environment.Exit(0); } if (result.HasErrors) { Environment.Exit(1); } if (commandLineParser.Object.NoPathsSet()) { commandLineParser.HelpOption.ShowHelp(commandLineParser.Options); Environment.Exit(1); } return(commandLineParser.Object); }
public static FluentCommandLineParsingResult GetCustomResult( this ICommandLineParserResult parserResult) { if (parserResult.HelpCalled) { return(FluentCommandLineParsingResult.Help); } return(parserResult.HasErrors ? FluentCommandLineParsingResult.Failure : FluentCommandLineParsingResult.Success); }
private static void ShowErrors(ICommandLineParserResult result) { Console.Write("ecf: Error parsing arguments."); foreach (var error in result.Errors) { Console.WriteLine($" {error.ToString()}"); } Console.WriteLine(); Console.WriteLine($"Try `ecf --help' for more information."); }
private void ExtractCommandLineParametersIntoObject(ICommandLineParserResult parseResult, IFluentCommandLineParser <CommandLineInputParameters> inputArguments) { _commandLineInputParameters = inputArguments.Object; if (_commandLineInputParameters.IsInputInCSVFormat) { _csvParameters = _mapper.Map <CSVParameters>(_commandLineInputParameters); } _employeeDetailsInput = _mapper.Map <EmployeeDetailsInput>(_commandLineInputParameters); }
/// <summary> /// /// </summary> /// <param name="args"></param> public static void Main(string[] args) { var certificateHost = string.Empty; var parser = new FluentCommandLineParser(); parser.IsCaseSensitive = false; parser.Setup <string>("createCertificate") .Callback(item => { certificateHost = item; }) .WithDescription("Create selfsigned certificate for HOSTNAME"); parser.Setup <int>("httpPort") .Callback(item => { Config.LocalHttpServerPort = item; }) .SetDefault(80) .WithDescription("Define TCP port for incoming HTTP requests. Default port is \"80\""); parser.Setup <int>("httpsPort") .Callback(item => { Config.LocalHttpsServerPort = item; }) .SetDefault(443) .WithDescription("Define TCP port for incoming HTTPS requests. Default port is \"443\""); parser.Setup <string>("certificate") .Callback(item => { Config.CertificatePath = item; }) .WithDescription("Define certificate file path"); parser.Setup <Loglevel>("loglevel") .Callback(item => Config.CurrentLoglevel = item) .SetDefault(Loglevel.Info) .WithDescription("Define log level. Default level is \"Info\". Possible values are: " + string.Join(", ", Enum.GetNames(typeof(Loglevel)))); // sets up the parser to execute the callback when -? or --help is detected parser.SetupHelp("?", "help") .UseForEmptyArgs() .Callback(text => Console.WriteLine(text)); ICommandLineParserResult result = parser.Parse(args); if (result.HasErrors == true) { Console.WriteLine("{0}\r\n\r\n", result.ErrorText); } else if (!string.IsNullOrEmpty(certificateHost) && !string.IsNullOrWhiteSpace(certificateHost)) { Lib.CertificateHandler.Inst.CreateCertificate(certificateHost); } else if (string.IsNullOrEmpty(Config.CertificatePath)) { Console.WriteLine("You did not define a certificate file"); } else { StartProxyServer(); } }
static void Main(string[] args) { // create a generic parser for the ApplicationArguments type var fluentCommandLineParser = new FluentCommandLineParser <JiraOptions>(); fluentCommandLineParser.Setup(f => f.JiraUri).As('j', "uri").Required().WithDescription("Url to access Jira"); fluentCommandLineParser.Setup(f => f.Password) .As('p', "password") .Required() .WithDescription("Password to access TC"); fluentCommandLineParser.Setup(f => f.UserName) .As('u', "username") .Required() .WithDescription("Username to access TC"); fluentCommandLineParser.Setup(f => f.FixVersion) .As('f', "fix") .Required() .WithDescription("The main version we want to apply the fix for, e.g. 5.6.0 (not 5.6.0.XX)"); fluentCommandLineParser.Setup(f => f.AvailableFromVersion) .As('a', "available") .WithDescription("The version the tickets will be available from, e.g. 5.6.0.XX"); fluentCommandLineParser.Setup(f => f.ProjectKey) .As('k', "project") .WithDescription("The project key to update the version for"); fluentCommandLineParser.Setup(f => f.CustomFieldName) .As('c', "fieldName") .WithDescription("The name of the custom field to update e.g. customfield_XXX"); ICommandLineParserResult commandLineParserResult = fluentCommandLineParser.Parse(args); if (!commandLineParserResult.HasErrors) { var jiraOptions = fluentCommandLineParser.Object; var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterModule <NLogModule>(); containerBuilder.RegisterInstance(jiraOptions).As <IJiraOptions>().SingleInstance(); containerBuilder.RegisterType <MyApplication>().As <IApplication>().SingleInstance(); containerBuilder.RegisterType <DateTimeProvider>().As <IDateTimeProvider>().SingleInstance(); var container = containerBuilder.Build(); var application = container.Resolve <IApplication>(); bool success = application.Run(); if (!success) { Environment.Exit(-1); } } else { fluentCommandLineParser.SetupHelp("?", "help").Callback(text => Console.WriteLine(text)); Environment.Exit(-1); } }
static void Main(string[] args) { var p = new FluentCommandLineParser <Arguments>(); p.Setup(arg => arg.RootUri) .As('r', "rootUri") .Required() .WithDescription("Start crawling from this web page"); p.Setup(arg => arg.MaxPagesToIndex) .As('m', "maxPages") .SetDefault(DefaultMaxPagesToIndex) .WithDescription("Stop after having indexed this many pages. Default is " + DefaultMaxPagesToIndex + "; 0 means no limit."); p.Setup(arg => arg.ServiceName) .As('s', "ServiceName") .Required() .WithDescription("The name of your Azure Search service"); p.Setup(arg => arg.IndexName) .As('i', "IndexName") .Required() .WithDescription("The name of the index in your Azure Search service"); p.Setup(arg => arg.AdminApiKey) .As('a', "AdminApiKey") .Required(); p.SetupHelp("?", "h", "help").Callback(text => Console.Error.WriteLine(text)); ICommandLineParserResult result = p.Parse(args); if (result.HasErrors) { Console.Error.WriteLine(result.ErrorText); Console.Error.WriteLine("Usage: "); p.HelpOption.ShowHelp(p.Options); return; } if (result.HelpCalled) { return; } Arguments arguments = p.Object; var indexer = new AzureSearchIndexer(arguments.ServiceName, arguments.IndexName, arguments.AdminApiKey, new TextExtractor()); var crawler = new Crawler(indexer); crawler.Crawl(arguments.RootUri, maxPages: arguments.MaxPagesToIndex).Wait(); Console.Read(); // keep console open until a button is pressed so we see the output }
static void Main(string[] args) { var p = new FluentCommandLineParser <Arguments>(); p.Setup(arg => arg.RootUri) .As('r', "rootUri") .Required() .WithDescription("Start crawling from this web page"); p.Setup(arg => arg.MaxPagesToIndex) .As('m', "maxPages") .SetDefault(DefaultMaxPagesToIndex) .WithDescription("Stop after having indexed this many pages. Default is " + DefaultMaxPagesToIndex + "; 0 means no limit."); p.Setup(arg => arg.AccountName) .As('n', "StorageAccountName") .Required() .WithDescription("The name of your Azure Storage Account"); p.Setup(arg => arg.AccountKey) .As('k', "StorageAccountKey") .Required() .WithDescription("The key of your Azure Storage Account"); p.Setup(arg => arg.SqlConnectionString) .As('s', "SqlConnectionString") .Required() .WithDescription("Sql Connection String is required"); p.SetupHelp("?", "h", "help").Callback(text => Console.Error.WriteLine(text)); ICommandLineParserResult result = p.Parse(args); if (result.HasErrors) { Console.Error.WriteLine(result.ErrorText); Console.Error.WriteLine("Usage: "); p.HelpOption.ShowHelp(p.Options); return; } if (result.HelpCalled) { return; } Arguments arguments = p.Object; var handler = new WebPageHandler(arguments.AccountName, arguments.AccountKey, "search", arguments.SqlConnectionString); var crawler = new Crawler(handler); crawler.Crawl(arguments.RootUri, maxPages: arguments.MaxPagesToIndex).Wait(); Console.Read(); // keep console open until a button is pressed so we see the output }
private static int Main(string[] args) { CommandLineParser commandLineParser = new CommandLineParser(); ICommandLineParserResult commandLineParserResult = commandLineParser.Parse(args); int result = commandLineParserResult.Execute(); if (Debugger.IsAttached) { Console.ReadKey(); } return(result); }
public static void ProcessParsingResults( ICommandLineParserResult results, CommandDispatcher dispatcher) { if (results.HasErrors) { PostProcessInvalidArgs(results.Errors); } else { PostProcessValidArgs(dispatcher); } }
public static void Main(string[] args) { try { var p = new FluentCommandLineParser <CommandLineArgs>(); p.Setup(arg => arg.WaveFileName) .As('f', "WaveFileName") .WithDescription("Name of wave file to generate") .SetDefault("output.wav"); p.Setup(arg => arg.MP3FileName) .As('m', "MP3FileName") .WithDescription("Name of mp3 file to generate") .SetDefault("output.mp3"); p.Setup(arg => arg.IncludeMP3) .As('i', "IncludeMP3") .WithDescription("If true then the the output will also include an mp3 file") .SetDefault(true); p.SetupHelp("?", "help").Callback(text => ColorConsole.WriteLine(text, ConsoleColor.Blue)); ICommandLineParserResult parserResult = p.Parse(args); if (parserResult.HasErrors) { ColorConsole.WriteLine(parserResult.ErrorText, ConsoleColor.Red); p.HelpOption.ShowHelp(p.Options); } else { var arguments = p.Object; ColorConsole.WriteLine("Starting audio recorder...", ConsoleColor.Blue); Recorder recorder = new Recorder(); recorder.Record(arguments.WaveFileName, arguments.MP3FileName, arguments.IncludeMP3); ColorConsole.WriteLine("End of audio recorder", ConsoleColor.Blue); } } catch (Exception exception) { ColorConsole.WriteLine(exception.ToString(), ConsoleColor.Red); } }
public void Parse(string[] args) { ICommandLineParserResult result = m_Parser.Parse(args); if (!result.HasErrors) { ApplicationArguments = m_Parser.Object; HasError = false; } else { m_Console.WriteLine(result.ErrorText); m_Logger.Error(result.ErrorText); ApplicationArguments = Empty; HasError = true; } }
private static bool ShouldTerminateCli(ICommandLineParserResult parsingStatus, FluentCommandLineParser <CliOptions> parser) { if (parsingStatus.HelpCalled) { return(true); } if (parsingStatus.HasErrors) { Console.WriteLine(parsingStatus.ErrorText); foreach (var error in parsingStatus.Errors) { parser.HelpOption.ShowHelp(new[] { error.Option }); } return(true); } return(false); }
public static void Parse() { var p = new FluentCommandLineParser <ApplicationArguments>(); p.Setup(a => a.Directories) .As('d', "directory") .WithDescription("Active Directories for any start-up command. Also, if specified, the first active directory will be selected in the directory listing on application start. Otherwise, the selected directory from the last time the application ran will be selected"); p.Setup(a => a.Icon) .As('i', "icon") .WithDescription("Active Icon for any start-up command. Also, if specified, the active icon will be selected in the icon listing on application start. Otherwise, the selected icon from the last time the application ran will be selected"); p.Setup(a => a.Roots.Icons) .As('o', "icons") .WithDescription("Icons Root Directory"); p.Setup(a => a.Roots.Action) .As('r', "root") .WithDescription("Root Directory"); p.Setup(a => a.Roots.Content) .As('c', "content") .WithDescription("Content Root Directory"); Result = p.Parse(Arguments); Options = p.Object; }
private static void Main(string[] args) { FluentCommandLineParser <ApplicationArguments> parser = CreateParser(); ICommandLineParserResult result = parser.Parse(args); if (result.HasErrors) { System.Console.WriteLine(result.ErrorText); return; } using (var container = new WindsorContainer()) { container.Install(FromAssembly.This()); var finder = container.Resolve <IClosestPointsFinder>(); finder.Run(parser.Object); DisplayIds(finder.ClosestIds); container.Release(finder); } }
public static async Task Main(string[] args) { var parser = new FluentCommandLineParser <ApplicationArguments>(); parser .Setup(arg => arg.BuildDocumentation) .As('d', "docu") .SetDefault(false) .WithDescription("Build the documentation files in the app folder"); parser .SetupHelp("?", "help") .Callback(text => Console.WriteLine(text)); ICommandLineParserResult parseResult = parser.Parse(args); ApplicationArguments parsedArgs = !parseResult.HasErrors ? parser.Object : null; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; var services = await Initializer.InitializeServicesAndStartClientAsync(); _discordClient = services.GetRequiredService <DiscordClient>(); if (parsedArgs.BuildDocumentation) { var cNext = _discordClient.GetCommandsNext(); var docsHTML = Documentation.DocumentationBuilder.BuildDocumentation(cNext, Documentation.DocumentationOutputType.HTML); await File.WriteAllTextAsync(@"C:\temp\commands.html", docsHTML); var docsMD = Documentation.DocumentationBuilder.BuildDocumentation(cNext, Documentation.DocumentationOutputType.MarkDown); await File.WriteAllTextAsync(@"C:\temp\commands.md", docsMD); await Console.Out.WriteLineAsync("Documentation built"); } await Task.Delay(-1); // Prevent the console window from closing. }
public static bool HandleStandardResult(ICommandLineParserResult result) { if (result.HelpCalled) { return(true); } if (result.HasErrors) { Console.Error.WriteLine(result.ErrorText); Console.Error.WriteLine($"Type \"{Assembly.GetExecutingAssembly().GetName().Name} --help\" to show the command line syntax."); return(true); } foreach (var option in result.AdditionalOptionsFound) { Console.Error.WriteLine(string.IsNullOrEmpty(option.Value) ? $"Ignoring option {(option.Key.Length > 1 ? "--" : "-")}{option.Key}" : $"Ignoring option {(option.Key.Length > 1 ? "--" : "-")}{option.Key}='{option.Value}'"); } return(false); }
public static async Task Main(string[] args) { var parser = new FluentCommandLineParser <ApplicationArguments>(); _ = parser .Setup(arg => arg.BuildDocumentation) .As('d', "docu") .SetDefault(false) .WithDescription("Build the documentation files in the app folder"); _ = parser .SetupHelp("?", "help") .Callback(text => Console.WriteLine(text)); ICommandLineParserResult parseResult = parser.Parse(args); ApplicationArguments parsedArgs = !parseResult.HasErrors ? parser.Object : null; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; await DiscordClientConfiguration.EnsureExistsAsync().ConfigureAwait(false); // Ensure the configuration file has been created. services = await Initializer.InitializeAsync(parsedArgs).ConfigureAwait(false); await Task.Delay(-1).ConfigureAwait(false); // Prevent the console window from closing. }
public HelpAction(IEnumerable <TypeAttributePair> actions, Func <Type, IAction> createAction, IAction action, ICommandLineParserResult parseResult) : this(actions, createAction) { _action = action; _parseResult = parseResult; }
private static async Task AsyncMain(string[] args) { FluentCommandLineParser <BitCLIV1Args> commandLineParser = new FluentCommandLineParser <BitCLIV1Args>(); commandLineParser.Setup(arg => arg.Action) .As('a', "action") .SetDefault(BitCLIV1Action.Generate) .WithDescription($"Action to perform. {nameof(BitCLIV1Action.Clean)} || {nameof(BitCLIV1Action.Generate)} || {nameof(BitCLIV1Action.Validate)}. Required"); commandLineParser.Setup(arg => arg.Path) .As('p', "path") .Required() .WithDescription("Path to solution file. Required."); commandLineParser.SetupHelp("?", "help") .Callback(helpText => WriteInfo(helpText)); ICommandLineParserResult result = commandLineParser.Parse(args); if (result.HasErrors == true) { throw new Exception(result.ErrorText); } else { BitCLIV1Args typedArgs = commandLineParser.Object; typedArgs.Path = Path.Combine(Environment.CurrentDirectory, typedArgs.Path); if (!File.Exists(typedArgs.Path)) { throw new FileNotFoundException($"Solution could not be found at {typedArgs.Path}"); } WriteInfo($"Solution Path: {typedArgs.Path}"); WriteInfo($"Action: {typedArgs.Action}"); try { WriteMessage("DotNetBuild started..."); using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false)) using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) { using (Process dotnetBuildProcess = new Process()) { dotnetBuildProcess.StartInfo.UseShellExecute = false; dotnetBuildProcess.StartInfo.RedirectStandardOutput = dotnetBuildProcess.StartInfo.RedirectStandardError = true; dotnetBuildProcess.StartInfo.FileName = "dotnet"; dotnetBuildProcess.StartInfo.Arguments = $"build {typedArgs.Path}"; dotnetBuildProcess.StartInfo.CreateNoWindow = true; dotnetBuildProcess.StartInfo.WorkingDirectory = Directory.GetParent(typedArgs.Path).FullName; dotnetBuildProcess.OutputDataReceived += (sender, e) => { if (e.Data != null) { WriteMessage(e.Data); } else { outputWaitHandle.Set(); } }; dotnetBuildProcess.ErrorDataReceived += (sender, e) => { if (e.Data != null) { WriteError(e.Data); } else { errorWaitHandle.Set(); } }; dotnetBuildProcess.Start(); dotnetBuildProcess.BeginOutputReadLine(); dotnetBuildProcess.BeginErrorReadLine(); dotnetBuildProcess.WaitForExit(); outputWaitHandle.WaitOne(); errorWaitHandle.WaitOne(); } } WriteMessage("DotNetBuild completed"); } catch (Exception ex) { WriteError($"DotNetBuild Error => {ex.ToString()}"); } using (MSBuildWorkspace workspace = MSBuildWorkspace.Create()) { workspace.LoadMetadataForReferencedProjects = workspace.SkipUnrecognizedProjects = true; workspace.WorkspaceFailed += Workspace_WorkspaceFailed; await workspace.OpenSolutionAsync(typedArgs.Path); switch (typedArgs.Action) { case BitCLIV1Action.Generate: IProjectDtoControllersProvider controllersProvider = new DefaultProjectDtoControllersProvider(); IProjectDtosProvider dtosProvider = new DefaultProjectDtosProvider(controllersProvider); DefaultTypeScriptClientProxyGenerator generator = new DefaultTypeScriptClientProxyGenerator(new DefaultBitCodeGeneratorOrderedProjectsProvider(), new DefaultBitConfigProvider(), dtosProvider, new DefaultTypeScriptClientProxyDtoGenerator(), new DefaultTypeScriptClientContextGenerator(), controllersProvider, new DefaultProjectEnumTypesProvider(controllersProvider, dtosProvider)); await generator.GenerateCodes(workspace); break; case BitCLIV1Action.Validate: throw new NotImplementedException("Validate"); case BitCLIV1Action.Clean: throw new NotImplementedException("Clean"); default: throw new NotSupportedException(); } } } }
static void Main(string[] args) { FluentCommandLineParser <ApplicationArguments> parser = new FluentCommandLineParser <ApplicationArguments>(); parser.Setup(arg => arg.IP).As('i', "ip").SetDefault("127.0.0.1").WithDescription("(optional) IP address of the MySQL server, will use 127.0.0.1 if not specified"); parser.Setup(arg => arg.Port).As('n', "port").SetDefault(3306).WithDescription("(optional) Port number of the MySQL server, will use 3306 if not specified"); parser.Setup(arg => arg.User).As('u', "user").SetDefault("root").WithDescription("(optional) Username, will use root if not specified"); parser.Setup(arg => arg.Password).As('p', "password").SetDefault(String.Empty).WithDescription("(optional) Password, will use empty password if not specified"); parser.Setup(arg => arg.Database).As('d', "database").Required().WithDescription("Database name"); parser.Setup(arg => arg.Table).As('t', "table").SetDefault(String.Empty).WithDescription("(optional) Table name, will generate entire database if not specified"); parser.Setup(arg => arg.Namespace).As('s', "namespace").SetDefault(String.Empty).WithDescription("(optional) Namespace name, will add a namespace to the cs file."); parser.Setup(arg => arg.GenerateConstructorAndOutput).As('g', "generateconstructorandoutput").SetDefault(false).WithDescription("(optional) Generate a reading constructor and SQL statement output - Activate with -g true"); parser.Setup(arg => arg.GenerateMarkupPages).As('m', "generatemarkuppages").SetDefault(false).WithDescription("(optional) Generate markup pages for database and tables which can be used in wikis - Activate with -m true"); parser.Setup(arg => arg.MarkupDatabaseNameReplacement).As('r', "markupdatabasenamereplacement").SetDefault("").WithDescription("(optional) Will use this instead of database name for wiki breadcrump generation"); parser.SetupHelp("?", "help").Callback(text => Console.WriteLine(text)); ICommandLineParserResult result = parser.Parse(args); if (!result.HasErrors) { ApplicationArguments conf = parser.Object as ApplicationArguments; if (conf.Database is null) { Console.WriteLine("You didn't specify a database"); return; } string confString = $"Server={conf.IP};Port={conf.Port};Uid={conf.User};Pwd={conf.Password};Database={conf.Database}"; Console.WriteLine("Database connection: {0}", $"Server={conf.IP};Port={conf.Port};Uid={conf.User};Database={conf.Database}"); Console.WriteLine("Defined Namespace: {0}", conf.Namespace); Dictionary <string, List <Column> > database = new Dictionary <string, List <Column> >(); using (MySqlConnection con = new MySqlConnection(confString)) { con.Open(); Console.WriteLine("Connection opened ..."); using (MySqlCommand cmd = con.CreateCommand()) { cmd.CommandText = $"SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{conf.Database}'"; if (!conf.Table.Equals(string.Empty)) { cmd.CommandText += $" AND TABLE_NAME = '{conf.Table}'"; } MySqlDataReader reader = cmd.ExecuteReader(); if (!reader.HasRows) { return; } while (reader.Read()) { if (database.ContainsKey(reader.GetString(0))) { database[reader.GetString(0)].Add(new Column(reader)); } else { database.Add(reader.GetString(0), new List <Column>() { new Column(reader) }); } } } Console.WriteLine("Retrived table information ..."); foreach (KeyValuePair <string, List <Column> > table in database) { using (MySqlCommand cmd = con.CreateCommand()) { // lul - is there a way to do this without this senseless statement? cmd.CommandText = $"SELECT * FROM `{table.Key}` LIMIT 0"; MySqlDataReader reader = cmd.ExecuteReader(); DataTable schema = reader.GetSchemaTable(); foreach (Column column in table.Value) { column.Type = schema.Select($"ColumnName = '{column.Name}'")[0]["DataType"] as Type; } } } Console.WriteLine("Retrived column types ..."); con.Close(); } DbToClasses(conf.Database, database, conf.GenerateConstructorAndOutput, conf); if (conf.GenerateMarkupPages) { DbToMarkupPage(String.IsNullOrEmpty(conf.MarkupDatabaseNameReplacement) ? conf.Database : conf.MarkupDatabaseNameReplacement, database); } Console.WriteLine("Successfully generated C# classes!"); } else { Console.WriteLine("Entered command line arguments has errors!"); } Console.ReadLine(); }
/// <summary> /// Very useful utility to check if width of backstory titles in pixels. Check Verse.Text class for more correct work. Width of field is 160px /// </summary> /// <param name="args"></param> static void Main(string[] args) { // create a generic parser for the ApplicationArguments type var p = new FluentCommandLineParser <ApplicationArguments>(); p.Setup(arg => arg.BackstoriesFileName) .As('b', "backstories") .Required() .WithDescription("Backstories original file path"); p.Setup(arg => arg.MaxWidth) .As('w', "width") .Required() .WithDescription("Max line width"); p.Setup(arg => arg.ReportOutputFileName) .As('o', "output") .Required() .WithDescription("Report file path"); ICommandLineParserResult result = p.Parse(args); if (result.HasErrors) { Console.WriteLine(result.ErrorText); return; } XDocument backstoriesDoc = XDocument.Load(p.Object.BackstoriesFileName); Font font = new Font("Arial", 10.5f); Bitmap bmp = new Bitmap(500, 100, PixelFormat.Format32bppPArgb); float maxWidth = p.Object.MaxWidth; List <BackstoryLine> oversizedBackstories = new List <BackstoryLine>(); using (Graphics graphics = Graphics.FromImage(bmp)) { Brush background = new SolidBrush(Color.FromArgb(255, Color.Black)); Brush foreground = new SolidBrush(Color.White); graphics.FillRectangle(background, new RectangleF(0, 0, bmp.Width, bmp.Height)); //string iii = "I i i i i i i i i i i i i i i i i i i i i i i i i"; //SizeF stringSize = graphics.MeasureString(iii, font); //graphics.DrawRectangle(new Pen(Color.Red, 1), 0f, 0f, stringSize.Width, stringSize.Height); //graphics.DrawString(iii, font, foreground, new PointF(0, 0)); foreach (XElement storyElem in backstoriesDoc.Root.Elements()) { string title = CapitalizeFirst(storyElem.Element("title").Value); float titleWidth = graphics.MeasureString(title, font).Width; if (titleWidth > maxWidth) { oversizedBackstories.Add( new BackstoryLine() { Title = title, Width = titleWidth, }); } string titleFemale = storyElem.Element("titleFemale")?.Value; if (titleFemale != null) { titleFemale = CapitalizeFirst(titleFemale); float titleFemaleWidth = graphics.MeasureString(titleFemale, font).Width; if (titleFemaleWidth > maxWidth) { oversizedBackstories.Add( new BackstoryLine() { Title = titleFemale, Width = titleFemaleWidth, }); } } } } oversizedBackstories = oversizedBackstories.OrderByDescending(bs => bs.Width).ToList(); using (TextWriter writer = File.CreateText(p.Object.ReportOutputFileName)) { writer.WriteLine("Width > {0}:", maxWidth); foreach (BackstoryLine line in oversizedBackstories) { writer.WriteLine("{0:0.0}\t{1}", line.Width, line.Title); } writer.Close(); } }
static void Main(string[] args) { //arguments setup var p = new FluentCommandLineParser <Options>(); p.Setup(o => o.Floors) .As('f', "floors") .WithDescription("The amount of floors.") .Required(); p.Setup(o => o.Height) .As('h', "height") .WithDescription("The height of each floor in meters.") .Required(); p.Setup(o => o.Speed) .As('s', "speed") .WithDescription("The elevator speed in m/s.") .Required(); p.Setup(o => o.Delay) .As('d', "delay") .WithDescription("The time span between opening and closing the door in seconds.") .Required(); p.SetupHelp("?", "help") .Callback(text => Console.WriteLine(text)); ICommandLineParserResult result = null; try { result = p.Parse(args); if (result.HasErrors) { Console.Write(result.ErrorText + "\nType --help or -? for help"); } else if (!result.HelpCalled) { //creates the building Building building = new Building((uint)p.Object.Floors, p.Object.Height); //adds an elevator Elevator elevator = building.AddElevator(p.Object.Speed, p.Object.Delay); //setup events elevator.OnDoorOpen += (floor) => { Console.WriteLine("##### DOOR OPENED ON FLOOR " + floor); }; elevator.OnDoorClose += (floor) => { Console.WriteLine("##### DOOR CLOSED ON FLOOR " + floor); }; elevator.OnPassFloor += (floor) => { Console.WriteLine("##### PASSED ON THE FLOOR " + floor); }; for (; ;) { try { Console.WriteLine("Type the floor number (between 0 and " + (building.Floors - 1) + ")"); elevator.Visit(uint.Parse(Console.ReadLine())); } catch (ArgumentException e) { Console.WriteLine(e.Message); } catch { Console.WriteLine("An unexpected error has occurred"); } } } } catch (Exception e) { Console.Write(e.InnerException is ArgumentException ? e.InnerException.Message : "An unexpected error has happened"); } }
public CliArgumentsException(string message, ICommandLineParserResult parseResults, params CliArgument[] arguments) : this(message, arguments) { ParseResults = parseResults; }