Create a Shell - adamadair/NCmd GitHub Wiki

A shell is a user interface that provides access to a console programs services. Its called the shell because it is the layer that surrounds the programs actual functionality. The shell takes typed commands from the user, interprets that commands, and executes the appropriate function.

Creating a shell

To create a shell extend the NCmd.Cmd class.

using NCmd;

namespace MyConsoleApp
{
  class MyShell : Cmd
  {
   ...
  }
}

Adding commands to the shell

A shell is useless unless there are commands for the user to type. There are two ways of adding commands to your shell: by naming convention and by using method attributes.

Adding commands by naming convention

To add a command to the shell simply add a public method that takes a single string parameter, and the name of the method must begin with the characters 'Do_'. The following example creates a 'something' command that the user will be able to type at the prompt:

    /// <summary>
    /// A command by naming convention
    /// </summary>
    /// <param name="arg">Anything typed after the command name at the shell prompt</param>
    public void Do_something(string arg)
    {
        if (string.IsNullOrEmpty(arg))
        {
            Console.WriteLine("Doing something...");
        }
        else
        {
            Console.WriteLine($"What do you mean by '{arg}'?");
        }
    }

During execution, anything that the user types after the something command is passed to the Do_something method as the arg parameter.

Adding commands by method attribute

If you don't like the 'Do_' way of naming your methods, you can use the CmdCommand method attribute, and set the Command name. In the following example a command named date is created so that when the user types date at the shell prompt the date is written to the console:

    [CmdCommand(Command = "date")]
    public void ShowDate(string arg)
    {
        Console.WriteLine(DateTime.Now.ToShortDateString());    
    }

In both the methods of adding commands the string argument for the backing method is required.

Starting the shell

To start the shell to begin accepting user input instantiate your shell object and call the CmdLoop() method:

    var myShell = new MyShell();
    myShell.CmdLoop();

Exiting the shell

⚠️ **GitHub.com Fallback** ⚠️