ParseArguments() public static méthode

Parses a System.String array of command line arguments, setting values read in options parameter instance.
Thrown if is null. Thrown if is null.
public static ParseArguments ( string args, object options ) : bool
args string A array of command line arguments.
options object An instance to receive values. /// Parsing rules are defined using derived types.
Résultat bool
Exemple #1
0
        private static void Main(string[] args)
        {
            var parser = new Parser(config => config.HelpWriter = Console.Out);
            if (args.Length == 0)
            {
                parser.ParseArguments<Options>(new[] { "--help" });
                return;
            }

            Options options = null;
            parser.ParseArguments<Options>(args)
                  .WithParsed(r => { options = r; });

            if (string.IsNullOrEmpty(options.Job))
            {
                Console.WriteLine("Job required!");
                return;
            }

            Console.WriteLine(options.Job);
            switch (options.Job.ToLower())
            {
                case "sqlread":
                    SqlBenchmark.ReadAsync(options.Parallel).Wait();
                    break;

                case "migrate":
                    Sql2MongoMigrator.MigrateAsync().Wait();
                    break;

                case "read":
                    MongoDbBenchmark.ReadAsync(options.Parallel).Wait();
                    break;

                case "duplicate":
                    MongoDbBenchmark.DuplicateAsync(options.Parallel).Wait();
                    break;

                case "replace":
                    MongoDbBenchmark.ReplaceAsync(options.Parallel).Wait();
                    break;

                case "savesimple":
                    MongoDbBenchmark.SaveSimpleAsync(options.Parallel).Wait();
                    break;

                case "savecomplex":
                    MongoDbBenchmark.SaveComplexAsync(options.Parallel, false).Wait();
                    break;

                case "savecomplexfull":
                    MongoDbBenchmark.SaveComplexAsync(options.Parallel, true).Wait();
                    break;

                default:
                    Console.WriteLine("Invalid job!");
                    break;
            }
        }
Exemple #2
0
        /// <summary>
        /// Main method that runs the install program.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        private static void Main(string[] args)
        {
            InstallOptions installOptions = new InstallOptions();
            Environment.CurrentDirectory = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName;

            if (args.Contains("--help"))
            {
                Console.Write(installOptions.GetUsage());
                Environment.Exit(0);
            }

            installLogger = new InstallLogger(installOptions.Quiet);

            Parser parser = new Parser(settings => { settings.MutuallyExclusive = true; });
            if (!parser.ParseArguments(args, installOptions))
            {
                installLogger.LogErrorLine("Invalid command line parameters");
                Environment.Exit(1);
            }

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                                                {
                Formatting = Formatting.None,
                ContractResolver = new DiscretionalContractResolver(),
                Converters = new JsonConverter[] { new JsonKnownTypeConverter() }
            };

            new Program().Run(installOptions);
        }
Exemple #3
0
        public static int Main(string[] args)
        {
            //Check that all the necessary directories exist.
            CPFilePath.CreateDefaultDirectories();

            //Create the CLI parser.
            CLIParser = new CommandLine.Parser(with => with.AutoVersion = false);

            //Based on the given command line flags, execute.
            if (args.Length > 0 && args[0] == "pkg")
            {
                return(CLIParser.ParseArguments <PackageManagerCLIOptions>(args)
                       .MapResult(
                           (PackageManagerCLIOptions opts) => { new Sharpie(opts); return 0; },
                           errs => HandleCLIParseErrors(errs)
                           ));
            }
            else
            {
                return(CommandLine.Parser.Default.ParseArguments <InlineCLIOptions>(args)
                       .MapResult(
                           (InlineCLIOptions opts) => RunAlgoInline(opts, args),
                           errs => HandleCLIParseErrors(errs)
                           ));
            }
        }
        /// <summary>
        /// Run the OpenHardwareMonitor application as a console application
        /// </summary>
        /// <param name="args"></param>
        /// <returns>0 in case of success, 1 if arguments mismatch, 2 if required application files are missing, 3 in case of unexpected errors, 9 if administrative privileges are missing, or higher values for task specific errors</returns>
        static int Main(string[] args)
        {
            int ExitCode = 0;

            try
            {
                if (!AllRequiredFilesAvailable())
                {
                    return(2);
                }

                CommandLine.Parser CaseInsensitiveParser = new CommandLine.Parser(settings =>
                {
                    settings.CaseSensitive             = false;
                    settings.HelpWriter                = CommandLine.Parser.Default.Settings.HelpWriter;
                    settings.EnableDashDash            = CommandLine.Parser.Default.Settings.EnableDashDash;
                    settings.CaseInsensitiveEnumValues = CommandLine.Parser.Default.Settings.CaseInsensitiveEnumValues;
                    settings.IgnoreUnknownArguments    = CommandLine.Parser.Default.Settings.IgnoreUnknownArguments;
                    settings.MaximumDisplayWidth       = CommandLine.Parser.Default.Settings.MaximumDisplayWidth;
                    settings.ParsingCulture            = CommandLine.Parser.Default.Settings.ParsingCulture;
                });

                var Result = CaseInsensitiveParser.ParseArguments <CommandLineOptions.RunWebserver, CommandLineOptions.ReportToConsole, CommandLineOptions.ReportToFile>(args);
                ExitCode = Result.MapResult(
                    (CommandLineOptions.RunWebserver opts) => RunConsoleHttpServerAndReturnExitCode(opts),
                    (CommandLineOptions.ReportToConsole opts) => RunConsoleReportAndReturnExitCode(opts),
                    (CommandLineOptions.ReportToFile opts) => RunFileReportAndReturnExitCode(opts),
                    errs => 1);
            }
            catch (Exception ex)
            {
                if (VerboseMode)
                {
                    Utility.WriteLogMessage("ERROR: " + ex.ToString(), null, true);
                }
                else
                {
                    Utility.WriteLogMessage("ERROR: " + ex.Message, null, true);
                }
                ExitCode = 3;
            }
            if ((ExitCode == 1) && (!Utility.IsUserAdministrator()))
            {
                System.Console.Out.WriteLine("WARNING: you need to run this application with administrator permission");
                System.Console.Out.WriteLine();
            }


            if (WaitOnExitForSeconds > 0)
            {
                Console.Out.WriteLine("Waiting " + WaitOnExitForSeconds.ToString() + " seconds before exiting . . .");
                System.Threading.Thread.Sleep(WaitOnExitForSeconds * 1000);
            }
            if (WaitOnExitForEnterKey)
            {
                Console.Out.WriteLine("Press <Enter> to exit . . .");
                Console.ReadLine();
            }
            return(ExitCode);
        }
        static void Main(string[] args)
        {
            //(1)コマンドラインパーサーの初期化
            ParserSettings setting = new ParserSettings();
            setting.HelpWriter = Console.Error;
            var parser = new Parser(setting);

            //(2)オプション用クラスに引数を展開
            var option = new ConsoleOption();
            if (!parser.ParseArguments(args, option))
            {
                //パラメータに問題がある場合は、失敗ステータスで終了
                Environment.Exit(1);
            }
            var filePath = System.IO.Path.GetFullPath(option.OutputDirPath);

            var createYoutubeQRCode = new CreateYoutubeQRCodeLib.CreateYoutubeQRCode();
            createYoutubeQRCode.TargetContentType = CreateYoutubeQRCodeLib.contentType.User;
            createYoutubeQRCode.ConsumerKey = option.ClientID;
            createYoutubeQRCode.ConsumerSecret = option.ClientSeacret;
            createYoutubeQRCode.TargetFolderPath = filePath;

            var t = createYoutubeQRCode.CreateQR();
            t.Wait();
        }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        static protected void Run(string[] args)
        {
            Thread.CurrentThread.Name = "NativeHost::Main";

            try {
                SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlHandler), true);
                regService = new RegistryService(endpoint.Properties);

                BrowserType caller = endpoint.CheckBrowserCall(args);

                if (caller == BrowserType.Unknown)
                {
                    Log.Debug("Native host started with args {0} ", args);

                    Parser parser = new CommandLine.Parser(with => with.HelpWriter = null);
                    parserResult = parser.ParseArguments <Options>(args);
                    parser.Dispose();

                    parserResult
                    .WithParsed(options => RunAndReturnExitCode(options))
                    .WithNotParsed(errors => DisplayHelp(errors));
                }
                else
                {
                    Log.Debug("Native host called by {1} with args {0} ", args, caller);
                    DoHostListen(caller);
                }
            } catch (Exception e) {
                Log.Fatal(e.Message);
            }

            Log.CloseAndFlush();
            Log.Debug("Native host will now exit");
        }
