当前位置: 首页>>代码示例>>C#>>正文


C# CommandLineParser.ParseCommandLine方法代码示例

本文整理汇总了C#中CommandLineParser.ParseCommandLine方法的典型用法代码示例。如果您正苦于以下问题:C# CommandLineParser.ParseCommandLine方法的具体用法?C# CommandLineParser.ParseCommandLine怎么用?C# CommandLineParser.ParseCommandLine使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在CommandLineParser的用法示例。


在下文中一共展示了CommandLineParser.ParseCommandLine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        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;
            }
        }
开发者ID:MartinClementson,项目名称:3d-projekt,代码行数:25,代码来源:Program.cs

示例2: Main

		/// <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;
		}
开发者ID:demiurghg,项目名称:FusionEngine,代码行数:36,代码来源:FBuild.cs

示例3: Main

        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;
        }
开发者ID:fengweijp,项目名称:Win2D,代码行数:27,代码来源:Program.cs

示例4: Main

        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;
        }
开发者ID:fengweijp,项目名称:Win2D,代码行数:26,代码来源:Program.cs

示例5: ParseCommandLine_ThrowsCommandLineExpectionWhenUnknownCommand

 public void ParseCommandLine_ThrowsCommandLineExpectionWhenUnknownCommand()
 {
     // Arrange 
     var cmdMgr = new Mock<ICommandManager>();
     cmdMgr.Setup(cm => cm.GetCommand(It.IsAny<string>())).Returns<ICommand>(null);
     CommandLineParser parser = new CommandLineParser(cmdMgr.Object);
     List<string> input = new List<string>() { "SomeUnknownCommand", "SomeArgs" };
     string expectedExceptionMessage = "Unknown command: 'SomeUnknownCommand'";
     // Act & Assert
     ExceptionAssert.Throws<CommandLineException>(() => parser.ParseCommandLine(input), expectedExceptionMessage);
 }
开发者ID:monoman,项目名称:NugetCracker,代码行数:11,代码来源:CommandLinePaserTests.cs

示例6: CanParseSwitches

        public void CanParseSwitches()
        {
            CommandLineParser clp = new CommandLineParser(new string[] { "/" }, new string[] { ":" });
            clp.Add<bool>("activate");
            clp.Add<bool>("option");

            string[] unParsed;
            Dictionary<string, object> results = clp.ParseCommandLine(new string[] { "/activate:false", "/skipThisParam", "/option" }, out unParsed);

            Assert.IsTrue(results.Count == 2, @"There should only be 2 options parsed");
            Assert.IsTrue(results.Any(kvp => kvp.Key == "activate"), @"The ""activate"" key should exist in the result");
            Assert.IsTrue(results.Any(kvp => kvp.Key == "option"), @"The ""option"" key should exist in the result");
            Assert.IsFalse((bool)results.Single(kvp => kvp.Key == "activate").Value, @"The ""activate"" object should be false");
            Assert.IsTrue((bool)results.Single(kvp => kvp.Key == "option").Value, @"The ""option"" object should be true");
            Assert.IsTrue(unParsed.Single() == "/skipThisParam", @"There should be one unparsed option in the command line: /skipThisParam");
        }
开发者ID:CodeAwhile,项目名称:CommandLineParser,代码行数:16,代码来源:CommandLineParserBasicTests.cs

示例7: Main

 static int Main(string[] args)
 {
     Encoding encoding = new ASCIIEncoding();
     var options = new CommandLineOptions();
     var parser = new CommandLineParser(options);
     if (!parser.ParseCommandLine(args))
     {
         Console.ReadLine();
         return -1;
     }
     var encrypter = HashingFactory.GetInstance(options.HashingAlgorithm);
     if (encrypter is KeyedHashAlgorithm)
     {
         ((KeyedHashAlgorithm)encrypter).Key = encoding.GetBytes(options.Key ?? "");
     }
     var bytes = encrypter.ComputeHash(encoding.GetBytes(options.Message));
     var converted = Convert.ToBase64String(bytes);
     Console.WriteLine(converted);
     Console.ReadLine();
     return 0;
 }
开发者ID:bruinbrown,项目名称:HashCalculator,代码行数:21,代码来源:Program.cs

