How to Improve the .NET Console Application Experience?

How to Improve the .NET Console Application Experience?

Come on, I'll teach you to write cool console applications

Last updated 4/4/2022 11:21 AM
古道轻风
6 min read
Category
.NET
Topic
C# Open Source Projects
Tags
.NET C# Console Cool Console

In the .NET ecosystem, console applications tend to have a relatively poor reputation. Typically, such projects are often used as demo samples. It's time for console applications to get the respect they deserve.

Advances in terminal technology have sparked a renaissance in enhancing user experience. ITerm2, Hyper, Windows Terminal — all these tools add some flair to the otherwise monotonous console experience. While these tools allow users to customize their own experience, developers also want to inject some programmatic style into their console applications.

In this blog post, we'll look at how to spice up our console programs using some excellent open-source projects. The order here doesn't indicate which project is better or worse — they are all great options for improving our console experience.

1. Colorful.Console

Colorful.Console is a NuGet package that enhances our control over the styling of console output text. We can use colors defined in System.Drawing.Color to define the color scheme of our console programs.

using System;
using System.Drawing;
using Console = Colorful.Console;
...
...
Console.WriteLine("console in pink", Color.Pink);
Console.WriteLine("console in default");

Additionally, Colorful.Console allows us to output colored ASCII art using FIGlet fonts.

FigletFont font = FigletFont.Load("chunky.flf");
Figlet figlet = new Figlet(font);

Console.WriteLine(figlet.ToAscii("Belvedere"), ColorTranslator.FromHtml("#8AFFEF"));
Console.WriteLine(figlet.ToAscii("ice"), ColorTranslator.FromHtml("#FAD6FF"));
Console.WriteLine(figlet.ToAscii("cream."), ColorTranslator.FromHtml("#B8DBFF"));

The output is a hacker's dream.

I recommend visiting the official site of Colorful.Console to see all the effects this library can achieve, so you can better improve your console experience.

2. ConsoleTables

The ConsoleTables package was written by me (the author) — a bit shameless. This library makes it easy for developers to display a set of objects in a table format in the console.

static void Main(String[] args)
{
    var table = new ConsoleTable("one", "two", "three");
    table.AddRow(1, 2, 3)
         .AddRow("this line should be longer", "yes it is", "oh");

    table.Write();
    Console.WriteLine();

    var rows = Enumerable.Repeat(new Something(), 10);

    ConsoleTable
        .From<Something>(rows)
        .Configure(o => o.NumberAlignment = Alignment.Right)
        .Write(Format.Alternative);

    Console.ReadKey();
}

Who wouldn't want to output a table in the console?

FORMAT: Default:

 --------------------------------------------------
 | one                        | two       | three |
 --------------------------------------------------
 | 1                          | 2         | 3     |
 --------------------------------------------------
 | this line should be longer | yes it is | oh    |
 --------------------------------------------------

 Count: 2


FORMAT: Alternative:

+----------------------------+-----------+-------+
| one                        | two       | three |
+----------------------------+-----------+-------+
| 1                          | 2         | 3     |
+----------------------------+-----------+-------+
| this line should be longer | yes it is | oh    |
+----------------------------+-----------+-------+

Since ConsoleTables was released, many developers have created their own console table libraries. Some are even better — you can search for them yourself.

3. ShellProgressBar

Like other applications, console programs can execute long-running tasks. ShellProgressBar is a fantastic library that lets you output some impressive progress bars in the console. Moreover, ShellProgressBar supports nesting of progress bars, as shown in the GIF animation below.

ShellProgressBar is quite straightforward to use.

const int totalTicks = 10;
var options = new ProgressBarOptions
{
    ProgressCharacter = '─',
    ProgressBarOnBottom = true
};
using (var pbar = new ProgressBar(totalTicks, "Initial message", options))
{
    pbar.Tick(); //will advance pbar to 1 out of 10.
    //we can also advance and update the progressbar text
    pbar.Tick("Step 2 of 10");
}

Thank you, Martijin Larrman, this is a really useful library.

4. GUI.CS

GUI.CS is an excellent console UI toolkit. It provides a full-featured toolbox that developers can use to build a user interface common in early console applications.

This UI toolbox includes the following controls:

  1. Buttons
  2. Labels
  3. Text Entry
  4. Text View
  5. User Inputs
  6. Windows
  7. Menus
  8. ScrollBars

With it, developers can achieve some incredible effects in console applications. This library was written by Miguel De Icaza and represents the pinnacle of console technology. Let's take a look at a sample program.

using Terminal.Gui;

class Demo {
    static void Main ()
    {
        Application.Init ();
        var top = Application.Top;

    // Create the top-level window
        var win = new Window ("MyApp") {
        X = 0,
        Y = 1, // Reserve space for the menu row

        // Use Dim.Fill(), it automatically adjusts the window size for responsiveness without manual intervention
        Width = Dim.Fill (),
        Height = Dim.Fill ()
    };
        top.Add (win);

    // Create a menu
        var menu = new MenuBar (new MenuBarItem [] {
            new MenuBarItem ("_File", new MenuItem [] {
                new MenuItem ("_New", "Creates new file", NewFile),
                new MenuItem ("_Close", "", () => Close ()),
                new MenuItem ("_Quit", "", () => { if (Quit ()) top.Running = false; })
            }),
            new MenuBarItem ("_Edit", new MenuItem [] {
                new MenuItem ("_Copy", "", null),
                new MenuItem ("C_ut", "", null),
                new MenuItem ("_Paste", "", null)
            })
        });
        top.Add (menu);

    var login = new Label ("Login: ") { X = 3, Y = 2 };
    var password = new Label ("Password: ") {
            X = Pos.Left (login),
        Y = Pos.Top (login) + 1
        };
    var loginText = new TextField ("") {
                X = Pos.Right (password),
                Y = Pos.Top (login),
                Width = 40
        };
        var passText = new TextField ("") {
                Secret = true,
                X = Pos.Left (loginText),
                Y = Pos.Top (password),
                Width = Dim.Width (loginText)
        };

    // Add some other controls
    win.Add (
        // This is my favorite layout
          login, password, loginText, passText,

        // Using absolute positioning here
            new CheckBox (3, 6, "Remember me"),
            new RadioGroup (3, 8, new [] { "_Personal", "_Company" }),
            new Button (3, 14, "Ok"),
            new Button (10, 14, "Cancel"),
            new Label (3, 18, "Press F9 or ESC plus 9 to activate the menubar"));

        Application.Run ();
    }
}

Conclusion

As developers, we can be addicted to GUIs — and rightfully so, they make us more productive. But console applications are equally powerful. The next time you write a console program, consider using some of the libraries introduced above to add some color to your console app.

Original title: Upgrade Your .NET Console App Experience
Original link: https://khalidabuhakmeh.com/upgraded-dotnet-console-experience
Original author: Khalid Abuhakmeh
Translation: Lamond Lu
This article is reposted from CNBlogs (古道轻风): https://www.cnblogs.com/88223100/p/upgraded-dotnet-console-experience.html

Keep Exploring

Related Reading

More Articles