Gives parsed values for the command line arguments
Exemple #1
0
        public static CommandLineOptions ParseArgs(string[] args)
        {
            var options = new CommandLineOptions();
            var parser = new CommandLineParser();

            parser.AddOption("--debug");
            parser.AddOption("--release");

            parser.Parse(args);

            var s = parser.GetArgument(0);

            if (s != null)
            {
                options.ScriptName = s;
                options.Debug = false;
                options.UserArguments = Runtime.AsList(parser.GetArgumentArray(1));
            }

            if (parser.GetOption("release") != null)
            {
                options.Debug = false;
            }

            if (parser.GetOption("debug") != null)
            {
                options.Debug = true;
            }

            return options;
        }
Exemple #2
0
 public static Options Parse(string[] args)
 {
     var options = new Options();
     var parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));
     options.IsValid = parser.ParseArguments(args, options);
     return options;
 }
Exemple #3
0
		/// <summary>
		/// Run with following arguments:
		/// 
		/// </summary>
		/// <param name="args"></param>
		/// <returns></returns>
		static int Main ( string[] args )
		{
			Thread.CurrentThread.CurrentCulture	=	System.Globalization.CultureInfo.InvariantCulture;
			Log.AddListener( new StdLogListener() );

			var options = new BuildOptions();
			var parser = new CommandLineParser( options );


			try {

				if ( args.Any( a => a=="/help" )) {
					PrintHelp( parser );
					return 0;
				}

				if ( !parser.ParseCommandLine( args ) ) {
					return 1;
				}

				Builder.Build( options );


			} catch ( Exception ex ) {
				parser.ShowError( ex.Message );
				return 1;
			}

			return 0;
		}
Exemple #4
0
 public static void Main(string[] args)
 {
     new ConsoleApplication().Run(() => {
         var arguments = new CommandLineParser().Parse<ApplicationArguments>(args);
         Main(arguments);
     });
 }
Exemple #5
0
		static void Main(string[] args) {
			options = new TProgrammOptions();
			var parser = new CommandLineParser(options);
			parser.Parse();

			CommandLineThread.start();

			if (options.help) {
				Console.WriteLine(parser.UsageInfo.GetOptionsAsString(78));
				Environment.Exit(0);
			}
			else if (parser.HasErrors) {
				Console.WriteLine(parser.UsageInfo.GetErrorsAsString(78));
				Environment.Exit(0);
			}
			else if (options.temp) {
				startTemp();
				Environment.Exit(0);
			}
			else if (options.test) {
				startTest();
				Environment.Exit(0);
			}
			else {
				startApp();
				Environment.Exit(0);
			}

		}
        public void NoArgs_Creates_Empty_Options()
        {
            var parser = new CommandLineParser<OptionsWithOneArg>();
            var options = parser.Parse(new string[0]);

            Assert.That(options.Action, Is.Null);
        }
        public void Parser_UnrecognizedArguments()
        {
            CommandLineParser parser;
            IEnumerable<ArgumentInstance> instances;
            TestLogger logger;

            string[] args = new string[] { "/a:XXX", "/unrecognized" };

            ArgumentDescriptor d1 = new ArgumentDescriptor("id1", new string[] { "/a:" }, true, "desc1", false);

            // 1. Don't allow unrecognized
            parser = new CommandLineParser(new ArgumentDescriptor[] { d1 }, false);

            logger = CheckProcessingFails(parser, args);

            logger.AssertSingleErrorExists("/unrecognized");
            logger.AssertErrorsLogged(1);

            // 2. Allow unrecognized
            parser = new CommandLineParser(new ArgumentDescriptor[] { d1 }, true);
            logger = new TestLogger();
            instances = CheckProcessingSucceeds(parser, logger, args);

            AssertExpectedValue("id1", "XXX", instances);
            AssertExpectedInstancesCount(1, instances);
            logger.AssertMessagesLogged(0); // expecting unrecognized arguments to be ignored silently
        }
        public void SingleStringArg_with_no_key()
        {
            var parser = new CommandLineParser<OptionsWithOneArg>();
            var options = parser.Parse(new[] { "connect" });

            Assert.That(options.Action, Is.EqualTo("connect"));
        }
        public void MasksSecretArgs()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                // Arrange.
                CommandLineParser clp = new CommandLineParser(
                    hc,
                    secretArgNames: new[] { "SecretArg1", "SecretArg2" });

                // Assert.
                clp.Parse(new string[]
                {
                    "cmd",
                    "--secretarg1",
                    "secret value 1",
                    "--publicarg",
                    "public arg value",
                    "--secretarg2",
                    "secret value 2",
                });

                // Assert.
                _secretMasker.Verify(x => x.AddValue("secret value 1"));
                _secretMasker.Verify(x => x.AddValue("secret value 2"));
                _secretMasker.Verify(x => x.AddValue(It.IsAny<string>()), Times.Exactly(2));
            }
        }
Exemple #10
0
        static int Main(string[] args)
        {
            // Parse commandline options.
            var options = new CommandLineOptions();
            var parser = new CommandLineParser(options);

            if (!parser.ParseCommandLine(args))
            {
                return 1;
            }

            // Run the program logic.
            try
            {
                var docsrc = PreprocessDocuments(options);

                GenerateIndexTopics(options, docsrc);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error: {0}\n\n{1}:\n{2}", e.Message, e.GetType(), e.StackTrace);
                return 1;
            }

            return 0;
        }
        public void Parser_Multiples()
        {
            CommandLineParser parser;
            IEnumerable<ArgumentInstance> instances;
            TestLogger logger;

            string[] args = new string[] { "zzzv1", "zzzv2", "zzzv3" };

            // 1. Don't allow multiples
            ArgumentDescriptor d1 = new ArgumentDescriptor("id", new string[] { "zzz" }, true, "desc1", false /* no multiples */);
            parser = new CommandLineParser(new ArgumentDescriptor[] { d1 }, false);

            logger = CheckProcessingFails(parser, args);

            logger.AssertSingleErrorExists("zzzv2", "v1");
            logger.AssertSingleErrorExists("zzzv3", "v1");
            logger.AssertErrorsLogged(2);

            // 2. Allow multiples
            d1 = new ArgumentDescriptor("id", new string[] { "zzz" }, true, "desc1", true /* allow multiple */);
            parser = new CommandLineParser(new ArgumentDescriptor[] { d1 }, true);
            logger = new TestLogger();
            instances = CheckProcessingSucceeds(parser, logger, args);

            AssertExpectedValues("id", instances, "v1", "v2", "v3");
            AssertExpectedInstancesCount(3, instances);
        }
Exemple #12
0
        static int Main(string[] args)
        {
            //Console.WriteLine("Anzahl: " + args.Count());

              Options options = new Options();
              CommandLineParser parser = new CommandLineParser(options);
              parser.Parse();
              Console.WriteLine(parser.UsageInfo.GetHeaderAsString(consoleWidth));

              if (options.Help)
              {
            Console.WriteLine(parser.UsageInfo.GetOptionsAsString(consoleWidth));
            StopApp();
            return 0;
              }
              else if (parser.HasErrors)
              {
            Console.WriteLine(parser.UsageInfo.GetErrorsAsString(consoleWidth));
            StopApp();
            return -1;
              }
              //Console.WriteLine("Hello {0}!", options.Name);

              Converter.Converter conv = new Converter.Converter(parser, options);
              String ret = conv.StartConverting();

              Console.WriteLine(ret);

              StopApp();
              return 0;
        }
