Category Archives: CommandLine

Cinchoo – Command Line Argument Parser, Part 1

Simplified Command Line Argument Parser

Cinchoo framework offers an another feature, simplified command line argument parser. It provides the below set of features

  • Auto-generation of usage
  • Able to check required and optional parameters
  • Type safe command line argument object
  • Support flag parameters
  • Read command line arguments from file etc

Overview

The command line input, read from the Environment.GetCommandLineArg as string array, is then pushed to an instance of a custom type decorated with ChoCmdLineArgumentObjectAttrribue and derived from ChoCmdLineArgumntObject by the framework. You just have to create this class with one field for each command line value decorated with ChoCmdLineArgumentAttribute.

How to use

First, add a reference to Cinchoo.Core.dll to your project.

Namespace: Cinchoo.Core.Shell

Then, create your custom class to consume  -I -O:\OutDir -N:4 C:\InputDir1;C:\InputDir2 command line arguments,

where

-N   Number of spaces for TAB character (integer type)

-I    Include sub directory

-O  Output directory

-F   Semi-Colon separated list of Folders

Here is the custom class reflects the above specification

[ChoCommandLineArgObject]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
	[ChoCommandLineArg("N", DefaultValue = 100, Description = "No of spaces for a TAB.")]
	public int Count
	{
		get;
		set;
	}

	[ChoCommandLineArg("I", DefaultValue = false, FallbackValue = true, Description = "Include Sub directory.")]
	public bool IncludeSubDir
	{
		get;
		set;
	}

	[ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
	public string OutputDir
	{
		get;
		set;
	}

	[ChoCommandLineArg("F", IsRequired = true, Description = "Semi-colon seperated list of folders")]
	public string Folders
	{
		get;
		set;
	}
}

Finally instantiate and use the object from the above custom command line class

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();

Please note the instance created above is the singleton. The Cinchoo framework always return the same instance no matter how many times you instantiate using new operator.

That’s all folks, please try it out.


Cinchoo – Command Line Argument Parser, Part 2

Inside Command Line Argument Parser

In this section, I’ll talk about some of the Command Line argument Parser features

  • Automatic initialization: Class members are automatically set based on the command-line arguments.
  • Default Value: Set in a value when the command line switch is not specified.
  • Fallback Value: Set in a value when the command line switch value is not specified.
  • Value conversion: Uses the powerful .NET converter and ChoConverter classes for value conversion.
  • Boolean flags: Flags can be specified by simply using the argument (ex, /b for true, otherwise false) or by adding the value /b:true /b:false.
  • Auto Help Text: Automatically framework creates usage text.
  • Load command-line arguments from a file: If you have multiple large, complex sets of command-line arguments that you want to run multiple times.
  • Event Handlers: Provides better event handler mechanism to carryout validation, value conversion, inspection etc

Automatic Initialization

Cinchoo framework automatically set the members of Command Line argument object while creating instance of it. For a below sample command line argument object

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

[ChoCommandLineArgObject]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("N", DefaultValue = 100, Description = "No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue=true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutputDir
    {
        get;
        set;
    }
}

If a application containing above type executed with the below command line arguments

-N:100 /I -O:C:\output

When creating instance of MyCommandLineArgObject, the framework automatically parses the command line arguments and sets the values appropriately to the members of this object.

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());
Output will be as below
-- Cinchoo.Core.CommandLineArgs.Test.MyCommandLineArgObject Dump --
 Count: 100
 IncludeSubDir: True
 OutputDir: C:\output

During the course of command line parsing, any failure will be thrown as ChoCommandLineArgException.


Cinchoo – Command Line Argument Parser, Part 3

Inside Command Line Argument Parser – Default Value

In this section, I’ll talk about defining and using DefaultValue in the members of command line argument object. You can specify DefaultValue for each members of Command Line object.

Cinchoo framework will set the default values to members if the corresponding command line argument switch is missing.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

In a sample Command Line object below,

[ChoCommandLineArgObject]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("N", DefaultValue = 100, Description ="No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue=true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutputDir
    {
        get;
        set;
    }
}

If a application containing above type executed with the below command line arguments

/I -O:C:\output

When creating instance of MyCommandLineArgObject, the framework automatically parses the command line arguments and sets the values appropriately to the members of this object.

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());
In this sample, the Count parameter will be defaulted to 100, as it is missing from command line arguments.
Output will be as below
-- Cinchoo.Core.CommandLineArgs.Test.MyCommandLineArgObject Dump --
 Count: 100
 IncludeSubDir: True
 OutputDir: C:\output

