ConsoleApp.CommandLine 1.3.2

Command line application utility package. Provides API for parsing and binding command line arguments to .NET methods.

Install-Package ConsoleApp.CommandLine -Version 1.3.2
dotnet add package ConsoleApp.CommandLine --version 1.3.2
<PackageReference Include="ConsoleApp.CommandLine" Version="1.3.2" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add ConsoleApp.CommandLine --version 1.3.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Build Status

Introduction

Tools for building console application.

Installation

Install-Package ConsoleApp.CommandLine

Quick Start

Basics

To start, you need to configure the entry point to the application. Where "ConsoleApp" will be your class with a command handler.

using System

class Program
{
	public static int Main()
	{
		return CommandLine.Run<Program>(CommandLine.Arguments, defaultCommandName: "SayHello")
	}	
	public static int SayHello()
	{
		Console.WriteLine("Hello!");
		return 0;
	}
}

CommandLine.Run relies on reflection to find methods. So they should be static and return int which is Exit Code

Now you can test your application:

myapp.exe SayHello 
#>Hello!
myapp.exe SAYHELLO
#>Hello! -- command name is case-insensitive (parameters are not!)
myapp.exe 
#>Hello! - Too because 'defaultCommandName' is set to 'SayHello'

Parameter bindings

Positional and named parameters

You can add parameters to your command which is automatically binds by name or position

public static int SayHello(string name)
{
	Console.WriteLine("Hello " + name + "!");
	return 0;
}

Testing:

myapp.exe SayHello Mike 
#>Hello Mike!
myapp.exe SayHello --name Jake
#>Hello Jake!

List parameters

You can add array parameter to collect multiple values as shown below:

public static int SayHello(string[] names)
{
	Console.WriteLine("Hello " + string.Join(", ", names) + "!");
	return 0;
}

Testing:

myapp.exe SayHello --names Mike Jake
#>Hello Mike, Jake!

Parameter accepting multiple values can be only named.

Optional parameters

You can make any parameter optional by specifying default value.

public static int ShowOptionalParameter(int myOptionalParam = 100)
{
	Console.WriteLine("My optional parameter is " + myOptionalParam);
	return 0;
}

Testing:

myapp.exe ShowOptionalParameter --myOptionalParam 200
#>My optional parameter is 200
myapp.exe ShowOptionalParameter 300
#>My optional parameter is 300
myapp.exe ShowOptionalParameter
#>My optional parameter is 100

Flag parameters

You can have a flag(true/false) parameter. It's presence is considered to be "True" and absence is "False".

public static int ShowFlag(bool myFlag)
{
	Console.WriteLine(myFlag ? "Flag is set" : "Flag is not set");
	return 0;
}

Testing:

myapp.exe ShowFlag --myFlag
#>Flag is set
myapp.exe ShowFlag
#>Flag is not set

Parameters values starting with hyphen(-) symbol

Negative numbers (such as -1000) are interpreted as values by default. But strings like "-a", "-hello" are interpreted as named parameters.
To stop this interpretation you could place bare hyphen:

myapp.exe - --message -hello --class -a

Enforcing positional parameters

You could pass bare double hyphen(--) and anything after it will be threated as positional parameters.

myapp.exe --type message -- value1 value2 value3

No special symbols are interpeted after double hyphen(--) even another double hypthen:

myapp.exe --type message -- -value1 --value2 --value3-- --

Supported Parameter Types

  • Primitive types (int, byte, char ...)
  • BCL types (String, DateTime, Decimal)
  • Nullable types
  • Enum types
  • Types with TypeConverterAttribute (Point, Guid, Version, TimeSpan ...)
  • Types with Parse(string value) method (IpAddress, Guid ...)
  • Types with explicit/implicit conversion from string

–°ommands Hierarchy

Suppose you want to build a complex API where commands are grouped by purpose.

Example:

myfinance.exe Account Show --id 0a0e0000000

Each group must be defined as method(command) with one CommandLineArguments argument.

public static int Account(CommandLineArguments arguments)
{
	return CommandLine.Run<AccountCommands>(arguments);
}

class AccountCommands
{
	public static int Show()
	{
		// ...
	}
}