示例8: BuildAsset

		/// <summary>
		/// 
		/// </summary>
		/// <param name="processor"></param>
		/// <param name="fileName"></param>
		void BuildAsset ( AssetProcessor processor, string[] args, AssetSource assetFile, ref BuildResult buildResult )
		{					
			try {
				
				//	Is up-to-date?
				if (!context.Options.ForceRebuild) {
					if (!Wildcard.Match(assetFile.KeyPath, context.Options.CleanPattern, true)) {
						if (assetFile.IsUpToDate) {
							buildResult.UpToDate ++;
							return;
						}
					}
				}


				var keyPath = assetFile.KeyPath;

				if (keyPath.Length > 40) {
					keyPath = "..." + keyPath.Substring( keyPath.Length - 40 + 3 );
				}

				Log.Message("{0,-40} {1,-5}   {3}", keyPath, Path.GetExtension(keyPath), string.Join(" ", args), assetFile.Hash );

				// Apply attribute :
				var parser =	new CommandLineParser( processor );
				parser.Configuration.OptionLeadingChar = '/';
				parser.Configuration.ThrowExceptionOnShowError = true;

				parser.ParseCommandLine( args );

				//
				//	Build :
				//
				processor.Process( assetFile, context );

				buildResult.Succeded ++;

			} catch ( Exception e ) {
				Log.Error( "{0} : {1}", assetFile.KeyPath, e.Message );
				buildResult.Failed ++;
			}
		}
开发者ID:demiurghg,项目名称:FusionEngine,代码行数:47,代码来源:Builder.cs

示例9: Push

        /// <summary>
        /// Executes given string.
        /// </summary>
        /// <param name="command"></param>
        public void Push( string commandLine, bool echoCommand )
        {
            if (echoCommand) {
                Log.Message(commandLine);
            }

            var argList	=	CommandLineParser.SplitCommandLine( commandLine ).ToArray();

            if (!argList.Any()) {
                Log.Warning("Empty command line.");
                return;
            }

            var cmdName	=	argList[0];
            argList		=	argList.Skip(1).ToArray();

            lock (lockObject) {
                var command	=	GetCommand( cmdName );

                var parser	=	new CommandLineParser( command, true, cmdName );

                parser.ParseCommandLine( argList );

                Push( command );
            }
        }
开发者ID:temik911,项目名称:audio,代码行数:30,代码来源:Invoker.cs

示例10: Push

        /// <summary>
        /// Parses and pushes command to the queue.
        /// </summary>
        /// <param name="commandLine"></param>
        /// <returns></returns>
        public Command Push( string commandLine )
        {
            var argList	=	CommandLineParser.SplitCommandLine( commandLine ).ToArray();

            if (!argList.Any()) {
                throw new CommandLineParserException("Empty command line.");
            }

            var cmdName	=	argList[0];
            argList		=	argList.Skip(1).ToArray();

            lock (lockObject) {
                var command	=	GetCommand( cmdName );

                var parser	=	new CommandLineParser( command, true, cmdName );

                parser.ParseCommandLine( argList );

                Push( command );

                return command;
            }
        }
开发者ID:Annaero,项目名称:FusionFramework,代码行数:28,代码来源:Invoker.cs

