Trivial.Console 3.5.2

The useful utilities for console application including command dispatcher, arguments parser and some rich user interface console controls.

There is a newer version of this package available.
See the version list below for details.
Install-Package Trivial.Console -Version 3.5.2
dotnet add package Trivial.Console --version 3.5.2
<PackageReference Include="Trivial.Console" Version="3.5.2" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Trivial.Console --version 3.5.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Trivial.Console

This library includes these useful tools and controls about console app.

  • Cmd arguments parser and processor.
  • Rich components of CLI.

Import

Just add following namespace to your code file to use.

using Trivial.Console;

Parse

The cmd arguments is an array of string.
You can parse it to a program readable object with structured information.

void Main(string[] args)
{
    var arguments = new Arguments(args);
    Console.WriteLine("{0} {1}", arguments["say"], arguments["name"]);
}
>  a.exe --name Kingcean Tuan --say Hello
Hello Kingcean Tuan

You can also parse a string directly.

void Main(string[] args)
{
    var str = Console.ReadLine();
    var arguments = new Arguments(str);
    Console.WriteLine("{0} {1}", arguments[1], arguments[0]);
}
>  a.exe
>  hijklmn abcdefg
abcdefg hijklmn

Verb

If your application contains a set of functionalities, you may need verbs to help you to build a more flexible console application.
Each verb can has its own business logic. The arguments will be filled into the property with attribute ArgumentAttribute.

class FirstVerb: Verb
{
    [Argument("name")]
    public string Name { get; set; }

    public override string Description => "Test 1";

    public override void Process()
    {
        Console.WriteLine("This is the verb handler 1.");
        Console.WriteLine("Name is {0}.", Name);
        Console.WriteLine("Name is {0}.", Arguments["name"]);
    }
}

And you can also define a verb handler with async process method.

class SecondVerb: AsyncVerb
{
    public override string Description => "Test 2";

    public override async Task Process()
    {
        Console.WriteLine("This is the verb handler 2. Step 1.");
        await Task.Run(() => {
            Console.WriteLine("This is the verb handler 2. Step 2.");
        });
    }
}

Then you can use dispatcher to dispatch the correct verb handler to process.

static async Task Main(string[] args)
{
    var dispatcher = new Dispatcher();
    dispatcher.Register<FirstVerb>("one");
    dispatcher.Register<SecondVerb>("two");

    await dispatcher.ProcessAsync(args);
}
>  a.exe one --name Test
This is the verb handler 1.
Name is Test.
Name is Test.
>  a.exe two
This is the verb handler 2. Step 1.
This is the verb handler 2. Step 2.

Line

We provide a line component for the standard output stream that you can write a string which you can update before the line terminator.
Following is a sample.

var line = new Line();
    
// Write something.
line.Write("Loading {0}......", "something");

// Remove some charactors and add other string with color.
line.Backspace(3);
line.Write(ConsoleColor.Green, "  Done!");

// And you can append other string following above in the same line and in the default color.
line.Write(" This is only for test.");

// Add terminator.
line.End();

// You cannot add further terminator if there is no any string output.
line.End();

// So following will be in a new line.
line.Write("Next line. ");

// We can turn off the auto flush so that all strings write later will be in an output queue.
line.AutoFlush = false;
line.Write(ConsoleColor.Red, ConsoleColor.Yellow, "Red foreground and yellow background");
line.End();
line.Write("This will not be output immediately, neither.");

// Now let's write them.
line.Flush();

// Following will not output until we call Flush member method or set AutoFlush property as true.
line.Write(" Hello?");
line.AutoFlush = true;
line.End();

And you can also read the password into a SecureString with the optional text mask.

var line = new Line();

// Read password.
line.Write("Type password: ");
var password = line.ReadPassword('*', ConsoleColor.Yellow);
line.WriteLine();

// Write a secure string to the standard output stream.
line.Write("Your password is ");
line.Write(ConsoleColor.Magenta, password);
line.WriteLine('.');

Select

You can output a beautiful list or table with customized style to the standard output stream
so that user just need press the arrow buttons and ENTER in keyboard to select.

// Create an instance for adding items and setting options.
var col = new SelectionData<string>();

