예제 #1
0
        public void ExpandKeyValuesMerge()
        {
            StringWriter writer = new StringWriter();

            writer.WriteLine("[web]");
            writer.WriteLine(" protocol = http");
            writer.WriteLine("[server]");
            writer.WriteLine(" domain1 = ${web|protocol}://nini.sf.net/");
            IniConfigSource source = new IniConfigSource
                                         (new StringReader(writer.ToString()));

            StringWriter newWriter = new StringWriter();

            newWriter.WriteLine("[web]");
            newWriter.WriteLine(" apache = Apache implements ${protocol}");
            newWriter.WriteLine("[server]");
            newWriter.WriteLine(" domain2 = ${web|protocol}://nini.sf.net/");
            IniConfigSource newSource = new IniConfigSource
                                            (new StringReader(newWriter.ToString()));

            source.Merge(newSource);
            source.ExpandKeyValues();

            IConfig config = source.Configs["web"];

            Assert.AreEqual("http", config.Get("protocol"));
            Assert.AreEqual("Apache implements http", config.Get("apache"));
            config = source.Configs["server"];
            Assert.AreEqual("http://nini.sf.net/", config.Get("domain1"));
            Assert.AreEqual("http://nini.sf.net/", config.Get("domain2"));
        }
예제 #2
0
        /*
         * public static Form StartGui(IConfig config, ViewerProxy form, Func<Form> createForm) {
         *  if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) {
         *      Form f = createForm();
         *      StartProxyClient(config, form, f);
         *      f.ShowDialog();
         *      return f;
         *  } else {
         *      object createLock = new object();
         *      Form f = null;
         *      bool started = false;
         *      Thread t = new Thread(() => {
         *          f = createForm();
         *          lock (createLock)
         *              MonitorChanged.PulseAll(createLock);
         *          started = true;
         *          StartProxyClient(config, form, f);
         *          f.ShowDialog();
         *      });
         *      t.SetApartmentState(ApartmentState.STA);
         *      t.Begin();
         *      if (!started)
         *          lock (createLock)
         *              MonitorChanged.Wait(createLock);
         *      return f;
         *  }
         * }
         *
         * private static void StartProxyClient(IConfig config, ViewerProxy form, Form f) {
         *  f.VisibleChanged += (source, args) => {
         *      if (!f.Visible)
         *          return;
         *      bool autostartProxy = Get(config, "AutoStartProxy", false);
         *      bool autostartClient = Get(config, "AutoStartClient", false);
         *
         *      if (autostartProxy || autostartClient)
         *          while (!form.StartProxy())
         *              form.ProxyConfig.ProxyPort++;
         *      if (autostartClient)
         *          form.StartClient();
         *  };
         * }
         */

        public static IConfigSource AddFile(IConfigSource config, string file)
        {
            if (File.Exists(file) && Path.GetExtension(file).ToUpper().Equals(".CONFIG"))
            {
                try {
                    DotNetConfigSource dotnet = new DotNetConfigSource(file);
                    //config.Merge(dotnet);
                    dotnet.Merge(config);
                    return(dotnet);
                } catch (Exception e) {
                    Logger.Warn("Unable to load app configuration file " + file + "'." + e.Message + ".\n" + e.StackTrace);
                }
            }
            else if (File.Exists(file) && Path.GetExtension(file).ToUpper().Equals(".INI"))
            {
                try {
                    IniDocument     doc = new IniDocument(file, IniFileType.WindowsStyle);
                    IniConfigSource ini = new IniConfigSource(doc);
                    //config.Merge(ini);
                    ini.Merge(config);
                    return(ini);
                } catch (Exception e) {
                    Logger.Warn("Unable to load ini configuration file " + file + "'." + e.Message + ".\n" + e.StackTrace);
                }
            }
            return(config);
        }