Exemple #7
0
        /// <summary>
        /// Main entry point of the program
        /// </summary>
        /// <param name="args">Command line arguments to be parsed</param>
        static void Main(string[] args)
        {
            // We create your own command line parser to setup wanted options
            CommandLine.Parser parser = new CommandLine.Parser(
                with =>
            {
                //with.HelpWriter = Console.Error;
                with.HelpWriter             = null; // To display myself the help
                with.IgnoreUnknownArguments = false;
                with.CaseSensitive          = false;
            }
                );

            // Make the parsing
            ParserResult <CommandLineArguments> result = parser.ParseArguments <CommandLineArguments>(args);

            // In function of parser result, we run the program of we handle the errors
            result.WithParsed <CommandLineArguments>(opts => Run(opts))
            .WithNotParsed <CommandLineArguments>((errs) => HandleParseError(errs, result)
                                                  );

            // Only for debug, when the program is launch under Visual Studio.
            if (Debugger.IsAttached)
            {
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            using var parser = new CommandLine.Parser((settings) =>
            {
                settings.CaseInsensitiveEnumValues = true;
                settings.HelpWriter = null;
            });

            var result = parser.ParseArguments <
                CalculateOptions
                >(args);

            result.MapResult(
                (CalculateOptions options) =>
            {
                return(Task.Run(async() =>
                {
                    return await new Calculator(options).Run();
                }).GetAwaiter().GetResult());
            },
                errors =>
            {
                var helpText       = HelpText.AutoBuild(result, 96);
                helpText.Copyright = "Copyright (C) 2020 Frozen Mountain Software Ltd.";
                helpText.AddEnumValuesToHelpText = true;
                Console.Error.Write(helpText);
                return(1);
            });
        }
        public static ScryptCommandLineArgs Parse(string[] args, out string verb)
        {
            if (args.Length == 0)
            {
                // Work around a bug in CommandLineParser that doesn't correctly support a custom 'help' verb.
                Console.WriteLine(HelpText.AutoBuild(new ScryptCommandLineArgs(), _ => { }, true));
                Environment.Exit(Parser.DefaultExitCodeFail);
            }

            string verbForClosure = null;

            var arguments = new ScryptCommandLineArgs();
            var parser = new Parser(settings => { settings.HelpWriter = null; });

            var parseSucceed = parser.ParseArguments(args, arguments,
                (foundVerb, subOptions) =>
                {
                    verbForClosure = foundVerb;
                });
            if (!parseSucceed)
            {
                Console.WriteLine(HelpText.AutoBuild(arguments, _ => { }, true));
                Environment.Exit(Parser.DefaultExitCodeFail);
            }

            verb = verbForClosure;

            return arguments;
        }
Exemple #10
0
        public bool TryParseArguments(IEnumerable <string> args, out ParserResult <Options> results)
        {
            _log.LogTrace("Trying to parse Options");
            results = _parser.ParseArguments <Options>(args);

            return(results.Tag == ParserResultType.Parsed);
        }
        static int Main(string[] args)
        {
            log.Info("Start.");
            var parser = new Parser(with => { with.HelpWriter = Console.Out; with.EnableDashDash = true; });
            try
            {
                objWS_S = new EArchiveClient("EArchiveDefaultTest");
                var isRunning = objWS_S.IsRunning();
                if (!isRunning)
                {
                    log.Error("Connection to webservice failed. Service is not running.");
                    return 2;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex, "Connection to webservice failed. Is certificate configured properly?");
                return 1;
            }

            var result = parser.ParseArguments<SendLDocOptions, GetLDocOptions, SendLDocCSVOptions, GetSendLDocSchemaOptions>(args);
            var exitCode = result.MapResult(
                    (SendLDocOptions opts) => RunSendAndReturnExitCode(opts),
                    (GetLDocOptions opts) => RunGetAndReturnExitCode(opts),
                    (SendLDocCSVOptions opts) => RunSendFromCsvAndReturnExitCode(opts),
                    (GetSendLDocSchemaOptions opts) => RunGetSchemaAndReturnExitCode(opts),
                    errs => 1
                );
            objWS_S.Close();
            log.Info("All done.");
            return exitCode;
        }
        public string GetUsageHelp()
        {
            using (var parser = new CommandLine.Parser((settings) => { settings.HelpWriter = null; }))
            {
                var args = Environment.GetCommandLineArgs();

                var r = parser.ParseArguments <CommandLineOptions>(args).WithNotParsed(errs => { });

                var help = HelpText.AutoBuild(r,
                                              (ht) => ht,
                                              (ex) => ex
                                              );

                help.AddPreOptionsLine(" ");
                help.AddPreOptionsLine(string.Format("Usage: {0} --from Source --to Destination [--number number] [--log LogFileName]", ExeUtils.GetExeName()));
                help.AddPreOptionsLine(string.Format("   or: {0} --config ConfigFileName", ExeUtils.GetExeName()));

                help.AddPostOptionsLine("");
                help.AddPostOptionsLine("Endpoint type: dir (directory) | cs (content storage)");
                help.AddPostOptionsLine("Connection info:");
                help.AddPostOptionsLine("  dir     : directory_name");
                help.AddPostOptionsLine("  cs      : container_name token");
                help.AddPostOptionsLine("");

                help.AddPostOptionsLine(string.Format(@"Example: {0} -f cs TestContainer werlewkj32lwkejr324pfwer -t dir D:\Backup\TestContainer", ExeUtils.GetExeName()));
                help.AddPostOptionsLine("");

                return(help);
            }
        }
Exemple #13
0
        public void Execute <T>(ICommandHandler handler, string[] args, CommandContext context)
        {
            var parser = new Clp.Parser(settings =>
            {
                settings.AutoHelp               = true;
                settings.AutoVersion            = false;
                settings.HelpWriter             = null;
                settings.IgnoreUnknownArguments = false;
                settings.CaseSensitive          = false;
            });

            var result = parser.ParseArguments <T>(args).WithParsed(options => Execute(handler, options, context));

            result.WithNotParsed(errors => {
                var help = new HelpText(String.Empty, String.Empty)
                {
                    AutoHelp          = true,
                    AutoVersion       = false,
                    AddDashesToOption = true
                };
                help = HelpText.DefaultParsingErrorsHandler(result, help);
                help = help.AddOptions(result);

                var errorList = errors.ToList();
                if (errorList.Count == 0 ||
                    errorList.Count == 1 && errorList[0].Tag == ErrorType.HelpRequestedError)
                {
                    context.Output.WriteLine(help);
                }
                else
                {
                    context.ErrorOutput.WriteLine(help);
                }
            });
        }
Exemple #14
0
        public static void Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLine.Parser();

            if (parser.ParseArguments(args, options))
            {
                var configManager = new CliConfigManager();
                Config = configManager.GetConfig();

                var configEntry = Config.Areas.FirstOrDefault(x => x.Id.Equals(options.ServiceEndpoint));
                if (configEntry == null)
                {
                    Console.WriteLine("Invalid endpoint!");
                    return;
                }

                var service = new Bus13RouteDataService(configEntry.Endpoint, configEntry.Id);
                if (options.List)
                {
                    ListVehicles(service);
                }

                if (options.Trace)
                {
                    if (string.IsNullOrEmpty(options.VehicleId))
                    {
                        Console.WriteLine("Vehicle id must be supplied!");
                        return;
                    }

                    if (!string.IsNullOrEmpty(options.OutputDir) && !Directory.Exists(options.OutputDir))
                    {
                        Console.WriteLine("Directory {0} doesn't exist!", options.OutputDir);
                        return;
                    }

                    IVehicleTraceOutputWriter outputWriter = null;
                    if (string.IsNullOrEmpty(options.OutputType) ||
                        string.Equals("kml", options.OutputType, StringComparison.InvariantCultureIgnoreCase))
                    {
                        outputWriter = new KmlOutputWriter(GetOutputDir(options));
                    }

                    if (string.Equals("json", options.OutputType, StringComparison.InvariantCultureIgnoreCase))
                    {
                        outputWriter = new JsonOutputWriter(GetOutputDir(options));
                    }

                    if (outputWriter == null)
                    {
                        outputWriter = new KmlOutputWriter(GetOutputDir(options));
                    }

                    Trace(service, options.VehicleId, outputWriter);
                    Console.ReadKey();
                }
            }
        }
