3

I'm trying to see the errors that occur when parsing command-line arguments using the CommandLineParser package and Visual Studio Professional 2015 (Update 3). Here is the code I'm working with:

using System;
using System.IO;

namespace SampleParser
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set the CommandLineParser configuration options.
            var commandLineParser = new CommandLine.Parser(x =>
            {
                x.MutuallyExclusive = true;
                x.HelpWriter = Console.Error;
                x.IgnoreUnknownArguments = false;
            });

            // Parse the command-line arguments.
            var options = new CommandLineOptions();
            var optionsAreValid = commandLineParser.ParseArguments(args, options);

            if (!optionsAreValid)
            {
                return;
            }
        }
    }
}

I was expecting to see some helpful info about the problems that cause optionsAreValid to be set to false appear in the Debug > Windows > Output window. However, nothing's showing up... am I doing something wrong, am I looking in the wrong place, or are there other settings that need to be toggled before I'll see this info?

UPDATE #1

Here is the class that models the command line options after being (successfully) parsed:

namespace SampleParser
{
    class CommandLineOptions
    {
        [Option(HelpText = @"When set to ""true"", running the application will not make any changes.", Required = false)]
        public bool Preview { get; set; }


        [HelpOption]
        public string GetUsage()
        {
            return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
        }
    }
}
Mass Dot Net
  • 2,150
  • 9
  • 38
  • 50
  • Do you have rules/options defined in the `CommandLineOptions` class? – NicoE Feb 02 '17 at 20:52
  • Yes -- I just updated my OP to include the rules/options class I'm using. – Mass Dot Net Feb 03 '17 at 17:54
  • Generally you have to explicitly call Debug or Trace class methods to have output in the output window of visual studio. For your `optionsAreValid` to be true you should invoke the cmd with 'cmd --preview' or just 'cmd' with no arguments. – NicoE Feb 03 '17 at 19:17
  • How are you suggesting that I explicitly call the *Debug* or *Trace* class, so that they can "see" the validation errors that CommandLineParser is identifying? I would have thought that the `CommandLine.Parser` type's `HelpWriter` would be the key to making this happen, but I'm not sure how to accomplish what you're suggesting. – Mass Dot Net Feb 06 '17 at 15:51
  • 1
    Are "they" the end users of the application? You are correct that `HelpWriter` is the key. If the the parser cannot parse the arguments it will display the help text - this is the same information you get when you run the cmd with 'cmd --help'. I mentioned Debug/Trace since you were asking about seeing information in the visual studio output window. – NicoE Feb 06 '17 at 16:15
  • I think I might have confused things a bit. I originally assumed that `HelpWriter` would send info to the Visual Studio _"Output"_ window, but I believe I was mistaken. Rather, that seems to be how CommandLineParser gets the info it needs to write things to the console window, *not* the _"Output" window. I'm going to mark this question as answered, since your comments did help lead me to this understanding. It seems v2.0 beta of CommandLineParser does a slightly better job of exposing parsing errors it comes across; I'll follow up in GitHub with further questions. Thank you! – Mass Dot Net Feb 06 '17 at 18:19

2 Answers2

16

I know this is a very old question, but it is still ranked first result in google for my particular search. Since there is no satisfying solution given, I'm going to add one:

To just print the errors you can use the SentenceBuilder provided by the library itself:

using System;
using CommandLine;
using CommandLine.Text;

...

var result = Parser.Default.ParseArguments<Options>(args);
result
    .WithParsed(opt => ...)
    .WithNotParsed(errors => {
        var sentenceBuilder = SentenceBuilder.Create();
        foreach (var error in errors)
            Console.WriteLine(sentenceBuilder.FormatError(error));
    });

To print the full help information including the errors encountered use the following:

using System;
using CommandLine;
using CommandLine.Text;

...

var result = Parser.Default.ParseArguments<Options>(args);
result
    .WithParsed(opt => ...)
    .WithNotParsed(errors => {
        var helpText = HelpText.AutoBuild(result,
                                          h => HelpText.DefaultParsingErrorsHandler(result, h), 
                                          e => e);
        Console.WriteLine(helpText);
    });

I hope this helps someone in the future!

jswolf19
  • 2,303
  • 15
  • 16
Simon
  • 1,244
  • 8
  • 21
2

I mistakenly assumed that the HelpText property would send info to the Visual Studio Output window; however, I was wrong. Instead, it's how the CommandLineParser gets the info it needs to write info to the console window, which pops up when running a console application project (tx @NicoE ).

Here is some boilerplate code (targeting the v2.1.1-beta NuGet package) which, while still not giving me as much info as I'd like about parser errors, exposes them in a fashion that is easier for me to handle programmatically.

// Set the CommandLineParser configuration options.
var commandLineParser = new CommandLine.Parser(x =>
{
    x.HelpWriter = null;
    x.IgnoreUnknownArguments = false;
    //x.CaseSensitive = false;
});

// Parse the command-line arguments.
CommandLineOptions options;
var errors = new List<CommandLine.Error>();

var parserResults = commandLineParser.ParseArguments<CommandLineOptions>(args)
    .WithNotParsed(x => errors = x.ToList())
    .WithParsed(x => options = x)
;

if (errors.Any())
{
    errors.ForEach(x => Console.WriteLine(x.ToString()));
    Console.ReadLine();
    return;
}
Community
  • 1
  • 1
Mass Dot Net
  • 2,150
  • 9
  • 38
  • 50