Demo4 - Custom Extensions

This demo illustrates how to extend CLArgs functionality to meet your custom needs.

Custom Context property type

Imagin you want a Context with a property having custom type that is not supported out of the box. There is no built-in converter to convert command-line arguments into a property of type DirectoryInfo, and we need to create and register a custom converter.

public class Demo4Context
{
 [OptionDescriptor("Directory", new []{"Dir", "d"}, helpText : "Specify an existing directory." )]
 public DirectoryInfo? Dir { get; set; }
}

Define the custom DirectoryInfo converter

/// <summary>
/// Custom argument to DirectoryInfo converter.
/// </summary>
public class DirectoryInfoConverter : IArgumentConverter
{
    public object Convert(string optionValue, string optionName, ErrorDetailList errors, Type targetType)
    {
        if( !Directory.Exists(optionValue))
            errors.AddError(optionName, $"The specified directory does not exist: '{optionValue}'.");
        
        return new DirectoryInfo(optionValue);
    }
}

Register the custom during start-up using ContextBuilderConfigureConverters.

//...
var host = CommandHostBuilder.Create(args).Build();

ContextBuilder cb = host.Services.GetRequiredService<ContextBuilder>();
cb.ConfigureConverters( converters =>converters.AddCustomConverter(
    typeof(DirectoryInfo), new DirectoryInfoConverter()));
    
// The ContextBuilder.Build() is called implicitly right before the Command executes.
host.Run();
protected override void Execute()
{
    Console.WriteLine($"Directory full-name: {this.Context.Dir!.FullName}");
    Console.WriteLine($"Directory parent: {this.Context.Dir!.Parent}");
}

> demo4App.exe ARGS DEMO1 /d c:\\windows
Directory full-name: c:\windows
Directory parent: c:\

Custome validation

Use the erroscollection instead of throwing exception if you want to collect and return multiple error results.

if( optionValue.Length< 3) 
        errors.AddError(optionName, "Option value is too short!");
if( !Directory.Exists(optionValue))
        errors.AddError(optionName, $"The specified directory does not exist: '{optionValue}'.");

Last updated