Exemple #15
0
        public static void Main(string[] args)
        {
            var parser = new CommandLine.Parser(configuration => configuration.HelpWriter = null);

            parser.ParseArguments <Options>(args)
            .WithParsed <Options>(Run)
            .WithNotParsed((errors) => Console.WriteLine($"Usage: ledger <journal>"));
        }
        public static IArgOptions Parse(string[] args, out bool parsedOK)
        {
            var options = new ArgOptions();
            var parser  = new CommandLine.Parser();

            parsedOK = parser.ParseArguments(args, options);
            return(options);
        }
Exemple #17
0
        public static void Main(string[] args)
        {
            var parser = new CommandLine.Parser(configuration => configuration.HelpWriter = null);

            parser.ParseArguments <Options>(args)
            .WithParsed <Options>(Run)
            .WithNotParsed((errors) => Console.WriteLine($"Usage: sherlock <db> [--password password] [--script script] [--item path]"));
        }
        private static void Main(string[] args)
        {
            try
            {
                //Set lower priority for the process
                Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
                //Use only first processor
                Process.GetCurrentProcess().ProcessorAffinity = (IntPtr)1;
                //Change culture to en-US in order to use . as decimal separator
                System.Threading.Thread.CurrentThread.CurrentCulture =
                    System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
                //Initializing arguments
                var options = new Options();
                //Parsing arguments
                // CommandLine.Parser.Default.ParseArgumentsStrict(args, options);
                var parser       = new CommandLine.Parser(with => with.HelpWriter = null);
                var parserResult = parser.ParseArguments <Options>(args);
                parserResult
                .WithParsed <Options>(opt => options = opt)
                .WithNotParsed(errs => DisplayHelp(parserResult, errs));
                //Load XML with performance counters and calculate result
                //Load XML file
                using (var perfCounterList = new PerfCounterList(options.XmlFile, (string[])options.XmlParameters, options.Verbose))
                {
                    //Taking samples and calculate result of performance counters
                    perfCounterList.Calculate(options.MaxSamples, options.TimeSamples);
                    //No errors in PerfCounter, all counters are between ranges
                    if (perfCounterList.GetGlobalExitCode() == 0)
                    {
                        Console.WriteLine(
                            $"{perfCounterList.GetGlobalStatus()} - All performance counters between range {perfCounterList.GlobalPerfOutput}");
                    }
                    //Some counters has values out of thresholds
                    else
                    {
                        //Generate output with errors and performance data
                        Console.WriteLine(
                            $"{perfCounterList.GetGlobalStatus()} - {perfCounterList.GlobalOutput} {perfCounterList.GlobalPerfOutput}");
                    }

                    //Exit code for monitoring software
                    if (!options.NoAlerts)
                    {
                        Environment.Exit(perfCounterList.GetGlobalExitCode());
                    }
                    else
                    {
                        Environment.Exit(0);
                    }
                }
            }
            catch (Exception e)
            {
                //Return status and code unknown for monitoring software
                Console.WriteLine("Unknown: " + e.Message);
                Environment.Exit(3);
            }
        }
Exemple #19
0
 public static void Main(string[] args)
 {
     var parser = new CommandLine.Parser(settings => settings.HelpWriter = null);
     var result = parser.ParseArguments <EncodeOptions, DecodeOptions>(args);
     int output = result.MapResult(
         (EncodeOptions options) => { Watson.Encode(options, Console.OpenStandardOutput()); return(0); },
         (DecodeOptions options) => { Watson.Decode(options, Console.OpenStandardOutput()); return(0); },
         (errs) => { DisplayHelp(result); return(1); });
 }