예제 #3
0
        public void MergeAndSave()
        {
            string fileName = "NiniConfig.ini";

            StreamWriter fileWriter = new StreamWriter(fileName);

            fileWriter.WriteLine("[Pets]");
            fileWriter.WriteLine("cat = Muffy");  // overwrite
            fileWriter.WriteLine("dog = Rover");  // new
            fileWriter.WriteLine("bird = Tweety");
            fileWriter.Close();

            StringWriter writer = new StringWriter();

            writer.WriteLine("[Pets]");
            writer.WriteLine("cat = Becky");     // overwrite
            writer.WriteLine("lizard = Saurus"); // new
            writer.WriteLine("[People]");
            writer.WriteLine(" woman = Jane");
            writer.WriteLine(" man = John");
            IniConfigSource iniSource = new IniConfigSource
                                            (new StringReader(writer.ToString()));

            IniConfigSource source = new IniConfigSource(fileName);

            source.Merge(iniSource);

            IConfig config = source.Configs["Pets"];

            Assert.AreEqual(4, config.GetKeys().Length);
            Assert.AreEqual("Becky", config.Get("cat"));
            Assert.AreEqual("Rover", config.Get("dog"));
            Assert.AreEqual("Saurus", config.Get("lizard"));

            config = source.Configs["People"];
            Assert.AreEqual(2, config.GetKeys().Length);
            Assert.AreEqual("Jane", config.Get("woman"));
            Assert.AreEqual("John", config.Get("man"));

            config.Set("woman", "Tara");
            config.Set("man", "Quentin");

            source.Save();

            source = new IniConfigSource(fileName);

            config = source.Configs["Pets"];
            Assert.AreEqual(4, config.GetKeys().Length);
            Assert.AreEqual("Becky", config.Get("cat"));
            Assert.AreEqual("Rover", config.Get("dog"));
            Assert.AreEqual("Saurus", config.Get("lizard"));

            config = source.Configs["People"];
            Assert.AreEqual(2, config.GetKeys().Length);
            Assert.AreEqual("Tara", config.Get("woman"));
            Assert.AreEqual("Quentin", config.Get("man"));

            File.Delete(fileName);
        }
예제 #4
0
        public void MergeItself()
        {
            StringWriter writer = new StringWriter();

            writer.WriteLine("[People]");
            writer.WriteLine(" woman = Jane");
            writer.WriteLine(" man = John");
            IniConfigSource iniSource =
                new IniConfigSource(new StringReader(writer.ToString()));

            iniSource.Merge(iniSource);  // exception
        }
예제 #5
0
        public Config()
        {
            var configSource = new IniConfigSource();

            configSource.AutoSave = true;

            CreateOrLoadIniConfig(configSource);
            havenConfig = configSource.Configs["haven"] ?? configSource.AddConfig("haven");

            var commandLineConfigSource = LoadCommandLineConfig();

            configSource.Merge(commandLineConfigSource);
        }
예제 #6
0
        // We call this from our plugin module to get our configuration
        public IConfig GetConfig()
        {
            IConfig config = null;

            config = ServerUtils.GetConfig(ConfigFile, ConfigName);

            // Our file is not here? We can get one to bootstrap our plugin module
            if (config == null)
            {
                IConfigSource remotesource = GetConfigSource();

                if (remotesource != null)
                {
                    IniConfigSource initialconfig = new IniConfigSource();
                    initialconfig.Merge(remotesource);
                    initialconfig.Save(ConfigFile);
                }

                config = remotesource.Configs[ConfigName];
            }

            return(config);
        }
예제 #7
0
        private static Settings GetSettingsFromIniFiles()
        {
            FileInfo defaultConfigFile = new FileInfo("conf/default.ini");

            if (!defaultConfigFile.Exists)
            {
                log.Fatal("The default config file at conf/default.ini does not exist");
                throw new Exception("The default config file at conf/default.ini does not exist");
            }

            IConfigSource baseConfig = new IniConfigSource(new IniDocument("conf/default.ini", IniFileType.MysqlStyle));

            List <String> userConfigFiles = new List <String>(Directory.GetFiles("userconf", "*.ini"));

            userConfigFiles.Sort();
            userConfigFiles.ForEach(f => baseConfig.Merge(new IniConfigSource(new IniDocument(f, IniFileType.MysqlStyle))));
            AddConfigAliasses(baseConfig);

            Settings settings = GetSettingsFromMergedIni(baseConfig);

            LoadFolderConfigs(settings);

            return(settings);
        }