Cinchoo – Command Line Argument Parser, Part 4

Inside Command Line Argument Parser – Fallback value

In this section, I’ll explain about defining and using Fallback Value in the members of command line argument object. You can specify optional Fallback Value for each member of Command Line object.

Cinchoo framework will set these Fallback values to members if the corresponding command line argument switch value is null/empty.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

In a sample Command Line object below,

[ChoCommandLineArgObject]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("N", DefaultValue = 100, Description ="No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue=true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutputDir
    {
        get;
        set;
    }
}

If the application containing above type executed with the below command line arguments

/I -O:C:\output

In here, the command-line switch “I” is specified with no value. In this case, the framework uses the FallbackValue for “I” command-line switch.

When creating instance of MyCommandLineArgObject, the framework automatically parses the command line arguments and sets the Fallback value for“I” command-line switch to true, as no value is passed.

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());
In this sample, the Count parameter will be defaulted to 100, as it is missing from command line arguments.
Output will be as below
-- Cinchoo.Core.CommandLineArgs.Test.MyCommandLineArgObject Dump --
 Count: 100
 IncludeSubDir: True
 OutputDir: C:\output

The difference between DefaultValue and FallbackValue is that, the DefaultValue will be set irrespective of the command-line switch passed or not. FallbackValue will be set only when the corresponding command-line switch passed with  null/empty value.


Cinchoo – Command Line Argument Parser, Part 5

Inside Command Line Argument Parser – Required Value

In this section, I’ll explain about defining Required command-line  arguments members in command line argument object. You can specify required flag to any member of Command Line object.

Cinchoo framework will validate and throw an exception if a required command-line argument is missing.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

In a sample Command Line object below,

public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("N", DefaultValue = 100, Description ="No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue=true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutputDir
    {
        get;
        set;
    }
}

If the application containing above type executed with the below command line arguments

/N:200 /I

Or

N:200 /I -O:

When creating instance of MyCommandLineArgObject, the framework automatically parses the command line arguments, sees there is no value passed for “O” argument and throws an exception with the below message

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());
In this sample, framework throws a ChoCommandLineArgException with the below message
Found exception while loading `O` command line argument.

Missing arg value for 'O' required command line switch.

Cinchoo.Core.CommandLineArgs.Test.exe -N:<int> -I:{True|False} -O:[<string>]

Where
        -D      Business Date.
        -N      No of spaces for a TAB.
        -I      Include Sub directory.
        -O      Output Directory.

Cinchoo – Command Line Argument Parser, Part 6

Inside Command Line Argument Parser – Default Argument

In this section, I’ll talk about defining and using Default command-line arguments member in command line argument object. There may be only one Default command-line argument can be defined in Command-line object.

Default command-line argument is an argument passed without any switch (ex: the argument “C:\Source1;C:\Source2″ is the default argument).

N:200 /I -O:C:\Log "C:\Source1;C:\Source2"

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

In a sample Command Line object below,

[ChoCommandLineArgObject]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("N", DefaultValue = 100, Description = "No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue = true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutFolder
    {
        get;
        set;
    }

    [ChoDefaultCommandLineArg(IsRequired = true, Description = "Semi-colon seperated list of folders")]
    [ChoTypeConverter(typeof(ChoStringToStringArrayConverter))]
    public string[] Folders
    {
        get;
        set;
    }
}

The Folders member is the default command-line argument member. It is decorated with ChoDefaultCommandLineArgAttribute.

If the application containing above type executed with the below command line arguments

N:200 /I -O:C:\Log "C:\Source1;C:\Source2"

When creating instance of MyCommandLineArgObject as below,

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());

And run the application, the commandLineArgObject will contain the below values

-- Cinchoo.Core.CommandLineArgs.Test.MyCommandLineArgObject Dump --
 Today: 1/3/2012 4:53:00 PM
 Count: 100
 IncludeSubDir: True
 OutFolder: C:\Log
 Folders: C:\Source1; C:\Source2

Cinchoo – Command Line Argument Parser, Part 7

Inside Command Line Argument Parser – Value Converters

Here I’ll talk about the way of converting command-line argument value to the underlying member type. Most of the intrinsic types (int, bool, long etc) are converted automatically and stored to corresponding members. For others, there is no straight conversion available, you can provide Converter for them in order to convert the value to underlying member type.

Cinchoo framework provides some converters out of the box for you to use. You can also create one for your need (Will talk about on creating value converter later).

