demo
demo

Reputation: 6235

How to use Command Line Parser Library in case Error happend?

I use Command Line Parser Library to parse command lines parameters.

I have declared class Options

internal class Options
{
    [Option('r', "read", Required = true,
        HelpText = "Input file to be processed.")]
    public string InputFile { get; set; }

    [Option('f', "date from", Required = false,
        HelpText = "Date from which get statistic.")]
    public string DateFrom { get; set; }

    [Option('t', "date to", Required = false,
        HelpText = "Date to which get statistic.")]
    public string DateTo { get; set; }

    [Option('v', "verbose", DefaultValue = true,
        HelpText = "Prints all messages to standard output.")]
    public bool Verbose { get; set; }

    [ParserState]
    public IParserState LastParserState { get; set; }

    [HelpOption]
    public string GetUsage()
    {
        return HelpText.AutoBuild(this,
            (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
    }
}

And this is how i try to use Parser :

private static void Main(string[] args)
    {
        Console.WriteLine("Hello and welcome to a test application!");

        string filePath = string.Empty;
        string fromDate = string.Empty, toDate = string.Empty;
        DateTime dateTo, dateFrom;

        Console.ReadLine();

        var options = new Options();
        if (CommandLine.Parser.Default.ParseArguments(args, options))
        {
            // Values are available here
            if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile);

            if (string.IsNullOrWhiteSpace(options.InputFile))
            {
                filePath = ConfigurationManager.AppSettings["FilePath"];
                if (string.IsNullOrWhiteSpace(filePath))
                {
                    filePath = Directory.GetCurrentDirectory() + @"\Report.xlsx";
                }
            }
            else
            {
                filePath = options.InputFile;
            }
            fromDate = string.IsNullOrWhiteSpace(options.DateFrom)
                ? ConfigurationManager.AppSettings["DateFrom"]
                : options.DateFrom;
            toDate = string.IsNullOrWhiteSpace(options.DateTo) ? ConfigurationManager.AppSettings["DateTo"] : options.DateTo;
        }
        else
        {
            return;
        }

//other code }

But in case of some error application just stop working.

So i want to know how to repeat first step of inputting values in case of error.

while (!CommandLine.Parser.Default.ParseArguments(args, options)){...} - makes loop

Upvotes: 2

Views: 6415

Answers (1)

Steven Scott
Steven Scott

Reputation: 11250

I use the Command Line Parser as such.

Declare a common wrapper for multiple projects

public class CommandLineOptions
{
    public const bool CASE_INSENSITIVE = false;
    public const bool CASE_SENSITIVE = true;
    public const bool MUTUALLY_EXCLUSIVE = true;
    public const bool MUTUALLY_NONEXCLUSIVE = false;
    public const bool UNKNOWN_OPTIONS_ERROR = false;
    public const bool UNKNOWN_OPTIONS_IGNORE = true;

    public CommandLineOptions();

    public string[] AboutText { get; set; }
    [ParserState]
    public IParserState LastParserState { get; set; }

    [HelpOption(HelpText = "Display this Help Screen")]
    public virtual string GetUsage();
    public bool ParseCommandLine(string[] Args);
    public bool ParseCommandLine(string[] Args, bool IgnoreUnknownOptions);
    public bool ParseCommandLine(string[] Args, bool IgnoreUnknownOptions, bool EnableMutuallyExclusive);
    public bool ParseCommandLine(string[] Args, bool IgnoreUnknownOptions, bool EnableMutuallyExclusive, bool UseCaseSensitive);
}

Create an Application Command Line class for this application

public class ApplicationCommandLine : CommandLineOptions
{
    [Option('d', "download", HelpText = "Download Items before running")]
    virtual public bool Download { get; set; }

    [Option('g', "generate", HelpText = "Generate Mode (Generate New Test Results)", MutuallyExclusiveSet = "Run-Mode")]
    virtual public bool GenerateMode { get; set; }

    [Option('r', "replay", HelpText = "Replay Mode (Run Test)", MutuallyExclusiveSet = "Run-Mode")]
    virtual public bool ReplayMode { get; set; }
}

Main Program:

ApplicationCommandLine AppCommandLine = new ApplicationCommandLine();

try
{
    // Parsers and sets the variables in AppCommandLine
    if (AppCommandLine.ParseCommandLine(args))
    {
        // Use the Download option from the command line.
        if (AppCommandLine.Download) { 
            DataFileDownload();
        }
        if (AppCommandLine.GenerateMode) { 
            GenerateProcessingData();
        }

        ...

    }
}

catch (Exception e)
{
    ...
}

Upvotes: 2

Related Questions