This is a handler I wrote based on the Novell Options
class.
This one is aimed at console applications that execute a while (input !="exit")
style loop, an interactive console such as an FTP console for example.
Example usage:
static void Main(string[] args)
{
// Setup
CommandHandler handler = new CommandHandler();
CommandOptions options = new CommandOptions();
// Add some commands. Use the v syntax for passing arguments
options.Add("show", handler.Show)
.Add("connect", v => handler.Connect(v))
.Add("dir", handler.Dir);
// Read lines
System.Console.Write(">");
string input = System.Console.ReadLine();
while (input != "quit" && input != "exit")
{
if (input == "cls" || input == "clear")
{
System.Console.Clear();
}
else
{
if (!string.IsNullOrEmpty(input))
{
if (options.Parse(input))
{
System.Console.WriteLine(handler.OutputMessage);
}
else
{
System.Console.WriteLine("I didn't understand that command");
}
}
}
System.Console.Write(">");
input = System.Console.ReadLine();
}
}
And the source:
///
/// A class for parsing commands inside a tool. Based on Novell Options class (http://www.ndesk.org/Options).
///
public class CommandOptions
{
private Dictionary> _actions;
private Dictionary _actionsNoParams;
///
/// Initializes a new instance of the class.
///
public CommandOptions()
{
_actions = new Dictionary>();
_actionsNoParams = new Dictionary();
}
///
/// Adds a command option and an action to perform when the command is found.
///
/// The name of the command.
/// An action delegate
/// The current CommandOptions instance.
public CommandOptions Add(string name, Action action)
{
_actionsNoParams.Add(name, action);
return this;
}
///
/// Adds a command option and an action (with parameter) to perform when the command is found.
///
/// The name of the command.
/// An action delegate that has one parameter - string[] args.
/// The current CommandOptions instance.
public CommandOptions Add(string name, Action action)
{
_actions.Add(name, action);
return this;
}
///
/// Parses the text command and calls any actions associated with the command.
///
/// The text command, e.g "show databases"
public bool Parse(string command)
{
if (command.IndexOf(" ") == -1)
{
// No params
foreach (string key in _actionsNoParams.Keys)
{
if (command == key)
{
_actionsNoParams[key].Invoke();
return true;
}
}
}
else
{
// Params
foreach (string key in _actions.Keys)
{
if (command.StartsWith(key) && command.Length > key.Length)
{
string options = command.Substring(key.Length);
options = options.Trim();
string[] parts = options.Split(' ');
_actions[key].Invoke(parts);
return true;
}
}
}
return false;
}
}