// Add some items. For each item, you can set a string value,
// an additional data, an additional displayed title and an additional hot key.
col.Add('a', "char a", "a", "char [a]");
col.Add('b', "char b", "b", "char [b]");
for (var i = 0; i < 120; i++)
{
    col.Add("num " + i, i.ToString());
}

// Create an options for display.
var options = new SelectionOptions
{
    // You can define a question string after the list.
    Question = "Please select one: ",

    // We can define the colors of the item selected.
    SelectedForegroundColor = ConsoleColor.White,
    SelectedBackgroundColor = ConsoleColor.Blue,

    // The selected item will also be displayed after the question string.
    // So you can define its color.
    DefaultValueForegroundColor = ConsoleColor.Cyan,

    // At the end of the list, the tips will be displayed before user press any key.
    // There is a default value and you can customize it.
    // And you can disable it by set it as null.
    Tips = "Tips: You can use arrow key to select and press ENTER key to continue.",

    // Then you can define its color.
    TipsForegroundColor = ConsoleColor.Yellow,

    // You can define the prefix for the item and the one selected.
    SelectedPrefix = "√ ",
    Prefix = " ",

    // You can define the column count for the list.
    Column = 5,

    // You can define the maximum rows to displayed.
    // A paging will be displayed if the count of the list is greater than it.
    MaxRow = 10,

    // Press ESC can cancel this selection.
    // But you can enable the manual way by set a manual question
    // so that user can type the words directly.
    ManualQuestion = "Type: "
};

// Write it to the standard output stream and wait for user selection.
var result = LineUtilities.Select(col, options);

// You can get the result.
Console.WriteLine("The result is {0}.", result.Value);

Progress

You can output a progress bar to update during a task running.

// Define an options that you can custom the style.
var progressOptions = new ProgressLineOptions();

// Ouput the component in console and get the progress instance to update.
var progress = LineUtilities.WriteLine("Processing", progressOptions);

// A time-consuming work here.
for (var i = 0; i <= 50; i++)
{
    await Task.Delay(10);

    // And report the progress updated.
    progress.Report(0.02 * i);
}

Trivial.Console

This library includes these useful tools and controls about console app.

  • Cmd arguments parser and processor.
  • Rich components of CLI.

Import

Just add following namespace to your code file to use.

using Trivial.Console;

Parse

The cmd arguments is an array of string.
You can parse it to a program readable object with structured information.

void Main(string[] args)
{
    var arguments = new Arguments(args);
    Console.WriteLine("{0} {1}", arguments["say"], arguments["name"]);
}
>  a.exe --name Kingcean Tuan --say Hello
Hello Kingcean Tuan

You can also parse a string directly.

void Main(string[] args)
{
    var str = Console.ReadLine();
    var arguments = new Arguments(str);
    Console.WriteLine("{0} {1}", arguments[1], arguments[0]);
}
>  a.exe
>  hijklmn abcdefg
abcdefg hijklmn

Verb

If your application contains a set of functionalities, you may need verbs to help you to build a more flexible console application.
Each verb can has its own business logic. The arguments will be filled into the property with attribute ArgumentAttribute.

class FirstVerb: Verb
{
    [Argument("name")]
    public string Name { get; set; }

    public override string Description => "Test 1";

    public override void Process()
    {
        Console.WriteLine("This is the verb handler 1.");
        Console.WriteLine("Name is {0}.", Name);
        Console.WriteLine("Name is {0}.", Arguments["name"]);
    }
}

And you can also define a verb handler with async process method.

class SecondVerb: AsyncVerb
{
    public override string Description => "Test 2";

    public override async Task Process()
    {
        Console.WriteLine("This is the verb handler 2. Step 1.");
        await Task.Run(() => {
            Console.WriteLine("This is the verb handler 2. Step 2.");
        });
    }
}

Then you can use dispatcher to dispatch the correct verb handler to process.

static async Task Main(string[] args)
{
    var dispatcher = new Dispatcher();
    dispatcher.Register<FirstVerb>("one");
    dispatcher.Register<SecondVerb>("two");

    await dispatcher.ProcessAsync(args);
}
>  a.exe one --name Test
This is the verb handler 1.
Name is Test.
Name is Test.
>  a.exe two
This is the verb handler 2. Step 1.
This is the verb handler 2. Step 2.

Line

We provide a line component for the standard output stream that you can write a string which you can update before the line terminator.
Following is a sample.

var line = new Line();
    