示例11: Main

		static int Main ( string[] args )
		{
			Thread.CurrentThread.CurrentCulture	=	System.Globalization.CultureInfo.InvariantCulture;
			Log.AddListener( new StdLogListener() );

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

			try {

				//	parse arguments :
				if (!parser.ParseCommandLine( args )) {
					return 1;
				}

				//	change extension of output not set :
				if (options.Output==null) {
					options.Output = Path.ChangeExtension( options.Input, ".scene");
				}
				

				//
				//	run fbx loader :
				//
				Log.Message("Reading FBX: {0}", options.Input);

				var loader = new FbxLoader();
				using ( var scene  = loader.LoadScene( options.Input, options ) ) {
				
					//
					//	Save scene :
					//					
					Log.Message("Preparation...");
					foreach ( var mesh in scene.Meshes ) {
						if (mesh!=null) {
							mesh.MergeVertices( options.MergeTolerance );
							mesh.DefragmentSubsets(scene, true);
							mesh.ComputeTangentFrame();
							mesh.ComputeBoundingBox();
						}
					}

					Log.Message("Merging instances...");
					scene.DetectAndMergeInstances();
					
					if (options.BaseDirectory!=null) {

						Log.Message("Resolving assets path...");
						
						var relativePath = ContentUtils.MakeRelativePath( options.BaseDirectory + @"\", options.Input );
						var relativeDir  = Path.GetDirectoryName( relativePath );
						var sceneDir	 = Path.GetDirectoryName( options.Input );
						Log.Message("...scene directory      : {0}", sceneDir);
						Log.Message("...scene base directory : {0}", options.BaseDirectory);
						Log.Message("...scene relative path  : {0}", relativePath);
						Log.Message("...scene relative dir   : {0}", relativeDir);

						foreach ( var mtrl in scene.Materials ) {
							ResolveMaterial( mtrl, relativeDir, sceneDir );
						}
					}

					//
					//	Save scene :
					//					
					Log.Message("Writing binary file: {0}", options.Output);
					using ( var stream = File.OpenWrite( options.Output ) ) {
						scene.Save( stream );
					}


					if (options.Report) {
						var reportPath = options.Input + ".html";
						Log.Message("Writing report: {0}", reportPath);
						File.WriteAllText( reportPath, SceneReport.CreateHtmlReport(scene));
					}
				}

				Log.Message("Done.");

			} catch ( Exception e ) {
				parser.ShowError( "{0}", e.ToString() );

				if (options.Wait) {
					Log.Message("Press any key to continue...");
					Console.ReadKey();
				}

				return 1;
			}

			if (options.Wait) {
				Log.Message("Press any key to continue...");
				Console.ReadKey();
			}

			return 0;
		}
开发者ID:demiurghg,项目名称:FusionEngine,代码行数:98,代码来源:FScene.cs

示例12: Parse

        /// <summary>
        /// Parses the command line.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        /// <returns>
        /// Command line parameters.
        /// </returns>
        public static CommandLine Parse(string[] args)
        {
            var parser = new CommandLineParser();
            parser.IgnoreCase = true;

            var commandLine = new CommandLine();
            parser.ExtractArgumentAttributes(commandLine);
            parser.ParseCommandLine(args);

            return commandLine;
        }
开发者ID:tparvi,项目名称:tomato,代码行数:20,代码来源:CommandLine.cs

示例13: Main

        static int Main(string[] args)
        {
#if WINDOWS
            // Set the correct directory for our dependency files.
            var is32Bit = IntPtr.Size == 4;
            var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                string.Format("Dependencies{0}{1}", Path.DirectorySeparatorChar, is32Bit ? "x32" : "x64"));
            SetDllDirectory(directory);
#endif

            var content = new BuildContent();

            // Parse the command line.
            var parser = new CommandLineParser(content)
            {
                Title = "MonoGame Content Builder\n" +
                        "Builds optimized game content for MonoGame projects."
            };
            if (!parser.ParseCommandLine(args))
                return -1;

            // Process all resoponse files.
            foreach (var r in content.ResponseFiles)
            {
                // Read in all the lines, trim whitespace, and remove empty or comment lines.
                var commands = File.ReadAllLines(r).
                                Select(x => x.Trim()).
                                Where(x => !string.IsNullOrEmpty(x) && !x.StartsWith("#")).
                                ToArray();

                // Parse the commands like they came from the command line.
                if (!parser.ParseCommandLine(commands))
                    return -1;
            }
            
            // Do we have anything to do?
            if (!content.HasWork)
            {
                parser.ShowUsage();
                return 0;
            }

            // Print a startup message.            
            var buildStarted = DateTime.Now;
            if (!content.Quiet)
                Console.WriteLine("Build started {0}\n", buildStarted);

            // Let the content build.
            int successCount, errorCount;
            content.Build(out successCount, out errorCount);

            // Print the finishing info.
            if (!content.Quiet)
            {
                Console.WriteLine("\nBuild {0} succeeded, {1} failed.\n", successCount, errorCount);
                Console.WriteLine("Time elapsed {0:hh\\:mm\\:ss\\.ff}.", DateTime.Now - buildStarted);
            }

            // Return the error count.
            return errorCount;
        }
开发者ID:Boerlam001,项目名称:MonoGame,代码行数:61,代码来源:Program.cs