In here, I’ll will show you on how to convert comma separated string value to string array. The Folders member is decorated ChoTypeConverterAttribute with ChoStringToStringArrayConverter.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

ChoStringToStringArrayConverter takes string value, split them by ‘;’ separator to string array.

[ChoCommandLineArgObject(ApplicationName = "Hello World", Copyright = "Copyright (c) Cinchoo Inc.")]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("N", DefaultValue = 100, Description = "No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue = true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutFolder
    {
        get;
        set;
    }

    [ChoDefaultCommandLineArg(IsRequired = true, Description = "Semi-colon seperated list of folders")]
    [ChoTypeConverter(typeof(ChoStringToStringArrayConverter))]
    public string[] Folders
    {
        get;
        set;
    }
}

If the application containing above type executed with the below command line arguments

N:200 /I -O:C:\Log "C:\Source1;C:\Source2"

When creating instance of MyCommandLineArgObject as below,

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());

And run the application, the commandLineArgObject will contain the below values

-- Cinchoo.Core.CommandLineArgs.Test.MyCommandLineArgObject Dump --
 Today: 1/3/2012 4:53:00 PM
 Count: 100
 IncludeSubDir: True
 OutFolder: C:\Log
 Folders: C:\Source1; C:\Source2

Cinchoo – Command Line Argument Parser, Part 8

Inside Command Line Argument Parser – Value Converters

Here I’ll show you another way of converting command-line argument value to the underlying member type. Most of the intrinsic types (int, bool, long etc) are converted automatically and stored to corresponding members. For others, there is no straight conversion or Converters available, Cinchoo framework provides a callback mechanism where you have opportunity to convert the value to native member type.

In here, I’ll will show you on how to convert comma separated string value to string array. Define a callback method OnBeforeCommandLineArgLoadedHandler decorated with ChoBeforeCommandLineArgLoadedHandlerAttribute. In there, you can do the conversion in Value member of ChoPreviewCommandLineArgEventArgs and assign to Folders member. Make sure you set false to Cancel to tell the Cinchoo framework to stop processing this member.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

[ChoCommandLineArgObject(ApplicationName = "Hello World", Copyright = "Copyright (c) Cinchoo Inc.")]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("N", DefaultValue = 100, Description = "No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue = true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutFolder
    {
        get;
        set;
    }

    [ChoDefaultCommandLineArg(IsRequired = true, Description = "Semi-colon seperated list of folders")]
    public string[] Folders
    {
        get;
        set;
    }

    [ChoBeforeCommandLineArgLoadedHandler]
    public void OnBeforeCommandLineArgLoadedHandler(object sender, ChoPreviewCommandLineArgEventArgs args)
    {
        if (args.MemberName == "Folders")
        {
            if (args.Value is string)
            {
                string folders = args.Value as string;

                if (!folders.IsNullOrWhiteSpace())
                {
                    Folders = folders.SplitNTrim(";");
                    args.Cancel = true;
                }
            }
        }
    }
}

If the application containing above type executed with the below command line arguments

N:200 /I -O:C:\Log "C:\Source1;C:\Source2"

When creating instance of MyCommandLineArgObject as below,

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());

And run the application, the commandLineArgObject will contain the below values

-- Cinchoo.Core.CommandLineArgs.Test.MyCommandLineArgObject Dump --
 Today: 1/3/2012 4:53:00 PM
 Count: 100
 IncludeSubDir: True
 OutFolder: C:\Log
 Folders: C:\Source1; C:\Source2

Cinchoo – Command Line Argument Parser, Part 9

Inside Command Line Argument Parser – Events

In this section, I’ll brief you about list of callback event mechanism available during Command-Line argument parsing, where you can carry out custom actions to meet your needs.

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

Below are the events fired by Cinchoo framework while loading the command line arguments

Object level events
  • BeforeCommandLineArgObjectLoaded – Event fired before command line arguments are parsed and loaded.
[ChoBeforeCommandLineArgObjectLoadedHandler]
public void OnBeforeCommandLineArgObjectLoadedHandler(object sender, ChoPreviewCommandLineArgObjectEventArgs args)
{
    args.Cancel = false;
}
  • AfterCommandLineArgObjectLoaded – Event fired after command line arguments are parsed and loaded successfully.
[ChoAfterCommandLineArgObjectLoadedHandler]
public void OnAfterCommandLineArgObjectLoadedHandler(object sender, ChoCommandLineArgObjectEventArgs args)
{
}
  • CommandLineArgObjectLoadError – Event fired when there was exception found while parsing the command line arguments.