Exemple #13
0
 private static void Main(string[] args)
 {
     var console = new DefaultConsole();
     var parser = new CommandLineParser<CommandLineContext>(console);
     var result = parser.Parse(args);
     if (result.Kind == ParsingResultKind.Success)
     {
         try
         {
             result.Context.Command.ExecuteCommand();
         }
         catch (ArgumentException)
         {
             console.WriteLine(WriteKind.Error, "The url should be absolute");
         }
         catch (WebException)
         {
             console.WriteLine(WriteKind.Error, "Couldn't process the page");
         }
         catch (UnauthorizedAccessException)
         {
             console.WriteLine(WriteKind.Error, "Access denied.");
             console.WriteLine(WriteKind.Info, "Try running as administrator");
         }
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ArchiveGenerationParameters"/> class.
        /// </summary>
        /// <param name="args">The application's command line arguments.</param>
        public ArchiveGenerationParameters(String[] args)
        {
            if (args == null || !args.Any())
                throw new InvalidCommandLineException();

            var parser = new CommandLineParser(args);
            if (!parser.IsParameter(args.First()))
                throw new InvalidCommandLineException();

            switch (args.First().ToLowerInvariant())
            {
                case "-pack":
                    Command = ArchiveGenerationCommand.Pack;
                    ProcessPackParameters(args, parser);
                    break;

                case "-list":
                    Command = ArchiveGenerationCommand.List;
                    ProcessListParameters(args, parser);
                    break;

                default:
                    throw new InvalidCommandLineException();
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FontGenerationParameters"/> class.
        /// </summary>
        /// <param name="args">The application's command line arguments.</param>
        public FontGenerationParameters(String[] args)
        {
            if (args == null || !args.Any())
                throw new InvalidCommandLineException();

            var parser = new CommandLineParser(args.Skip(1));
            if (parser.IsParameter(args.First()))
            {
                throw new InvalidCommandLineException();
            }

            NoBold   = parser.HasArgument("nobold");
            NoItalic = parser.HasArgument("noitalic");

            FontName = args.First();
            FontSize = parser.GetArgumentOrDefault<Single>("fontsize", 16f);
            Overhang = parser.GetArgumentOrDefault<Int32>("overhang", 0);
            PadLeft = parser.GetArgumentOrDefault<Int32>("pad-left", 0);
            PadRight = parser.GetArgumentOrDefault<Int32>("pad-right", 0);
            SuperSamplingFactor = parser.GetArgumentOrDefault<Int32>("supersample", 2);

            if (SuperSamplingFactor < 1)
                SuperSamplingFactor = 1;

            SourceText    = parser.GetArgumentOrDefault<String>("sourcetext");
            SourceFile    = parser.GetArgumentOrDefault<String>("sourcefile");
            SourceCulture = parser.GetArgumentOrDefault<String>("sourceculture");

            if (SourceText != null && SourceFile != null)
                throw new InvalidCommandLineException("Both a source text and a source file were specified. Pick one!");

            SubstitutionCharacter = parser.GetArgumentOrDefault<Char>("sub", '?');
        }
Exemple #16
0
        private static Command GetCommand(string[] args, ILogger logger)
        {
            try
            {
                var parser = new CommandLineParser<RasDialOptions>();
                var options = parser.Parse(args);

                var commandType = typeof(Command).Assembly
                                                 .GetTypes()
                                                 .SingleOrDefault(x => x.Name.Equals(options.Action, StringComparison.InvariantCultureIgnoreCase));

                if (commandType == null)
                {
                    throw new ArgumentException(string.Format("No action found for {0}.", options.Action));
                }

                return (Command)Activator.CreateInstance(commandType, new object[] { options, logger });
            }
            catch (Exception e)
            {
                logger.Error("Failed to find command.", e);
            }

            return null;
        }
Exemple #17
0
		static int Main(string[] args)
		{
			CommandLineParser parser = new CommandLineParser( args );

			if (parser.RegistrationPath.Length == 0)
					parser.RegistrationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(RegistrarApp)).Location);

			try
			{
				AssemblyRegistrar registrar = new AssemblyRegistrar( parser );

				if( parser.RegisterMode == CommandLineParser.InstallMode.Register )
					registrar.Register();
				else
				{
					try
					{
						registrar.UnRegister();
					}
					catch
					{
						// ignore the exception
					}
				}
				return (int) ReturnValue.Success;
			}
			catch( Exception ex )
			{
				System.Diagnostics.Debug.Assert(false, ex.Message);
				ErrorReporter reporter = new ErrorReporter(parser.RegistrationPath, parser.SilentMode);
				reporter.Report(ex.Message);
				return (int) ReturnValue.Failure;
			}
		}
Exemple #18
0
        public static void Main(string[] args)
        {
            var parser = new CommandLineParser(typeof(ProgramArguments));
            try
            {
                if (args.Length != 0 && !args.SequenceEqual(new[] { "/help" }))
                {
                    Process((ProgramArguments)parser.Parse(args));
                    return;
                }
            }
            catch (CommandLineArgumentException ex)
            {
                using (LineWrappingTextWriter writer = LineWrappingTextWriter.ForConsoleError())
                using (new ConsoleColorer(ConsoleColor.Red))
                {
                    writer.WriteLine();
                    writer.WriteLine(ex.Message);
                    writer.WriteLine();
                }
            }

            parser.WriteUsageToConsole(new WriteUsageOptions
                {
                    IncludeAliasInDescription = true,
                });
        }
Exemple #19
0
        static int Main(string[] args)
        {
            _options = new Options();
            CommandLineParser parser = new CommandLineParser(_options);
            parser.Parse();

            if (_options.Help)
            {
                Console.WriteLine(parser.UsageInfo.ToString(78, false));
                return 0;
            }

            if (parser.HasErrors)
            {
                Console.WriteLine(parser.UsageInfo.ToString(78, true));
                return -1;
            }

            if(_options.Test)
                Test();
            if (_options.TestString != null)
                TestString();
            else
                RunDec0de();

            return 0;
        }
Exemple #20
0
        static int Main(string[] args)
        {
            // Read command line
            var options = new CommandLineOptions();
            
            var parser = new CommandLineParser(options);
            if (!parser.ParseCommandLine(args))
            {
                return 1;
            }

            var config = LoadConfig(options);

            // Export Samples
            foreach (var sample in config.Samples)
            {
                SampleExporter.Export(config, sample);
            }

            // Copy individual files
            foreach (var file in config.FilesToCopy)
            {
                File.Copy(Path.Combine(config.Options.Root, file), Path.Combine(config.Options.Dest, file), true);
            }

            return 0;
        }
Exemple #21
0
        public void Show()
        {
            CommandLineParser p = new CommandLineParser();
            p.RegisterArgumentsForCommand<ArgumentWithSameFirstLetter>("test");

            Console.Write(p.WhatsRegistered());
        }
Exemple #22
0
        static int Main(string[] args)
        {
            try
            {
                var commandLineParser = new CommandLineParser(args);

                if (commandLineParser.HasErrors)
                {
                    using (Foreground.Red)
                        foreach (var error in commandLineParser.Errors)
                            Console.WriteLine(error);

                    Console.WriteLine("Usage: Fixie.Console [custom-options] assembly-path...");
                    return FatalError;
                }

                int failed = 0;

                foreach (var assemblyPath in commandLineParser.AssemblyPaths)
                {
                    var result = Execute(assemblyPath, args);

                    failed += result.Failed;
                }

                return failed;
            }
            catch (Exception exception)
            {
                using (Foreground.Red)
                    Console.WriteLine("Fatal Error: {0}", exception);
                return FatalError;
            }
        }
Exemple #23
0
 public void ParsingTest()
 {
     var parser = new CommandLineParser();
     parser.Parse(new string[] { "file.txt", "/i", "command" });
     Assert.AreEqual(3, parser.ParametersCount, "Invalid count of parameters");
     Assert.IsTrue(parser.IsActive("i"), "Expected option not found");
 }
        private static int Main(string[] args)
        {
            string log4NetFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                              "loggingSettings.xml");
            XmlConfigurator.Configure(new FileInfo(log4NetFile));
            var programParams = new ProgramParams();
            var parser = new CommandLineParser(programParams);
            parser.Parse();

            if (programParams.Help)
            {
                Console.WriteLine(parser.UsageInfo.ToString(78, false));
            }
            else if (parser.HasErrors)
            {
                Console.WriteLine(parser.UsageInfo.ToString(78, true));
                return -1;
            }

            try
            {
                new Program(programParams);
            }
            catch (Exception e)
            {
                log.Error(e.Message, e);
                Console.Out.WriteLine("ERROR: " + e.Message);
                return -1;
            }
            return 0;
        }
Exemple #25
0
 public void ParseOptionsWithoutValues()
 {
     var parser = new CommandLineParser();
     parser.Parse(new string[] { "file.txt", "/i", "fileinputname" });
     Assert.AreEqual(3, parser.ParametersCount, "Invalid count of parameters");
     Assert.Throws<System.Collections.Generic.KeyNotFoundException>(() => parser.GetNamedOption("i"));
 }
		public void TestIgnoresBogusCommands()
		{
			string [] commandLine = new String[3];
			commandLine[0] = "/u";
			commandLine[1] = "q:\\test\\other\\";
			commandLine[2] = "/t";
			CommandLineParser parser = new CommandLineParser(commandLine);
			Assert.IsTrue( parser.RegistrationPath == "q:\\test\\other\\" );
			Assert.IsTrue( parser.RegisterMode == CommandLineParser.InstallMode.Unregister );

			commandLine = new String[3];
			commandLine[0] = "/u";
			commandLine[1] = "/YYYYY";
			commandLine[2] = "/t";
			parser = new CommandLineParser(commandLine);
			Assert.IsTrue( parser.RegistrationPath == "" );
			Assert.IsTrue( parser.RegisterMode == CommandLineParser.InstallMode.Unregister );

			commandLine = new String[2];
			commandLine[0] = "/YYYYY";
			commandLine[1] = "/t";
			parser = new CommandLineParser(commandLine);
			Assert.IsTrue( parser.RegistrationPath == "" );
			Assert.IsTrue( parser.RegisterMode == CommandLineParser.InstallMode.Register );
		}
        public static int Main(string[] args)
        {
            // Parse the commandline options.
            var options = new CommandLineOptions();
            var parser = new CommandLineParser(options);

            if (!parser.ParseCommandLine(args))
                return 1;

            try
            {
                // Convert the font.
                MakeSpriteFont(options);
                
                return 0;
            }
            catch (Exception e)
            {
                // Print an error message if conversion failed.
                Console.WriteLine();
                Console.Error.WriteLine("Error: {0}", e.Message);
     
                return 1;
            }
        }
Exemple #28
0
 public void TestWithFlagSuffixFalse()
 {
     var parser = new CommandLineParser();
      var args = new[] { "Unused0", "/Help-", "Unused1" };
      var actual = parser.Parse<Flag>(args);
      Assert.That(actual.Option.FlagValue, Is.False);
      Assert.That(actual, Is.EquivalentTo(new[] { "Unused0", "Unused1" }));
 }
Exemple #29
0
 public void TestWithoutArgument()
 {
     var parser = new CommandLineParser();
      var args = new[] { "Unused0", "/Help", "Unused1" };
      var actual = parser.Parse<Flag>(args);
      Assert.That(actual.Option.FlagValue, Is.True);
      Assert.That(actual, Is.EquivalentTo(new[] { "Unused0", "Unused1" }));
 }
 public void ParsesAssemblyPathsList()
 {
     var parser = new CommandLineParser("foo.dll", "bar.dll");
     parser.AssemblyPaths.ShouldEqual("foo.dll", "bar.dll");
     parser.Options.ShouldBeEmpty();
     parser.HasErrors.ShouldBeFalse();
     parser.Errors.ShouldBeEmpty();
 }
Exemple #31
0
 /// <summary>
 /// Processes user-specified parameters for the pack command.
 /// </summary>
 /// <param name="args">The application's command line arguments.</param>
 /// <param name="parser">The command line argument parser.</param>
 private void ProcessPackParameters(String[] args, CommandLineParser parser)
 {
     PackOutput      = args.Skip(1).Take(1).Single();
     PackDirectories = args.Skip(2).ToList();
 }
 public void ShouldParseLeftCommand()
 {
     var parsedCommand = CommandLineParser.Parse("LEFT");
     
     Assert.IsType<LeftCommand>(parsedCommand);
 }
Exemple #33
0
        private static bool ParseCommandLine(string[] args, out CommandLineParser parser)
        {
            try
            {
                parser = new CommandLineParser(args);
            }
            catch (Exception)
            {
                throw new InvalidOperationException(
                          "An error occurred whilst parsing the command line; try -? for command line arguments.");
            }

            try
            {
                parser.ExtractAndValidateArguments();

                if (parser.PrintUsage)
                {
                    System.Console.WriteLine(parser.Usage());
                    return(false);
                }


                if (parser.PrintVersion)
                {
                    var entryAssembly = System.Reflection.Assembly.GetEntryAssembly();
                    if (entryAssembly == null)
                    {
                        Logger.Warn("No entry assembly, running from unmanaged application");
                    }
                    else
                    {
                        var version = entryAssembly.GetName().Version;
                        System.Console.WriteLine("OpenCover version {0}", version);
                        if (args.Length == 1)
                        {
                            return(false);
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(parser.TargetDir) && !Directory.Exists(parser.TargetDir))
                {
                    System.Console.WriteLine("TargetDir '{0}' cannot be found - have you specified your arguments correctly?", parser.TargetDir);
                    return(false);
                }

                if (parser.Service)
                {
                    try
                    {
                        using (var service = new ServiceController(parser.Target))
                        {
                            var name = service.DisplayName;
                            System.Console.WriteLine("Service '{0}' found", name);
                        }
                    }
                    catch (Exception)
                    {
                        System.Console.WriteLine("Service '{0}' cannot be found - have you specified your arguments correctly?", parser.Target);
                        return(false);
                    }
                }
                else if (!File.Exists(ResolveTargetPathname(parser)))
                {
                    System.Console.WriteLine("Target '{0}' cannot be found - have you specified your arguments correctly?", parser.Target);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("Incorrect Arguments: {0}", ex.Message);
                System.Console.WriteLine("");
                System.Console.WriteLine(parser.Usage());
                return(false);
            }
            return(true);
        }
Exemple #34
0
        public static int Main(string[] args)
        {
            if (args.Length == 2 && args[0] == "--post-build-check")
            {
                return(PostBuildChecker.RunPostBuildChecks(args[1], System.Reflection.Assembly.GetExecutingAssembly()));
            }

            CommandLine cmdLine;

            try
            {
                cmdLine = CommandLineParser.Parse <CommandLine>(args);
            }
            catch (CommandLineParseException e)
            {
                e.WriteUsageInfoToConsole();
                return(1);
            }

            var serviceProcess = new SingleSelfServiceProcess <PropellerService>();
            var service        = (PropellerService)serviceProcess.Services.First();

            service.SettingsPath = cmdLine.SettingsPath;

            Console.WriteLine("Propeller invoked with action: " + cmdLine.Action);
            Console.WriteLine("Settings file: " + (cmdLine.SettingsPath ?? "(default)"));

            switch (cmdLine.Action)
            {
            case Action.RunAsStandalone:
                var thread = new Thread(() => { service.RunAsStandalone(args); });
                thread.Start();
                Console.WriteLine("Running. Press ENTER to exit.");
                Console.ReadLine();
                Console.WriteLine("Shutting down...");
                service.Shutdown();
                thread.Join();
                break;

            case Action.Install:
                var arguments = "service";
                if (cmdLine.SettingsPath != null)
                {
                    arguments += @" -s ""{0}""".Fmt(cmdLine.SettingsPath);
                }
                serviceProcess.Install(ServiceAccount.NetworkService, arguments);
                break;

            case Action.Uninstall:
                serviceProcess.Uninstall();
                break;

            case Action.Start:
                serviceProcess.StartAll();
                break;

            case Action.Stop:
                serviceProcess.StopAll();
                break;

            case Action.Service:
                serviceProcess.ExecuteServices();
                break;

            default:
                Console.WriteLine("Unknown arguments.");
                return(1);
            }

#if DEBUG
            Console.WriteLine("Done. Press ENTER to exit.");
            Console.ReadLine();
#endif

            return(0);
        }
Exemple #35
0
        static void Main(string[] args)
        {
            Console.WriteLine("Virtual eXecuter Assembler by Claus Andersen");
            Console.WriteLine("Version: 0.03 - June 22nd 2008");
            Console.WriteLine("");

            try
            {
                #region Parse command line
                Dictionary <string, List <string> > options = CommandLineParser.Run(args);

                if (options == null || options.Count == 0)
                {
                    Help();
                    Quit();
                    return;
                }

                if (options.ContainsKey("default"))
                {
                    sourceFileName = options["default"][0];
                    if (File.Exists(sourceFileName) == false)
                    {
                        Console.WriteLine("The specified source file does not exist");
                        Quit();
                        return;
                    }
                    outputFileName = Path.ChangeExtension(sourceFileName, ".vxx");
                }

                if (options.ContainsKey("o"))
                {
                    outputFileName = options["o"][0];
                }

                if (options.ContainsKey("l"))
                {
                    if (options["l"].Count == 0)
                    {
                        listFileName = Path.ChangeExtension(sourceFileName, ".lst");
                    }
                    else if (options["l"].Count == 1)
                    {
                        listFileName = options["l"][0];
                    }
                    else
                    {
                        Console.WriteLine("More than one list file was specified");
                    }
                }

                if (options.ContainsKey("m"))
                {
                    if (options["m"].Count == 0)
                    {
                        mapFileName = Path.ChangeExtension(sourceFileName, ".map");
                    }
                    else if (options["m"].Count == 1)
                    {
                        mapFileName = options["m"][0];
                    }
                    else
                    {
                        Console.WriteLine("More than one map file was specified");
                    }
                }

                if (sourceFileName == "")
                {
                    Help();
                    Quit();
                    return;
                }

                if (options.ContainsKey("w"))
                {
                    waitWhenExiting = true;
                }
                #endregion

                outputFile = File.Create(outputFileName);

                if (listFileName != "")
                {
                    Informer.Instance.SetListFile(listFileName);
                }

                if (mapFileName != "")
                {
                    Informer.Instance.SetMapFile(mapFileName);
                }

                Assembler asm = new Assembler();

                StreamReader preprocessedSourceFile = asm.Preprocessor(sourceFileName);

                asm.FindLabels(preprocessedSourceFile);
                asm.GenerateCode(preprocessedSourceFile);
                asm.GenerateExecutable(outputFile);

                preprocessedSourceFile.Close();
                outputFile.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
            }
            Quit();
        }
Exemple #36
0
        protected override DependencyObject CreateShell()
        {
            var settings = Container.Resolve <IApplicationSettings>();

            settings.Reload();

            var arguments = new CommandLineProvider <CommandLineOptions>().CreateArgumentsModel(CommandLineParser.Parse(args));

            if (arguments.IsValid)
            {
                if (arguments.Reset)
                {
                    settings.Reset();
                }
            }

            var model = Container.Resolve <IMainWindowViewModel>();

            model.ShowView();

            return(model.View as DependencyObject);
        }
Exemple #37
0
        internal static int AppMain(string[] args, IOStreams streams)
        {
            var parser = new CommandLineParser(args, Switches);

            return(Bootstrapper.Run(AppMain, parser, streams));
        }
    /// <summary>
    /// Gives us an example command line for getting a site inventory
    /// </summary>
    /// <param name="pathToExportDir"></param>
    /// <param name="siteUrl"></param>
    /// <param name="userName"></param>
    /// <param name="password"></param>
    /// <param name="isSiteAdmin"></param>
    /// <param name="commandLineOut">Command line as text ready to show the user</param>
    /// <param name="parsedCommandLine">Command line as set of </param>
    public static void GenerateCommandLine_SiteExport(
        bool showPasswordInUi,
        string pathToExportDir,
        string siteUrl,
        string userName,
        string password,
        bool isSiteAdmin,
        string exportSingleProject,
        string exportOnlyWithTag,
        bool removeExportTag,
        string pathToLogFile,
        string pathToErrorsFile,
        bool backgroundKeepAliveRequests,
        bool logVerbose,
        bool generateDownloadInfoFiles,
        out string commandLineOut,
        out CommandLineParser parsedCommandLine)
    {
        string uiPassword = helper_DetermineIfDummyPasswordNeeded(showPasswordInUi, password);
        //We will return a the list of ordered command line arguments as an array
        var arguments = new List <string>();

        var sb = new StringBuilder();

        helper_AppendParameter(arguments, sb, Parameter_Command, ParameterValue_Command_Export);
        helper_AppendParameter(arguments, sb, Parameter_FromUserId, userName);
        helper_AppendParameter(arguments, sb, Parameter_FromUserPassword, password, uiPassword);
        helper_AppendParameter(arguments, sb, Parameter_ExportDirectory, pathToExportDir);
        helper_AppendParameter(arguments, sb, Parameter_FromSiteUrl, siteUrl);
        helper_AppendParameter(arguments, sb, Parameter_FromSiteIsSystemAdmin, helper_BoolToText(isSiteAdmin));
        helper_AppendParameter(arguments, sb, Parameter_BackgroundKeepAlive, helper_BoolToText(backgroundKeepAliveRequests));
        helper_AppendParameter(arguments, sb, Parameter_LogVerbose, helper_BoolToText(logVerbose));
        helper_AppendParameter(arguments, sb, Parameter_GenerateInfoFilesForDownloads, helper_BoolToText(generateDownloadInfoFiles));

        //Export only a single project?
        if (!string.IsNullOrWhiteSpace(exportSingleProject))
        {
            helper_AppendParameter(arguments, sb, Parameter_ExportSingleProject, exportSingleProject);
        }

        //Export only if tagged
        if (!string.IsNullOrWhiteSpace(exportOnlyWithTag))
        {
            helper_AppendParameter(arguments, sb, Parameter_ExportOnlyWithTag, exportOnlyWithTag);
            helper_AppendParameter(arguments, sb, Parameter_RemoveTagAfterExport, helper_BoolToText(removeExportTag));
        }


        //Log file?
        if (!string.IsNullOrWhiteSpace(pathToLogFile))
        {
            helper_AppendParameter(arguments, sb, Parameter_LogFile, pathToLogFile);
        }

        //Errors file?
        if (!string.IsNullOrWhiteSpace(pathToErrorsFile))
        {
            helper_AppendParameter(arguments, sb, Parameter_ErrorsFile, pathToErrorsFile);
        }

        //In the command line we generate, by default include the 'exit on finish'
        helper_AppendParameter(arguments, sb, Parameter_ExitWhenDone, helper_BoolToText(true));

        //Return the raw command line, quoted values as necessary
        commandLineOut = sb.ToString();

        //Return the arugments as an array
        parsedCommandLine = new CommandLineParser(arguments);
    }
    /// <summary>
    /// Site import from local file system
    /// </summary>
    /// <param name="showPasswordInUi"></param>
    /// <param name="pathToImportFrom"></param>
    /// <param name="siteUrl"></param>
    /// <param name="userName"></param>
    /// <param name="password"></param>
    /// <param name="isSiteAdmin"></param>
    /// <param name="remapDataServerReferences"></param>
    /// <param name="pathToDbCredentialsFile"></param>
    /// <param name="pathToLogFile"></param>
    /// <param name="pathToErrorsFile"></param>
    /// <param name="pathToManualStepsFile"></param>
    /// <param name="remapContentOwnership"></param>
    /// <param name="logVerbose"></param>
    /// <param name="commandLineOut"></param>
    /// <param name="parsedCommandLine"></param>
    internal static void GenerateCommandLine_SiteImport(
        bool showPasswordInUi,
        string pathToImportFrom,
        string siteUrl,
        string userName,
        string password,
        bool isSiteAdmin,
        bool remapDataServerReferences,
        string pathToDbCredentialsFile,
        string pathToLogFile,
        string pathToErrorsFile,
        string pathToManualStepsFile,
        bool remapContentOwnership,
        bool logVerbose,
        out string commandLineOut,
        out CommandLineParser parsedCommandLine)
    {
        //We will return a the list of ordered command line arguments as an array
        var    arguments  = new List <string>();
        string uiPassword = helper_DetermineIfDummyPasswordNeeded(showPasswordInUi, password);

        var sb = new StringBuilder();

        helper_AppendParameter(arguments, sb, Parameter_Command, ParameterValue_Command_Import);
        helper_AppendParameter(arguments, sb, Parameter_ToUserId, userName);
        helper_AppendParameter(arguments, sb, Parameter_ToUserPassword, password, uiPassword);
        helper_AppendParameter(arguments, sb, Parameter_ImportDirectory, pathToImportFrom);
        helper_AppendParameter(arguments, sb, Parameter_ToSiteUrl, siteUrl);
        helper_AppendParameter(arguments, sb, Parameter_ToSiteIsSiteAdmin, helper_BoolToText(isSiteAdmin));
        helper_AppendParameter(arguments, sb, Parameter_RemapDataserverReferences, helper_BoolToText(remapDataServerReferences));
        helper_AppendParameter(arguments, sb, Parameter_ImportAssignContentOwnership, helper_BoolToText(remapContentOwnership));
        helper_AppendParameter(arguments, sb, Parameter_LogVerbose, helper_BoolToText(logVerbose));

        //Credentials file?
        if (!string.IsNullOrWhiteSpace(pathToDbCredentialsFile))
        {
            helper_AppendParameter(arguments, sb, Parameter_DBCredentialsFile, pathToDbCredentialsFile);
        }

        //Log file?
        if (!string.IsNullOrWhiteSpace(pathToLogFile))
        {
            helper_AppendParameter(arguments, sb, Parameter_LogFile, pathToLogFile);
        }

        //Errors file?
        if (!string.IsNullOrWhiteSpace(pathToErrorsFile))
        {
            helper_AppendParameter(arguments, sb, Parameter_ErrorsFile, pathToErrorsFile);
        }

        //Manual steps file?
        if (!string.IsNullOrWhiteSpace(pathToManualStepsFile))
        {
            helper_AppendParameter(arguments, sb, Parameter_ManualStepsFile, pathToManualStepsFile);
        }


        //In the command line we generate, by default include the 'exit on finish'
        helper_AppendParameter(arguments, sb, Parameter_ExitWhenDone, helper_BoolToText(true));

        //Return the raw command line, quoted values as necessary
        commandLineOut = sb.ToString();

        //Return the arugments as an array
        parsedCommandLine = new CommandLineParser(arguments);
    }
Exemple #40
0
 public void SetUp()
 {
     _target = new CommandLineParser <Options>();
 }
 public void ShouldParseReportCommand()
 {
     var parsedCommand = CommandLineParser.Parse("REPORT");
     
     Assert.IsType<ReportCommand>(parsedCommand);
 }
 public void ShouldParsePlaceCommand()
 {
     var parsedCommand = CommandLineParser.Parse("PLACE 1,2,NORTH");
     
     Assert.IsType<PlaceCommand>(parsedCommand);
 }
Exemple #43
0
        private static void RunService(CommandLineParser parser, Action <StringDictionary> environment, ILog logger)
        {
            if (ServiceEnvironmentManagementEx.IsServiceDisabled(parser.Target))
            {
                logger.ErrorFormat("The service '{0}' is disabled. Please enable the service.",
                                   parser.Target);
                return;
            }

            var service = new ServiceController(parser.Target);

            try
            {
                if (service.Status != ServiceControllerStatus.Stopped)
                {
                    logger.ErrorFormat(
                        "The service '{0}' is already running. The profiler cannot attach to an already running service.",
                        parser.Target);
                    return;
                }

                // now to set the environment variables
                var profilerEnvironment = new StringDictionary();
                environment(profilerEnvironment);

                var serviceEnvironment = new ServiceEnvironmentManagement();

                try
                {
                    serviceEnvironment.PrepareServiceEnvironment(
                        parser.Target,
                        parser.ServiceEnvironment,
                        (from string key in profilerEnvironment.Keys
                         select string.Format("{0}={1}", key, profilerEnvironment[key])).ToArray());

                    // now start the service
                    var old = service;
                    service = new ServiceController(parser.Target);
                    old.Dispose();

                    if (parser.Target.ToLower().Equals("w3svc"))
                    {
                        // Service will not automatically start
                        if (!TerminateCurrentW3SvcHost(logger) ||
                            !ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
                        {
                            service.Start();
                        }
                    }
                    else
                    {
                        service.Start();
                    }
                    logger.InfoFormat("Service starting '{0}'", parser.Target);
                    service.WaitForStatus(ServiceControllerStatus.Running, parser.ServiceStartTimeout);
                    logger.InfoFormat("Service started '{0}'", parser.Target);
                }
                catch (InvalidOperationException fault)
                {
                    logger.FatalFormat("Service launch failed with '{0}'", fault);
                }
                finally
                {
                    // once the serice has started set the environment variables back - just in case
                    serviceEnvironment.ResetServiceEnvironment();
                }

                // and wait for it to stop
                service.WaitForStatus(ServiceControllerStatus.Stopped);
                logger.InfoFormat("Service stopped '{0}'", parser.Target);

                // Stopping w3svc host
                if (parser.Target.ToLower().Equals("w3svc"))
                {
                    logger.InfoFormat("Stopping svchost to clean up environment variables for {0}", parser.Target);
                    if (ServiceEnvironmentManagementEx.IsServiceStartAutomatic(parser.Target))
                    {
                        logger.InfoFormat("Please note that the 'w3svc' service may automatically start");
                    }
                    TerminateCurrentW3SvcHost(logger);
                }
            }
            finally
            {
                service.Dispose();
            }
        }
Exemple #44
0
 private static bool TryParse <T>(IEnumerable <string> args, T dest, CommandLineParserOptions options = null) where T : class =>
 CommandLineParser.TryParse(args, dest, options ?? new CommandLineParserOptions {
     DisplayUsageInfoOnError = false
 });
Exemple #45
0
        private void SetupCommandLine(CommandLineParser parser)
        {
            // #CommandLineDefinitions
            parser.ParameterSetsWhereQualifiersMustBeFirst = new string[] { "run", "UserCommand" };
            parser.NoDashOnParameterSets = true;

            parser.DefineOptionalQualifier("LogFile", ref LogFile, "Send messages to this file instead launching the GUI.  Intended for batch scripts and other automation.");

            // These apply to start, collect and run
            parser.DefineOptionalQualifier("BufferSize", ref BufferSizeMB, "The size the buffers (in MB) the OS should use to store events waiting to be written to disk."); // TODO remove eventually.
            parser.DefineOptionalQualifier("Circular", ref CircularMB, "Do Circular logging with a file size in MB.  Zero means non-circular.");                             // TODO remove eventually.
            parser.DefineOptionalQualifier("BufferSizeMB", ref BufferSizeMB, "The size the buffers (in MB) the OS should use to store events waiting to be written to disk.");
            parser.DefineOptionalQualifier("CircularMB", ref CircularMB, "Do Circular logging with a file size in MB.  Zero means non-circular.");
            parser.DefineOptionalQualifier("InMemoryCircularBuffer", ref InMemoryCircularBuffer, "Keeps the circular buffer in memory until the session is stopped.");
            parser.DefineOptionalQualifier("StackCompression", ref StackCompression, "Use stack compression (only on Win 8+) to make collected file smaller.");
            parser.DefineOptionalQualifier("MaxCollectSec", ref MaxCollectSec,
                                           "Turn off collection (and kill the program if perfView started it) after this many seconds. Zero means no timeout.");
            parser.DefineOptionalQualifier("StopOnPerfCounter", ref StopOnPerfCounter,
                                           "This is of the form CATEGORY:COUNTERNAME:INSTANCE OP NUM  where CATEGORY:COUNTERNAME:INSTANCE, identify " +
                                           "a performance counter (same as PerfMon), OP is either < or >, and NUM is a number.  " +
                                           "When that condition is true then collection will stop.  You can specify this qualifier more than once (logical OR).  See 'Stop Trigger' in the users guide for more.");
            parser.DefineOptionalQualifier("StopOnEventLogMessage", ref StopOnEventLogMessage,
                                           "Stop when an event log message that matches the given (ignore case) regular expression is written to the Windows 'Application' event log.  " +
                                           "You can specify a particular event log with the syntax eventLogName@RegExp.   Can be specified more than once (logical OR).");

            parser.DefineOptionalQualifier("StopOnEtwEvent", ref StopOnEtwEvent,
                                           "This is of the form PROVIDER/EVENTNAME;key1=value1;key2=value2... " +
                                           "This option is quite powerful, See the users guide for more details.");

            int StopOnRequestOverMsec   = 0;
            int StopOnGCSuspendOverMSec = 0;

            // These are basically special cases of the /StopOnEtwEvent
            parser.DefineOptionalQualifier("StopOnRequestOverMsec", ref StopOnRequestOverMsec,
                                           "Trigger a stop of a collect command if there is any IIS request that is longer than the given number of MSec.");
            parser.DefineOptionalQualifier("StopOnGCOverMsec", ref StopOnGCOverMsec,
                                           "Trigger a stop of a collect command if there is a .NET Garbage Collection (GC) is longer than the given number of MSec.");
            parser.DefineOptionalQualifier("StopOnGCSuspendOverMSec", ref StopOnGCSuspendOverMSec,
                                           "Trigger a stop of a collect command if there is a .NET Garbage Collection (GC) where suspending for the GC took over the given number of MSec.");
            parser.DefineOptionalQualifier("StopOnBGCFinalPauseOverMsec", ref StopOnBGCFinalPauseOverMsec,
                                           "Trigger a stop of a collect command if there is a background .NET Garbage Collection (GC) whose final pause is longer than the given number of MSec. To work correctly, " +
                                           "this requires that heap survival and movement tracking is not enabled.");
            parser.DefineOptionalQualifier("StopOnAppFabricOverMsec", ref StopOnAppFabricOverMsec,
                                           "Trigger a stop of a collect command if there is a AppFabric request is longer than the given number of MSec.");

            parser.DefineOptionalQualifier("StopOnException", ref StopOnException,
                                           "Where the text is a regular expression that will be used to match the full name and message of the .NET Exception thrown." +
                                           "The empty string represents any exception.");
            parser.DefineOptionalQualifier("StopOnGen2GC", ref StopOnGen2GC,
                                           "This will stop on any non-background Gen2 GC from the given process (can be a process ID or a process Name (exe file name without path or extension) or * (any process)");

            parser.DefineOptionalQualifier("Process", ref Process, "A process name (exe file name without directory or extension) or the Decimal Process ID.  " +
                                           "If used with the /StopOn* qualifiers using ETW events, will restrict events to only that process.");
            parser.DefineOptionalQualifier("DecayToZeroHours", ref DecayToZeroHours,
                                           "The trigger value used in StopOnPerfCounter or StopOn*OverMSec will decay to zero in this interval of time.");
            parser.DefineOptionalQualifier("MinSecForTrigger", ref MinSecForTrigger,
                                           "The number of seconds a perf Counter has to be above threshold before it is considered triggered.");
            parser.DefineOptionalQualifier("DelayAfterTriggerSec", ref DelayAfterTriggerSec,
                                           "Wait this number of seconds after a trigger before actually stopping the trace.");
            parser.DefineOptionalQualifier("CollectMultiple", ref CollectMultiple, "Collect Multiple instance (used in conjunction with StopTrigger).");
            parser.DefineOptionalQualifier("StartOnPerfCounter", ref StartOnPerfCounter,
                                           "This is of the form CATEGORY:COUNTERNAME:INSTANCE OP NUM  where CATEGORY:COUNTERNAME:INSTANCE, identify " +
                                           "a performance counter (same as PerfMon), OP is either < or >, and NUM is a number.  " +
                                           "When that condition is true then collection will start.  You can specify this qualifier more than once.  Search for 'MonitorPerfCounter' in the users guide for more.");
            parser.DefineOptionalQualifier("StopCommand", ref StopCommand,
                                           "If present this command is executed when a PerfView stops.  It is useful to stopping other tracing logic external to PerfView.");

            List <string> etwStopEvents = new List <string>();

            if (StopOnRequestOverMsec != 0)
            {
                etwStopEvents.Add("Microsoft-Windows-IIS/EventID(1);Level=Critical;TriggerMSec=" + StopOnRequestOverMsec);
            }

            if (StopOnGCSuspendOverMSec != 0)
            {
                etwStopEvents.Add("E13C0D23-CCBC-4E12-931B-D9CC2EEE27E4/GC/SuspendEEStart;StopEvent=GC/SuspendEEStop;StartStopID=ThreadID;Keywords=0x1;TriggerMSec=" + StopOnGCSuspendOverMSec);
            }

            if (0 < etwStopEvents.Count)
            {
                if (StopOnEtwEvent != null)
                {
                    etwStopEvents.AddRange(StopOnEtwEvent);
                }

                StopOnEtwEvent = etwStopEvents.ToArray();
            }

            // Respect the /Process and /DecayToZeroHours options by tacking them on the end if they are not already present.
            if (StopOnEtwEvent != null && (Process != null || DecayToZeroHours != 0))
            {
                etwStopEvents.Clear();
                foreach (var stopEtwEvent in StopOnEtwEvent)
                {
                    var newStopEtwEvent = stopEtwEvent;
                    if (Process != null && !stopEtwEvent.Contains(";Process="))
                    {
                        newStopEtwEvent += ";Process=" + Process;
                    }

                    if (DecayToZeroHours != 0 && !stopEtwEvent.Contains(";DecayToZeroHours="))
                    {
                        newStopEtwEvent += ";DecayToZeroHours=" + DecayToZeroHours;
                    }

                    etwStopEvents.Add(newStopEtwEvent);
                }
                StopOnEtwEvent = etwStopEvents.ToArray();
            }

            parser.DefineOptionalQualifier("MonitorPerfCounter", ref MonitorPerfCounter,
                                           "This is of the form CATEGORY:COUNTERNAME:INSTANCE@NUM  where CATEGORY:COUNTERNAME:INSTANCE, identify " +
                                           "a performance counter (same as PerfMon), and NUM is a number representing seconds.  The @NUM part is " +
                                           "optional and defaults to 2.   The value of the performance counter is logged to the ETL file as an " +
                                           "event ever NUM seconds");
            parser.DefineOptionalQualifier("CpuSampleMSec", ref CpuSampleMSec,
                                           "The interval (MSec) between CPU samples (.125Msec min).");

            // These apply to Stop Collect and Run
            parser.DefineOptionalQualifier("Merge", ref Merge, "Do a merge after stopping collection.");
            parser.DefineOptionalQualifier("Zip", ref Zip, "Zip the ETL file (implies /Merge).");
            parser.DefineOptionalQualifier("Wpr", ref Wpr, "Make output mimic WPR (Windows Performance Recorder). Don't ZIP, make a .ngenpdbs directory.  " +
                                           "This also enables threadTime as well as user mode providers WPR would normally collect by default.   This option can also be used " +
                                           "On the unzip command.   See 'Working with WPA' in the help for more.");
            parser.DefineOptionalQualifier("LowPriority", ref LowPriority, "Do merging and ZIPing at low priority to minimize impact to system.");
            parser.DefineOptionalQualifier("NoRundown", ref NoRundown, "Don't collect rundown events.  Use only if you know the process of interest has exited.");
            parser.DefineOptionalQualifier("FocusProcess", ref FocusProcess, "Either a decimal process ID or a process name (exe name without path but WITH extension) to focus ETW commands." +
                                           "All NON-KERNEL providers are only send to this process (and rundown is only done on this process) which can cut overhead significantly in some cases.");

            parser.DefineOptionalQualifier("NoNGenPdbs", ref NoNGenPdbs, "Don't generate NGEN Pdbs");
            parser.DefineOptionalQualifier("NoNGenRundown", ref NoNGenRundown,
                                           "Don't do rundown of symbolic information in NGEN images (only needed pre V4.5).");
            parser.DefineOptionalQualifier("NoClrRundown", ref NoClrRundown,
                                           "Don't do rundown .NET (CLR) rundown information )(for symbolic name lookup).");
            parser.DefineOptionalQualifier("RundownTimeout", ref RundownTimeout,
                                           "Maximum number of seconds to wait for CLR rundown to complete.");
            parser.DefineOptionalQualifier("MinRundownTime", ref MinRundownTime,
                                           "Minimum number of seconds to wait for CLR rundown to complete.");
            parser.DefineOptionalQualifier("KeepAllEvents", ref KeepAllEvents,
                                           "A debug option to keep all events, even symbolic rundown events.");
            parser.DefineOptionalQualifier("MaxEventCount", ref MaxEventCount, "Limits the total number of events.  " +
                                           "Useful for trimming large ETL files. 1M typically yields 300-400 Meg of data considered.");
            parser.DefineOptionalQualifier("SkipMSec", ref SkipMSec, "Skips the first N MSec of the trace.  " +
                                           "Useful for trimming large ETL files in conjunction with the /MaxEventCount qualifier.");
            parser.DefineOptionalQualifier("StartTime", ref StartTime, "The start date and time used to filter events of the input trace for formats that support this.");
            parser.DefineOptionalQualifier("EndTime", ref EndTime, "The end date and time used to filter events of the input trace for formats that support this.");
            parser.DefineOptionalQualifier("ContinueOnError", ref ContinueOnError, "Processes bad traces as best it can.");

            parser.DefineOptionalQualifier("CpuCounters", ref CpuCounters,
                                           "A comma separated list of hardware CPU counters specifications NAME:COUNT to turn on.  " +
                                           "See Users guide for details.  See ListCpuCounters for available sources (Win8 only)");

            parser.DefineOptionalQualifier("Providers", ref Providers,
                                           "Additional providers.  This is comma separated list of ProviderGuid:Keywords:Level:Stack specs.  " +
                                           "This qualifier has the same syntax as the Additional Providers TextBox in the collection window.  " +
                                           " See help on that for more.");

            string[] onlyProviders = null;
            parser.DefineOptionalQualifier("OnlyProviders", ref onlyProviders,
                                           "Like the Providers qualifier, but also turns off the default Kernel and CLR providers.");
            if (onlyProviders != null)
            {
                // Allow stack traces to work if 'stacks' was specified.
                bool hasStacks = false;
                bool hasTpl    = false;
                foreach (var provider in onlyProviders)
                {
                    if (0 <= provider.IndexOf("@StacksEnabled=true", StringComparison.OrdinalIgnoreCase))
                    {
                        hasStacks = true;
                    }

                    if (0 <= provider.IndexOf("@EventIDStacksToEnable", StringComparison.OrdinalIgnoreCase))
                    {
                        hasStacks = true;
                    }

                    if (provider.StartsWith(".NETTasks", StringComparison.OrdinalIgnoreCase))
                    {
                        hasTpl = true;
                    }
                }

                if (hasStacks)
                {
                    KernelEvents = KernelTraceEventParser.Keywords.Process | KernelTraceEventParser.Keywords.Thread | KernelTraceEventParser.Keywords.ImageLoad;
                    ClrEvents    = ClrTraceEventParser.Keywords.Jit | ClrTraceEventParser.Keywords.Loader;
                }
                else
                {
                    KernelEvents  = KernelTraceEventParser.Keywords.None;
                    ClrEvents     = ClrTraceEventParser.Keywords.None;
                    NoNGenRundown = true;   // We still do normal rundown because EventSource rundown is done there.
                    NoClrRundown  = true;
                }

                if (!hasTpl)
                {
                    // Turn on causality tracking.
                    TplEvents = TplEtwProviderTraceEventParser.Keywords.TasksFlowActivityIds;
                }

                Providers = onlyProviders;
            }
            parser.DefineOptionalQualifier("ThreadTime", ref ThreadTime, "Shortcut for turning on context switch and readyThread events");
            if (ThreadTime)
            {
                KernelEvents = KernelTraceEventParser.Keywords.ThreadTime;
            }

            parser.DefineOptionalQualifier("GCOnly", ref GCOnly, "Turns on JUST GC collections an allocation sampling.");
            if (GCOnly)
            {
                // TODO this logic is cloned.  We need it in only one place.  If you update it do the other location as well
                // For stack parsing.
                KernelEvents = KernelTraceEventParser.Keywords.Process | KernelTraceEventParser.Keywords.Thread | KernelTraceEventParser.Keywords.ImageLoad | KernelTraceEventParser.Keywords.VirtualAlloc;
                ClrEvents    = ClrTraceEventParser.Keywords.GC | ClrTraceEventParser.Keywords.GCHeapSurvivalAndMovement | ClrTraceEventParser.Keywords.Stack |
                               ClrTraceEventParser.Keywords.Jit | ClrTraceEventParser.Keywords.StopEnumeration | ClrTraceEventParser.Keywords.SupressNGen |
                               ClrTraceEventParser.Keywords.Loader | ClrTraceEventParser.Keywords.Exception | ClrTraceEventParser.Keywords.Type | ClrTraceEventParser.Keywords.GCHeapAndTypeNames;
                TplEvents = TplEtwProviderTraceEventParser.Keywords.None;

                // This is not quite correct if you have providers of your own, but this covers the most important case.
                if (Providers == null)
                {
                    Providers = new string[] { "Microsoft-Windows-Kernel-Memory:0x60" };
                }

                CommandProcessor.s_UserModeSessionName = "PerfViewGCSession";
                DataFile = "PerfViewGCOnly.etl";
            }
            parser.DefineOptionalQualifier("GCCollectOnly", ref GCCollectOnly, "Turns on GC collections (no allocation sampling).");
            parser.DefineOptionalQualifier("GCTriggeredStacks", ref GCTriggeredStacks, "Collects a stack for each triggered GC.");
            if (GCCollectOnly)
            {
                ConfigureForGCCollectOnly(this);
                CommandProcessor.s_UserModeSessionName = "PerfViewGCSession";
                DataFile = "PerfViewGCCollectOnly.etl";
            }

            // WPR option implies a bunch of kernel events.
            if (Wpr)
            {
                KernelEvents = KernelTraceEventParser.Keywords.ThreadTime |
                               KernelTraceEventParser.Keywords.DeferedProcedureCalls |
                               KernelTraceEventParser.Keywords.Driver |
                               KernelTraceEventParser.Keywords.Interrupt;
            }

            parser.DefineOptionalQualifier("DumpHeap", ref DumpHeap, "Capture a heap snapshot on profile stop");
            parser.DefineOptionalQualifier("ClrEventLevel", ref ClrEventLevel, "The verbosity for CLR events");
            parser.DefineOptionalQualifier("ClrEvents", ref ClrEvents,
                                           "A comma separated list of .NET CLR events to turn on.  See Users guide for details.");
            parser.DefineOptionalQualifier("KernelEvents", ref KernelEvents,
                                           "A comma separated list of windows OS kernel events to turn on.  See Users guide for details.");
            parser.DefineOptionalQualifier("TplEvents", ref TplEvents,
                                           "A comma separated list of Task Parallel Library (TPL) events to turn on.  See Users guide for details.");

            parser.DefineOptionalQualifier("DotNetAlloc", ref DotNetAlloc, "Turns on per-allocation .NET profiling.");
            parser.DefineOptionalQualifier("DotNetAllocSampled", ref DotNetAllocSampled, "Turns on per-allocation .NET profiling, sampling types in a smart way to keep overhead low.");
            parser.DefineOptionalQualifier("DotNetCalls", ref DotNetCalls, "Turns on per-call .NET profiling.");
            parser.DefineOptionalQualifier("DotNetCallsSampled", ref DotNetCallsSampled, "Turns on per-call .NET profiling, sampling types in a smart way to keep overhead low.");
            parser.DefineOptionalQualifier("DisableInlining", ref DisableInlining, "Turns off inlining (but only affects processes that start after trace start.");
            parser.DefineOptionalQualifier("JITInlining", ref JITInlining, "Turns on logging of successful and failed JIT inlining attempts.");
            parser.DefineOptionalQualifier("CCWRefCount", ref CCWRefCount, "Turns on logging of information about .NET Native CCW reference counting.");
            parser.DefineOptionalQualifier("RuntimeLoading", ref RuntimeLoading, "Turn on logging of runtime loading operations.");
            parser.DefineOptionalQualifier("OSHeapProcess", ref OSHeapProcess, "Turn on per-allocation profiling of allocation from the OS heap for the process with the given process ID.");
            parser.DefineOptionalQualifier("OSHeapExe", ref OSHeapExe, "Turn on per-allocation profiling of allocation from the OS heap for the process with the given EXE (only filename WITH extension).");

            parser.DefineOptionalQualifier("NetworkCapture", ref NetworkCapture, "Captures the full data of every network packet entering or leaving the OS.");
            parser.DefineOptionalQualifier("NetMonCapture", ref NetMonCapture, "Create _netmon.etl file that NetMon.exe can read, along with the standard ETL file.   Implies /NetworkCapture.");

            parser.DefineOptionalQualifier("ForceNgenRundown", ref ForceNgenRundown,
                                           "By default on a V4.0 runtime NGEN rundown is suppressed, because NGEN PDB are a less expensive way of getting symbolic " +
                                           "information for NGEN images.  This option forces NGEN rundown, so NGEN PDBs are not needed.  This can be useful " +
                                           "in some scenarios where NGEN PDB are not working properly.");
            parser.DefineOptionalQualifier("NoV2Rundown", ref NoV2Rundown,
                                           "Don't do rundown for .NET (CLR) V2 processes.");
            parser.DefineOptionalQualifier("TrustPdbs", ref TrustPdbs, "Normally PerfView does not trust PDBs outside the _NT_SYMBOL_PATH and pops a dialog box.  Suppress this.");
            parser.DefineOptionalQualifier("AcceptEULA", ref AcceptEULA, "Accepts the EULA associated with PerfView.");
            parser.DefineOptionalQualifier("DataFile", ref DataFile,
                                           "FileName of the profile data to generate.");
            parser.DefineOptionalQualifier("NoView", ref NoView,
                                           "Normally after collecting data the data is viewed.  This suppresses that.");
            parser.DefineOptionalQualifier("UnsafePDBMatch", ref UnsafePDBMatch,
                                           "Allow the use of PDBs even when the trace does not contain PDB signatures.");
            parser.DefineOptionalQualifier("ShowUnknownAddresses", ref ShowUnknownAddresses,
                                           "Displays the hexadecimal address rather than ? when the address is unknown.");
            parser.DefineOptionalQualifier("ShowOptimizationTiers", ref ShowOptimizationTiers,
                                           "Displays the optimization tier of each code version executed for the method.");
            parser.DefineOptionalQualifier("NoGui", ref NoGui,
                                           "Use the Command line version of the command (like on ARM).  Brings up a console window.  For batch scripts/automation use /LogFile instead (see users guide under 'Scripting' for more).");
            parser.DefineOptionalQualifier("SafeMode", ref SafeMode, "Turn off parallelism and other risky features.");
            parser.DefineOptionalQualifier("RestartingToElevelate", ref RestartingToElevelate, "Internal: indicates that perfView is restarting to get Admin privileges.");

            string sessionName = null;

            parser.DefineOptionalQualifier("SessionName", ref sessionName, "Define the name for the user mode session (kernel session will also be named analogously) Useful for collecting traces when another ETW profiler (including PerfView) is being used.");
            if (sessionName != null)
            {
                if (Environment.OSVersion.Version.Major * 10 + Environment.OSVersion.Version.Minor < 62)
                {
                    throw new ApplicationException("SessionName qualifier only works on Windows 8 and above.");
                }
                CommandProcessor.s_UserModeSessionName = sessionName;
                CommandProcessor.s_KernelessionName    = sessionName + "Kernel";
            }

            parser.DefineOptionalQualifier("MaxNodeCountK", ref MaxNodeCountK,
                                           "The maximum number of objects (in K or thousands) that will even be examined when dumping the heap.  Avoids memory use at collection time.  " +
                                           "This is useful if heap dumping causes out of memory exceptions.");

            parser.DefineOptionalQualifier("EnableEventsInContainers", ref EnableEventsInContainers,
                                           "Enable user mode events inside of containers to flow back to the host for collection.");
            parser.DefineOptionalQualifier("EnableSourceContainerTracking", ref EnableSourceContainerTracking,
                                           "Emit the container ID as part of the payload of each usermode event emitted inside of a container.");

            /* end of qualifier that apply to more than one parameter set (command) */
            /****************************************************************************************/
            /* Parameter set (command) definitions */
            parser.DefineParameterSet("run", ref DoCommand, App.CommandProcessor.Run,
                                      "Starts data collection, runs a command and stops.");
            parser.DefineParameter("CommandAndArgs", ref CommandAndArgs,
                                   "Command to run and arguments (PerfView options must come before run command).");

            parser.DefineParameterSet("collect", ref DoCommand, App.CommandProcessor.Collect,
                                      "Starts data collection, wait for user input, then stops.");
            parser.DefineOptionalParameter("DataFile", ref DataFile,
                                           "ETL file containing profile data.");

            parser.DefineParameterSet("start", ref DoCommand, App.CommandProcessor.Start,
                                      "Starts machine wide profile data collection.");
            parser.DefineOptionalParameter("DataFile", ref DataFile, "ETL file containing profile data.");

            parser.DefineParameterSet("stop", ref DoCommand, App.CommandProcessor.Stop,
                                      "Stop collecting profile data (machine wide).  If you specified EventSources with the /Providers qualifier on start you should repeat them here to ensure manifest rundown.");

            parser.DefineParameterSet("mark", ref DoCommand, App.CommandProcessor.Mark,
                                      "Add a PerfView 'Mark' event to the event stream with a optional string message");
            parser.DefineOptionalParameter("Message", ref Message, "The string message to attach to the PerfView Mark event.");

            parser.DefineParameterSet("abort", ref DoCommand, App.CommandProcessor.Abort,
                                      "Ensures that any active PerfView sessions are stopped.");

            parser.DefineParameterSet("merge", ref DoCommand, App.CommandProcessor.Merge,
                                      "Combine separate ETL files into a single ETL file (that can be decoded on another machine).");
            parser.DefineOptionalParameter("DataFile", ref DataFile, "ETL file containing profile data.");
            parser.DefineOptionalQualifier("ImageIDsOnly", ref ImageIDsOnly,
                                           "Only perform image ID injection during the merge operation.");

            parser.DefineParameterSet("unzip", ref DoCommand, App.CommandProcessor.Unzip,
                                      "Unpack a ZIP file into its ETL file (and possibly its NGEN PDBS) /WPR option can be specified.");
            parser.DefineOptionalParameter("DataFile", ref DataFile, "ETL file containing profile data.");

            parser.DefineParameterSet("listSessions", ref DoCommand, App.CommandProcessor.ListSessions,
                                      "Lists active ETW sessions.");

            parser.DefineParameterSet("ListCpuCounters", ref DoCommand, App.CommandProcessor.ListCpuCounters,
                                      "Lists the ListCpuCounters CPU counters available on the system (win8+ only).");

            parser.DefineParameterSet("EnableKernelStacks", ref DoCommand, App.CommandProcessor.EnableKernelStacks,
                                      "On X64 machines if you have problems with broken stacks when the code is executing in the kernel," +
                                      " setting this option and rebooting may improve things");

            parser.DefineParameterSet("DisableKernelStacks", ref DoCommand, App.CommandProcessor.DisableKernelStacks,
                                      "Resets the registry keys set by EnableKernelStack.");

            string ProcessParam = null;

            parser.DefineParameterSet("HeapSnapshot", ref DoCommand, App.CommandProcessor.HeapSnapshot,
                                      "Take a snapshot of the CLR GC heap of a process.");
            parser.DefineParameter("Process", ref ProcessParam, "The process ID or Process Name (Exe without extension) of the process  take a heap snapshot.");
            parser.DefineOptionalParameter("DataFile", ref DataFile, "The name of the file to place the heap snapshot.");
            parser.DefineOptionalQualifier("SaveETL", ref SaveETL, "Save an ETL file along with the GCDump file when dumping the JS Heap.");
            parser.DefineOptionalQualifier("MaxDumpCountK", ref MaxDumpCountK,
                                           "The maximum number of objects (in K or thousands) to place int the .gcDump file.   Sample sufficiently to hit this metric.");
            parser.DefineOptionalQualifier("Freeze", ref Freeze, "Freeze the dump while data is taken.");

            parser.DefineParameterSet("ForceGC", ref DoCommand, App.CommandProcessor.ForceGC,
                                      "Forces a GC on the specified process");
            parser.DefineParameter("Process", ref ProcessParam, "The process ID or Process Name (Exe without extension) of the process to force a GC.");

            // We have both a qualifier and a parameter named Process. It is OK that they use the same variable, but the parameter should not
            // overwrite the qualifier if it is null.
            if (ProcessParam != null)
            {
                Process = ProcessParam;
            }

            parser.DefineParameterSet("HeapSnapshotFromProcessDump", ref DoCommand, App.CommandProcessor.HeapSnapshotFromProcessDump,
                                      "Extract the CLR GC heap from a process dump file specified.");
            parser.DefineParameter("ProcessDumpFile", ref ProcessDumpFile, "The name of the input process dump file.");
            parser.DefineOptionalParameter("DataFile", ref DataFile, "The name of the file to place the heap snapshot.");
            // TODO FIX NOW parser.DefineOptionalQualifier("DumpData", ref DumpData, "Dump the data as well as the connectivity information.");

            parser.DefineParameterSet("GuiRun", ref DoCommand, App.CommandProcessor.GuiRun, "Opens the 'Run' dialog box.");
            parser.DefineParameterSet("GuiCollect", ref DoCommand, App.CommandProcessor.GuiCollect, "Opens the 'Collect' dialog box.");
            parser.DefineParameterSet("GuiHeapSnapshot", ref DoCommand, App.CommandProcessor.GuiHeapSnapshot,
                                      "Opens the 'TakeHeapSnapshot' dialog box.");

            parser.DefineParameterSet("UserCommand", ref DoCommand, App.CommandProcessor.UserCommand,
                                      "Runs a user defined command.  Type 'PerfView UserCommandHelp' to see the help for all the user commands. " +
                                      "See PerfView Extensions in the users guide for more on creating user commands.");
            parser.DefineParameter("CommandAndArgs", ref CommandAndArgs, "User command to run and any arguments.");

            parser.DefineParameterSet("UserCommandHelp", ref DoCommand, App.CommandProcessor.UserCommandHelp,
                                      "Displays help for user commands.  Also see Help->User Command Help in the GUI.");

            parser.DefineParameterSet("CreateExtensionProject", ref DoCommand, App.CommandProcessor.CreateExtensionProject,
                                      "Creates a VS project for creates a perfView extension.");
            parser.DefineOptionalParameter("ExtensionName", ref ExtensionName, "The name of the extension (no .DLL)");

#if CROSS_GENERATION_LIVENESS
            parser.DefineParameterSet("CollectCrossGenerationLiveness", ref DoCommand, App.CommandProcessor.CollectCrossGenerationLiveness,
                                      "Collect a heap snapshot that can be used to do cross-generation liveness analysis.");
            parser.DefineQualifier("PID", ref CGL_PID, "The process ID of the process to snapshot.");
            parser.DefineQualifier("Generation", ref CGL_Generation, "The generation of the GC to collect.");
            parser.DefineQualifier("PromotedBytesThreshold", ref CGL_PromotedBytesThreshold, "The threshold of promoted bytes after which a snapshot of the heap should be collected.");
            parser.DefineQualifier("OutputFile", ref CGL_PathToOutputFile, "The full path including filename where the resulting gcdump file should be stored.");
#endif

            parser.DefineDefaultParameterSet(ref DoCommand, App.CommandProcessor.View, "View profile data.");
            parser.DefineOptionalParameter("DataFile", ref DataFile, "ETL or ETLX file containing profile data.");
        }
Exemple #46
0
        static int Main(string[] args)
        {
            CommandLineOptions options = new CommandLineOptions();
            CommandLineParser  parser  = new CommandLineParser(options);

            parser.Parse();

            if (parser.HasErrors)
            {
                Console.WriteLine(parser.UsageInfo.ToString(78, true));
#if DEBUG
                Console.ReadKey();
#endif
                return(1);
            }

            if (options.DoHelp)
            {
                Console.WriteLine(parser.UsageInfo.ToString());
#if DEBUG
                Console.ReadKey();
#endif
                return(0);
            }

            if (!options.Silent)
            {
                Console.WriteLine("BrokenEvent.ILStrip.CLI, (C)2017, Broken Event");
            }

            if (!options.Silent)
            {
                Console.WriteLine("Reading: " + options.InputFilename);
            }

            ILStrip ilStrip = new ILStrip(options.InputFilename);

            if (!options.Silent)
            {
                ilStrip.Logger = new CommandLineLogger();
            }

            foreach (string s in options.EntryPoints)
            {
                ilStrip.EntryPoints.Add(s);
            }

            ilStrip.ScanUsedClasses();
            ilStrip.ScanUnusedClasses();

            if (options.CleanUnusedClasses)
            {
                ilStrip.CleanupUnusedClasses();
            }

            if (options.CleanUnusedReferences)
            {
                ilStrip.CleanupUnusedReferences();
            }

            if (options.CleanUnusedResources)
            {
                ilStrip.CleanupUnusedResources();
            }

            if (options.HideApi)
            {
                foreach (string s in options.HideExclusions)
                {
                    ilStrip.MakeInternalExclusions.Add(s);
                }

                ilStrip.MakeNotPublic();
            }

            if (!options.Silent)
            {
                Console.WriteLine("Writing: " + options.OutputFilename);
            }
            ilStrip.Save(options.OutputFilename);

#if DEBUG
            Console.ReadKey();
#endif
            return(0);
        }
        static void Main(string[] argv)
        {
            // Set working directory to exe
            var pathSet = false;
            var path    = Path.GetDirectoryName(Application.ExecutablePath);

            if (path != null)
            {
                Environment.CurrentDirectory = path;
                pathSet = true;
            }

            // Add common folder to path for launched processes
            var pathVar = Environment.GetEnvironmentVariable("PATH");

            pathVar += ";" + Path.Combine(Environment.CurrentDirectory, "common");
            Environment.SetEnvironmentVariable("PATH", pathVar);


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            //Console.OutputEncoding = System.Text.Encoding.Unicode;
            // #0 set this first so data parsing will work correctly
            Globals.JsonSettings = new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore,
                Culture = CultureInfo.InvariantCulture
            };

            // #1 first initialize config
            ConfigManager.InitializeConfig();

            // #2 check if multiple instances are allowed
            var startProgram = true;

            if (ConfigManager.GeneralConfig.AllowMultipleInstances == false)
            {
                try
                {
                    var current = Process.GetCurrentProcess();
                    foreach (var process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            startProgram = false;
                        }
                    }
                }
                catch { }
            }

            if (startProgram)
            {
                if (ConfigManager.GeneralConfig.LogToFile)
                {
                    Logger.ConfigureWithFile();
                }

                if (ConfigManager.GeneralConfig.DebugConsole)
                {
                    PInvokeHelpers.AllocConsole();
                }

                // init active display currency after config load
                ExchangeRateApi.ActiveDisplayCurrency = ConfigManager.GeneralConfig.DisplayCurrency;

                // #2 then parse args
                var commandLineArgs = new CommandLineParser(argv);

                Helpers.ConsolePrint("NICEHASH", "Starting up NiceHashMiner v" + Application.ProductVersion);

                if (!pathSet)
                {
                    Helpers.ConsolePrint("NICEHASH", "Path not set to executable");
                }

                var tosChecked = ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer;
                if (!tosChecked || !ConfigManager.GeneralConfigIsFileExist() && !commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH",
                                         "No config file found. Running NiceHash Miner Legacy for the first time. Choosing a default language.");
                    Application.Run(new Form_ChooseLanguage());
                }

                // Init languages
                International.Initialize(ConfigManager.GeneralConfig.Language);

                if (commandLineArgs.IsLang)
                {
                    Helpers.ConsolePrint("NICEHASH", "Language is overwritten by command line parameter (-lang).");
                    International.Initialize(commandLineArgs.LangValue);
                    ConfigManager.GeneralConfig.Language = commandLineArgs.LangValue;
                }

                // check WMI
                if (Helpers.IsWmiEnabled())
                {
                    if (ConfigManager.GeneralConfig.agreedWithTOS == Globals.CurrentTosVer)
                    {
                        Application.Run(new Form_Main());
                    }
                }
                else
                {
                    MessageBox.Show(International.GetText("Program_WMI_Error_Text"),
                                    International.GetText("Program_WMI_Error_Title"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemple #48
0
        public static async Task <int> Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;

            return(await CommandLineParser.Create(_serviceCollection).InvokeAsync(args));
        }
Exemple #49
0
        public static int Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;

            string inputFile   = null;
            string outputFile  = null;
            string scriptFile  = null;
            bool   showHelp    = false;
            bool   quitOnError = true;

            var p = new OptionSet
            {
                { "i|input-file=", "read configuration from {FILE}", value => inputFile = value },
                { "o|output-file=", "write results to {FILE}", value => outputFile = value },
                { "s|script-file=", "runs commands from {FILE}", value => scriptFile = value },
                { "c|continue", "continues when an error occurs while loading the configuration", value => quitOnError = value == null },
                { "h|help", "show this help message and exit", value => showHelp = value != null }
            };

            try
            {
                p.Parse(args);
            }
            catch (OptionException)
            {
                ShowHelp(p);
                return(-1);
            }

            if (showHelp || string.IsNullOrEmpty(inputFile))
            {
                ShowHelp(p);
                return(-1);
            }

            HCContext  context;
            TextWriter output = null;

            try
            {
                if (!string.IsNullOrEmpty(outputFile))
                {
                    output = new StreamWriter(outputFile);
                }

                Console.Write("Reading configuration file \"{0}\"... ", Path.GetFileName(inputFile));
                Language language = XmlLanguageLoader.Load(inputFile, quitOnError ? (Action <Exception, string>)null : (ex, id) => { });
                Console.WriteLine("done.");

                context = new HCContext(language, output ?? Console.Out);
                Console.Write("Compiling rules... ");
                context.Compile();
                Console.WriteLine("done.");
                Console.WriteLine("{0} loaded.", language.Name);
                Console.WriteLine();
            }
            catch (IOException ioe)
            {
                Console.WriteLine();
                Console.WriteLine("IO Error: " + ioe.Message);
                output?.Close();
                return(-1);
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("Load Error: " + e.Message);
                output?.Close();
                return(-1);
            }

            ConsoleCommand[] commands = { new ParseCommand(context), new TracingCommand(context), new TestCommand(context), new StatsCommand(context) };

            string input;

            if (!string.IsNullOrEmpty(scriptFile))
            {
                using (var scriptReader = new StreamReader(scriptFile))
                {
                    input = scriptReader.ReadLine();
                    while (input != null)
                    {
                        if (!input.Trim().StartsWith("#") && input.Trim() != "")
                        {
                            string[] cmdArgs = CommandLineParser.Parse(input);
                            ConsoleCommandDispatcher.DispatchCommand(commands, cmdArgs, context.Out);
                        }
                        input = scriptReader.ReadLine();
                    }
                }
            }
            else
            {
                Console.Write("> ");
                input = Console.ReadLine();
                while (input != null && input.Trim() != "exit")
                {
                    if (input.Trim().IsOneOf("?", "help"))
                    {
                        ConsoleHelp.ShowSummaryOfCommands(commands, Console.Out);
                    }
                    else
                    {
                        string[] cmdArgs = CommandLineParser.Parse(input);
                        ConsoleCommandDispatcher.DispatchCommand(commands, cmdArgs, context.Out);
                    }
                    Console.Write("> ");
                    input = Console.ReadLine();
                }
            }

            output?.Close();

            return(0);
        }
Exemple #50
0
        static void RunRadegast(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // Increase the number of IOCP threads available. Mono defaults to a tragically low number
            int workerThreads, iocpThreads;

            ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);

            if (workerThreads < 500 || iocpThreads < 1000)
            {
                if (workerThreads < 500)
                {
                    workerThreads = 500;
                }
                if (iocpThreads < 1000)
                {
                    iocpThreads = 1000;
                }
                ThreadPool.SetMaxThreads(workerThreads, iocpThreads);
            }

            // Read command line options
            CommandLine = new CommandLine();
            CommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, CommandLine))
            {
                Environment.Exit(1);
            }

            // Change current working directory to Radegast install dir
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // See if we only wanted to display list of grids
            if (CommandLine.ListGrids)
            {
                Console.WriteLine(CommandLine.GetHeader());
                Console.WriteLine();
                GridManager grids = new GridManager();
                Console.WriteLine("Use Grid ID as the parameter for --grid");
                Console.WriteLine("{0,-25} - {1}", "Grid ID", "Grid Name");
                Console.WriteLine("========================================================");

                for (int i = 0; i < grids.Count; i++)
                {
                    Console.WriteLine("{0,-25} - {1}", grids[i].ID, grids[i].Name);
                }

                Environment.Exit(0);
            }

            // Create main Radegast instance
            RadegastInstance instance = RadegastInstance.GlobalInstance;

            Application.Run(instance.MainForm);
            OpenMetaverse.WorkPool.Shutdown();
        }
Exemple #51
0
        protected override async void OnActivated(IActivatedEventArgs args)
        {
            Logger.Info("App activated");

            // Window management
            if (!(Window.Current.Content is Frame rootFrame))
            {
                rootFrame              = new Frame();
                rootFrame.CacheSize    = 1;
                Window.Current.Content = rootFrame;
            }

            var currentView = SystemNavigationManager.GetForCurrentView();

            switch (args.Kind)
            {
            case ActivationKind.Protocol:
                var eventArgs = args as ProtocolActivatedEventArgs;

                if (eventArgs.Uri.AbsoluteUri == "files-uwp:")
                {
                    rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
                }
                else
                {
                    var trimmedPath = eventArgs.Uri.OriginalString.Split('=')[1];
                    rootFrame.Navigate(typeof(MainPage), @trimmedPath, new SuppressNavigationTransitionInfo());
                }

                // Ensure the current window is active.
                Window.Current.Activate();
                Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;
                Window.Current.CoreWindow.Activated      += CoreWindow_Activated;
                currentView.BackRequested += Window_BackRequested;
                return;

            case ActivationKind.CommandLineLaunch:
                var cmdLineArgs    = args as CommandLineActivatedEventArgs;
                var operation      = cmdLineArgs.Operation;
                var cmdLineString  = operation.Arguments;
                var activationPath = operation.CurrentDirectoryPath;

                var parsedCommands = CommandLineParser.ParseUntrustedCommands(cmdLineString);

                if (parsedCommands != null && parsedCommands.Count > 0)
                {
                    foreach (var command in parsedCommands)
                    {
                        switch (command.Type)
                        {
                        case ParsedCommandType.OpenDirectory:
                            rootFrame.Navigate(typeof(MainPage), command.Payload, new SuppressNavigationTransitionInfo());

                            // Ensure the current window is active.
                            Window.Current.Activate();
                            Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;
                            Window.Current.CoreWindow.Activated      += CoreWindow_Activated;
                            currentView.BackRequested += Window_BackRequested;
                            return;

                        case ParsedCommandType.OpenPath:

                            try
                            {
                                var det = await StorageFolder.GetFolderFromPathAsync(command.Payload);

                                rootFrame.Navigate(typeof(MainPage), command.Payload, new SuppressNavigationTransitionInfo());

                                // Ensure the current window is active.
                                Window.Current.Activate();
                                Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;
                                Window.Current.CoreWindow.Activated      += CoreWindow_Activated;
                                currentView.BackRequested += Window_BackRequested;

                                return;
                            }
                            catch (System.IO.FileNotFoundException ex)
                            {
                                //Not a folder
                                Debug.WriteLine($"File not found exception App.xaml.cs\\OnActivated with message: {ex.Message}");
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine($"Exception in App.xaml.cs\\OnActivated with message: {ex.Message}");
                            }

                            break;

                        case ParsedCommandType.Unknown:
                            rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
                            // Ensure the current window is active.
                            Window.Current.Activate();
                            Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;
                            Window.Current.CoreWindow.Activated      += CoreWindow_Activated;
                            currentView.BackRequested += Window_BackRequested;
                            return;
                        }
                    }
                }
                break;
            }

            rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());

            // Ensure the current window is active.
            Window.Current.Activate();
            Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;
            Window.Current.CoreWindow.Activated      += CoreWindow_Activated;
        }
Exemple #52
0
 public override void CLParse(ref IExtractorOption model, string[] args)
 {
     model = CommandLineParser.Parse(model as DCInsideExtractorOption, args);
 }
Exemple #53
0
        public static async Task <CompilerInvocation> CreateFromJsonAsync(string jsonContents)
        {
            var invocationInfo = JsonConvert.DeserializeObject <CompilerInvocationInfo>(jsonContents);

            Assumes.Present(invocationInfo);

            // We will use a Workspace to simplify the creation of the compilation, but will be careful not to return the Workspace instance from this class.
            // We will still provide the language services which are used by the generator itself, but we don't tie it to a Workspace object so we can
            // run this as an in-proc source generator if one day desired.
            var workspace = new AdhocWorkspace();

            var languageName     = GetLanguageName(invocationInfo);
            var languageServices = workspace.Services.GetLanguageServices(languageName);

            var mapPath = GetPathMapper(invocationInfo);

            var splitCommandLine = CommandLineParser.SplitCommandLineIntoArguments(invocationInfo.Arguments, removeHashComments: false).ToList();

            // Unfortunately for us there are a few paths that get directly read by the command line parse which we need to remap,
            // such as /ruleset files. So let's go through and process them now.
            for (var i = 0; i < splitCommandLine.Count; i++)
            {
                const string RuleSetSwitch = "/ruleset:";

                if (splitCommandLine[i].StartsWith(RuleSetSwitch, StringComparison.Ordinal))
                {
                    var rulesetPath = splitCommandLine[i].Substring(RuleSetSwitch.Length);

                    var quoted = rulesetPath.Length > 2 &&
                                 rulesetPath.StartsWith("\"", StringComparison.Ordinal) &&
                                 rulesetPath.EndsWith("\"", StringComparison.Ordinal);

                    if (quoted)
                    {
                        rulesetPath = rulesetPath.Substring(1, rulesetPath.Length - 2);
                    }

                    rulesetPath = mapPath(rulesetPath);

                    if (quoted)
                    {
                        rulesetPath = "\"" + rulesetPath + "\"";
                    }

                    splitCommandLine[i] = RuleSetSwitch + rulesetPath;
                }
            }

            var commandLineParserService = languageServices.GetRequiredService <ICommandLineParserService>();
            var parsedCommandLine        = commandLineParserService.Parse(splitCommandLine, Path.GetDirectoryName(invocationInfo.ProjectFilePath), isInteractive: false, sdkDirectory: null);

            var analyzerLoader = new DefaultAnalyzerAssemblyLoader();

            var projectId = ProjectId.CreateNewId(invocationInfo.ProjectFilePath);

            var projectInfo = ProjectInfo.Create(
                projectId,
                VersionStamp.Default,
                name: Path.GetFileNameWithoutExtension(invocationInfo.ProjectFilePath),
                assemblyName: parsedCommandLine.CompilationName !,
                language: languageName,
                filePath: invocationInfo.ProjectFilePath,
                outputFilePath: parsedCommandLine.OutputFileName,
                parsedCommandLine.CompilationOptions,
                parsedCommandLine.ParseOptions,
                parsedCommandLine.SourceFiles.Select(s => CreateDocumentInfo(unmappedPath: s.Path)),
                metadataReferences: parsedCommandLine.MetadataReferences.Select(r => MetadataReference.CreateFromFile(mapPath(r.Reference), r.Properties)),
                additionalDocuments: parsedCommandLine.AdditionalFiles.Select(f => CreateDocumentInfo(unmappedPath: f.Path)),
                analyzerReferences: parsedCommandLine.AnalyzerReferences.Select(r => new AnalyzerFileReference(r.FilePath, analyzerLoader)))
                              .WithAnalyzerConfigDocuments(parsedCommandLine.AnalyzerConfigPaths.Select(CreateDocumentInfo));

            workspace.AddProject(projectInfo);

            var compilation = await workspace.CurrentSolution.GetProject(projectId) !.GetRequiredCompilationAsync(CancellationToken.None);

            return(new CompilerInvocation(compilation, languageServices, invocationInfo.ProjectFilePath, workspace.CurrentSolution.Options));

            // Local methods:
            DocumentInfo CreateDocumentInfo(string unmappedPath)
            {
                var mappedPath = mapPath(unmappedPath);

                return(DocumentInfo.Create(
                           DocumentId.CreateNewId(projectId, mappedPath),
                           name: mappedPath,
                           filePath: mappedPath,
                           loader: new FileTextLoader(mappedPath, parsedCommandLine.Encoding)));
            }
        }
Exemple #54
0
 /// <summary>
 /// Processes user-specified parameters for the list command.
 /// </summary>
 /// <param name="args">The application's command line arguments.</param>
 /// <param name="parser">The command line argument parser.</param>
 private void ProcessListParameters(String[] args, CommandLineParser parser)
 {
     ListInput = args.Skip(1).Take(1).Single();
 }
        /// <summary>
        /// The main entry point for the MP 2 client application.
        /// </summary>
        private static void Main(params string[] args)
        {
            Thread.CurrentThread.Name = "Main";

#if !DEBUG
            SplashScreen splashScreen = CreateSplashScreen();
            splashScreen.ShowSplashScreen();
#endif

            // Parse Command Line options
            CommandLineOptions mpArgs = new CommandLineOptions();
            ICommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));
            if (!parser.ParseArguments(args, mpArgs, Console.Out))
            {
                Environment.Exit(1);
            }

