public static FlexibleOptions Initialize(string[] args, bool thrownOnError, InitializationOptions options = null) { InitOptions = options; DefaultProgramInitialization(); ProgramOptions = CheckCommandLineParams(args, thrownOnError); if (ProgramOptions.Get <bool> ("help", false) || ProgramOptions.Get <bool> ("h", false)) { show_help(""); CloseApplication(0, true); } // display program initialization header if (!Console.IsOutputRedirected) { ConsoleUtils.DisplayHeader( typeof(ConsoleUtils).Namespace.Replace(".SimpleHelpers", ""), "options: " + (ProgramOptions == null ? "none" : "\n# " + String.Join("\n# ", ProgramOptions.Options.Select(i => i.Key + "=" + i.Value)))); } else { var logger = GetLogger(); if (logger.IsDebugEnabled) { logger.Debug("options: " + (ProgramOptions == null ? "none" : "\n# " + String.Join("\n# ", ProgramOptions.Options.Select(i => i.Key + "=" + i.Value)))); } } return(ProgramOptions); }
private static FlexibleOptions parseFile(string content) { var options = new FlexibleOptions(); // detect xml if (content.TrimStart().StartsWith("<")) { var xmlDoc = System.Xml.Linq.XDocument.Parse(content); var root = xmlDoc.Descendants("config").FirstOrDefault(); if (root != null && root.HasElements) { foreach (var i in root.Elements()) { options.Set(i.Name.ToString(), i.Value); } } } else { var json = Newtonsoft.Json.Linq.JObject.Parse(content); foreach (var i in json) { options.Set(i.Key, i.Value.ToString(Newtonsoft.Json.Formatting.None)); } } return(options); }
/// <summary> /// Merge together FlexibleOptions instances, the last object in the list has priority in conflict resolution (overwrite). /// </summary> /// <param name="items"></param> /// <returns></returns> public static FlexibleOptions Merge(params FlexibleOptions[] items) { var merge = new FlexibleOptions(); if (items != null) { foreach (var i in items) { if (i == null) { continue; } foreach (var o in i.Options) { merge.Options[o.Key] = o.Value; } } } return(merge); }
private static FlexibleOptions ParseCommandLineArguments(string[] args) { var argsOptions = new FlexibleOptions(); if (args != null) { string arg; bool openTag = false; string lastTag = null; for (int ix = 0; ix < args.Length; ix++) { arg = args[ix]; // check for option with key=value sintax (restriction: the previous tag must not be an open tag) // also valid for --key:value bool hasStartingMarker = arg.StartsWith("-", StringComparison.Ordinal) || arg.StartsWith("/", StringComparison.Ordinal); int p = arg.IndexOf('='); if (p > 0 && (hasStartingMarker || !openTag)) { argsOptions.Set(arg.Substring(0, p).Trim().TrimStart('-', '/'), arg.Substring(p + 1).Trim()); lastTag = null; openTag = false; } // search for tag stating with special character else if (hasStartingMarker) { lastTag = arg.Trim().TrimStart('-', '/'); argsOptions.Set(lastTag, "true"); openTag = true; } // set value of last tag else if (lastTag != null) { argsOptions.Set(lastTag, arg.Trim()); openTag = false; } } } return(argsOptions); }
/// <summary> /// Initializes a new instance of the <see cref="FlexibleOptions" /> class. /// </summary> /// <param name="instance">Another FlexibleObject instance to be cloned.</param> /// <param name="caseInsensitive">If the intenal dictionary should have case insensitive keys.</param> public FlexibleOptions(FlexibleOptions instance, bool caseInsensitive) { _caseInsensitive = caseInsensitive; _options = new Dictionary <string, string> (instance.Options, _caseInsensitive ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); }
/// <summary> /// Checks the command line params.<para/> /// arguments format: key=value or --key value /// </summary> /// <param name="args">The args.</param> internal static FlexibleOptions CheckCommandLineParams(string[] args, bool thrownOnError) { FlexibleOptions mergedOptions = null; FlexibleOptions argsOptions = null; FlexibleOptions localOptions = new FlexibleOptions(); FlexibleOptions externalLoadedOptions = null; try { // parse local configuration file // display the options listed in the configuration file try { var appSettings = System.Configuration.ConfigurationManager.AppSettings; foreach (var k in appSettings.AllKeys) { localOptions.Set(k, appSettings[k]); } } catch (Exception appSettingsEx) { if (thrownOnError) { throw; } GetLogger().Warn(appSettingsEx); } // parse console arguments // parse arguments like: key=value argsOptions = ParseCommandLineArguments(args); // merge arguments with app.config options. Priority: arguments > app.config mergedOptions = FlexibleOptions.Merge(localOptions, argsOptions); // adjust alias for web hosted configuration file if (String.IsNullOrEmpty(mergedOptions.Get("config"))) { mergedOptions.Set("config", mergedOptions.Get("S3ConfigurationPath", mergedOptions.Get("webConfigurationFile"))); } // load and parse web hosted configuration file (priority order: argsOptions > localOptions) string externalConfigFile = mergedOptions.Get("config", ""); bool configAbortOnError = mergedOptions.Get("configAbortOnError", true); if (!String.IsNullOrWhiteSpace(externalConfigFile)) { foreach (var file in externalConfigFile.Trim(' ', '\'', '"', '[', ']').Split(',', ';')) { GetLogger().Debug("Loading configuration file from {0} ...", externalConfigFile); externalLoadedOptions = FlexibleOptions.Merge(externalLoadedOptions, LoadExtenalConfigurationFile(file.Trim(' ', '\'', '"'), configAbortOnError)); } } } catch (Exception ex) { // initialize log before dealing with exceptions if (mergedOptions != null) { InitializeLog(mergedOptions.Get("logFilename"), mergedOptions.Get("logLevel", "Info"), InitOptions); } if (thrownOnError) { throw; } GetLogger().Error(ex); } // merge options with the following priority: // 1. console arguments // 2. web configuration file // 3. local configuration file (app.config or web.config) mergedOptions = FlexibleOptions.Merge(mergedOptions, externalLoadedOptions, argsOptions); // reinitialize log options if different from local configuration file InitializeLog(mergedOptions.Get("logFilename"), mergedOptions.Get("logLevel", "Info"), InitOptions); // return final merged options ProgramOptions = mergedOptions; return(mergedOptions); }