[ChoCommandLineArgObjectLoadErrorHandler]
public void OnCommandLineArgObjectLoadError(object sender, ChoCommandLineArgObjectErrorEventArgs args)
{
    Exception ex = args.Exception;
    args.Handled = true;
}
Member level events
  • BeforeCommandLineArgLoaded – Event fired before each command-line argument member loaded.
[ChoBeforeCommandLineArgLoadedHandler]
public void OnBeforeCommandLineArgLoadedHandler(object sender, ChoPreviewCommandLineArgEventArgs args)
{
    if (args.MemberName == "Folders")
    {
        if (args.Value is string)
        {
            string folders = args.Value as string;

            if (!folders.IsNullOrWhiteSpace())
            {
                Folders = folders.SplitNTrim(";");
                args.Cancel = true;
            }
        }
    }
}
  • AfterCommandLineArgLoaded – Event fired after each command-line argument member loaded successfully.
[ChoAfterCommandLineArgLoadedHandler]
public void OnAfterCommandLineArgLoadedHandler(object sender, ChoCommandLineArgEventArgs args)
{
    if (args.MemberName == "Folders")
    {
    }
}
  • CommandLineArgLoadError – Event fired when there was error while loading command-line argument member.
[ChoCommandLineArgObjectLoadErrorHandler]
public void OnCommandLineArgObjectLoadError(object sender, ChoCommandLineArgObjectErrorEventArgs args)
{
    Exception ex = args.Exception;
    args.Handled = true;
}
  • CommandLineArgMemberNotFound – Event fired when there is no command-line member defined for a command-line switch.
[ChoCommandLineArgMemberNotFoundHandler]
public void OnCommandLineArgMemberNotFoundHandler(object sender, ChoCommandLineArgNotFoundEventArgs args)
{
    string cmdLineArgSwitch = args.CmdLineArgSwitch;
    string cmdLineArgValue = args.CmdLineArgValue;
}
  • UnrecognizedCommandLineArgFound – Event fired when there is an unrecognized command line switch found.
[ChoUnrecognizedCommandLineArgFoundHandler]
public void OnUnrecognizedCommandLineArgFoundHandler(object sender, ChoUnrecognizedCommandLineArgEventArg args)
{
    string cmdLineArgValue = args.CmdLineArgValue;
}

Cinchoo – Command Line Argument Parser, Part 10

Inside Command Line Argument Parser – Parameterized Arguments

Sometimes you may want to pass and assign parameterized dynamic value to command line argument. Cinchoo framework addresses this need.

Let say, you want to pass current date time as command line argument, you can do so as below

N:200 /I -O:C:\Log -D:%NOW%

1. Add a reference to Cinchoo.Core.dll

2. Namespace: Cinchoo.Core.Shell

Cinchoo framework looks into the %NOW% command line argument value, replaces and assigns current date time to corresponding member (Today).

[ChoCommandLineArgObject(ApplicationName = "Hello World", Copyright = "Copyright (c) Cinchoo Inc.")]
public class MyCommandLineArgObject : ChoCommandLineArgObject
{
    [ChoCommandLineArg("D", DefaultValue = "%NOW%", Description = "Business Date.", ShortName = "Today")]
    public DateTime Today
    {
        get;
        set;
    }

    [ChoCommandLineArg("N", DefaultValue = 100, Description = "No of spaces for a TAB.")]
    public int Count
    {
        get;
        set;
    }

    [ChoCommandLineArg("I", DefaultValue = false, FallbackValue = true, Description = "Include Sub directory.")]
    public bool IncludeSubDir
    {
        get;
        set;
    }

    [ChoCommandLineArg("O", IsRequired = true, Description = "Output Directory.")]
    public string OutFolder
    {
        get;
        set;
    }
}

If the application containing above type executed with the below command line arguments

N:200 /I -O:C:\Log -D:%NOW%

When creating instance of MyCommandLineArgObject as below,

MyCommandLineArgObject commandLineArgObject = new MyCommandLineArgObject();
Console.WriteLine(commandLineArgObject.ToString());

And run the application, the commandLineArgObject will contain the below values

Hello World [Version 1.0.0.0]
Copyright (c) Cinchoo Inc.

-- Cinchoo.Core.CommandLineArgs.Test.MyCommandLineArgObject Dump --
Today: 1/6/2012 12:32:00 PM
Count: 200
IncludeSubDir: True
OutFolder: C:\Log

In next section, I’ll list you the possible properties available in Cinchoo framework for use…


Follow

Get every new post delivered to your Inbox.