#if !DEBUG
            string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Team MediaPortal\MP2-Client\Log");
#endif

            SystemStateService systemStateService = new SystemStateService();
            ServiceRegistration.Set <ISystemStateService>(systemStateService);
            systemStateService.SwitchSystemState(SystemState.Initializing, false);

            try
            {
                ILogger logger = null;
                try
                {
                    // Check if user wants to override the default Application Data location.
                    ApplicationCore.RegisterCoreServices(mpArgs.DataDirectory);

                    logger = ServiceRegistration.Get <ILogger>();

#if !DEBUG
                    IPathManager pathManager = ServiceRegistration.Get <IPathManager>();
                    logPath = pathManager.GetPath("<LOG>");
#endif

                    UiExtension.RegisterUiServices();
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.Critical("Error starting application", e);
                    }
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;

                    UiExtension.DisposeUiServices();
                    ApplicationCore.DisposeCoreServices();

                    throw;
                }

                // Start the core
                logger.Debug("ApplicationLauncher: Starting application");

                try
                {
                    IPluginManager pluginManager = ServiceRegistration.Get <IPluginManager>();
                    pluginManager.Initialize();
                    pluginManager.Startup(false);
                    ApplicationCore.StartCoreServices();

                    ISkinEngine            skinEngine            = ServiceRegistration.Get <ISkinEngine>();
                    IWorkflowManager       workflowManager       = ServiceRegistration.Get <IWorkflowManager>();
                    IMediaAccessor         mediaAccessor         = ServiceRegistration.Get <IMediaAccessor>();
                    ILocalSharesManagement localSharesManagement = ServiceRegistration.Get <ILocalSharesManagement>();

                    // We have to handle some dependencies here in the start order:
                    // 1) After all plugins are loaded, the SkinEngine can initialize (=load all skin resources)
                    // 2) After the skin resources are loaded, the workflow manager can initialize (=load its states and actions)
                    // 3) Before the main window is shown, the splash screen should be hidden
                    // 4) After the workflow states and actions are loaded, the main window can be shown
                    // 5) After the skinengine triggers the first workflow state/startup screen, the default shortcuts can be registered
                    mediaAccessor.Initialize();         // Independent from other services
                    localSharesManagement.Initialize(); // After media accessor was initialized
                    skinEngine.Initialize();            // 1)
                    workflowManager.Initialize();       // 2)

#if !DEBUG
                    splashScreen.CloseSplashScreen(); // 3)
#endif

                    skinEngine.Startup();                                  // 4)
                    UiExtension.Startup();                                 // 5)

                    ApplicationCore.RegisterDefaultMediaItemAspectTypes(); // To be done after UI services are running

                    systemStateService.SwitchSystemState(SystemState.Running, true);

                    Application.Run();

                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true; // Block ServiceRegistration from trying to load new services in shutdown phase

                    // 1) Stop UI extensions (Releases all active players, must be done before shutting down SE)
                    // 2) Shutdown SkinEngine (Closes all screens, uninstalls background manager, stops render thread)
                    // 3) Shutdown WorkflowManager (Disposes all models)
                    // 4) Shutdown PluginManager (Shuts down all plugins)
                    // 5) Remove all services
                    UiExtension.StopUiServices();
                    skinEngine.Shutdown();
                    workflowManager.Shutdown();
                    pluginManager.Shutdown();
                    mediaAccessor.Shutdown();
                    localSharesManagement.Shutdown();
                    ApplicationCore.StopCoreServices();
                }
                catch (Exception e)
                {
                    logger.Critical("Error executing application", e);
                    systemStateService.SwitchSystemState(SystemState.ShuttingDown, true);
                    ServiceRegistration.IsShuttingDown = true;
                }
                finally
                {
                    UiExtension.DisposeUiServices();
                    ApplicationCore.DisposeCoreServices();

                    systemStateService.SwitchSystemState(SystemState.Ending, false);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ConsoleLogger log = new ConsoleLogger(LogLevel.All, false);
                log.Error(ex);
#else
                UiCrashLogger crash = new UiCrashLogger(logPath);
                crash.CreateLog(ex);
#endif
                systemStateService.SwitchSystemState(SystemState.Ending, false);
                Application.Exit();
            }
        }
 public void ShouldParseMoveCommand()
 {
     var parsedCommand = CommandLineParser.Parse("MOVE");
     
     Assert.IsType<MoveCommand>(parsedCommand);
 }
 public void ShouldNotParseNonExistingCommand()
 {
     var parsedCommand = CommandLineParser.Parse("STOP");
     
     Assert.Null(parsedCommand);
 }
