本文整理汇总了C#中CommandLineApplication.Command方法的典型用法代码示例。如果您正苦于以下问题:C# CommandLineApplication.Command方法的具体用法?C# CommandLineApplication.Command怎么用?C# CommandLineApplication.Command使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CommandLineApplication
的用法示例。
在下文中一共展示了CommandLineApplication.Command方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static int Main(string[] args)
{
var app = new CommandLineApplication();
app.Name = "dotnet";
app.Description = "The .NET CLI";
// Most commonly used commands
app.Command("init", c =>
{
c.Description = "Scaffold a basic .NET application";
c.OnExecute(() => Exec("dotnet-init", c.RemainingArguments));
});
app.Command("compile", c =>
{
c.Description = "Produce assemblies for the project in given directory";
c.OnExecute(() => Exec("dotnet-compile", c.RemainingArguments));
});
app.Command("restore", c =>
{
c.Description = "Restore packages";
c.OnExecute(() => Exec("dotnet-restore", c.RemainingArguments));
});
app.Command("pack", c =>
{
c.Description = "Produce a NuGet package";
c.OnExecute(() => Exec("dotnet-pack", c.RemainingArguments));
});
app.Command("publish", c =>
{
c.Description = "Produce deployable assets";
c.OnExecute(() => Exec("dotnet-publish", c.RemainingArguments));
});
// TODO: Handle unknown commands
app.OnExecute(() =>
{
app.ShowHelp();
return 2;
});
try
{
return app.Execute(args);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return 1;
}
示例2: Main
public int Main(string[] args)
{
var app = new CommandLineApplication
{
Name = "dnx Azure",
FullName = "Azure Message Queue Utils"
};
app.HelpOption(HELP_TEMPLATE);
app.OnExecute(() => ShowHelp(app));
app.Command("send", send =>
{
send.Description = "Send a message";
send.HelpOption(HELP_TEMPLATE);
var queueName = send.Argument("[queueName]", "The name of the queue");
var message = send.Argument("[message]", "The message to send");
var connectionString = send.Argument("[connectionString]", "The connection string");
send.OnExecute(() =>
{
var factory = MessagingFactory.CreateFromConnectionString(connectionString.Value);
var queue = factory.CreateQueueClient(queueName.Value);
var packet = new BrokeredMessage(message.Value);
queue.Send(packet);
return 0;
});
});
app.Command("receive", receive =>
{
receive.Description = "Receive a message";
receive.HelpOption(HELP_TEMPLATE);
var queueName = receive.Argument("[queueName]", "The name of the queue");
var connectionString = receive.Argument("[connectionString]", "The connection string");
receive.OnExecute(() =>
{
var factory = MessagingFactory.CreateFromConnectionString(connectionString.Value);
var queue = factory.CreateQueueClient(queueName.Value);
var message = queue.Receive();
Console.WriteLine(message.GetBody<string>());
message.Complete(); // must signal to queue that the message has been handled
return 0;
});
});
return app.Execute(args);
}
示例3: Main
public int Main(string[] args)
{
try
{
var app = new CommandLineApplication();
app.Name = "project-stats";
app.FullName = "Project Stats";
app.Description = "Shows stats about a project such as number of files and SLOC";
app.ShortVersionGetter = () => "1.0.0";
app.HelpOption("-h");
app.Command("files", c =>
{
c.Description = "Gets stats about filetypes";
var optionProject = c.Option("-p|--project <PATH>", "Path to the project, default is current directory", CommandOptionType.SingleValue);
c.HelpOption("-h");
c.OnExecute(() =>
{
var projectPath = optionProject.Value() ?? Directory.GetCurrentDirectory();
return new FilesCommand().Execute(projectPath);
});
});
app.Command("sloc", c =>
{
c.Description = "Gets stats about source lines of code";
var optionProject = c.Option("-p|--project <PATH>", "Path to the project, default is current directory", CommandOptionType.SingleValue);
var fileTypeArgs = c.Argument("[filetypes]", "Filetype(s) to include, e.g. .cs .json", multipleValues: true);
c.HelpOption("-h");
c.OnExecute(() =>
{
var projectPath = optionProject.Value() ?? Directory.GetCurrentDirectory();
var typesFilters = fileTypeArgs.Values;
return new SlocCommand().Execute(projectPath, typesFilters);
});
});
return app.Execute(args);
}
catch (Exception)
{
return 0;
}
}
示例4: RegisterAddSubcommand
private static void RegisterAddSubcommand(CommandLineApplication packagesCmd, ReportsFactory reportsFactory)
{
packagesCmd.Command("add", c =>
{
c.Description = "Add a NuGet package to the specified packages folder";
var argNupkg = c.Argument("[nupkg]", "Path to a NuGet package");
var argSource = c.Argument("[source]", "Path to packages folder");
c.HelpOption("-?|-h|--help");
c.OnExecute(async () =>
{
c.ShowRootCommandFullNameAndVersion();
var options = new AddOptions
{
Reports = reportsFactory.CreateReports(quiet: false),
SourcePackages = argSource.Value,
NuGetPackage = argNupkg.Value
};
var command = new Packages.AddCommand(options);
var success = await command.Execute();
return success ? 0 : 1;
});
});
}
示例5: Register
public static void Register(CommandLineApplication cmdApp, Microsoft.Extensions.PlatformAbstractions.IApplicationEnvironment appEnvironment, Microsoft.Extensions.PlatformAbstractions.IAssemblyLoadContextAccessor loadContextAccessor, Microsoft.Extensions.PlatformAbstractions.IRuntimeEnvironment runtimeEnvironment)
{
cmdApp.Command("graph", (Action<CommandLineApplication>)(c => {
c.Description = "Perform parsing, static analysis, semantic analysis, and type inference";
c.HelpOption("-?|-h|--help");
c.OnExecute((Func<System.Threading.Tasks.Task<int>>)(async () => {
var jsonIn = await Console.In.ReadToEndAsync();
var sourceUnit = JsonConvert.DeserializeObject<SourceUnit>(jsonIn);
var root = Directory.GetCurrentDirectory();
var dir = Path.Combine(root, sourceUnit.Dir);
var context = new GraphContext
{
RootPath = root,
SourceUnit = sourceUnit,
ProjectDirectory = dir,
HostEnvironment = appEnvironment,
LoadContextAccessor = loadContextAccessor,
RuntimeEnvironment = runtimeEnvironment
};
var result = await GraphRunner.Graph(context);
Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
return 0;
}));
}));
}
示例6: Register
public static void Register(CommandLineApplication cmdApp, IApplicationEnvironment appEnvironment)
{
cmdApp.Command("scan", c => {
c.Description = "Scan a directory tree and produce a JSON array of source units";
var repoName = c.Option ("--repo <REPOSITORY_URL>", "The URI of the repository that contains the directory tree being scanned", CommandOptionType.SingleValue);
var subdir = c.Option ("--subdir <SUBDIR_PATH>", "The path of the current directory (in which the scanner is run), relative to the root directory of the repository being scanned", CommandOptionType.SingleValue);
c.HelpOption("-?|-h|--help");
c.OnExecute(() => {
var repository = repoName.Value();
var dir = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), subdir.Value()));
//Console.WriteLine($"Repository: {repository}");
//Console.WriteLine($"Directory: {dir}");
var sourceUnits = new List<SourceUnit>();
foreach(var proj in Scan(dir))
{
//Console.WriteLine($"Found project: {proj.Name} ({proj.Version}, {proj.CompilerServices})");
sourceUnits.Add(SourceUnit.FromProject(proj, dir));
}
//Console.Error.Write($"Current dir: {Environment.CurrentDirectory}\n");
Console.WriteLine(JsonConvert.SerializeObject(sourceUnits, Formatting.Indented));
return 0;
});
});
}
示例7: Register
public static void Register(CommandLineApplication cmdApp, IApplicationEnvironment appEnv, IRuntimeEnvironment runtimeEnv)
{
if (runtimeEnv.OperatingSystem == "Windows")
{
_dnuPath = new Lazy<string>(FindDnuWindows);
}
else
{
_dnuPath = new Lazy<string>(FindDnuNix);
}
cmdApp.Command("depresolve", c => {
c.Description = "Perform a combination of parsing, static analysis, semantic analysis, and type inference";
c.HelpOption("-?|-h|--help");
c.OnExecute(async () => {
//System.Diagnostics.Debugger.Launch();
var jsonIn = await Console.In.ReadToEndAsync();
var sourceUnit = JsonConvert.DeserializeObject<SourceUnit>(jsonIn);
var dir = Path.Combine(Directory.GetCurrentDirectory(), sourceUnit.Dir);
var deps = await DepResolve(dir);
var result = new List<Resolution>();
foreach(var dep in deps)
{
result.Add(Resolution.FromLibrary(dep));
}
Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
return 0;
});
});
}
示例8: Register
public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment appEnvironment)
{
cmdApp.Command("list", c =>
{
c.Description = "Print the dependencies of a given project";
var showAssemblies = c.Option("-a|--assemblies",
"Show the assembly files that are depended on by given project",
CommandOptionType.NoValue);
var frameworks = c.Option("--framework <TARGET_FRAMEWORK>",
"Show dependencies for only the given frameworks",
CommandOptionType.MultipleValue);
var runtimeFolder = c.Option("--runtime <PATH>",
"The folder containing all available framework assemblies",
CommandOptionType.SingleValue);
var details = c.Option("--details",
"Show the details of how each dependency is introduced",
CommandOptionType.NoValue);
var mismatched = c.Option("--mismatched",
"Show the mismatch dependencies.",
CommandOptionType.NoValue);
var resultsFilter = c.Option("--filter <PATTERN>",
"Filter the libraries referenced by the project base on their names. The matching pattern supports * and ?",
CommandOptionType.SingleValue);
var argProject = c.Argument("[project]", "Path to project, default is current directory");
c.HelpOption("-?|-h|--help");
c.OnExecute(() =>
{
c.ShowRootCommandFullNameAndVersion();
var options = new DependencyListOptions(reportsFactory.CreateReports(verbose: true, quiet: false), argProject)
{
ShowAssemblies = showAssemblies.HasValue(),
RuntimeFolder = runtimeFolder.Value(),
Details = details.HasValue(),
ResultsFilter = resultsFilter.Value(),
Mismatched = mismatched.HasValue()
};
options.AddFrameworkMonikers(frameworks.Values);
if (!options.Valid)
{
if (options.Project == null)
{
options.Reports.Error.WriteLine(string.Format("Unable to locate {0}.".Red(), Runtime.Project.ProjectFileName));
return 1;
}
else
{
options.Reports.Error.WriteLine("Invalid options.".Red());
return 2;
}
}
var command = new DependencyListCommand(options, appEnvironment.RuntimeFramework);
return command.Execute();
});
});
}
示例9: Main
public int Main(string[] args)
{
try
{
var description = "Creates table and indexes in Microsoft SQL Server database " +
"to be used for distributed caching";
var app = new CommandLineApplication();
app.Name = "sqlservercache";
app.Description = description;
app.HelpOption("-?|-h|--help");
app.Command("create", command =>
{
command.Description = description;
var connectionStringArg = command.Argument(
"[connectionString]",
"The connection string to connect to the database.");
var schemaNameArg = command.Argument("[schemaName]", "Name of the table schema.");
var tableNameArg = command.Argument("[tableName]", "Name of the table to be created.");
command.HelpOption("-?|-h|--help");
command.OnExecute(() =>
{
if (string.IsNullOrEmpty(connectionStringArg.Value)
|| string.IsNullOrEmpty(schemaNameArg.Value)
|| string.IsNullOrEmpty(tableNameArg.Value))
{
_logger.LogWarning("Invalid input");
app.ShowHelp();
return 2;
}
_connectionString = connectionStringArg.Value;
_schemaName = schemaNameArg.Value;
_tableName = tableNameArg.Value;
CreateTableAndIndexes();
return 0;
});
});
// Show help information if no subcommand/option was specified.
app.OnExecute(() =>
{
app.ShowHelp();
return 2;
});
return app.Execute(args);
}
catch (Exception exception)
{
_logger.LogCritical("An error occurred. {Message}", exception.Message);
return 1;
}
}
示例10: Register
public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment applicationEnvironment, IServiceProvider serviceProvider)
{
cmdApp.Command("publish", c =>
{
c.Description = "Publish application for deployment";
var argProject = c.Argument("[project]", "Path to project, default is current directory");
var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})",
CommandOptionType.SingleValue);
var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages",
CommandOptionType.NoValue);
var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include, or \"active\" for current runtime on PATH",
CommandOptionType.MultipleValue);
var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.",
CommandOptionType.NoValue);
var optionIncludeSymbols = c.Option("--include-symbols", "Include symbols in output bundle",
CommandOptionType.NoValue);
var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory",
CommandOptionType.SingleValue);
var optionWwwRootOut = c.Option("--wwwroot-out <NAME>",
"Name of public folder in the output, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified",
CommandOptionType.SingleValue);
var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of published files",
CommandOptionType.NoValue);
c.HelpOption("-?|-h|--help");
c.OnExecute(() =>
{
c.ShowRootCommandFullNameAndVersion();
var options = new PublishOptions
{
OutputDir = optionOut.Value(),
ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
Configuration = optionConfiguration.Value() ?? "Debug",
RuntimeTargetFramework = applicationEnvironment.RuntimeFramework,
WwwRoot = optionWwwRoot.Value(),
WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(),
NoSource = optionNoSource.HasValue(),
Runtimes = optionRuntime.HasValue() ?
string.Join(";", optionRuntime.Values).
Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
new string[0],
Native = optionNative.HasValue(),
IncludeSymbols = optionIncludeSymbols.HasValue(),
Reports = reportsFactory.CreateReports(optionQuiet.HasValue())
};
var manager = new PublishManager(serviceProvider, options);
if (!manager.Publish())
{
return -1;
}
return 0;
});
});
}
示例11: Create
public static CommandLineApplication Create()
{
var app = new CommandLineApplication()
{
Name = "dotnet ef",
FullName = "Entity Framework 6 .NET Core CLI Commands"
};
app.HelpOption();
app.VersionOption(GetVersion);
app.Command("database", c => DatabaseCommand.Configure(c));
app.Command("migrations", c => MigrationsCommand.Configure(c));
app.OnExecute(() => app.ShowHelp());
return app;
}
示例12: Main
public static void Main(string[] args)
{
var app = new CommandLineApplication
{
Name = "Project.Json.Patcher",
Description = "Patch project.json files with new version and release notes",
FullName = "Project.Json Patcher"
};
app.HelpOption("-h|--help");
app.Command("Patch", commandAppConfing =>
{
commandAppConfing.Description = "Patches the project.json file";
CommandOption fileOption = commandAppConfing.Option("-f|--File <FilePath>",
"OPTIONAL. Path to project.json", CommandOptionType.SingleValue);
CommandOption versionOption = commandAppConfing.Option("-v|--Version <Version>",
"Target version of project.json", CommandOptionType.SingleValue);
CommandOption releaseNotesOption = commandAppConfing.Option("-r|--RealeaseNotes <ReleaseNotes>",
"OPTIONAL. Release notes of this version", CommandOptionType.SingleValue);
commandAppConfing.HelpOption("-h|--help");
commandAppConfing.OnExecute(() =>
{
string filePath = GetFilePath(fileOption);
string version = GetVersion(versionOption);
string releaseNotes = releaseNotesOption.Value();
Console.WriteLine($"FilePath: {filePath}, " +
$"Version: {version}, " +
$"ReleaseNotes: {releaseNotes}");
Patch(filePath, version, releaseNotes);
Console.WriteLine("Patching Complete");
return 0;
});
});
app.OnExecute(() =>
{
app.ShowHelp();
return 2;
});
app.Execute(args);
}
示例13: Main
public int Main(params string[] args)
{
ServicePointManager.DefaultConnectionLimit = 1000;
ServicePointManager.MaxServicePoints = 1000;
var proxies = CreateClients().ToList();
if (!proxies.Any())
{
Console.WriteLine("No Bolt servers running ...".Red());
return 1;
}
var app = new CommandLineApplication();
app.Name = "bolt";
app.OnExecute(() =>
{
app.ShowHelp();
return 2;
});
app.Command("test", c =>
{
c.Description = "Tests the Bolt performance.";
var output = c.Option("--output <PATH>", "Directory or configuration file path. If no path is specified then the 'bolt.configuration.json' configuration file will be generated in current directory.", CommandOptionType.SingleValue);
var argRepeats = c.Option("-r <NUMBER>", "Number of repeats for each action.", CommandOptionType.SingleValue);
var argConcurrency = c.Option("-c <NUMBER>", "Concurrency of each action.", CommandOptionType.SingleValue);
c.HelpOption("-?|-h|--help");
int cnt = 100;
int degree = 1;
c.OnExecute(() =>
{
if ( argRepeats.HasValue())
{
cnt = int.Parse(argRepeats.Value());
}
if (argConcurrency.HasValue())
{
degree = int.Parse(argConcurrency.Value());
}
ExecuteActions(proxies, cnt, degree);
Console.WriteLine("Test finished. Press any key to exit program ... ");
System.Console.ReadLine();
return 0;
});
});
return app.Execute(args);
}
示例14: Register
public static void Register(CommandLineApplication app, IAssemblyLoadContext assemblyLoadContext)
{
app.Command("resolve-taghelpers", config =>
{
config.Description = "Resolves TagHelperDescriptors in the specified assembly(s).";
config.HelpOption("-?|-h|--help");
var clientProtocol = config.Option(
"-p|--protocol",
"Provide client protocol version.",
CommandOptionType.SingleValue);
var assemblyNames = config.Argument(
"[name]",
"Assembly name to resolve TagHelperDescriptors in.",
multipleValues: true);
config.OnExecute(() =>
{
var messageBroker = new CommandMessageBroker();
var plugin = new RazorPlugin(messageBroker);
var resolvedProtocol = ResolveProtocolCommand.ResolveProtocol(clientProtocol, plugin.Protocol);
plugin.Protocol = resolvedProtocol;
var success = true;
foreach (var assemblyName in assemblyNames.Values)
{
var messageData = new ResolveTagHelperDescriptorsRequestData
{
AssemblyName = assemblyName,
SourceLocation = SourceLocation.Zero
};
var message = new RazorPluginRequestMessage(
RazorPluginMessageTypes.ResolveTagHelperDescriptors,
JObject.FromObject(messageData));
success &= plugin.ProcessMessage(JObject.FromObject(message), assemblyLoadContext);
}
var resolvedDescriptors = messageBroker.Results.SelectMany(result => result.Data.Descriptors);
var resolvedErrors = messageBroker.Results.SelectMany(result => result.Data.Errors);
var resolvedResult = new ResolvedTagHelperDescriptorsResult
{
Descriptors = resolvedDescriptors,
Errors = resolvedErrors
};
var serializedResult = JsonConvert.SerializeObject(resolvedResult, Formatting.Indented);
Console.WriteLine(serializedResult);
return success ? 0 : 1;
});
});
}
示例15: Execute
public void Execute(string[] args)
{
var app = new CommandLineApplication();
app.Command(ActionDescriptor.Generator.Name, c =>
{
c.HelpOption("--help|-h|-?");
BuildCommandLine(c);
});
app.Execute(args);
}