Skip to content

Instantly share code, notes, and snippets.

@CVertex
Last active December 15, 2015 04:50
Show Gist options
  • Select an option

  • Save CVertex/5204213 to your computer and use it in GitHub Desktop.

Select an option

Save CVertex/5204213 to your computer and use it in GitHub Desktop.
BaseConsole class used for simple command line interface. See the Program class below for a simple usage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using C = System.Console;
namespace Tafe120.Console
{
/// <summary>
/// Base class for a command line interface
/// </summary>
public abstract class BaseConsole
{
#region Constructor
public BaseConsole()
{
Commands = new Dictionary<string, Action>()
{
{"help", () => PrintCommands()}
};
LoadCommands();
}
#endregion
#region Console Properties
public abstract string Name { get; }
#endregion
#region Commands
protected static readonly string[] exitCommands = new string[] { "done", "exit", "quit" };
public Dictionary<string, Action> Commands
{
get;
protected set;
}
protected abstract void LoadCommands();
#endregion
#region Command Processing
protected virtual void ProcessCommand(string cmd)
{
Action action = null;
if (Commands.TryGetValue(cmd, out action))
{
action();
}
else
{
System.Console.WriteLine("Unknown command");
}
}
protected virtual void PrintCommands()
{
System.Console.WriteLine("Available Commands:");
foreach (var c in Commands)
{
System.Console.WriteLine("\t" + c.Key);
}
}
#endregion
#region Run
public void Run()
{
C.WriteLine(Name);
C.WriteLine("=====================================");
C.WriteLine("Type 'help' to get available commands");
C.WriteLine("Type 'exit','done' or 'quit' to exit");
C.WriteLine();
C.Write(">>");
string input = C.ReadLine();
// While not exit command entered, process each command
while (!exitCommands.Contains(input, StringComparer.CurrentCultureIgnoreCase))
{
try
{
// process command
ProcessCommand(input);
}
catch (Exception ex)
{
C.WriteLine(ex.ToString());
}
finally
{
C.WriteLine();
C.Write(">>");
input = C.ReadLine();
}
}
Finished();
}
#endregion
#region Finished
protected virtual void Finished()
{
}
#endregion
}
}
class Program : BaseConsole
{
static void Main(string[] args)
{
new Program().Run();
}
public override string Name
{
get { return "Console App"; }
}
protected override void LoadCommands()
{
// add the command into the command dictionary
Commands.Add("hello", () =>
{
System.Console.WriteLine("Hi there user");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment