Experience. NET Core command line application - CommandLineUtils

Preface

In our development, we may need to design one-time applications that can take advantage of the proximity to the original source code, but can be launched in a security context that is completely independent of the main Web application. The specific reasons are listed in [management process] (https://12factor.net/admin-processes).

Create console app

Open the command prompt, create a folder to create ConsoleDemo, and type the following fragment

dotnet new console

dotnet run
dotnet run

Hello World!

Or we can compile the code through dotnet build without running the generated console application. This time, the compiled application is generated as a DLL file based on the name of the project. In this case, the file created is named ConsoleDemo.dll. At this time, we can use dotnet bin\Debug\netcoreapp3.1\ConsoleDemo.dll on Windows to run (non Windows system uses /).

dotnet bin\Debug\netcoreapp3.1\ConsoleDemo.dll

Hello World!

When you compile an application, an operating system specific executable is created along with ConsoleDemo.dll. On Windows, this will be ConsoleDemo.exe; on Linux or Mac OS, this will be ConsoleDemo. In the above example, name the file with ConsoleDemo.exe or ConsoleDemo. You can run the executable directly.

.\bin\Debug\netcoreapp3.1\ConsoleDemo.exe

Hello World!

HelloWord

First, we will introduce the following package into our console application

Install-Package  McMaster.Extensions.CommandLineUtils

Attribute API

using System;
using McMaster.Extensions.CommandLineUtils;

public class Program
{
    public static int Main(string[] args)
        => CommandLineApplication.Execute<Program>(args);

    [Option(Description = "The subject")]
    public string Subject { get; }

    [Option(ShortName = "n")]
    public int Count { get; }

    private void OnExecute()
    {
        var subject = Subject ?? "world";
        for (var i = 0; i < Count; i++)
        {
            Console.WriteLine($"Hello {subject}!");
        }
    }
}

Builder API

using System;
using McMaster.Extensions.CommandLineUtils;

public class Program
{
    public static int Main(string[] args)
    {
        var app = new CommandLineApplication();

        app.HelpOption();
        var optionSubject = app.Option("-s|--subject <SUBJECT>", "The subject", CommandOptionType.SingleValue);
        var optionRepeat = app.Option<int>("-n|--count <N>", "Repeat", CommandOptionType.SingleValue);

        app.OnExecute(() =>
        {
            var subject = optionSubject.HasValue()
                ? optionSubject.Value()
                : "world";

            var count = optionRepeat.HasValue() ? optionRepeat.ParsedValue : 1;
            for (var i = 0; i < count; i++)
            {
                Console.WriteLine($"Hello {subject}!");
            }
            return 0;
        });

        return app.Execute(args);
    }
}

The above code is directly from the official I'm too lazy to write by myself

Let's test it

dotnet run -help
Usage:  [options]

Options:
  -?|-h|--help            Show help information
  -s|--subject <SUBJECT>  The subject
  -n|--count <N>          Repeat

dotnet run -s Fh
Hello Fh!

[Command]
These properties are all provided by CommandLineUtils to generate the actual command line parser. Command stands for command (go to number) with options and parameters. Any decorated class [command] must also implement a method OnExecuteAsync() called OnExecute() or. The return type must be void or int (Task or Task in the case of asynchronous variables) and the parameters will be injected from your dependency injection container (in this case, Microsoft.Extensions.Dependency.Injection).

[HelpOption]
There are many properties with the word "Option". These add command line options that the command will accept. In this case, we want the top-level command to use the default - h or - help Option to help. When this is done, the subcommand also provides help in a similar way.

[Subcommand]
The [Subcommand] property is required to indicate which commands will be subcommands of the current command. Knowing all the subcommands in your code at compile time is mature for convention based optimization. Choosing to organize in the current way allows us to reuse subcommands between commands.

Reference

https://natemcmaster.github.io/CommandLineUtils/v2.5/api/McMaster.Extensions.CommandLineUtils.OptionAttribute.html

https://github.com/hueifeng/BlogSample/tree/master/src/ConsoleDemo

Published 50 original articles, won praise 52, visited 1468
Private letter follow

Tags: Windows github Fragment Linux

Posted on Mon, 13 Jan 2020 07:37:42 -0800 by Gmans