Beispiel #1
0
        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);
        }
Beispiel #3
0
        private static FlexibleOptions ParseCommandLineArguments(string[] args)
        {
            var argsOptions = new FlexibleOptions();

            if (args != null)
            {
                string arg;
                string lastTag = null;
                for (int ix = 0; ix < args.Length; ix++)
                {
                    arg = args[ix];
                    // check for option with key=value sintax
                    // also valid for --key:value
                    int p = arg.IndexOf('=');
                    if (p > 0)
                    {
                        argsOptions.Set(arg.Substring(0, p).Trim().TrimStart('-', '/'), arg.Substring(p + 1).Trim());
                        lastTag = null;
                        continue;
                    }

                    // search for tag stating with special character
                    if (arg.StartsWith("-", StringComparison.Ordinal) || arg.StartsWith("/", StringComparison.Ordinal))
                    {
                        lastTag = arg.Trim().TrimStart('-', '/');
                        argsOptions.Set(lastTag, "true");
                        continue;
                    }

                    // set value of last tag
                    if (lastTag != null)
                    {
                        argsOptions.Set(lastTag, arg.Trim());
                    }
                }
            }
            return(argsOptions);
        }
Beispiel #4
0
        public static FlexibleOptions Initialize(string[] args, bool thrownOnError)
        {
            DefaultProgramInitialization();

            InitializeLog();

            ProgramOptions = CheckCommandLineParams(args, thrownOnError);

            if (ProgramOptions.Get <bool> ("help", 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))));
            }

            return(ProgramOptions);
        }
 /// <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);
 }
Beispiel #6
0
        /// <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;
                    }
                    LogManager.GetCurrentClassLogger().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(',', ';'))
                    {
                        LogManager.GetCurrentClassLogger().Info("Loading configuration file from {0} ...", externalConfigFile);
                        externalLoadedOptions = FlexibleOptions.Merge(externalLoadedOptions, LoadExtenalConfigurationFile(file.Trim(' ', '\'', '"'), configAbortOnError));
                    }
                }
            }
            catch (Exception ex)
            {
                if (thrownOnError)
                {
                    throw;
                }
                LogManager.GetCurrentClassLogger().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"));

            // return final merged options
            ProgramOptions = mergedOptions;
            return(mergedOptions);
        }