where AccountCommands is class with list of commands as described in "Basics".

Commands Description

Your command line application can generate help for the user. This requires to define Help method with following code inside

public static int Help()
{
	return CommandLine.Describe<ConsoleApp>();
}

Testing:

myapp.exe Help
> 	HELP

Not too much information :)

You can decorate the method with DescriptionAttribute attributes to expand 'Help' information.

using System.ComponentModel;

[Description("Display this help.")]
public static int Help()
{
	return CommandLine.Describe<ConsoleApp>();
}

Testing:

myapp.exe Help
> 	HELP - Display this help.

You can add these attributes to the methods, parameters and classes. All of them are involved in the generation of reference.

Handling Errors

To catch and handle binding or execution errors you could subscribe on CommandLine.UnhandledException method.

CommandLine.UnhandledException += (sender, args) => Console.WriteLine(args.Exception.ToString());

Build Status

Introduction

Tools for building console application.

Installation

Install-Package ConsoleApp.CommandLine

Quick Start

Basics

To start, you need to configure the entry point to the application. Where "ConsoleApp" will be your class with a command handler.

using System

class Program
{
	public static int Main()
	{
		return CommandLine.Run<Program>(CommandLine.Arguments, defaultCommandName: "SayHello")
	}	
	public static int SayHello()
	{
		Console.WriteLine("Hello!");
		return 0;
	}
}

CommandLine.Run relies on reflection to find methods. So they should be static and return int which is Exit Code

Now you can test your application:

myapp.exe SayHello 
#>Hello!
myapp.exe SAYHELLO
#>Hello! -- command name is case-insensitive (parameters are not!)
myapp.exe 
#>Hello! - Too because 'defaultCommandName' is set to 'SayHello'

Parameter bindings

Positional and named parameters

You can add parameters to your command which is automatically binds by name or position

public static int SayHello(string name)
{
	Console.WriteLine("Hello " + name + "!");
	return 0;
}

Testing:

myapp.exe SayHello Mike 
#>Hello Mike!
myapp.exe SayHello --name Jake
#>Hello Jake!

List parameters

You can add array parameter to collect multiple values as shown below:

public static int SayHello(string[] names)
{
	Console.WriteLine("Hello " + string.Join(", ", names) + "!");
	return 0;
}

Testing:

myapp.exe SayHello --names Mike Jake
#>Hello Mike, Jake!

Parameter accepting multiple values can be only named.

Optional parameters

You can make any parameter optional by specifying default value.

public static int ShowOptionalParameter(int myOptionalParam = 100)
{
	Console.WriteLine("My optional parameter is " + myOptionalParam);
	return 0;
}

Testing:

myapp.exe ShowOptionalParameter --myOptionalParam 200
#>My optional parameter is 200
myapp.exe ShowOptionalParameter 300
#>My optional parameter is 300
myapp.exe ShowOptionalParameter
#>My optional parameter is 100

Flag parameters

You can have a flag(true/false) parameter. It's presence is considered to be "True" and absence is "False".

public static int ShowFlag(bool myFlag)
{
	Console.WriteLine(myFlag ? "Flag is set" : "Flag is not set");
	return 0;
}

Testing:

myapp.exe ShowFlag --myFlag
#>Flag is set
myapp.exe ShowFlag
#>Flag is not set

Parameters values starting with hyphen(-) symbol

Negative numbers (such as -1000) are interpreted as values by default. But strings like "-a", "-hello" are interpreted as named parameters.
To stop this interpretation you could place bare hyphen:

myapp.exe - --message -hello --class -a

Enforcing positional parameters

You could pass bare double hyphen(--) and anything after it will be threated as positional parameters.

myapp.exe --type message -- value1 value2 value3

No special symbols are interpeted after double hyphen(--) even another double hypthen:

myapp.exe --type message -- -value1 --value2 --value3-- --

Supported Parameter Types

  • Primitive types (int, byte, char ...)
  • BCL types (String, DateTime, Decimal)
  • Nullable types
  • Enum types
  • Types with TypeConverterAttribute (Point, Guid, Version, TimeSpan ...)
  • Types with Parse(string value) method (IpAddress, Guid ...)
  • Types with explicit/implicit conversion from string