Exemple #58
0
        public void ItSetsRemainingArguments_List()
        {
            var result = CommandLineParser.ParseArgs <RemainingArgs_List>("a", "b");

            Assert.Equal(new[] { "a", "b" }, result.RemainingArguments);
        }
 public void ShouldParseRightCommand()
 {
     var parsedCommand = CommandLineParser.Parse("RIGHT");
     
     Assert.IsType<RightCommand>(parsedCommand);
 }
Exemple #60
0
        // asynchronous server

        static void Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }

            using (var context = ZContext.Create())
            {
                using (var socket = new ZSocket(context, ZSocketType.ROUTER))
                {
                    foreach (var bindEndPoint in options.BindEndPoints)
                    {
                        socket.Bind(bindEndPoint);
                    }

                    var opllItem = ZPollItem.CreateReceiver();

                    while (true)
                    {
                        Thread.Sleep(options.Delay);

                        ZMessage message;
                        ZError   error;

                        //
                        if (socket.PollIn(opllItem, out message, out error, new TimeSpan(10 * 1000)))
                        {
                            message.DumpZmsg("--------------------------");

                            var rcvdMsg = message[2].ReadString(Encoding.UTF8);
                            Console.WriteLine("Received: " + rcvdMsg);

                            //be carefull the message format
                            var outMsg = new ZMessage();
                            outMsg.Add(message[0]);
                            outMsg.Add(new ZFrame());

                            var replyMsg   = options.ReplyMessage.Replace("#msg#", rcvdMsg);
                            var replyFrame = new ZFrame(replyMsg);
                            outMsg.Add(replyFrame);

                            Console.WriteLine("Sending : " + replyMsg + Environment.NewLine);

                            socket.Send(outMsg);
                        }


                        //2) sync
                        //using (ZMessage identity = socket.ReceiveMessage())
                        //{
                        //    identity.DumpZmsg("--------------------------");

                        //    var rcvdMsg = identity[2].ReadString(Encoding.UTF8);
                        //    Console.WriteLine("Received: " + rcvdMsg);

                        //    //be carefull the message format
                        //    var outMsg = new ZMessage();
                        //    outMsg.Add(identity[0]);
                        //    outMsg.Add(new ZFrame());

                        //    var replyMsg = options.ReplyMessage.Replace("#msg#", rcvdMsg);
                        //    var replyFrame = new ZFrame(replyMsg);
                        //    outMsg.Add(replyFrame);

                        //    Console.WriteLine("Sending : " + replyMsg + Environment.NewLine);

                        //    socket.Send(outMsg);
                        //}
                    }
                }
            }
        }