Exemple #20
0
        public static int Main(string[] args)
        {
            Options options = new Options();

            using (Parser cmdParser = new Parser())
            {
                cmdParser.ParseArguments(args, options);
            }

            List<string> files = Directory.EnumerateFiles(Environment.CurrentDirectory, options.Input, SearchOption.TopDirectoryOnly).ToList();

            if (files.Count == 0)
            {
                Console.Error.WriteLine("File {0} not found", options.Input);

                return -1;
            }

            StreamWriter streamWriter;
            IParser parser;

            int result = AssertConditions(options, out streamWriter, out parser);

            if (result != 0)
            {
                string usage = options.GetUsage();

                Console.WriteLine(usage);

                return result;
            }

            using (CSVWriter csvWriter = new CSVWriter(',', streamWriter))
            {
                foreach(string file in files)
                {
                    using (StreamReader reader = new StreamReader(file))
                    {
                        if (options.Header)
                        {
                            string[] header = parser.GetHeader();

                            csvWriter.Append(header);
                        }

                        IEnumerable<string[]> rows = parser.Read(reader);

                        foreach (string[] row in rows)
                        {
                            csvWriter.Append(row);
                        }
                    }
                }
            }

            return 0;
        }
        static void Main(string[] args)
        {
            var parser       = new CommandLine.Parser(with => with.HelpWriter = null);
            var parserResult = parser.ParseArguments <Options>(args);

            parserResult
            .WithParsed <Options>(options => Run(options))
            .WithNotParsed(errs => DisplayHelp(parserResult, errs));
        }
Exemple #22
0
        static void Main(string[] args)
        {
            // Create the cli parser with HelpWriter disabled,
            // since a custom help text will be used
            var cliParser       = new CommandLine.Parser(with => with.HelpWriter = null);
            var cliParserResult = cliParser.ParseArguments(args, LoadVerbs());

            cliParserResult.WithParsed(RunVerb);
            cliParserResult.WithNotParsed(errors => PrintHelp(cliParserResult));
        }
 private void InitializeOptions(IEnumerable <string> args)
 {
     _options = new CommandLineOptions();
     using (var parser = new CommandLine.Parser((settings) => { settings.HelpWriter = null; }))
     {
         parser.ParseArguments <CommandLineOptions>(args)
         .WithParsed <CommandLineOptions>(opts => { _options = opts; })
         .WithNotParsed(errs => { });
     }
 }
Exemple #24
0
        static void Main(string[] args)
        {
            var container = CreateContainer();
            var parser = new CommandLine.Parser();
            var settings = new Settings();
            parser.ParseArguments(args, settings);
            container.Resolve<TagsCloudVizualizer>()
                .GenerateCloud( settings.TextColor,settings.BackgroundColor,new Font(settings.FontName,10),new Size(10000,10000), settings.InputFileName, settings.OutputFileName);

        }
Exemple #25
0
        public bool Load(String[] args)
        {
            var parser = new CommandLine.Parser((settings) =>
            {
                settings.CaseSensitive = false;
                settings.HelpWriter    = null;
            });

            return(parser.ParseArguments(args, this));
        }
        /// <summary>
        /// Console entry point
        /// </summary>
        /// <param name="args">command line arguments</param>
        /// <returns>0 if all extractions are successful.</returns>
        private static int Main(string[] args)
        {
            var options = new Options();

            var parser = new Parser(settings =>
            {
                settings.CaseSensitive = false;
                settings.HelpWriter = Console.Error;
                settings.ParsingCulture = CultureInfo.InvariantCulture;
            });

            var result = parser.ParseArguments(args, options);

            if (!result)
            {
                Fail();
                return -1;
            }

            TfsTeamProjectCollection tfs =
                TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(options.Collection));
            try
            {
                tfs.EnsureAuthenticated();
            }
            catch (Exception)
            {
                Fail("Connection to TFS failed");
                return -1;
            }

            // Getting Identity Service
            var ims = tfs.GetService<IIdentityManagementService>();

            var someExtractionFail = false;
            foreach (var userName in options.Users)
            {
                Console.WriteLine("===== Extracting Permissions for User {0} ======", userName);
                var fileName = Helpers.GenerateFileName(userName, options.OutputFile);
                var extractionStatus = ExtractPermissionForUserName(ims, userName, options, fileName, tfs);

                if (!extractionStatus)
                {
                    someExtractionFail = true;
                }
            }

            if (someExtractionFail)
            {
                Fail("An error occured during the extraction");
                return -1;
            }

            return 0;
        }
Exemple #27
0
        static void Main(string[] args)
        {
            // NOTES
            // 1. Start running in Debug mode in VS, I have set start up args (on project page) to be:

            // gitout.exe --plugin releasenotes --verbose --issuetracker "github" --accesstoken "sometoken" --reponame "myrepo"

            // you could also use:

            // gitout.exe --plugin semver

            // I have also set a post-build event on the ReleaseNotesPlugin project and the SemanticVersionPlugin project,
            // so that their assemblies are copied into the GitOut.exe directory, so that they can be discovered at runtime as a plugins.

            var parser     = new CommandLine.Parser(with => with.IgnoreUnknownArguments = true);
            var appOptions = new Options();

            if (parser.ParseArguments(args, appOptions))
            {
                // parsing succeds
                // discover / load plugins
                var pluginManager = new PluginManager();
                var plugin        = pluginManager.GetPluginInstanceByName(appOptions.PluginName);

                if (plugin == null)
                {
                    Console.WriteLine("Plugin not found for a command named: " + appOptions.PluginName);
                    return;
                }

                try
                {
                    // plugin execution context is context that we can pass to any plugin - and also could provide
                    // the ability for plugins to access shared / central state.
                    // it could contain commonly needed things like IssueTrackers, Loggers, or a service locator etc.
                    var pluginExecutionContext = new PluginExecutionContext();
                    pluginExecutionContext.Args = args; // command line args defferred to the plugin.
                    // Execute the plugin.
                    plugin.Execute(pluginExecutionContext);
                }
                catch (Exception e)
                {
                    HandlePluginExecutionError(e);
                    return;
                }
            }
            else
            {
                // In addition to allowing particular plugins to be invoked on their own,
                // We could allow a workflow execution, based on a config file.
                // we could do that here by parsing a command that points to the yaml config
                // which would define which plugins were executed, with which settings, and in which order?
                Console.WriteLine("Failed to parse args, see usage.");
            }
        }
