Now we turn our attention to Program.cs, making the changes needed to use the Niche.CommandLineProcessor) library to actually parse the arguments supplied by a user. One of the goals of the v3.0 release of the library was to make this as simple as possible.

The easiest approach is to let the Niche.CommandLineProcessor do all the heavy lifting on your behalf.

To begin, we have the usual declaration for Main, followed by the creation of our logger. Note that the logger is not a part of the library.

public static int Main(string[] args)
    _logger = new ConsoleLogger();

Next, we create a processor to handle the arguments we’ve been supplied, inside a using clause so that it can tidy itself up when we’re finished with it.

    using (var processor = new CommandLineProcessor(args))

When an error happens during parsing, we want to write those error messages to our logger as failures:

        processor.WithErrorAction(errors => _logger.Failure(errors));

Errors can happen when a mandatory parameter is missing, when a value can’t be converted into the expected type, or when an exception is thrown.

Calling the error action is deferred until the processor is disposed at the end of the using block.

If the user requests help (by using the --help or -h options), we also want those messages to be written to our log.

        processor.WithHelpAction(help => _logger.Detail(help));

Similarly to the way the error action is deferred, calling the help action is deferred until the processor is disposed at the end of the using block.

Both WithErrorAction() and WithHelpAction() allow you to cleanly inject your own handlers with the behavior you want/need for your application. For example, you could emulate msiexec and display a dialog showing your parameter help, instead of logging those help messages to the console.

Lastly, we invoke the processor to parse the available arguments and to execute our application by calling MainImpl().

        return processor.Parse(new RootMode())

The Niche.CommandLineProcessor library takes care of these common cases:

  • If the user requests parameter help (by specifying --help or -h arguments), help will be shown, using the action supplied to WithHelpAction().
  • If anything goes wrong during parsing, the errors will be shown, using the action supplied to WithErrorAction().
  • The method supplied to Execute() will be executed only if there are no errors and help has not been requested.


blog comments powered by Disqus
Next Post
Using Extension Methods  30 Dec 2017
Prior Post
Defining command line parameters  16 Dec 2017
Related Posts
Defining command line parameters  16 Dec 2017
December 2017