// Write something.
line.Write("Loading {0}......", "something");

// Remove some charactors and add other string with color.
line.Backspace(3);
line.Write(ConsoleColor.Green, "  Done!");

// And you can append other string following above in the same line and in the default color.
line.Write(" This is only for test.");

// Add terminator.
line.End();

// You cannot add further terminator if there is no any string output.
line.End();

// So following will be in a new line.
line.Write("Next line. ");

// We can turn off the auto flush so that all strings write later will be in an output queue.
line.AutoFlush = false;
line.Write(ConsoleColor.Red, ConsoleColor.Yellow, "Red foreground and yellow background");
line.End();
line.Write("This will not be output immediately, neither.");

// Now let's write them.
line.Flush();

// Following will not output until we call Flush member method or set AutoFlush property as true.
line.Write(" Hello?");
line.AutoFlush = true;
line.End();

And you can also read the password into a SecureString with the optional text mask.

var line = new Line();

// Read password.
line.Write("Type password: ");
var password = line.ReadPassword('*', ConsoleColor.Yellow);
line.WriteLine();

// Write a secure string to the standard output stream.
line.Write("Your password is ");
line.Write(ConsoleColor.Magenta, password);
line.WriteLine('.');

Select

You can output a beautiful list or table with customized style to the standard output stream
so that user just need press the arrow buttons and ENTER in keyboard to select.

// Create an instance for adding items and setting options.
var col = new SelectionData<string>();

// Add some items. For each item, you can set a string value,
// an additional data, an additional displayed title and an additional hot key.
col.Add('a', "char a", "a", "char [a]");
col.Add('b', "char b", "b", "char [b]");
for (var i = 0; i < 120; i++)
{
    col.Add("num " + i, i.ToString());
}

// Create an options for display.
var options = new SelectionOptions
{
    // You can define a question string after the list.
    Question = "Please select one: ",

    // We can define the colors of the item selected.
    SelectedForegroundColor = ConsoleColor.White,
    SelectedBackgroundColor = ConsoleColor.Blue,

    // The selected item will also be displayed after the question string.
    // So you can define its color.
    DefaultValueForegroundColor = ConsoleColor.Cyan,

    // At the end of the list, the tips will be displayed before user press any key.
    // There is a default value and you can customize it.
    // And you can disable it by set it as null.
    Tips = "Tips: You can use arrow key to select and press ENTER key to continue.",

    // Then you can define its color.
    TipsForegroundColor = ConsoleColor.Yellow,

    // You can define the prefix for the item and the one selected.
    SelectedPrefix = "√ ",
    Prefix = " ",

    // You can define the column count for the list.
    Column = 5,

    // You can define the maximum rows to displayed.
    // A paging will be displayed if the count of the list is greater than it.
    MaxRow = 10,

    // Press ESC can cancel this selection.
    // But you can enable the manual way by set a manual question
    // so that user can type the words directly.
    ManualQuestion = "Type: "
};

// Write it to the standard output stream and wait for user selection.
var result = LineUtilities.Select(col, options);

// You can get the result.
Console.WriteLine("The result is {0}.", result.Value);

Progress

You can output a progress bar to update during a task running.

// Define an options that you can custom the style.
var progressOptions = new ProgressLineOptions();

// Ouput the component in console and get the progress instance to update.
var progress = LineUtilities.WriteLine("Processing", progressOptions);

// A time-consuming work here.
for (var i = 0; i <= 50; i++)
{
    await Task.Delay(10);

    // And report the progress updated.
    progress.Report(0.02 * i);
}

  • .NETCoreApp 3.1

    • No dependencies.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version History

Version Downloads Last updated
3.6.0 66 11/12/2020
3.6.0-preview2 120 8/27/2020
3.6.0-preview1 67 8/26/2020
3.5.2 187 4/14/2020
3.5.1 188 4/12/2020
3.5.0 181 4/1/2020
3.4.0 235 2/20/2020
3.3.0 281 2/14/2020
3.2.0 507 1/22/2020
3.1.0 552 12/30/2019
3.0.1 465 12/26/2019
2.2.0 307 2/19/2020
2.1.0 536 12/24/2019
2.0.0 489 8/31/2019
1.2.0 498 5/20/2019
1.1.0 484 5/8/2019
1.0.0 495 5/1/2019