예제 #8
0
        public ConfigurationLoader(string masterConfigLocation, string overridesConfigLocation)
        {
            #region Overrides File Creation

            // Create the user config include file if it doesn't exist to
            // prevent a warning message at startup
            try
            {
                string userConfigPath = GetConfigPath(SIMIAN_CONFIG_USER_FILE);
                if (!File.Exists(userConfigPath))
                {
                    using (FileStream stream = File.Create(userConfigPath))
                    { }
                }
            }
            catch { }

            #endregion Overrides File Creation

            #region MIME Type File

            string mimeConfigPath = GetConfigPath(MIME_TYPE_CONFIG_FILE);

            // Load and parse the MIME type file
            try
            {
                string[] mimeLines = File.ReadAllLines(mimeConfigPath);

                char[] splitChars = new char[] { ' ', '\t' };

                for (int i = 0; i < mimeLines.Length; i++)
                {
                    string line = mimeLines[i].Trim();

                    if (!String.IsNullOrEmpty(line) && line[0] != '#')
                    {
                        string[] parts = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
                        if (parts.Length > 1)
                        {
                            string mimeType = parts[0];
                            m_typesToExtensions[mimeType] = parts[1];

                            for (int j = 1; j < parts.Length; j++)
                            {
                                m_extensionsToTypes[parts[j]] = mimeType;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                m_log.Error("Failed to load MIME types from  " + mimeConfigPath + ": " + ex.Message);
            }

            #endregion MIME Type File

            // Load the master ini file
            IniConfigSource masterConfig = LoadConfig(GetConfigPath(masterConfigLocation));

            // Load the overrides ini file
            IniConfigSource overridesConfig = LoadConfig(GetConfigPath(overridesConfigLocation));

            // Merge
            masterConfig.Merge(overridesConfig);

            // Save the merged config file in-memory so we can make copies later
            using (MemoryStream stream = new MemoryStream())
            {
                masterConfig.Save(stream);
                m_configData = stream.ToArray();
            }
        }
예제 #9
0
        private static IniConfigSource LoadConfig(string location)
        {
            IniConfigSource currentConfig      = new IniConfigSource();
            List <string>   currentConfigLines = new List <string>();

            string[] configLines = null;

            if (IsUrl(location))
            {
                // Web-based loading
                string responseStr;
                if (WebUtil.TryGetUrl(location, out responseStr))
                {
                    configLines = responseStr.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    m_log.Error("Failed to load web config file " + location + ": " + responseStr);
                }
            }
            else
            {
                // Local file loading
                try
                {
                    configLines = new List <string>(File.ReadAllLines(location)).ToArray();
                }
                catch (Exception ex)
                {
                    m_log.Error("Failed to load config file " + location + ": " + ex.Message);
                }
            }

            if (configLines != null)
            {
                for (int i = 0; i < configLines.Length; i++)
                {
                    string line = configLines[i].Trim();

                    if (line.StartsWith("Include "))
                    {
                        // Compile the current config lines, compile the included config file, and combine them
                        currentConfig.Merge(CompileConfig(currentConfigLines));
                        currentConfigLines.Clear();

                        // Compile the included config file
                        string          includeFilename = GetConfigPath(line.Substring(8).Trim());
                        IniConfigSource includeConfig   = LoadConfig(includeFilename);

                        // Merge the included config with the curent config
                        currentConfig.Merge(includeConfig);
                    }
                    else if (!String.IsNullOrEmpty(line) && !line.StartsWith(";"))
                    {
                        currentConfigLines.Add(line);
                    }
                }

                currentConfig.Merge(CompileConfig(currentConfigLines));
            }

            return(currentConfig);
        }
예제 #10
0
        /// <summary>
        ///     Loads the region configuration
        /// </summary>
        /// <param name="argvSource">Parameters passed into the process when started</param>
        /// <returns>A configuration that gets passed to modules</returns>
        public IConfigSource LoadConfigSettings(IConfigSource argvSource)
        {
            iniFilePath = "";
            bool iniFileExists = false;
            bool oldoptions    = false;

            string mainIniDirectory     = Constants.DEFAULT_CONFIG_DIR;
            string mainIniFileName      = defaultIniFile;
            string secondaryIniFileName = "";
            string worldIniFileName     = "MyWorld.ini";

            List <string> sources  = new List <string>();
            string        basePath = Util.configDir();

            if (argvSource != null)
            {
                IConfig startupConfig = argvSource.Configs["Startup"];


                oldoptions =
                    startupConfig.GetBoolean("oldoptions", false);

                inidbg =
                    startupConfig.GetBoolean("inidbg", inidbg);

                showIniLoading =
                    startupConfig.GetBoolean("inishowfileloading", showIniLoading);

                if (oldoptions)
                {
                    string masterFileName =
                        startupConfig.GetString("inimaster", String.Empty);

                    string iniGridName =
                        startupConfig.GetString("inigrid", String.Empty);

                    if (iniGridName == string.Empty) //Read the old name then
                    {
                        iniGridName =
                            startupConfig.GetString("inifile", String.Empty);
                    }

                    string iniSimName =
                        startupConfig.GetString("inisim", defaultIniFile);

                    //Be mindful of these when modifying...
                    //1) When file A includes file B, if the same directive is found in both, that the value in file B wins.
                    //2) That inifile may be used with or without inimaster being used.
                    //3) That any values for directives pulled in via inifile (Config Set 2) override directives of the same name found in
                    //    the directive set (Config Set 1) created by reading in bin/WhiteCore.ini and its subsequently included files
                    //    or that created by reading in whatever file inimaster points to and its subsequently included files.

                    if (IsUri(masterFileName))
                    {
                        if (!sources.Contains(masterFileName))
                        {
                            sources.Add(masterFileName);
                        }
                    }
                    else
                    {
                        string masterFilePath = Util.BasePathCombine(masterFileName);

                        if (masterFileName != String.Empty &&
                            File.Exists(masterFilePath) &&
                            (!sources.Contains(masterFilePath)))
                        {
                            sources.Add(masterFilePath);
                        }
                        if (iniGridName == "") //Then it doesn't exist and we need to set this
                        {
                            iniFilePath = masterFilePath;
                        }
                        if (iniSimName == "") //Then it doesn't exist and we need to set this
                        {
                            iniFilePath = masterFilePath;
                        }
                    }

                    if (iniGridName != "")
                    {
                        if (IsUri(iniGridName))
                        {
                            if (!sources.Contains(iniGridName))
                            {
                                sources.Add(iniGridName);
                            }
                            iniFilePath = iniGridName;
                        }
                        else
                        {
                            iniFilePath = Util.BasePathCombine(iniGridName);

                            if (File.Exists(iniFilePath))
                            {
                                if (!sources.Contains(iniFilePath))
                                {
                                    sources.Add(iniFilePath);
                                }
                            }
                        }
                    }

                    if (iniSimName != "")
                    {
                        if (IsUri(iniSimName))
                        {
                            if (!sources.Contains(iniSimName))
                            {
                                sources.Add(iniSimName);
                            }
                            iniFilePath = iniSimName;
                        }
                        else
                        {
                            iniFilePath = Util.BasePathCombine(iniSimName);

                            if (File.Exists(iniFilePath))
                            {
                                if (!sources.Contains(iniFilePath))
                                {
                                    sources.Add(iniFilePath);
                                }
                            }
                        }
                    }

                    string iniDirName =
                        startupConfig.GetString("inidirectory", "");

                    if (iniDirName != "" && Directory.Exists(iniDirName))
                    {
                        Console.WriteLine(string.Format("Searching folder {0} for config ini files",
                                                        iniDirName));

                        string[] fileEntries = Directory.GetFiles(iniDirName);

                        foreach (string filePath in fileEntries.Where(filePath =>
                        {
                            var extension = Path.GetExtension(filePath);
                            return(extension != null &&
                                   extension.ToLower() == ".ini");
                        })
                                 .Where(
                                     filePath =>
                                     !sources.Contains(Path.Combine(iniDirName, filePath)))
                                 )
                        {
                            sources.Add(Path.Combine(iniDirName, filePath));
                        }
                    }
                }
                else
                {
                    mainIniDirectory     = startupConfig.GetString("mainIniDirectory", mainIniDirectory);
                    mainIniFileName      = startupConfig.GetString("mainIniFileName", defaultIniFile);
                    secondaryIniFileName = startupConfig.GetString("secondaryIniFileName", secondaryIniFileName);
                }
            }

            if (!oldoptions)
            {
                if (mainIniDirectory != "")
                {
                    basePath = mainIniDirectory;
                }
                if (mainIniFileName != "")
                {
                    if (IsUri(mainIniFileName))
                    {
                        if (!sources.Contains(mainIniFileName))
                        {
                            sources.Add(mainIniFileName);
                        }
                    }
                    else
                    {
                        string mainIniFilePath = Path.Combine(mainIniDirectory, mainIniFileName);
                        if (!sources.Contains(mainIniFilePath))
                        {
                            sources.Add(mainIniFilePath);
                        }
                    }
                }

                if (secondaryIniFileName != "")
                {
                    if (IsUri(secondaryIniFileName))
                    {
                        if (!sources.Contains(secondaryIniFileName))
                        {
                            sources.Add(secondaryIniFileName);
                        }
                    }
                    else
                    {
                        string secondaryIniFilePath = Path.Combine(mainIniDirectory, secondaryIniFileName);
                        if (!sources.Contains(secondaryIniFilePath))
                        {
                            sources.Add(secondaryIniFilePath);
                        }
                    }
                }
            }

            IConfigSource m_config     = new IniConfigSource();
            IConfigSource m_fakeconfig = new IniConfigSource();

            //Console.WriteLine(string.Format("[Config]: Reading configuration settings"));

            if (sources.Count == 0)
            {
                Console.WriteLine(string.Format("[CONFIG]: Could not load any configuration"));
                Console.WriteLine(
                    string.Format("[CONFIG]: Did you copy the " + defaultIniFile + ".example file to " + defaultIniFile +
                                  "?"));
                throw new NotSupportedException();
            }

            List <string> triedPaths = new List <string>();

            for (int i = 0; i < sources.Count; i++)
            {
                //Read all non .example files first, then read all the example ones

                if (File.Exists(sources[i]) &&
                    ReadConfig(sources[i], i, m_fakeconfig))
                {
                    iniFileExists = true;
                }
                else if (File.Exists(sources[i] + ".example") &&
                         ReadConfig(sources[i] + ".example", i, m_fakeconfig))
                {
                    iniFileExists = true;
                }
                AddIncludes(sources, basePath, ref i, ref triedPaths, m_fakeconfig);
            }

            //
            sources.Reverse();
            for (int i = 0; i < sources.Count; i++)
            {
                //Read all non .example files first, then read all the example ones

                if (File.Exists(sources[i]))
                {
                    ReadConfig(sources[i], i, m_config);
                }
                else if (File.Exists(sources[i] + ".example"))
                {
                    ReadConfig(sources[i] + ".example", i, m_config);
                }
            }

            // add override paramteres if they exist ONLY for standalone operation
            if (!mainIniFileName.Contains("GridServer"))
            {
                string worldIniFilePath = Path.Combine(mainIniDirectory, worldIniFileName);
                if (File.Exists(worldIniFilePath))
                {
                    ReadConfig(worldIniFilePath, 0, m_config);
                }
            }

            FixDefines(ref m_config);

            if (!iniFileExists)
            {
                Console.WriteLine(string.Format("[CONFIG]: Could not load any configuration"));
                Console.WriteLine(string.Format("[CONFIG]: .. or Configuration possibly exists, but there was an error loading it!"));
                Console.WriteLine(string.Format("[CONFIG]: Configuration : " + mainIniDirectory + ", " + mainIniFileName));
                throw new NotSupportedException();
            }
            // Make sure command line options take precedence
            if (argvSource != null)
            {
                m_config.Merge(argvSource);
            }

            return(m_config);
        }