This project is read-only.

Defining the application options

Previous: Setting up the project | Table of contents | Next: Defining the application arguments

The next step is to define the options of the application.

/verbose - Generate verbose output

Specifying this option will cause the application to generate detailed output to the console as it runs. This is a simple option that does not need any additional data; the application's behavior changes based on presence of the option... in this case, detailed output if the option is specified, no detailed output if the option is not specified.

Before we add code to define the /verbose option, we must first define a boolean variable that will store whether we need to generate verbose output or not. This can be a field or property, but must be static. This variable will be used in the Handler method as part of the backup logic.

private static bool VerboseOutput;

Next, to define the /verbose option, we use the AddOption method of the ConsoleProgram class.

app.AddOption("verbose", "v");
  • The first parameter is the name of the option, in this case "verbose".
  • The second parameter is optional, and can specify a shorter alternative name for the option; in this case "v".
  • There are many additional named parameters for the AddOption method, which can control the behavior of the option. We will cover some of these parameters later in this section. For the /verbose option, the default values should suffice.

Next, we specify what to do if the /verbose option is specified. In this case, we simply want to set the VerboseOutput boolean field to true. ConsoleFx provides a method called Flag that can be used to set boolean variables easily, based on the presence of an option.

app.AddOption("verbose", "v")
    .Flag(() => VerboseOutput);

/type - Backup type

The /type option specifies the type of backup we want to perform. This can either be a full backup or an incremental backup. If this option is not specified, we default to a full backup.

Before we start defining this option, let's create an enum to specify the backup types:

public enum BackupType
{
    Full,
    Incremental,
}

Next, just like we did for the /verbose option, we declare a static field of type BackupType that will contain the backup type. We initialize it to the default backup type, which is Full, in case it isn't specified on the command-line.

private static BackupType BackupType = BackupType.Full;

Now, define the option for backup type using the AddOption method:

app.AddOption("type", "t", expectedParameters: 1);
  • Here we see one of the additional parameters that can be specified in the AddOption method. expectedParameters specifies the number of parameters we want passed along with the option. In this case, we expect one parameter, which will specify either Full or Incremental.

Now that we've started using parameters, we need to be able to validate them and ensure that only valid values are specified. ConsoleFx provides an extensible validation framework to create parameter validators. It also provides a set of built-in validators that cover most validation needs.

In this case, we want the parameter for the /type option to be a value from the BackupType enum, i.e. Full or Incremental. To validate this parameter, we use the EnumValidator class from the ConsoleFx.Validators namespace.

To validate a parameter, we use ConsoleFx's ValidateWith method, in which we specify the validator we want to use and optionally the index of the parameter we want to validate. If the parameter index is omitted, the first parameter is validated.

app.AddOption("type", "t", expectedParameters: 1)
    .ValidateWith(new EnumValidator<BackupType> { ErrorMessage: "Invalid backup type. Specify Full or Incremental" });
  • All validator classes allow their validation error messages to be customized, either through optional parameters in the constructor (or factory method) or through properties. See the validator reference for more details.

Finally, if the option is specified on the command-line, we need to set the BackupType static field with the right value. This is done with the AssignTo method.

app.AddOption("type", "t", expectedParameters: 1)
    .ValidateWith(EnumValidator.Create<BackupType>(errorMessage: "Invalid backup type. Specify Full or Incremental"))
    .AssignTo(() => BackupType);
  • AssignTo can automatically assign values to any primitive type (int, long, byte, etc.), strings or enumeration types. For other types, AssignTo provides an optional Converter<string, T> parameter that can be used to do a custom conversion.

/exclude - Exclude files from the backup

The final option, /exclude, is used for excluding files from the backup process. It can accept any number of parameters (separated by commas), each parameter specifying a file name or a DOS file mask. For example, to exclude all image files, you could specify the option like so:

/exclude:*.png,*.bmp,*.gif,*.jpg

In addition, to aid in typing in a lot of file exclusions, the option can be specified more than once on the command-line like so:

/exclude:*.png,*.bmp,*.gif,*.jpg /exclude:*.exe,*.dll

As usual, we start by declaring a static field to hold the list of excluded file names and masks. Since we can have multiple exclusions, we will declare this field as a List<string>.

private static readonly List<string> Exclusions = new List<string>();

Next, we define the option, give it a description and assign a regular expression validator for all the parameters:

app.AddOption("exclude", "e", maxOccurences: int.MaxValue, minParameters: 1, maxParameters: int.MaxValue)
    .ValidateWith(ParameterIndex.All, new RegexValidator(@"^[\w.*?]+$"));
  • This code demonstrates some additional optional parameters that can be specified with the AddOption method. The option can occur any number of times on the command-line, and for each occurence, it should have at least one parameter.
  • The ValidateWith method accepts a value to specify the index of the parameter on which to perform the validation. In this case, the special constant ParameterIndex.All indicates that the validation should be performed for all parameters.

In order to add each exclusion item to the Exclusions field, we use ConsoleFx's AddToList method, which is similar to the AssignTo method, but instead of directly assigning the parameter value to the specified property, it assumes that the property is a collection and adds the parameter value to it:

app.AddOption("exclude", "e", maxOccurences: int.MaxValue, minParameters: 1, maxParameters: int.MaxValue)
    .ValidateWith(ParameterIndex.All, new RegexValidator(@"^[\w.*?]+$"))
    .AddToList(() => Excludes);

Full code at this time

using System;
using System.Collections.Generic;

using ConsoleFx;
using ConsoleFx.Programs.Simple;
using ConsoleFx.Validators;

namespace Backup
{
    internal static class Program
    {
        private static int Main()
        {
            var app = new ConsoleProgram(Handler);
            try
            {
                app.AddOption("verbose", "v")
                    .Flag(() => VerboseOutput);
                app.AddOption("type", "t", expectedParameters: 1)
                    .ValidateWith(new EnumValidator<BackupType> { ErrorMessage: "Invalid backup type. Specify Full or Incremental" })
                    .AssignTo(() => BackupType);
                app.AddOption("exclude", "e", maxOccurences: int.MaxValue, minParameters: 1, maxParameters: int.MaxValue)
                    .ValidateWith(ParameterIndex.All, new RegexValidator(@"^[\w.*?]+$"))
                    .AddToList(() => Excludes);
                return app.Run();
            }
            catch (Exception ex)
            {
                return app.HandleException(ex);
            }
        }

        private static int Handler()
        {
            return 0;
        }

        private static bool VerboseOutput;
        private static BackupType BackupType;
        private static readonly List<string> Exclusions = new List<string>();
    }

    public enum BackupType
    {
        Full,
        Incremental,
    }
}

Previous: Setting up the project | Table of contents | Next: Defining the application arguments

Last edited Jun 22, 2012 at 1:25 PM by jeevanjj, version 6

Comments

andreymir Oct 15, 2014 at 8:02 AM 
Should be
return app.HandleError(ex);