Exemple #28
0
        static void Main(string[] args)
        {
            try
            {
                var settings = new Settings();
                using (var parser = new CommandLine.Parser(x =>
                {
                    x.CaseSensitive = false;
                    x.IgnoreUnknownArguments = true;
                }))
                {
                    if (!parser.ParseArguments(args, settings))
                    {
                        Console.Error.WriteLine(settings.GetUsage());
                        return;
                    }
                }

                if (settings.InputFiles == null)
                {
                    RunMultiDumper(ref settings);
                }
                else
                {
                    // We want to expand any wildcards in the input file list (and also fully qualify them)
                    settings.InputFiles = settings.InputFiles
                                          .SelectMany(s => Directory
                                                      .EnumerateFiles(Directory.GetCurrentDirectory(), s)
                                                      .OrderByAlphaNumeric(x => x))
                                          .ToList();
                }

                if (settings.InputFiles == null || !settings.InputFiles.Any())
                {
                    Console.Error.WriteLine(settings.GetUsage());
                    throw new Exception("No inputs specified");
                }

                using (var loader = new AudioLoader
                {
                    AutoScalePercentage = settings.AutoScalePercentage,
                    HighPassFilterFrequency = settings.HighPassFilterFrequency,
                    VerticalScaleMultiplier = settings.VerticalScaleMultiplier,
                })
                {
                    loader.LoadAudio(settings.InputFiles);
                    Render(settings, loader);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine($"Fatal: {e}");
            }
        }
Exemple #29
0
    private static void ParseOptions(string[] args, Options options)
    {
      var parser = new Parser(delegate(ParserSettings settings)
      {
        settings.CaseSensitive = false;
        settings.HelpWriter = Console.Error;
      });

      if (parser.ParseArguments(args, options) == false)
        throw new ArgumentException("Invalid command line");
    }
Exemple #30
0
 private static void Main(string[] args)
 {
     try
     {
         var parser = new Parser(config => config.HelpWriter = Console.Out);
         parser.ParseArguments<Options>(args).WithParsed(Remap);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
        public static void Main([NotNull] string[] args)
        {
            Assert.ArgumentNotNull(args, "args");

              CoreApp.InitializeLogging();

              CoreApp.LogMainInfo();

              Analytics.Start();

              var filteredArgs = args.ToList();
              var query = GetQueryAndFilterArgs(filteredArgs);
              var wait = GetWaitAndFilterArgs(filteredArgs);

              var parser = new Parser(with => with.HelpWriter = Console.Error);
              Assert.IsNotNull(parser, "parser");

              var options = new MainCommandGroup();
              EnsureAutoCompeteForCommands(options);
              if (!parser.ParseArguments(filteredArgs.ToArray(), options, delegate { }))
              {
            Console.WriteLine("Note, commands provide output when work is done i.e. without any progress indication.");
            Console.WriteLine("\r\n  --query\t   When specified, allows returning only part of any command's output");
            Console.WriteLine("\r\n  --data\t   When specified, allows returning only 'data' part of any command's output");
            Console.WriteLine("\r\n  --wait\t   When specified, waits for keyboard input before terminating");

            Environment.Exit(Parser.DefaultExitCodeFail);
              }

              var result = options.SelectedCommand.Execute();

              result = QueryResult(result, query);
              if (result == null)
              {
            return;
              }

              var serializer = new JsonSerializer
              {
            NullValueHandling = NullValueHandling.Ignore,
            Formatting = Formatting.Indented,
              };

              serializer.Converters.Add(new DirectoryInfoConverter());

              var writer = Console.Out;
              serializer.Serialize(writer, result);

              if (wait)
              {
            Console.ReadKey();
              }
        }
Exemple #32
0
        public static void CreateConfig()
        {
            if (!File.Exists(ConfigPath))
            {
                System.Text.StringBuilder oStringBuilder = new StringBuilder();
                oStringBuilder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                oStringBuilder.AppendLine("<configuration>");


                var oParser       = new CommandLine.Parser(with => with.HelpWriter = null);
                var oParserResult = oParser.ParseArguments <Options>("--help".Split());

                string sHelpText = HelpText.AutoBuild(oParserResult, HelpTextInstance =>
                {
                    HelpTextInstance.AdditionalNewLineAfterOption = false; //remove the extra newline between options
                    HelpTextInstance.Heading             = "";
                    HelpTextInstance.Copyright           = "";
                    HelpTextInstance.MaximumDisplayWidth = 50000;
                    HelpTextInstance.AddDashesToOption   = false;
                    HelpTextInstance.AutoVersion         = false;
                    HelpTextInstance.AutoHelp            = false;
                    return(HelpText.DefaultParsingErrorsHandler(oParserResult, HelpTextInstance));
                }, e => e);

                sHelpText = Regex.Replace(sHelpText, @"\n  ., ", "     ");
                sHelpText = Regex.Replace(sHelpText, @" \[-. ", " [Default: ");

                oStringBuilder.AppendLine("     <!--" + sHelpText.Replace("<br/>", "\n".PadRight(37)) + "\n\n");
                oStringBuilder.AppendLine("     To override a Key/Value pair, remove the leading and trailing HTML style comment tags surrounding the line (<!–– ––>)\n     -->\n");

                oParserResult = oParser.ParseArguments <Options>("".Split());
                oParserResult.WithParsed <Options>(options => CreateConfigSection(options, ref oStringBuilder));

                oStringBuilder.AppendLine("</configuration>");
                var oOptions = new Options();

                System.IO.File.WriteAllText(ConfigPath, oStringBuilder.ToString());
            }
        }
Exemple #33
0
 public void Main(string[] args)
 {
     Parser parser = new Parser(config =>
     {
       config.EnableDashDash = true;
       config.CaseSensitive = true;
       config.IgnoreUnknownArguments = false;
       config.HelpWriter = Out;
     });
     parser.ParseArguments<Options>(args)              
         .WithNotParsed(ArgumentsError)
         .WithParsed(Execute);
 }
Exemple #34
0
        static int Main(string[] args)
        {
            _logger.Info("App started");

            var options = new Options();
            var parser  = new CommandLine.Parser(s => { s.MutuallyExclusive = false; });

            var isValid = parser.ParseArguments(args, options);

            if (!isValid)
            {
                string msg = CommandLine.Text.HelpText.AutoBuild(options).ToString();
                Console.WriteLine(msg);
                return(-1);
            }



            CLITester tester = new CLITester(options.Host, options.Port);

            tester.TestRetryCount = options.RetryCount;

            try
            {
                if (options.TestCmd != null)
                {
                    _logger.Info("Run Test: " + options.TestCmd);
                    string data = tester.Test(options.TestCmd);
                    _logger.Info(data);
                }
                else if (options.Cmd != null)
                {
                    _logger.Info("Run Cmd: " + options.Cmd);
                    _logger.Info("Exp Val: " + options.ExpVal);
                    string data = tester.CmdWaitRegx(options.Cmd, options.ExpVal);
                    _logger.Info(data);
                }
            }
            catch (TestException ex)
            {
                _logger.Error(ex.Message);
                return(-1);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                return(-2);
            }

            return(0);
        }
Exemple #35
0
        public static void Main(string[] args)
        {
            var options = new Options();

            if (HasNoArguments(args))
            {
                Console.Write(options.GetUsage());
                Environment.Exit(1);
            }

            var parser = new Parser();

            if (parser.ParseArguments(args, options))
            {
                if (ShouldShowVersion(options))
                {
                    OutputVersion();
                    return;
                }

                try
                {
                    var config = ConfigFactory.Create(options);
                    var requester = new Requester();
                    var logger = LoggerFactory.Create(options);

                    var warmer = WarmerFactory.Create(options, config, requester, logger);

                    warmer.Warm();
                }
                catch (XmlException e)
                {
                    Console.WriteLine("");
                    Console.WriteLine("Invalid XML Config File");
                    Console.WriteLine("-----------------------");
                    Console.WriteLine(e.Message);
                }
                catch (FileNotFoundException e)
                {
                    Console.WriteLine("");
                    Console.WriteLine("Could not find the file specifed. {0}", options.Inputfiles);
                    Console.WriteLine("-----------------------");
                    Console.WriteLine(e.Message);
                }
            }
            else
            {
                Environment.Exit(1);
            }
        }
Exemple #36
0
        static void Main(string[] args)
        {
            var parser       = new CommandLine.Parser(with => with.HelpWriter = null);
            var parserResult = parser.ParseArguments <Options>(args);

            parserResult
            .WithParsed <Options>(options => new Program(options).Run())
            .WithNotParsed(errs => DisplayHelp(parserResult, errs));

#if DEBUG
            Console.Write("Press [Enter] to continue...");
            Console.ReadLine();
#endif
        }
        static int Main(string[] arguments)
        {
            CoreSettings settings = new CoreSettings();
            Parser parser = new Parser(s => {
                s.IgnoreUnknownArguments = true;
                s.CaseSensitive = true;
            });

            if(!parser.ParseArguments(arguments, settings)) {
                return 1;
            } else {
                return Launch(settings, arguments);
            }
        }
 static IProgramOptions ParseCommandLine(string[] args)
 {
     var options = new CommandLineOptions.CommandLineOptions();
     var parser = new Parser(settings =>
     {
         settings.IgnoreUnknownArguments = true;
         settings.CaseSensitive = false;
     });
     if (!parser.ParseArguments(args, options))
     {
         Environment.Exit(1);
     }
     return options;
 }
Exemple #39
0
        private static void Main(string[] args)
        {
            StringWriter writer = new StringWriter();
              Parser p = new Parser(with => with.HelpWriter = writer);
              TapCheckerOptions opts = new TapCheckerOptions();
              if (!p.ParseArguments(args, opts))
              {
            Console.WriteLine(writer.ToString());
            return;
              }

              List<string> files = new List<string>();
              if ((opts.Files.Length == 1) && (opts.Files[0] == "*"))
              {
            files.AddRange(Directory.GetFiles(".", "*.tap"));
              }
              else
              {
            files.AddRange(opts.Files.ToArray());
              }

              ConsoleColor currentColor = Console.ForegroundColor;
              TapChecker checker = new TapChecker();
              foreach (var fileToCheck in files)
              {
            List<ReportLine> report = checker.Check(fileToCheck, opts);

            foreach (var reportLine in report)
            {
              switch (reportLine.Status)
              {
            case ReportLineStatus.Info:
              Console.ForegroundColor = currentColor;
              break;
            case ReportLineStatus.Error:
              Console.ForegroundColor = ConsoleColor.Red;
              break;
            case ReportLineStatus.Warning:
              Console.ForegroundColor = ConsoleColor.Yellow;
              break;
              }
              Console.WriteLine(reportLine.Message);
            }
            Console.WriteLine();
              }
              Console.ForegroundColor = currentColor;
              Console.WriteLine("Press enter to exit");
              Console.ReadLine();
        }
Exemple #40
0
        static int Main(string[] args)
        {
            if (DebugEnabled)
            {
                Debug($"Received {args.Length} arguments: {string.Join(" ", args)}");
            }

            var code = -1;

            switch (args[0])
            {
            case "inspect":
                code = Inspect(args[1]);
                break;

            case "launcher":
                code = MakeLauncher(args.Skip(1));
                break;

            default:
                var parser = new CommandLine.Parser(with => with.HelpWriter = null);

                var result = parser.ParseArguments <BuildCommand>(args);
                if (result.Errors?.Any() == true)
                {
                    var text = HelpText.AutoBuild(result);
                    Console.Error.WriteLine(text.ToString());
                    return(-1);
                }
                var command = (BuildCommand)result.Value;

                switch (command.Action)
                {
                case "pack":
                case "restore":
                case "publish":
                case "build":
                    code = Build((BuildCommand)command);
                    break;

                default:
                    return(Fail($"Unknown command: {command.Action}"));
                }

                break;
            }
            Debug($"exiting with code {code}");
            return(code);
        }
        public static void Main(string[] args)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                // See  https://issues.bloomlibrary.org/youtrack/issue/BL-8475.
                Console.WriteLine("Harvester cannot run on Linux until we verify that phash computations always yield the same result on both Windows and Linux!");
                return;
            }

            // See https://github.com/commandlineparser/commandline for documentation about CommandLine.Parser
            var parser = new CommandLine.Parser((settings) =>
            {
                settings.CaseInsensitiveEnumValues = true;
                settings.CaseSensitive             = false;
                settings.HelpWriter = Console.Error;
            });

            try
            {
                parser.ParseArguments <HarvesterOptions, UpdateStateInParseOptions, BatchUpdateStateInParseOptions, GenerateProcessedFilesTSVOptions>(args)
                .WithParsed <HarvesterOptions>(options =>
                {
                    options.ValidateOptions();
                    Harvester.RunHarvest(options);
                })
                .WithParsed <UpdateStateInParseOptions>(options =>
                {
                    HarvestStateUpdater.UpdateState(options.ParseDBEnvironment, options.ObjectId, options.NewState);
                })
                .WithParsed <BatchUpdateStateInParseOptions>(options =>
                {
                    HarvestStateBatchUpdater.RunBatchUpdateStates(options);
                })
                .WithParsed <GenerateProcessedFilesTSVOptions>(options =>
                {
                    ProcessedFilesInfoGenerator.GenerateTSV(options);
                })
                .WithNotParsed(errors =>
                {
                    Console.Out.WriteLine("Error parsing command line arguments.");
                    Environment.Exit(1);
                });
            }
            catch (Exception e)
            {
                YouTrackIssueConnector.GetInstance(EnvironmentSetting.Unknown).ReportException(e, "An exception was thrown which was not handled by the program.", null);
                throw;
            }
        }
Exemple #42
0
        private static int Main(string[] args)
        {
            // Parse command line options

            if (args.Length == 1 && args[0].StartsWith("@"))
            {
                var argFile = args[0].Substring(1);
                if (File.Exists(argFile))
                {
                    args = File.ReadAllLines(argFile);
                }
                else
                {
                    Console.WriteLine("File not found: " + argFile);
                    return 1;
                }
            }

            var parser = new Parser(config => config.HelpWriter = Console.Out);
            if (args.Length == 0)
            {
                parser.ParseArguments<Options>(new[] { "--help" });
                return 1;
            }

            Options options = null;
            var result = parser.ParseArguments<Options>(args)
                               .WithParsed(r => { options = r; });

            // Run process !

            if (options != null)
                return Process(options);
            else
                return 1;
        }
Exemple #43
0
        private static int Main(string[] args)
        {
            // Set up the commandline parser
            var parser = new CommandLine.Parser(with =>
            {
                with.CaseSensitive = false;
                with.HelpWriter    = System.Console.Error;
            });

            // Parse the commandline arguments and if successful, pass them to ProcessFile
            return(parser.ParseArguments <CommandlineOptions>(args).MapResult(
                       (CommandlineOptions opts) => ProcessFile(opts.FilePath, opts.SortType.ToSortOrder()),
                       errs => 1
                       ));
        }
Exemple #44
0
        private static int Main(string[] args)
        {
            var parser = new Parser(
                (settings) =>
                    {
                        settings.EnableDashDash = true;
                        settings.HelpWriter = Console.Error;
                    });

            var orchestrator = new Orchestrator(parser);
            var parserResult = parser.ParseArguments<RunasOptions, ElevateOptions, BootstrapOptions>(args);
            var exitCode = parserResult.MapResult(
                (RunasOptions opts) =>
                {
                    // Split username from domain if given
                    var domainUserName = Utils.SplitUsernameAndDomain(opts.Username);
                    var domain = domainUserName.Key;
                    var userName = domainUserName.Value;

                    // Get password from command line if not given
                    SecureString passwordSecured;
                    if (opts.Password == null)
                    {
                        Console.Write("Password: ");
                        passwordSecured = Utils.GetConsoleSecurePassword();
                    }
                    else
                    {
                        passwordSecured = opts.Password.ConvertToSecureString();
                    }

                    // Exec
                    return orchestrator.RunAs(opts.Command, opts.Arguments, domain, userName, passwordSecured, opts.Elevated);
                },
                (ElevateOptions opts) =>
                {
                    // Exec
                    return orchestrator.Elevate(opts.Command, opts.Arguments, opts.LogFilePath, opts.InitVerb);
                },
                (BootstrapOptions opts) =>
                {
                    // Exec
                    return orchestrator.Bootstrap(opts.Command, opts.Arguments, opts.LogFilePath, opts.InitVerb);
                },
                errs => 1);

            return exitCode;
        }
Exemple #45
0
        public static async Task Main(string[] args)
        {
            var parser = new CommandLine.Parser(settings =>
            {
                settings.CaseSensitive             = false;
                settings.CaseInsensitiveEnumValues = true;
                settings.HelpWriter = null;
            });

            var parserResult = parser.ParseArguments <RunOptions>(args);

            await parserResult.MapResult(
                (RunOptions options) => Run(options),
                errors => DisplayHelp(parserResult)
                );
        }
Exemple #46
0
        public static void Main(string[] args)
        {
            Options = new AutomatrOptions();
            Parser parser = new Parser(new Action<ParserSettings>((ParserSettings p) => { p.CaseSensitive = false; p.IgnoreUnknownArguments = false; p.MutuallyExclusive = true; }));
            bool parse = parser.ParseArguments(args, Options);

            if (Options.Version)
            {
                AutomatrLog.Log("Automatr " + Version, AutomatrLog.LogLevel.Info);
                return;
            }

            AutomatrConfig config = AutomatrConfig.Load(Options.ConfigPath);
            Automatr automatr = new Automatr(config);
            automatr.Run();
        }
Exemple #47
0
        private static void Main(string[] args)
        {
            var parser = new CommandLine.Parser(with =>
            {
                with.CaseSensitive             = false;
                with.CaseInsensitiveEnumValues = true;
                with.HelpWriter     = Console.Error;
                with.EnableDashDash = true;
            });

            parser.ParseArguments <GenerateAllOptions, StepDefinitionOptions, NUnitOptions, MsTestOptions>(args)
            .WithParsed <GenerateAllOptions>(GenerateAll)
            .WithParsed <StepDefinitionOptions>(StepDefinitionReport)
            .WithParsed <NUnitOptions>(NUnitExecutionReport)
            .WithParsed <MsTestOptions>(MsTestExecutionReport)
            .WithNotParsed(err => Environment.ExitCode = ERROR_BAD_ARGUMENTS);
        }
        static void Main(string[] args)
        {
            var options = new Options();

            var parser = new Parser();

            //If parsing was successful verify either a server is given or the file and receivers are given
            if (parser.ParseArguments(args, options) && (!string.IsNullOrWhiteSpace(options.Server) || (!string.IsNullOrWhiteSpace(options.File) && options.Clients != null && options.Clients.Any())))
            {
                //If No Server is Given assume Current Box is the Server otherwise process act as if you are a client
                if (string.IsNullOrWhiteSpace(options.Server))
                {
                    var server = new CommandExecutionServer(options.Port, options.Timeout, options.File, options.Arguments, options.Clients, options.UseServer);

                    var result = server.Start();

                    Console.WriteLine(result ? "Execution Successful! Processes Running." : "An Error Occured while attempting to execute the processes!");
                }
                else
                {
                    var client = new CommandExecutionClient(options.Port, options.Server);

                    var process = client.Start();

                    if (process != null)
                    {
                        Console.WriteLine("Process Started!");
                        process.WaitForExit();
                        Console.WriteLine("Process Complete!");
                    }
                    else
                    {
                        Console.WriteLine("Error occured when attempting to execute process!");
                    }

                }
            }
            else
            {
                Console.WriteLine(options.GetUsage());
                return;
            }

            Console.WriteLine("Press Enter To Close The Console!");
            Console.ReadLine();
        }
Exemple #49
0
        public static void Run(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLine.Parser(s =>
            {
                s.CaseSensitive     = false;
                s.MutuallyExclusive = true;
                s.HelpWriter        = Console.Out;
                s.ParsingCulture    = System.Globalization.CultureInfo.InvariantCulture;
            });

            if (!parser.ParseArguments(args, options))
            {
                return;
            }

            if (options.Folders.Count > 0)
            {
                var firstFolder = options.Folders.First();
                var collection  = new MediaCollection <ConsoleFilm>(firstFolder).Items;

                if (options.List)
                {
                    foreach (var film in collection)
                    {
                        Console.WriteLine(String.Format("{0,-3} {1,-9} {2}", film.Rating, film.ImdbId, film.FolderName));
                    }
                }

                if (options.Decorate)
                {
                    new IconService().ProcessValidFilms(collection, validFilms =>
                                                        Console.WriteLine("Complete! " + validFilms.Count() + " folders have been decorated with icons."));
                }

                if (options.Watch)
                {
                    new ConsoleFilmProcessingWatcher(firstFolder).InfiniteWait();
                }
            }

            if (options.RunGui)
            {
                GuiApp.Run();
            }
        }
Exemple #50
0
        public static void Run(string[] args)
        {
            var options = new Options();
            var parser = new CommandLine.Parser(s =>
            {
                s.CaseSensitive = false;
                s.MutuallyExclusive = true;
                s.HelpWriter = Console.Out;
                s.ParsingCulture = System.Globalization.CultureInfo.InvariantCulture;
            });
            if (!parser.ParseArguments(args, options))
            {
                return;
            }

            if (options.Folders.Count > 0)
            {
                var firstFolder = options.Folders.First();
                var collection = new MediaCollection<ConsoleFilm>(firstFolder).Items;

                if (options.List)
                {
                    foreach (var film in collection)
                    {
                        Console.WriteLine(String.Format("{0,-3} {1,-9} {2}", film.Rating, film.ImdbId, film.FolderName));
                    }
                }

                if(options.Decorate)
                {
                    new IconService().ProcessValidFilms(collection, validFilms =>
                        Console.WriteLine("Complete! " + validFilms.Count() + " folders have been decorated with icons."));
                }

                if(options.Watch)
                {
                    new ConsoleFilmProcessingWatcher(firstFolder).InfiniteWait();
                }
            }

            if (options.RunGui)
            {
                GuiApp.Run();
            }
        }
Exemple #51
0
        static void Main(string[] args)
        {
            var options = new Options();
            var parser = new Parser(config => config.HelpWriter = Console.Out);
            var result = parser.ParseArguments(args, options);

            if (options.Timeout > 0)
            {
                timeout = TimeSpan.FromMilliseconds(options.Timeout);
            }

            if (options.MaxRetries > 0)
            {
                maxRetries = options.MaxRetries;
            }

            RunPackageInstall(options.PackagePath, options.SitecoreUrl);
        }
Exemple #52
0
        public static void Main(string[] cmdLineArgs)
        {
            try
            {
                var args = new Args();
                var parser = new Parser();

                if (!parser.ParseArguments(cmdLineArgs, args))
                {
                    log.Fatal("Command line args could not be parsed. Exiting the application.");
                    Environment.ExitCode = 1;
                }
                else
                {
                    if (args.ConfigCheck)
                    {
                        VerifyConfiguration();
                    }
                    else
                    {
                        if (!VerifyConfiguration())
                        {
                            log.Fatal("The configuration validation failed, exiting the application.");
                            Environment.ExitCode = 2;
                            return;
                        }

                        if (args.RunInConsole)
                        {
                            RunInConsole();
                        }
                        else
                        {
                            RunAsService();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
            }
        }
        private FormatOptions Parse(out int result, params string[] args)
        {
            result = 1;
            FormatOptions options = null;

            var parser = new Parser(settings =>
            {
                // CommandLine library help output is not thread-safe. We
                // disable console output entirely by providing a null writer
                settings.HelpWriter = null;
            });

            result = parser.ParseArguments<FormatOptions>(args)
                .Return(
                (FormatOptions parsedOptions) => { options = parsedOptions; return 0; },
                errs => ReportErrors(errs));

            return options;
        }
Exemple #54
0
        /// <summary>
        /// Called when the command line tool starts.
        /// </summary>
        /// <param name="args">Arguments for the application.</param>
        static void Main(string[] args)
        {
            // Parse the command line options
            var exitCode = 0;
            var options = new GlobalOptions();
            using (var parser = new Parser(settings => { settings.MutuallyExclusive = true; settings.HelpWriter = Console.Error; }))
            {
                if (!parser.ParseArguments(args, options, ExecuteVerb))
                {
                    exitCode = Parser.DefaultExitCodeFail;
                }
            }

            // Command line arguments not succesfully parsed
            #if DEBUG
            Console.ReadLine();
            #endif
            Environment.Exit(exitCode);
        }
Exemple #55
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandler);

            Printer.PrinterStream printerStream = new Printer.PrinterStream();
            Parser parser = new Parser(new Action<ParserSettings>(
                (ParserSettings p) => { p.CaseSensitive = false; p.IgnoreUnknownArguments = false; p.HelpWriter = printerStream; p.MutuallyExclusive = true; }));

            Options = new LogrOptions();
            if (!parser.ParseArguments(args, Options))
            {
                printerStream.Flush();
                Printer.RestoreDefaults();
                Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
            }
            
            Log log = new Log(Options.Repo, Options.LogFile, (Options.Limit > 0) ? Options.Limit : (int?)null);
            log.Update();
            log.Serialize();
        }
Exemple #56
0
        static void Main(string[] args)
        {
            var options = new Options();
            var parser = new Parser(config => config.HelpWriter = Console.Out);
            var result = parser.ParseArguments(args, options);

            if (options.Timeout > 0)
            {
                timeout = TimeSpan.FromMilliseconds(options.Timeout);
            }

            if (options.MaxRetries > 0)
            {
                maxRetries = options.MaxRetries;
            }

            Thread.Sleep(TimeSpan.FromSeconds(30));

            RunPublish(options.SitecoreUrl, options.SourceDatabaseName, options.TargetDatabaseNames, options.LanguageNames);
        }
Exemple #57
0
        public static int Main(string[] args)
        {
            #if DEBUG
            args = "-s example.js -w ./world -x 0 -y 4 -z 0".Split(' ');
            #endif

            #if !DEBUG
            try
            {
            #endif
                Options options = new Options();
                Parser cmdParser = new Parser();

                if (!cmdParser.ParseArguments(args, options))
                    throw new ArgumentException("Invalid Commandline parameter!");

                IntVector3 position = default(IntVector3);
                if (options.Output)
                {
                    if (options.PositionY != 0)
                    {
                        position = new IntVector3();
                        position.x = options.PositionX;
                        position.y = options.PositionY;
                        position.z = options.PositionZ;
                    }
                }

                JsScriptExecutor executor = new JsScriptExecutor();
                executor.Run(options.LibPath, options.ScriptFile, options.WorldDirectory, position, options.IsSchematic);
            #if !DEBUG
            }
            catch (Exception e)
            {
                Console.WriteLine("An Error of type {0} occured!", e.GetType());
                Console.WriteLine("Error Message: {0}", e.Message);
                return 1;
            }
            #endif
            return 0;
        }
Exemple #58
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Args: " + string.Join(", ", args));

            CommandLine.Parser commandLineParser = new Parser(settings =>
            {
                settings.HelpWriter = Console.Error;
                settings.CaseSensitive = false;
                settings.IgnoreUnknownArguments = true;
            });

            var options = new Options();
            if (commandLineParser.ParseArguments(args, options))
            {
                Console.WriteLine("Filename: {0}", options.InputFile);
                // Values are available here
                if (options.Verbose) Console.WriteLine("[Verbose] Args: {0}", string.Join(",", args));
            }

            Console.ReadKey();
        }
Exemple #59
0
        static void Main(string[] args)
        {
            var options = new Options();
            var parser = new CommandLine.Parser(with => with.HelpWriter = System.Console.Error);

            if (parser.ParseArguments(args, options)) {

                if (options.Debug) {

                    utils.Logger.Instance.BasicConfig();
                }
                else {
                    utils.Logger.Instance.XmlConfig();
                }

                utils.Logger.Instance.Log.Info("Program Start");
                utils.Logger.Instance.Log.Info("Arg RequestUri: " + options.RequestUri);

                Run(options);
            }
        }
        static void Main(string[] args)
        {
            var mediator = BuildMediator();
            var allTheCommands = (typeof(AddVerb).Assembly.GetTypes().Where(type => (typeof (IRequest).IsAssignableFrom(type)))).ToArray();

            var parser = new Parser(with => {
                with.EnableDashDash = true;
                with.CaseSensitive = false;
                with.HelpWriter = System.Console.Out;
            });

            var result = parser.ParseArguments(args, allTheCommands) as Parsed<object>;
            if (result != null)
            {
                mediator.Send((IRequest) result.Value);
            }
            else
            {
                Environment.Exit(1229);
            }
        }