/// <summary> /// Method that parses the supplied arguments which typically are supplied from the command line. /// </summary> /// <returns>An instance of <typeparamref name="TOptions"/> with values populated according to the inputs /// supplied by the user.</returns> /// <param name="arguments">A set of parameters provided by the user on the command line.</param> /// <exception cref="OptionRequiredException"/> /// <example> /// <code>MyApplicationOptions Parse("name=usera password=pwd")</code> /// </example> public TOptions Parse(params string [] arguments) { TOptions options = new TOptions(); // Parse the arguments and apply the default values to the options. _arguments.SetDefaults(options); // If there are any command line arguments supplied, then process them into the options file... if (arguments != null && arguments.Count() > 0) { OnParse(options, arguments); } else { // No arguments have been supplied, so check that there aren't any defaults that have been skipped. PropertyArgumentAttribute attribute = _arguments.FirstOrDefault(required => required.Required); if (attribute != null) { throw new OptionRequiredException(string.Format("Switch/Parameter '{0}' is required.", attribute.ParameterName)); } } return(options); }
/// <summary> /// Method that sets up the command line arguments set. /// </summary> /// <returns></returns> public static CommandLineArguments <TOptions> Setup() { Type optionsType = typeof(TOptions); CommandLineOptionsAttribute options = optionsType.GetCustomAttributes(typeof(CommandLineOptionsAttribute), true).Cast <CommandLineOptionsAttribute>().FirstOrDefault(); // Walk all of the properties in the options file. PropertyInfo [] properties = optionsType.GetProperties(); List <PropertyArgumentAttribute> arguments = new List <PropertyArgumentAttribute>(); foreach (PropertyInfo propertyInfo in properties) { PropertyArgumentAttribute attribute = propertyInfo.GetCustomAttributes(typeof(PropertyArgumentAttribute), true).Cast <PropertyArgumentAttribute>().SingleOrDefault(); if (attribute != null) { attribute.Configure(propertyInfo); arguments.Add(attribute); } } return(new CommandLineArguments <TOptions>(options, arguments)); }