Sometimes developers have to implement stupid things. One of this stupid things is parsing command line arguments that are used by a console application. That’s where my story begins.
Last time I had to implement such an algorithm for the thousandths time. One time too much. So I decided to write a framework which does the command line argument parsing for me. During my development I found out that there exists 3 different command line argument types.
Look at the definition of the DIR command in DOS.
DIR [directory] [/A:attributes] [/B] [/L] ...
Anonym argument: The parameter [directory] is an anonym argument, because it has no name and it’s always defined as the first parameter.
Argument: The [/A:attributes] parameter is an argument, because it has a name [A] and a value [attributes].
Command: The [/B] and [/L] parameter is a command, because it has a name, but no value.
The problem was now to prevent the SWITCH/CASE hell and to provide a simple API which can handle these 3 parameter types. The result of my research is a base class named 'CommandLine' that offers a few methods like AddArgument, AddCommandand AnonymArgument.
The handling of the command line parameters is based on Delegates which will be dynamically invoked when parsing the arguments by the CommandLine Base class.
I made a small Dir command rebuild. Here’s the command definition.
Code within the constructor
AnonymArgument = new Argument(new ArgumentDelegate(SetDir), "Directory to show.");
AddCommand ("?", new CommandDelegate(ShowHelp), "/?\tShows the parameters help.");
AddArgument ("A", new ArgumentDelegate(SetAttributes), setAttributeHelp);
The methods SetDir, ShowHelp and SetAttributes are invoked dynamically by the base class. So you only have to define the delegate methods.
Delegate method definition
private void SetAttributes (string content) { ... }
private void SetDir (string content) { ... }
private void ShowHelp () { ... }
With this functionality you are able to write console applications quite fast and you can invest your time in more relevant programming parts.
For a better re-use of the component I placed the common part in a separate assembly named AdFactum.CommandLine.dll.
The whole example can be downloaded using the following link:
CommandLine Framework