Command-line Parsing

Command-line parsing can be a tedious chore when you are building an application that accepts command-line arguments. But what if all you had to do was create a class with the properties that you want to accept? The BizArk framework offers a simple to use command-line parsing utility that allows you to do exactly that.

Command-line parsing in the BizArk framework has these key features:

So how do you use the command-line parsing? Start by creating a class that is derived from CmdLineObject. Add properties with data types that support conversion from a string using the BizArk ConvertEx class. In main, instantiate your class and call Initialize. That’s it.

If you want to validate your command-line or display help, you will need to check a couple of CmdLineObject properties. Other than that, you can just use your object as any other class.

Here’s an example custom command-line object:

    [CmdLineOptions(DefaultArgName = "Message")]
    public class MyCmdLine
        : CmdLineObject
    {
        public MyCmdLine()
        {
            Message = "";
        }

        [CmdLineArg(Alias = "M", Usage = "Message")]
        [Description("Message to display.")]
        public string Message { get; set; }
    }

This is the code to use it:

    static void Main(string[] args)
    {
        var cmdLine = new MyCmdLine();
        cmdLine.Initialize();
        // Validate only after checking to see if they requested help
        // in order to prevent displaying errors when they request help.
        if (cmdLine.Help || !cmdLine.IsValid())
        {
            Console.WriteLine(cmdLine.GetHelpText(Console.WindowWidth));
            return;
        }

        Console.WriteLine(cmdLine.Message);
    }

And to display a message, call it like this: MyProgram /M "Hello World"

BizArk also provides a convenient method that you can call that will automatically initialize your command line arguments and handle common scenarios such as requesting help and error handling. BizArk.Core.CmdLine.ConsoleApplication.RunProgram takes a generic argument that should be your custom command-line object and a delegate for a parameter that is your main program. Your Main() function should just have a single line of code in it to call the ConsoleApplication.RunProgram method.

    class Program
    {
        static void Main(string[] args)
        {
            ConsoleApplication.RunProgram<MyCmdLine>(Start);
        }

        private static void Start(MyCmdLine args)
        {
            // Your code goes here
        }
    }

ConsoleApplication.RunProgram will instantiate your custom CmdLineObject, initialize it, display help if necessary, display unhandled errors, and prompt the user to press a key to exit if CmdLineOptions.Wait is true.