示例14: Push

		/// <summary>
		/// Parses and pushes command to the queue.
		/// </summary>
		/// <param name="commandLine"></param>
		/// <returns></returns>
		public Command Push ( string commandLine )
		{				  
			var argList	=	CommandLineParser.SplitCommandLine( commandLine ).ToArray();

			if (!argList.Any()) {
				throw new CommandLineParserException("Empty command line.");
			} 



			var cmdName	=	argList[0];
			argList		=	argList.Skip(1).ToArray();
			

			lock (lockObject) {

				ConfigVariable variable;

				if (Variables.TryGetValue( cmdName, out variable )) {
					if (argList.Count()==0) {
						Log.Message("{0} = {1}", variable.FullName, variable.Get() );
						return null;
					} else {
						return Push( string.Format("set {0} \"{1}\"", cmdName, string.Join(" ", argList) ) );
					}
				}
				var command	=	GetCommand( cmdName );

				var parser	=	new CommandLineParser( command, cmdName );

				if (!parser.ParseCommandLine( argList )) {
					throw new CommandLineParserException("Failed to parse command line");
				}

				Push( command );

				return command;
			}
		}
开发者ID:demiurghg,项目名称:FusionEngine,代码行数:44,代码来源:Invoker.cs

示例15: MainCore

        public static int MainCore(string workingDirectory, string[] args)
        {
            // This is to avoid applying weak event pattern usage, which breaks under Mono or restricted environments, e.g. Windows Azure Web Sites.
            EnvironmentUtility.SetRunningFromCommandLine();

            // set output encoding to UTF8 if -utf8 is specified
            var oldOutputEncoding = System.Console.OutputEncoding;
            if (args.Any(arg => String.Equals(arg, "-utf8", StringComparison.OrdinalIgnoreCase)))
            {
                args = args.Where(arg => !String.Equals(arg, "-utf8", StringComparison.OrdinalIgnoreCase)).ToArray();
                SetConsoleOutputEncoding(System.Text.Encoding.UTF8);
            }

            // Increase the maximum number of connections per server.
            if (!EnvironmentUtility.IsMonoRuntime)
            {
                ServicePointManager.DefaultConnectionLimit = 64;
            }
            else
            {
                // Keep mono limited to a single download to avoid issues.
                ServicePointManager.DefaultConnectionLimit = 1;
            }

            NetworkProtocolUtility.ConfigureSupportedSslProtocols();

            var console = new Common.Console();
            var fileSystem = new PhysicalFileSystem(workingDirectory);

            Func<Exception, string> getErrorMessage = ExceptionUtilities.DisplayMessage;

            try
            {
                // Remove NuGet.exe.old
                RemoveOldFile(fileSystem);

                // Import Dependencies
                var p = new Program();
                p.Initialize(fileSystem, console);

                // Add commands to the manager
                foreach (ICommand cmd in p.Commands)
                {
                    p.Manager.RegisterCommand(cmd);
                }

                CommandLineParser parser = new CommandLineParser(p.Manager);

                // Parse the command
                ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;
                command.CurrentDirectory = workingDirectory;

                // Fallback on the help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    // Get the command name and add it to the argument list of the help command
                    string commandName = command.CommandAttribute.CommandName;

                    // Print invalid command then show help
                    console.WriteLine(LocalizedResourceManager.GetString("InvalidArguments"), commandName);

                    p.HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    SetConsoleInteractivity(console, command as Command);

                    // When we're detailed, get the whole exception including the stack
                    // This is useful for debugging errors.
                    if (console.Verbosity == Verbosity.Detailed)
                    {
                        getErrorMessage = e => e.ToString();
                    }

                    command.Execute();
                }
            }
            catch (AggregateException exception)
            {
                Exception unwrappedEx = ExceptionUtility.Unwrap(exception);
                if (unwrappedEx is ExitCodeException)
                {
                    // Return the exit code without writing out the exception type
                    var exitCodeEx = unwrappedEx as ExitCodeException;
                    return exitCodeEx.ExitCode;
                }

                console.WriteError(getErrorMessage(exception));
                return 1;
            }
            catch (Exception exception)
            {
                console.WriteError(getErrorMessage(exception));
                return 1;
            }
            finally
            {
                OptimizedZipPackage.PurgeCache();
                SetConsoleOutputEncoding(oldOutputEncoding);
            }
//.........这里部分代码省略.........
开发者ID:danni95,项目名称:Core,代码行数:101,代码来源:Program.cs


注:本文中的CommandLineParser.ParseCommandLine方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。