–°ommands Hierarchy

Suppose you want to build a complex API where commands are grouped by purpose.

Example:

myfinance.exe Account Show --id 0a0e0000000

Each group must be defined as method(command) with one CommandLineArguments argument.

public static int Account(CommandLineArguments arguments)
{
	return CommandLine.Run<AccountCommands>(arguments);
}

class AccountCommands
{
	public static int Show()
	{
		// ...
	}
}

where AccountCommands is class with list of commands as described in "Basics".

Commands Description

Your command line application can generate help for the user. This requires to define Help method with following code inside

public static int Help()
{
	return CommandLine.Describe<ConsoleApp>();
}

Testing:

myapp.exe Help
> 	HELP

Not too much information :)

You can decorate the method with DescriptionAttribute attributes to expand 'Help' information.

using System.ComponentModel;

[Description("Display this help.")]
public static int Help()
{
	return CommandLine.Describe<ConsoleApp>();
}

Testing:

myapp.exe Help
> 	HELP - Display this help.

You can add these attributes to the methods, parameters and classes. All of them are involved in the generation of reference.

Handling Errors

To catch and handle binding or execution errors you could subscribe on CommandLine.UnhandledException method.

CommandLine.UnhandledException += (sender, args) => Console.WriteLine(args.Exception.ToString());

Release Notes

# 1.3.1 - 1.3.2
- TypeConvert dependecy update (bug fixes)

# 1.3.0
- added TypeConverterAttribute support on command parameters. It's takes precendence before any other types of type conversions.

# 1.2.9
- added netcoreapp2.1 target platform
- dependencies update (internal)

# 1.2.7
- fixed exception when calling Describe while console output is redirected
- TypeConvert package update

# 1.2.6
- TypeConvert package update
- documentation update

# 1.2.5
- added WriteWholeErrorMessageOnBindFailure option for debugging purpose (it writes descriptive error message to stderr stream)
- added DescribeExitCode option for controlling exit code of Describe method
- tuned error messages when no command is specified or wrong parameters are passed
- tuned Describe method for better description text (friendly type names, nullable types support etc...)

# 1.2.4
- fixed binding error when no default action is specified
- added XML documentation file to package

# 1.2.3
- updated references for .NET Core Targets and .NET Standard

# 1.2.2
- returned original library name ConsoleApp.CommandLine.dll

# 1.2.1
- embedded TypeConvert dependency

# 1.2.0
- CommandLine.UnhandledException type changed to ExceptionEventHandler
- added custom description attributes as replacement to System.ComponentModel attributes: HelpTextAttribute and HiddenAttribute
- added support of .NET Standard platform

# 1.1.3
- refactored error messages fo parameters binding failure cases.
- added CommandLineException to signal binding failures.
- fixed few array parameter binding bugs

# 1.1.2
- added bare double hyphen to enforce positional parameters
- added bare single hyphen to disable hyphen interpretation in values
- added special treatment for negative numbers
- added CommandLine.DescribeOnBindFailure which controls reaction on method binding failure (true to run CommandLine.Describe(), false to throw exception).
- added enum flags binding subroutine, now "--flag Flag1 Flag2 Flag3" arguments are supported.
- changed method binding order to from most parameters to less (original was chaotic), binding strategy is still - "first match".
- added non-generic Run and Describe methods
- fixed bug with positional parameters binding

# 1.0.0
- initial release

  • .NETCoreApp 2.0

    • No dependencies.
  • .NETCoreApp 2.1

    • No dependencies.
  • .NETFramework 3.5

    • No dependencies.
  • .NETFramework 4.5

    • No dependencies.
  • .NETStandard 1.3

  • .NETStandard 2.0

    • No dependencies.

This package is not used by any popular GitHub repositories.

Version History

Version Downloads Last updated
1.3.2 964 7/5/2018
1.3.1 229 6/20/2018
1.2.9 252 5/31/2018
1.2.7 221 5/29/2018
1.2.6 225 5/21/2018
1.2.5 300 5/17/2018
1.2.2 1,008 3/9/2018
1.1.2 310 10/18/2017