private ControllerResult ProcessStandardMode() { IModelBindingDefinition <ControllerSelectionArgumentModel> definition = Args.Configuration.Configure <ControllerSelectionArgumentModel>(); ControllerSelectionArgumentModel model; try { model = definition.CreateAndBind(ApplicationContext.Args); //model = definition.CreateAndBind(_args); if (ApplicationContext.Args.First().ToLower().Contains(model.ControllerName)) { ApplicationContext.Args = ApplicationContext.Args.Skip(1).ToArray(); } } catch { model = new ControllerSelectionArgumentModel(); model.ControllerName = "Render"; } //IRtcController controller; ControllerResult result; switch (model.ControllerName.ToLowerInvariant()) { case "help": HelpController controllerHelp = new HelpController(); controllerHelp.ArgumentModel = Args.Configuration.Configure <HelpArgumentModel>().CreateAndBind(ApplicationContext.Args); result = controllerHelp.Execute(); break; case "install": InstallController controllerInstall = new InstallController(); //IModelBindingDefinition<InstallArgumentModel> controllerDefinition = // Args.Configuration.Configure<InstallArgumentModel>(); controllerInstall.ArgumentModel = Args.Configuration.Configure <InstallArgumentModel>().CreateAndBind(ApplicationContext.Args); result = controllerInstall.Execute(); break; default: RenderController controllerRender = new RenderController(); controllerRender.Context = ApplicationContext; IModelBindingDefinition <RenderArgumentModel> definitionRender = Args.Configuration.Configure <RenderArgumentModel>(); //IModelBindingDefinition<RenderArgumentModel> controllerDefinition = // Args.Configuration.Configure<RenderArgumentModel>(); string[] controllerArgs = (string[])ApplicationContext.Args.Clone(); controllerRender.ArgumentModel = definitionRender.CreateAndBind(controllerArgs); _logger.Info("Start Rendreding with arguments:"); _logger.Info("Template Content : " + controllerRender.ArgumentModel.TemplateContent); _logger.Info("Model Content : " + controllerRender.ArgumentModel.ModelContent); _logger.Info("Result path : " + controllerRender.ArgumentModel.ResultFile); result = controllerRender.Execute(); break; } return(result); }
public static void Binding() { bindingDefinition = Args.Configuration.Configure <Arguments>() .AsFluent() .ParsesArgumentsWith(typeof(string[]), new ArrayOfStringConverter()) .Initialize(); }
private static void ShowHelp(IModelBindingDefinition <ConversionOrder> argsDefinition) { var help = new Args.Help.HelpProvider().GenerateModelHelp(argsDefinition); var f = new ConsoleHelpFormatter(80, 1, 5); Console.WriteLine(f.GetHelp(help)); }
/// <summary> /// /// </summary> /// <typeparam name="TModel"></typeparam> /// <param name="definition"></param> /// <returns></returns> public ModelHelp GenerateModelHelp <TModel>(IModelBindingDefinition <TModel> definition) { var modelHelp = new ModelHelp { SwitchDelimiter = definition.SwitchDelimiter, Members = definition.Members.Select(GenerateMemberHelp).ToArray(), HelpText = definition.CommandModelDescription, }; if (string.IsNullOrEmpty(modelHelp.HelpText)) { var helpAttribute = typeof(TModel) #if NETSTANDARD_1_3 .GetTypeInfo() #endif .GetCustomAttributes(true).OfType <ResourceMemberHelpAttributeBase>().SingleOrDefault(); if (helpAttribute != null) { modelHelp.HelpText = helpAttribute.GetHelpText(); } } return(modelHelp); }
public static void Binding() { bindingDefinition = Args.Configuration.Configure<Arguments>() .AsFluent() .ParsesArgumentsWith(typeof(string[]), new ArrayOfStringConverter()) .Initialize(); }
private static void ShowHelp(IModelBindingDefinition<CmdLine> definition) { var help = new HelpProvider().GenerateModelHelp(definition); var helpFormatter = new ConsoleHelpFormatter(System.Console.WindowWidth, 1, 5); help.HelpText = Assembly.GetExecutingAssembly().FullName + Environment.NewLine; var helpString = helpFormatter.GetHelp(help); System.Console.Error.WriteLine(helpString); }
public void Validate(IModelBindingDefinition <MigrationParameters> commandLineParser) { if (Help || string.IsNullOrEmpty(Engine) || string.IsNullOrEmpty(ConnectionString) || string.IsNullOrEmpty(Migrations)) { throw new TerminateAndShowHelp(commandLineParser); } ResolvedEngine = DbEngine.LookUpByName(Engine); }
public HelpCommand(IModelBindingDefinition <Arguments> modelBindingDefinition) { if (modelBindingDefinition == null) { throw new ArgumentNullException("modelBindingDefinition"); } _modelBindingDefinition = modelBindingDefinition; }
private static void ShowHelp(IModelBindingDefinition <Options> argsConfig) { var helpProvider = new HelpProvider(); var help = helpProvider.GenerateModelHelp(argsConfig); var helpFormatter = new ConsoleHelpFormatter(); Console.WriteLine(helpFormatter.GetHelp(help)); Console.ReadKey(); }
public static void Main(string[] args) { AppLaunchingCommandLine commandLine; IModelBindingDefinition <AppLaunchingCommandLine> modelBindingDefinition = null; try { modelBindingDefinition = Configuration.Configure <AppLaunchingCommandLine>(); commandLine = modelBindingDefinition.CreateAndBind(args); /* * if (commandLine.ProductId == Guid.Empty) * { * Console.WriteLine(""); * Console.WriteLine("***Warning*** - no productId supplied"); * Console.WriteLine(""); * } */ } catch (Exception /*exception*/) { if (modelBindingDefinition != null) { var help = new HelpProvider(); var formatter = new ConsoleHelpFormatter(); var sw = new StringWriter(); var text = help.GenerateModelHelp(modelBindingDefinition); formatter.WriteHelp(text, sw); Console.Write(sw.ToString()); } else { Console.Write("Sorry - no help available!"); } return; } try { Console.WriteLine("AutomationHost starting"); using (var program = new Program(commandLine)) { Console.WriteLine("To show help, enter 'help'"); program.Run(); } } catch (QuitNowPleaseException) { Console.WriteLine("Goodbye"); } catch (Exception exception) { Console.WriteLine(string.Format("Exception seen {0} {1}", exception.GetType().FullName, exception.Message)); } }
private void DefineStartMode() { IModelBindingDefinition <ServerModeArgumentModel> definition = Args.Configuration.Configure <ServerModeArgumentModel>(); ServerModeArgumentModel model = null; try { model = definition.CreateAndBind(_args); ApplicationContext = new ApplicationContext(_args); ApplicationContext.StartMode = model; } catch { ApplicationContext = new ApplicationContext(_args); ApplicationContext.StartMode = new ServerModeArgumentModel() { ServerMode = ServerMode.StandAlone, StartOptions = string.Empty }; } _logger.Info("Start Mode : {0}", ApplicationContext.StartMode.ServerMode); if (ApplicationContext.StartMode.StartOptions != null && ApplicationContext.StartMode.StartOptions.Contains("wait")) { //Timer t = new Timer(5000); ////t.Elapsed += new ElapsedEventHandler(t_Elapsed); //bool waitForTimer = true; //t.Elapsed += (s,e) => {waitForTimer = false; }; //while (waitForTimer) //{ //} _logger.Info("Please attach a debugger to continue..."); while (!Debugger.IsAttached) { } _logger.Info("Debugger attached, let's continue"); } if (_args[0] == model.ServerMode.ToString()) { int start = 1; if (model != null && !string.IsNullOrEmpty(model.StartOptions) && _args.Length >= 3) { start = 3; } List <string> newargs = new List <string>(); for (int i = start; i < _args.Length; i++) { newargs.Add(_args[i]); } _args = newargs.ToArray(); ApplicationContext.Args = _args; } }
public void Initialize <TModel>(IModelBindingDefinition <TModel> init) { var modelAttribute = typeof(TModel).GetCustomAttributes(true).OfType <ArgsModelAttribute>().SingleOrDefault() ?? ArgsModelAttribute.Default; var modelDescriptionAttribute = typeof(TModel).GetCustomAttributes(true).OfType <DescriptionAttribute>().SingleOrDefault(); init.SwitchDelimiter = modelAttribute.SwitchDelimiter; init.StringComparer = modelAttribute.StringComparer; SortedDictionary <int, MemberInfo> ordinalArguments = new SortedDictionary <int, MemberInfo>(); if (modelDescriptionAttribute != null) { init.CommandModelDescription = modelDescriptionAttribute.Description; } var members = GetMembers(typeof(TModel)); foreach (MemberInfo member in members) { var memberBinding = init.GetOrCreateMemberBindingDefinition(member); var memberAttributes = member.GetCustomAttributes(true).ToArray(); var switchAttribute = memberAttributes.OfType <ArgsMemberSwitchAttribute>().SingleOrDefault(); if (switchAttribute != null) { if (switchAttribute.SwitchValues != null) { memberBinding.SwitchValues.AddRange(switchAttribute.SwitchValues); } if (switchAttribute.ArgumentIndex.HasValue) { ordinalArguments.Add(switchAttribute.ArgumentIndex.Value, member); } } else { memberBinding.SwitchValues.AddRange(new[] { member.Name, DeriveShortName(members, member) }.Distinct(init.StringComparer)); } var defaultValueAttribute = memberAttributes.OfType <DefaultValueAttribute>().SingleOrDefault(); if (defaultValueAttribute != null) { memberBinding.DefaultValue = defaultValueAttribute.Value; } var typeConverterAttribute = memberAttributes.OfType <TypeConverterAttribute>().SingleOrDefault(); if (typeConverterAttribute != null) { memberBinding.TypeConverter = (TypeConverter)ArgsTypeResolver.Current.GetService(Type.GetType(typeConverterAttribute.ConverterTypeName)); } } init.SetOrdinalArguments(ordinalArguments.Select(a => a.Value)); }
private static void ShowHelp(IModelBindingDefinition <GitReleaseNotesArguments> modelBindingDefinition, string reason = null) { var help = new HelpProvider().GenerateModelHelp(modelBindingDefinition); var f = new ConsoleHelpFormatter(); f.WriteHelp(help, Console.Out); if (reason != null) { Console.WriteLine(); Console.WriteLine(reason); } }
private static void ShowHelp(IModelBindingDefinition <GitReleaseNotesArguments> modelBindingDefinition, string reason = null) { var help = new HelpProvider().GenerateModelHelp(modelBindingDefinition); var bufferWidth = Console.IsOutputRedirected ? 80 : Console.BufferWidth; var f = new ConsoleHelpFormatter(bufferWidth, 1, 5); f.WriteHelp(help, Console.Out); if (reason != null) { Console.WriteLine(); Console.WriteLine(reason); } }
private static string FormatHelp(IModelBindingDefinition<MigrationParameters> commandLineParser) { var helpData = new HelpProvider().GenerateModelHelp(commandLineParser); var message = new StringBuilder(); message.AppendLine(); message.AppendLine(helpData.HelpText); message.AppendLine(); foreach (var member in helpData.Members) { message.AppendFormat("{0} (--{1})\r\n", member.Name, member.Switches.Aggregate((lhs, rhs) => String.Join(", --", lhs, rhs)). ToLowerInvariant()); message.AppendFormat(" {0}\r\n\r\n", member.HelpText); } return message.ToString(); }
private static string FormatHelp(IModelBindingDefinition <MigrationParameters> commandLineParser) { var helpData = new HelpProvider().GenerateModelHelp(commandLineParser); var message = new StringBuilder(); message.AppendLine(); message.AppendLine(helpData.HelpText); message.AppendLine(); foreach (var member in helpData.Members) { message.AppendFormat("{0} (--{1})\r\n", member.Name, member.Switches.Aggregate((lhs, rhs) => string.Join(", --", lhs, rhs)).ToLowerInvariant()); message.AppendFormat(" {0}\r\n\r\n", member.HelpText); } return(message.ToString()); }
public void SimpleModelFluentSetup() { definitionUnderTest = new ModelBindingDefinition <SimpleTestModel>() .AsFluent().UsingStringComparer(StringComparer.InvariantCulture) .UsingSwitchDelimiter("--") .ParsesArgumentsWith(typeof(int), new System.ComponentModel.Int16Converter()) .HasFirstOrdinalArgumentOf(a => a.FileName) .ForMember(a => a.Name) .WatchesFor("name", "nam") .ForMember(a => a.Id) .WatchesFor("id") .HasHelpTextOf("Hello World") .ForMember(a => a.Force) .WatchesFor("f") .ForMember(a => a.Speed) .WatchesFor("fs") .Initialize(); }
public void SimpleModelFluentSetup() { definitionUnderTest = new ModelBindingDefinition<SimpleTestModel>() .AsFluent().UsingStringComparer(StringComparer.InvariantCulture) .UsingSwitchDelimiter("--") .ParsesArgumentsWith(typeof(int), new System.ComponentModel.Int16Converter()) .HasFirstOrdinalArgumentOf(a => a.FileName) .ParsesArgumentsWith(typeof(string), s => String.IsNullOrEmpty(s) ? s : s.Substring(0, s.Length - 1)) .ForMember(a => a.Name) .WatchesFor("name", "nam") .ParsesArgumentWith(s => s) .ForMember(a => a.Id) .WatchesFor("id") .HasHelpTextOf("Hello World") .ForMember(a => a.Force) .WatchesFor("f") .ForMember(a => a.Speed) .WatchesFor("fs") .Initialize(); }
private static void PrintHelp(IModelBindingDefinition <CommandParameters> argumentModel) { Console.WriteLine("Invalid command line arguments specified."); Console.WriteLine(); var arguments = string.Join(" ", argumentModel.Members.Select(_ => $"<{_.MemberInfo.Name}>")); Console.WriteLine($"Usage: {arguments}"); Console.WriteLine(); var list = new List <string[]> { new[] { "Argument", "Description", "Is required", "Default value" } }; foreach (var member in argumentModel.Members) { list.Add(new[] { member.MemberInfo.Name, member.HelpText, member.Required.ToString(), member.DefaultValue?.ToString() ?? string.Empty }); } var lengths = Enumerable.Range(0, list[0].Length).Select(_ => list.Max(a => a[_].Length)).ToList(); var rowWidth = lengths.Sum() + list[0].Length * 3 + 1; PrintRowSeparator(rowWidth); PrintHelpRow(list[0], lengths); PrintRowSeparator(rowWidth); foreach (var row in list.Skip(1)) { PrintHelpRow(row, lengths); } PrintRowSeparator(rowWidth); }
public static void Main(string[] args) { IModelBindingDefinition <CommandArgs> config = null; String errorMessage = null; var showHelp = args.Length == 0; try { config = Configuration.Configure <CommandArgs>(); Command = config.CreateAndBind(args); } catch (InvalidOperationException ex) { showHelp = true; errorMessage = "Error: " + ex.Message; } if (showHelp) { var helpProvider = new HelpProvider(); var help = helpProvider.GenerateModelHelp(config); Console.WriteLine(help.HelpText); Console.WriteLine(errorMessage); return; } else { Console.WriteLine(@" <!-- This tool isn't aware of inherited methods, and the binding generator will complain that the xpath isn't found. -->"); Console.WriteLine(@" <!-- These nodes will be ignored by the generator. -->"); } var files = Directory.EnumerateFiles(Command.JavadocPath, "*.html", SearchOption.AllDirectories); // TODO: Optionally parse allclasses-noframe.html instead foreach (var file in files) { ParseFile(file); // TODO: write the attr nodes direct to metadata.xml. } }
private static void EnsureArgumentsValid(ProgramOptions options, IModelBindingDefinition<ProgramOptions> configuration) { try { Guard.That(options.Port).IsTrue(p => p > 0, "Port must be greater than 0."); // Replace requires an object ID if (options.Action.Equals("Replace", StringComparison.InvariantCultureIgnoreCase)) Guard.That(options.ObjectId).IsTrue(o => o != null, "Object ID must be supplied when action is Replace."); // Add and Replace require a file to upload and a description for documents if (options.Action.Equals("Add", StringComparison.InvariantCultureIgnoreCase) || options.Action.Equals("Replace", StringComparison.InvariantCultureIgnoreCase)) { Guard.That(options.File).IsTrue(f => !string.IsNullOrWhiteSpace(f), "File must be provided when action is Add or Replace."); var fileInfo = new FileInfo(options.File); if (!fileInfo.Exists) throw new ArgumentException("Invalid file specified."); if (options.Type.Equals("Document", StringComparison.InvariantCultureIgnoreCase)) Guard.That(options.Description).IsTrue(d => !string.IsNullOrWhiteSpace(d), "Description must be provided when type is Document and action is Add or Replace."); } if (!string.IsNullOrWhiteSpace(options.DelegateId)) { Guard.That(options.DelegateHash).IsTrue(dh => !string.IsNullOrWhiteSpace(dh), "Delegate user hash is required when /did parameter is used."); Guard.That(options.DelegatePassword).IsTrue(dp => !string.IsNullOrWhiteSpace(dp), "Delegate authorization password is required when /did parameter is used."); } } catch (Exception ex) { ConsoleHelper.WriteFail(ex.Message); OutputHelp(configuration); Environment.Exit(ExitCode.BadArguments); } }
public void Setup() { switchOnlyModelUnderTest = Configuration.Configure <SwitchOnlyModel>(); ordinalModelUnderTest = Configuration.Configure <OrdinalModel>(); }
private static void ShowHelp(IModelBindingDefinition<GitReleaseNotesArguments> modelBindingDefinition, string reason = null) { var help = new HelpProvider().GenerateModelHelp(modelBindingDefinition); var bufferWidth = Console.IsOutputRedirected ? 80 : Console.BufferWidth; var f = new ConsoleHelpFormatter(bufferWidth, 1, 5); f.WriteHelp(help, Console.Out); if (reason != null) { Console.WriteLine(); Console.WriteLine(reason); } }
public static FluentModelBindingConfiguration <TModel> AsFluent <TModel>(this IModelBindingDefinition <TModel> source) { return(new FluentModelBindingConfiguration <TModel>(source)); }
public TerminateAndShowHelp(IModelBindingDefinition<MigrationParameters> helpMessage) : base(FormatHelp(helpMessage), 0) { }
public HelpCommand(IModelBindingDefinition<Arguments> modelBindingDefinition) { if (modelBindingDefinition == null) throw new ArgumentNullException("modelBindingDefinition"); _modelBindingDefinition = modelBindingDefinition; }
private static void ShowHelp(IModelBindingDefinition<GitReleaseNotesArguments> modelBindingDefinition, string reason = null) { var help = new HelpProvider().GenerateModelHelp(modelBindingDefinition); var f = new ConsoleHelpFormatter(); f.WriteHelp(help, Console.Out); if (reason != null) { Console.WriteLine(); Console.WriteLine(reason); } }
public TerminateAndShowHelp(IModelBindingDefinition <MigrationParameters> helpMessage) : base(FormatHelp(helpMessage), 1) { }
private static void ShowHelp(IModelBindingDefinition<ConversionOrder> argsDefinition) { var help = new Args.Help.HelpProvider().GenerateModelHelp(argsDefinition); var f = new ConsoleHelpFormatter(80, 1, 5); Console.WriteLine(f.GetHelp(help)); }
public void SimpleModelConfigurationSetup() { simpleTestModelDefinitionUnderTest = Configuration.Configure<SimpleTestModel>(); simpleSwitchOnlyModelDefinitionUnderTest = Configuration.Configure<SimpleSwitchOnlyModel>(); }
private static void OutputHelp(IModelBindingDefinition<ProgramOptions> configuration) { var help = new HelpProvider(); var helpProvider = help.GenerateModelHelp(configuration); var consoleFormatter = new ConsoleHelpFormatter(80, 1, 5); Console.WriteLine(consoleFormatter.GetHelp(helpProvider)); }
public void SetUp() { modelWithRequiredFieldDefinition = Configuration.Configure <ModelWithRequiredField>(); }
private static void ShowHelp(IModelBindingDefinition<Options> argsConfig) { var helpProvider = new HelpProvider(); var help = helpProvider.GenerateModelHelp(argsConfig); var helpFormatter = new ConsoleHelpFormatter(); Console.WriteLine(helpFormatter.GetHelp(help)); Console.ReadKey(); }
public void SimpleModelConfigurationSetup() { simpleTestModelDefinitionUnderTest = Configuration.Configure <SimpleTestModel>(); simpleSwitchOnlyModelDefinitionUnderTest = Configuration.Configure <SimpleSwitchOnlyModel>(); }
public FluentModelBindingConfiguration(IModelBindingDefinition <TModel> source) { Source = source; }
public void SimpleModelConfigurationSetup() { definitionUnderTest = Configuration.Configure <SimpleTestModel>(); }
/// <summary> /// Mains the specified arguments. /// </summary> /// <param name="args">The arguments.</param> private static void Main(string[] args) { IModelBindingDefinition <CommandArgs> bindingDefinition = Configuration.Configure <CommandArgs>(); // Show help if required if (args.Length == 1 && args[0].Contains("?")) { ModelHelp modelHelp = new HelpProvider().GenerateModelHelp(bindingDefinition); Console.Write(new ConsoleHelpFormatter().GetHelp(modelHelp)); return; } // Bind cmd line args CommandArgs command = bindingDefinition.CreateAndBind(args); // Get a DeviceManager instance using (var deviceManager = new TC08DeviceManager()) { // List devices if requested if (command.Devices) { foreach (var dev in deviceManager.Devices) { Console.WriteLine(dev.Serial); } return; } // Get the specified device or the first found TC08Device device = string.IsNullOrWhiteSpace(command.Serial) ? deviceManager.Devices.FirstOrDefault() : deviceManager.Devices.FirstOrDefault(d => d.Serial.ToLower() == command.Serial.ToLower()); // Let them know if we couldn't find a device if (device == null) { Console.WriteLine("Device not found"); return; } // Set mains rejection to 60Hz if req if (command.RejFreq > 55) { device.FrequencyRejection = TC08DeviceImports.FreqRej.Sixty; } StringBuilder csvHeader = new StringBuilder(); csvHeader.Append("Time, "); if (command.Type.Length == 1) { SetChannel(device, command.Channel, command.Type[0]); csvHeader.Append("Ch"); csvHeader.Append(command.Channel); csvHeader.Append(", "); } else if (command.Type.Length == 8) { for (int i = 0; i < 8; i++) { char type = command.Type[i]; if (type == DisabledChannel) { continue; } SetChannel(device, i + 1, type); csvHeader.Append("Ch"); csvHeader.Append(i + 1); csvHeader.Append(", "); } } else { Console.WriteLine( "Type should be 1 or 8 characters long. Diasabled channels should be included with a '-'. " + "For example '---j--k-' would set channels 4 and 7 to J and K types respectivly."); return; } // Configure device ready for capture device.Configure(); // If we're in logging mode, write the CSV header if (command.Log) { Console.WriteLine(csvHeader.ToString().Trim(' ', ',')); } var tempUnit = GetUnits(command); do { var stopWatch = Stopwatch.StartNew(); float[] data = device.GetValues(tempUnit); StringBuilder csvLine = new StringBuilder(); if (command.Log) { csvLine.Append(DateTime.Now + ", "); } var values = string.Join(", ", data .Skip(1) // Skip the cold junction value .Where(w => !float.IsNaN(w)) // Ignore the NaNs as these channels are disabled .Select(s => s.ToString("F2"))); // Convert them to string with 2 decimal places csvLine.Append(values); Console.WriteLine(csvLine); // If we're logging, ensure we wait 1 second before continuing... if (command.Log) { Thread.Sleep((int)Math.Max(1, (1000 - stopWatch.ElapsedMilliseconds))); } // Only loop if we're in log mode } while (command.Log); } }