Exemple #1
0
 private void WriteFirstSection(IniSection section)
 {
     if (section.Name.Equals(IniSection.GlobalSectionName))
         this.WriteKeys(section.Keys);
     else
         this.WriteSection(section);
 }
Exemple #2
0
        private static void Create()
        {
            // Create new file with a default formatting.
            IniFile file = new IniFile(new IniOptions());

            // Add new content.
            IniSection section = new IniSection(file, IniSection.GlobalSectionName);
            IniKey key = new IniKey(file, "Key 1", "Value 1");
            file.Sections.Add(section);
            section.Keys.Add(key);

            // Add new content.
            file.Sections.Add("Section 2").Keys.Add("Key 2", "Value 2");
            
            // Add new content.
            file.Sections.Add(
                new IniSection(file, "Section 3",
                    new IniKey(file, "Key 3.1", "Value 3.1"),
                    new IniKey(file, "Key 3.2", "Value 3.2")));

            // Add new content.
            file.Sections.Add(
                new IniSection(file, "Section 4",
                    new Dictionary<string, string>()
                    {
                        {"Key 4.1", "Value 4.1"},
                        {"Key 4.2", "Value 4.2"}
                    }));
        }
Exemple #3
0
 public IniReader(IniOptions options)
 {
     this.options = options;
     this.currentEmptyLinesBefore = 0;
     this.currentTrailingComment = null;
     this.currentSection = null;
 }
        public override void ShowDialog(object sender, EventArgs e)
        {
            string[] files;
            string path;
            if (ConvDlg.Show("", GetOpenFilter(), out files, out path) == DialogResult.OK)
            {
                ProgressDlg pd = new ProgressDlg(DevStringTable.Instance["GUI:Converting"]);

                pd.MinVal = 0;
                pd.Value = 0;
                pd.MaxVal = files.Length;

                pd.Show();

                string dest = Path.Combine(path, "color.ini");
                ini = new IniConfiguration();

                iniSect = new IniSection("Textures");
                ini.Add(iniSect.Name, iniSect);

                for (int i = 0; i < files.Length; i++)
                {
                    Convert(new DevFileLocation(files[i]), null);

                    pd.Value = i;
                    Application.DoEvents();
                }
                pd.Close();
                pd.Dispose();

                ini.Save(dest);
            }
        }
Exemple #5
0
 public IniLineProcessor(IniFile iniFile)
 {
     _iniFile = iniFile;
     _currentSection = null;
     _currentKeyValue = null;
     _currentComments = new List<string>();
 }
Exemple #6
0
        public void ProcessLine(string line)
        {
            line = line.Trim();

            if (IsSection(line))
            {
                _currentSection = ProcessSection(line, _iniFile);
                _currentSection.Comments.AddRange(_currentComments);
                _currentComments.Clear();
            }
            else if (IsKeyValue(line))
            {
                if (_currentSection == null)
                {
                    _currentSection = new IniSection(string.Empty);
                    _iniFile.Sections.Add(_currentSection);
                }

                _currentKeyValue = ProcessKeyValue(line, _currentSection);
                _currentKeyValue.Comments.AddRange(_currentComments);
                _currentComments.Clear();
            }
            else if (IsComment(line))
            {
                string comment = ProcessComment(line, _currentKeyValue);
                _currentComments.Add(comment);
            }
            else
            {
                // Blank (or junk) line. Ignore.
            }
        }
Exemple #7
0
        private static void FormatEntries(IniSection section, TextWriter writer)
        {
            foreach (KeyValuePair<string, string> entry in section) {
            writer.WriteLine("{0}={1}", entry.Key, entry.Value);
              }

              writer.WriteLine();
        }
Exemple #8
0
	   private IniSection GetSection(string name) {
		  IniSection result;
		  if (!sections.TryGetValue(name.ToLower(), out result)) {
			 result = new IniSection(name);
			 sections.Add(name.ToLower(), result);
		  }
		  return result;
	   }
Exemple #9
0
			public PktMapEntry(IniSection sect) {
				Description = sect.ReadString("Description");
				MinPlayers = sect.ReadInt("MinPlayers");
				MaxPlayer = sect.ReadInt("MaxPlayers");
				string[] GameModes = sect.ReadString("GameMode").Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string g in GameModes)
					this.GameModes |= (GameMode)Enum.Parse(typeof(GameMode), g, true);
			}
Exemple #10
0
        public void AddsProperty()
        {
            var sentence = SectionFactory.CreateSection("foo", Grammar.DefaultDelimiters);
            var section = new IniSection(sentence, null);

            Assert.AreEqual("foo", section.Name);
            Assert.IsFalse(section.Comments.Any());
            Assert.IsFalse(section.Properties.Any());
        }
Exemple #11
0
		  public void AddSection(string name) {
			 if (currentSection != null) {
				Pop();
			 }

			 currentSection = Find(name);
			 if (currentSection == null) {
				currentSection = new IniSection(name);
			 }
		  }
Exemple #12
0
	   public static Category[] BuildCategories(IniSection[] sections) {
		  List<Category> categories = new List<Category>(sections.Length);
		  for (int i = 0; i < sections.Length; i++) {
			 Category category = Category.FromFormat(sections[i].Name, sections[i].Count);
			 for (int j = 0; j < sections[i].Count; j++) {
				category.Add(CategoryItem.FromFormat(sections[i][j]));
			 }
			 categories.Add(category);
		  }
		  return categories.ToArray();
	   }
Exemple #13
0
        public void DisallowsDuplicateProperties()
        {
            var sentence = SectionFactory.CreateSection("foo", Grammar.DefaultDelimiters);
            var section = new IniSection(sentence, new IniFile(sentence, new IniSettings
            {
                DuplicatePropertyHandling = DuplicatePropertyHandling.Disallow
            }));

            section.AddProperty("bar", "baz");
            section.AddProperty("bar", "qux");
        }
Exemple #14
0
        private void WriteSection(IniSection section)
        {
            this.WriteItem(section,
                // E.g. "   [SectionName]"
                new String(' ', section.LeftIndentation) +
                this.options.sectionWrapperStart +
                section.Name +
                this.options.sectionWrapperEnd);

            this.WriteKeys(section.Keys);
        }
Exemple #15
0
        public void AddPropertyTests()
        {
            var sentence = SectionFactory.CreateSection("foo", Grammar.DefaultDelimiters);
            var section = new IniSection(sentence, new IniFile());

            section.AddComment("baz");
            section.AddComment("qux");

            Assert.IsTrue(section.Comments.Count() == 2);
            Assert.IsTrue(section.Comments.ElementAt(0) == "baz");
            Assert.IsTrue(section.Comments.ElementAt(1) == "qux");
        }
Exemple #16
0
			public MissionEntry(IniSection iniSection) {
				Briefing = iniSection.ReadString("Briefing");
				UIName = iniSection.ReadString("UIName");
				Name = iniSection.ReadString("Name");
				LS640BriefLocX = iniSection.ReadInt("LS640BriefLocX");
				LS640BriefLocY = iniSection.ReadInt("LS640BriefLocY");
				LS800BriefLocX = iniSection.ReadInt("LS800BriefLocX");
				LS800BriefLocY = iniSection.ReadInt("LS800BriefLocY");
				LSLoadMessage = iniSection.ReadString("LSLoadMessage");
				LSLoadBriefing = iniSection.ReadString("LSLoadBriefing");
				LS640BkgdName = iniSection.ReadString("LS640BkgdName");
				LS800BkgdName = iniSection.ReadString("LS800BkgdName");
			}
Exemple #17
0
        public void AllowsDuplicateProperties()
        {
            var sentence = SectionFactory.CreateSection("foo", Grammar.DefaultDelimiters);
            var section = new IniSection(sentence, new IniFile(sentence, new IniSettings
            {
                DuplicatePropertyHandling = DuplicatePropertyHandling.Allow
            }));

            section.AddProperty("bar", "baz");
            section.AddProperty("bar", "qux");

            Assert.IsTrue(section.Properties.Count() == 2);
            Assert.IsTrue(section.Properties.Count(x => x.Name.Equals("bar", StringComparison.OrdinalIgnoreCase)) == 2);
        }
Exemple #18
0
        public void KeepsFirstDuplicateProperty()
        {
            var sentence = SectionFactory.CreateSection("foo", Grammar.DefaultDelimiters);
            var section = new IniSection(sentence, new IniFile(sentence, new IniSettings
            {
                DuplicatePropertyHandling = DuplicatePropertyHandling.KeepFirst
            }));

            section.AddProperty("bar", "baz");
            section.AddProperty("bar", "qux");

            Assert.IsTrue(section.Properties.Count() == 1);
            Assert.AreEqual("baz", section["bar"].Value);
        }
        public KHR_1HV_MotionFile()
        {
            khr_1hv_motion = new IniFile("");
            IniSection section = new IniSection();

            section.Add("Type", "0");
            section.Add("Width", "854");
            section.Add("Height", "480");
            section.Add("Items", "0");
            section.Add("Links", "0");
            section.Add("Start", "-1");
            section.Add("Name", "");
            section.Add("Ctrl", "65535");
            khr_1hv_motion.Add("GraphicalEdit", section);
        }
        public void AddSectionIntoIniStringsFile()
        {
            var iniFile = new IniStrings();
            var section = new IniSection("Test");

            section.Comment = "a\r\nb\r\nc\r\n";
            section.Add(new IniSectionItem("Connection", " a, b, c, d", "definition of connection string"));
            section.Add(new IniSectionItem("Type", "selector"));

            iniFile.Add(section);

            Assert.AreEqual(1, iniFile.Count);
            Assert.IsTrue(iniFile.Contains("test"));
            Assert.IsTrue(iniFile["test"].Contains("connection"));
            Assert.IsNotNull(iniFile.ToString());
        }
Exemple #21
0
 // Adds a section to the IniFile object, returns a IniSection object to the new or existing object
 public IniSection AddSection(string sSection )
 {
     IniSection s = null;
     sSection = sSection.Trim();
     // Trim spaces
     if (m_sections.ContainsKey(sSection))
     {
         s = (IniSection)m_sections[sSection];
     }
     else
     {
         s = new IniSection(this, sSection);
         m_sections[sSection] = s;
     }
     return s;
 }
        //=======================
        //  DEFAULT CONSTRUCTOR
        //=======================
        public KHR_1HV_IniFile()
        {
            khr_1hv_ini = new IniFile("./KHR-1HV.ini");
            if (khr_1hv_ini.Exists())
                khr_1hv_ini.Load();
            else
            {
                IniSection section = new IniSection();
                section.Add("IPAddress", "0.0.0.0");
                section.Add("Grid", "1");
                section.Add("GridWidth", "5");
                section.Add("GridHeight", "5");
                section.Add("Form", "804,900,-2147483633");
                section.Add("Bmp", "");
                section.Add("Background", "0");
                section.Add("CH1", "1,0,0,-2147483633,0,1,CH1");
                section.Add("CH2", "1,0,31,-2147483633,0,1,CH2");
                section.Add("CH3", "1,0,62,-2147483633,0,1,CH3");
                section.Add("CH4", "1,0,93,-2147483633,0,1,CH4");
                section.Add("CH5", "1,0,124,-2147483633,0,1,CH5");
                section.Add("CH6", "1,0,155,-2147483633,0,1,CH6");
                section.Add("CH7", "1,0,186,-2147483633,0,1,CH7");
                section.Add("CH8", "1,0,217,-2147483633,0,1,CH8");
                section.Add("CH9", "1,0,248,-2147483633,0,1,CH9");
                section.Add("CH10", "1,0,279,-2147483633,0,1,CH10");
                section.Add("CH11", "1,0,310,-2147483633,0,1,CH11");
                section.Add("CH12", "1,0,341,-2147483633,0,1,CH12");
                section.Add("CH13", "1,329,0,-2147483633,0,1,CH13");
                section.Add("CH14", "1,329,31,-2147483633,0,1,CH14");
                section.Add("CH15", "1,329,62,-2147483633,0,1,CH15");
                section.Add("CH16", "1,329,93,-2147483633,0,1,CH16");
                section.Add("CH17", "1,329,124,-2147483633,0,1,CH17");
                section.Add("CH18", "1,329,155,-2147483633,0,1,CH18");
                section.Add("CH19", "1,329,186,-2147483633,0,1,CH19");
                section.Add("CH20", "1,329,217,-2147483633,0,1,CH20");
                section.Add("CH21", "1,329,248,-2147483633,0,1,CH21");
                section.Add("CH22", "1,329,279,-2147483633,0,1,CH22");
                section.Add("CH23", "1,329,310,-2147483633,0,1,CH23");
                section.Add("CH24", "1,329,341,-2147483633,0,1,CH24");
                section.Add("SPEED", "1,0,372,-2147483633");
                section.Add("CMD", "1,0,403,-2147483633");
                section.Add("LINK", "1,329,372,-2147483633");
                khr_1hv_ini.Add("KHR-1HV", section);

                khr_1hv_ini.Save();
            }
        }
            public List <string> WriteNormalizedIni(IDictionary <IniSection, ISet <IIniLine> > iniDict)
            {
                var fileLines = new List <string>();

                IniSection lastKey = null;

                foreach (var item in iniDict)
                {
                    if (lastKey != item.Key)
                    {
                        lastKey = item.Key;
                        WriteIniLine(fileLines, item.Key);
                    }

                    foreach (var line in item.Value)
                    {
                        WriteIniLine(fileLines, line);
                    }
                }
                return(fileLines);
            }
Exemple #24
0
        /// <summary>
        /// Merges the IniDocument into the Configs when the document is
        /// reloaded.
        /// </summary>
        private void MergeDocumentIntoConfigs()
        {
            // Remove all missing configs first
            RemoveConfigs();

            IniSection section = null;

            for (int i = 0; i < iniDocument.Sections.Count; i++)
            {
                section = iniDocument.Sections[i];

                IConfig config = this.Configs[section.Name];
                if (config == null)
                {
                    // The section is new so add it
                    config = new ConfigBase(section.Name, this);
                    this.Configs.Add(config);
                }
                RemoveConfigKeys(config);
            }
        }
Exemple #25
0
        internal static bool LoadVerIni(out IniFile verIni, IniOptions verIniOptions, string verIniPath)
        {
            if (!LoadIni(out verIni, verIniOptions, verIniPath))
            {
                return(false);
            }

            if (!verIni.Sections.Contains(Strings.IniName.Ver.Section))
            {
                return(false);
            }

            IniSection clientVerSection = verIni.Sections[Strings.IniName.Ver.Section];

            if (!clientVerSection.Keys.Contains(Strings.IniName.Ver.Key))
            {
                return(false);
            }

            return(true);
        }
Exemple #26
0
        protected void LoadAllEntries(string basepath)
        {
            Trace.Call(basepath);

#if CONFIG_GCONF
            // TODO: GConf# has no way yet to get the sub-paths of a given path!
            // So we have to use Nini as primary config backend for now...
#elif CONFIG_NINI
            foreach (DictionaryEntry dec in m_IniDocument.Sections)
            {
                IniSection inisection = (IniSection)dec.Value;
                if (inisection.Name.StartsWith(basepath))
                {
                    foreach (string key in inisection.GetKeys())
                    {
                        m_Preferences[inisection.Name + "/" + key] = _Parse(inisection.GetValue(key));
                    }
                }
            }
#endif
        }
Exemple #27
0
        internal static bool LoadPatcherIni(out IniFile patcherIni, IniOptions patcherIniOptions, string patcherIniPath)
        {
            if (!LoadVerIni(out patcherIni, patcherIniOptions, patcherIniPath))
            {
                return(false);
            }

            if (!patcherIni.Sections.Contains(Strings.IniName.Patcher.Section))
            {
                return(false);
            }

            IniSection clientVerSection = patcherIni.Sections[Strings.IniName.Patcher.Section];

            if (!clientVerSection.Keys.Contains(Strings.IniName.Patcher.KeyDate))
            {
                return(false);
            }

            return(true);
        }
Exemple #28
0
        private static void Copy()
        {
            // Create new file.
            IniFile file = new IniFile();

            // Add new content.
            IniSection section = file.Sections.Add("Section");
            IniKey     key     = section.Keys.Add("Key");

            // Add duplicate section.
            file.Sections.Add(section.Copy());

            // Add duplicate key.
            section.Keys.Add(key.Copy());

            // Create new file.
            IniFile newFile = new IniFile(new IniOptions());

            // Import first file's section to second file.
            newFile.Sections.Add(section.Copy(newFile));
        }
Exemple #29
0
        public void DeleteKey(string sectionName, string keyName)
        {
            // Get / create section
            IniSection section = this[sectionName];

            if (section == null)
            {
                return; // no section, no key...
            }

            // Get / create Key
            IniKey key = section[keyName];

            if (key != null)
            {
                section.Keys.Remove(key);
                key.OnChange += null;
            }

            this.SetChanged();
        }
Exemple #30
0
    /// @brief Add section to file
    ///
    /// @param section_name section name
    /// @retval section
    public IniSection AddSection(string section_name)
    {
        int        id;
        IniSection section;

        section_name = section_name.Trim();

        id = _Sections.IndexOf(section_name.Trim());

        if (id == -1)
        {
            section = new IniSection(this, section_name);
            _Sections.Add(section);
        }
        else
        {
            section = (IniSection)_Sections[id];
        }

        return(section);
    }
Exemple #31
0
        /// <summary>
        /// Merges all of the configs from the config collection into the
        /// IniDocument before it is saved.
        /// </summary>
        private void MergeConfigsIntoDocument()
        {
            RemoveSections();
            foreach (IConfig config in this.Configs)
            {
                string[] keys = config.GetKeys();

                // Create a new section if one doesn't exist
                if (iniDocument.Sections[config.Name] == null)
                {
                    IniSection section = new IniSection(config.Name);
                    iniDocument.Sections.Add(section);
                }
                RemoveKeys(config.Name);

                for (int i = 0; i < keys.Length; i++)
                {
                    iniDocument.Sections[config.Name].Set(keys[i], config.Get(keys[i]));
                }
            }
        }
Exemple #32
0
        /// <inheritdoc />
        public IniSection Normalize(IniSection source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var destination = Options.IsCaseSensitive
                ? new IniSection(source.Name)
                : new IniSection(source.Name.ToUpperInvariant());

            if (source.IsEmpty)
            {
                return(destination);
            }

            CopyComments(source.Comments, destination.Comments);
            NormalizeInto(source.Properties, destination.Properties);

            return(destination);
        }
        private void LogIn()
        {
            IniFile iniFile = new IniFile();

            iniFile.Load(IniData.SettingIniFile);
            IniSection dbSection   = iniFile[DBConnect.IniSectionName];
            string     commandText = $@"Select * from {dbSection["UserTB"]}
                                     where {dbSection["UserTB_ID"]} = @ID and {dbSection["UserTB_PW"]} = @Password";
            SqlCommand command     = new SqlCommand(commandText);

            SqlParameter paramID = new SqlParameter("@ID", SqlDbType.VarChar, 40);

            paramID.Value = Txt_ID.Text;
            SqlParameter paramPW = new SqlParameter("@Password", SqlDbType.VarChar, 40);

            paramPW.Value = Txt_PW.Text;
            command.Parameters.Add(paramID);
            command.Parameters.Add(paramPW);

            DBConnect dbConnect = new DBConnect();
            DataSet   loginData;
            bool      result = dbConnect.Search(command, out loginData);

            if (result && loginData != null)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                if (result && loginData == null)
                {
                    FRM_MessageBox.Show("입력하신 ID 또는 PW가 맞지 않습니다", "로그인 실패");
                }
                else
                {
                    FRM_MessageBox.Show("로그인 DB의 접속에 실패했습니다", "로그인 실패");
                }
            }
        }
Exemple #34
0
        protected void ApplyLanguage(Control applyTo)
        {
            IGreenshotLanguageBindable languageBindable = applyTo as IGreenshotLanguageBindable;

            if (languageBindable == null)
            {
                // check if it's a menu!
                ToolStrip toolStrip = applyTo as ToolStrip;
                if (toolStrip != null)
                {
                    foreach (ToolStripItem item in toolStrip.Items)
                    {
                        ApplyLanguage(item);
                    }
                }
                return;
            }

            // Apply language text to the control
            ApplyLanguage(applyTo, languageBindable.LanguageKey);

            // Repopulate the combox boxes
            IGreenshotConfigBindable configBindable = applyTo as IGreenshotConfigBindable;
            GreenshotComboBox        comboxBox      = applyTo as GreenshotComboBox;

            if (configBindable != null && comboxBox != null)
            {
                if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName))
                {
                    IniSection section = IniConfig.GetIniSection(configBindable.SectionName);
                    if (section != null)
                    {
                        // Only update the language, so get the actual value and than repopulate
                        Enum currentValue = (Enum)comboxBox.GetSelectedEnum();
                        comboxBox.Populate(section.Values[configBindable.PropertyName].ValueType);
                        comboxBox.SetValue(currentValue);
                    }
                }
            }
        }
Exemple #35
0
        private void Patcher_PatcherCompleted(object sender, PatcherCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                Logger.Debug($"{sender.ToString()} cancelled");
                DeleteTmpFiles(e.Language);
            }
            else if (e.Error != null)
            {
                Logger.Error(e.Error);
                MsgBox.Error(Methods.ExeptionParser(e.Error));
                DeleteTmpFiles(e.Language);
            }
            else
            {
                Logger.Debug($"{sender.ToString()} successfuly completed");

                string clientIniPath = Path.Combine(UserSettings.GamePath, Strings.IniName.ClientVer);
                if (!Methods.LoadVerIni(out IniFile clientIni, clientIniPath))
                {
                    throw new Exception(StringLoader.GetText("exception_generic_read_error", clientIniPath));
                }
                IniSection clientVerSection = clientIni.Sections[Strings.IniName.Ver.Section];

                string translationIniPath = Path.Combine(e.Language.Path, Strings.IniName.Translation);
                var    translationIni     = new IniFile();

                IniKey     translationDateKey        = new IniKey(translationIni, Strings.IniName.Patcher.KeyDate, Methods.DateToString(e.Language.LastUpdate));
                IniSection translationPatcherSection = new IniSection(translationIni, Strings.IniName.Patcher.Section, translationDateKey);

                translationIni.Sections.Add(translationPatcherSection);
                translationIni.Sections.Add(clientVerSection.Copy(translationIni));
                Logger.Debug($"Saving translation config to [{translationIniPath}]");
                translationIni.Save(translationIniPath);
            }

            SWFileManager.DisposeFileData();
            GC.Collect();
            this.CurrentState = State.Idle;
        }
Exemple #36
0
        /// <summary>
        /// Deserializes the specified text into an INI file.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public IniFile Deserialize(String text)
        {
            try
            {
                var result      = new IniFile();
                var rawSections = text.Split(new String [] { "[" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var rawSection in rawSections)
                {
                    var rawProperties = rawSection.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                    var section = new IniSection()
                    {
                        Name = rawProperties[0].TrimEnd(']')
                    };
                    for (var i = 1; i < rawProperties.Length; i++)
                    {
                        var pieces = rawProperties[i].Split('=');
                        var key    = pieces?[0]?.Trim();
                        var val    = pieces?[1]?.Trim();
                        if (String.IsNullOrEmpty(key) && String.IsNullOrEmpty(val))
                        {
                            continue;
                        }

                        section.Properties.Add(new IniValue()
                        {
                            Key = key, Value = val
                        });
                    }
                    result.Sections.Add(section);
                }
                return(result);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
Exemple #37
0
        protected T Get <T>(string key, T defaultvalue)
        {
#if CONFIG_DEBUG
            Trace.Call(key, defaultvalue);
#endif

            string     inisection = _IniGetSection(key);
            string     inikey     = _IniGetKey(key);
            IniSection section    = m_IniDocument.Sections[inisection];
            if ((section == null) ||
                (!section.Contains(inikey)))
            {
                if (defaultvalue != null)
                {
                    _Set(key, defaultvalue);
                }
                return(defaultvalue);
            }
            else
            {
                // the section and key exist
                string strValue   = section.GetValue(inikey);
                Type   targetType = typeof(T);
                if (targetType == typeof(string))
                {
                    return((T)(object)strValue);
                }
                if (targetType == typeof(string[]))
                {
                    return((T)(object)GetList(key));
                }
                // handle empty booleans and integers
                if (targetType.IsValueType && String.IsNullOrEmpty(strValue))
                {
                    return(default(T));
                }

                return((T)Convert.ChangeType(strValue, targetType));
            }
        }
Exemple #38
0
        int ProcessLine(string line)
        {
            IniSection.FixLine(ref line);
            if (line.Length == 0)
            {
                return(0);
            }

            // Test if this line contains start of new section i.e. matches [*]
            if ((line[0] == '[') && (line[line.Length - 1] == ']'))
            {
                string sectionName = line.Substring(1, line.Length - 2);
                var    iniSection  = new IniSection(sectionName, Sections.Count);
                Sections.Add(iniSection);
                CurrentSection = iniSection;
            }
            else if (CurrentSection != null)
            {
                return(CurrentSection.ParseLine(line));
            }
            return(0);
        }
Exemple #39
0
        public void KeyValuesIndexerGet_IndexKeys_KeyValuesAreIndexed()
        {
            // Arrange
            IniSection section = new IniSection("testSection");

            section.KeyValues.Add("testKey1", "testValue1");
            section.KeyValues.Add("testKey2", "testValue2");
            section.KeyValues.Add("testKey3", "testValue3");

            // Act
            IniKeyValue indexedKeyValue1 = section.KeyValues["testKey1"];
            IniKeyValue indexedKeyValue2 = section.KeyValues["testKey2"];
            IniKeyValue indexedKeyValue3 = section.KeyValues["testKey3"];

            // Assert
            Assert.AreSame("testKey1", indexedKeyValue1.Key);
            Assert.AreSame("testKey2", indexedKeyValue2.Key);
            Assert.AreSame("testKey3", indexedKeyValue3.Key);
            Assert.AreSame("testValue1", indexedKeyValue1.Value);
            Assert.AreSame("testValue2", indexedKeyValue2.Value);
            Assert.AreSame("testValue3", indexedKeyValue3.Value);
        }
Exemple #40
0
        /// <summary>Reads the units.</summary>
        private void ReadUnits()
        {
            IniSection unitsSection = GetSection("Units");

            if (unitsSection == null)
            {
                Logger.Info("Units section unavailable in {0}", Path.GetFileName(FileName));
                return;
            }
            foreach (var v in unitsSection.OrderedEntries)
            {
                try {
                    string[] entries = ((string)v.Value).Split(',');
                    if (entries.Length <= 11)
                    {
                        continue;
                    }

                    string owner     = entries[0];
                    string name      = entries[1];
                    short  health    = short.Parse(entries[2]);
                    int    rx        = int.Parse(entries[3]);
                    int    ry        = int.Parse(entries[4]);
                    short  direction = short.Parse(entries[5]);
                    bool   onBridge  = entries[10] == "1";
                    var    u         = new Unit(owner, name, health, direction, onBridge);
                    u.Tile = Tiles.GetTileR(rx, ry);
                    if (u.Tile != null)
                    {
                        Units.Add(u);
                    }
                }
                catch (FormatException) {
                }
                catch (IndexOutOfRangeException) {
                }
            }
            Logger.Trace("Read {0} units", Units.Count);
        }
Exemple #41
0
        /// <summary>Reads the infantry. </summary>
        private void ReadInfantry()
        {
            IniSection infantrySection = GetSection("Infantry");

            if (infantrySection == null)
            {
                Logger.Info("Infantry section unavailable in {0}", Path.GetFileName(FileName));
                return;
            }

            foreach (var v in infantrySection.OrderedEntries)
            {
                try {
                    string[] entries = ((string)v.Value).Split(',');
                    if (entries.Length <= 8)
                    {
                        continue;
                    }
                    string owner     = entries[0];
                    string name      = entries[1];
                    short  health    = short.Parse(entries[2]);
                    int    rx        = int.Parse(entries[3]);
                    int    ry        = int.Parse(entries[4]);
                    short  direction = short.Parse(entries[7]);
                    bool   onBridge  = entries[11] == "1";
                    var    i         = new Infantry(owner, name, health, direction, onBridge);
                    i.Tile = Tiles.GetTileR(rx, ry);
                    if (i.Tile != null)
                    {
                        Infantries.Add(i);
                    }
                }
                catch (IndexOutOfRangeException) {
                }
                catch (FormatException) {
                }
            }
            Logger.Trace("Read {0} infantry objects", Infantries.Count);
        }
Exemple #42
0
        private static Dictionary <string, string> LoadPasswords(string url)
        {
            using (var client = new WebClient())
            {
                var result = new Dictionary <string, string>();

                byte[]  fileBytes = client.DownloadData(url);
                IniFile ini       = new IniFile();
                using (var ms = new MemoryStream(fileBytes))
                {
                    ini.Load(ms);
                }

                IniSection section = ini.Sections[Strings.IniName.Datas.SectionZipPassword];
                foreach (IniKey key in section.Keys)
                {
                    result.Add(key.Name, key.Value);
                }

                return(result);
            }
        }
Exemple #43
0
        public void TestSection()
        {
            IniSection s = new IniSection();

            Assert.AreEqual("", s.Name);
            Assert.AreEqual(0, s.Count);
            Assert.AreEqual(0, s.Keys.Length);

            s["a"] = "b";
            Assert.AreEqual(1, s.Count);
            Assert.AreEqual(1, s.Keys.Length);
            Assert.AreEqual("b", s["a"]);

            s["b"] = null;
            Assert.AreEqual(1, s.Count);
            Assert.AreEqual(1, s.Keys.Length);
            Assert.AreEqual("b", s["a"]);

            s["a"] = null;
            Assert.AreEqual(0, s.Count);
            Assert.AreEqual(0, s.Keys.Length);
        }
Exemple #44
0
        public void IndexerGet_IndexWithWeirdCasing_IndexerIsCaseInsensitive()
        {
            // Arrange
            IniFile    iniFile     = new IniFile();
            IniSection iniSection1 = new IniSection("testSection1");
            IniSection iniSection2 = new IniSection("testSection2");
            IniSection iniSection3 = new IniSection("testSection3");

            iniFile.Sections.Add(iniSection1);
            iniFile.Sections.Add(iniSection2);
            iniFile.Sections.Add(iniSection3);

            // Act
            IniSection indexedSection1 = iniFile["TeStSeCtIoN1"];
            IniSection indexedSection2 = iniFile["TESTSECTION2"];
            IniSection indexedSection3 = iniFile["testsection3"];

            // Assert
            Assert.AreSame(iniSection1, indexedSection1);
            Assert.AreSame(iniSection2, indexedSection2);
            Assert.AreSame(iniSection3, indexedSection3);
        }
Exemple #45
0
        /// <summary>
        /// ToString方法,得到Ini的内容
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            String iniContent = "";
            string line_end   = "\r\n";


            for (int i = 0; i < IniData.Count; i++)
            {
                IniSection isect = IniData[i];

                iniContent += ("[" + isect.SectionName + "]" + line_end);

                for (int j = 0; j < isect.KVList.Count; j++)
                {
                    iniContent += isect.KVList[j].Key + "=" + isect.KVList[j].Value + line_end;
                }

                iniContent += line_end;
            }

            return(iniContent);
        }
Exemple #46
0
        private void saveHUDLocation(DirectX_HUDs hud)
        {
            if (hud != null)
            {
                IniFile file = new IniFile(MainWindow.settings_path);
                if (file.Exists())
                {
                    file.Load();
                }
                IniSection section = new IniSection();
                string     str     = hud.ContentHUDType.ToString() + " HUD";
                if (file.HasSection(str))
                {
                    section = file[str];
                    file.Remove(str);
                }

                if (section.ContainsKey("X"))
                {
                    section["X"] = base.Location.X.ToString();
                }
                else
                {
                    section.Add("X", base.Location.X.ToString());
                }

                if (section.ContainsKey("Y"))
                {
                    section["Y"] = base.Location.Y.ToString();
                }
                else
                {
                    section.Add("Y", base.Location.Y.ToString());
                }

                file.Add(str, section);
                file.Save();
            }
        }
        private List <CoopHouseInfo> GetGenericHouseInfo(IniSection iniSection, string keyName)
        {
            var houseList = new List <CoopHouseInfo>();

            for (int i = 0; ; i++)
            {
                string[] houseInfo = iniSection.GetStringValue(keyName + i, string.Empty).Split(
                    new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                if (houseInfo.Length == 0)
                {
                    break;
                }

                int[] info   = Conversions.IntArrayFromStringArray(houseInfo);
                var   chInfo = new CoopHouseInfo(info[0], info[1], info[2]);

                houseList.Add(new CoopHouseInfo(info[0], info[1], info[2]));
            }

            return(houseList);
        }
        public static MemoryStream ReadPackedSection(IniSection mapPackSection)
        {
            var sb = new StringBuilder();
            for (var i = 1;; i++)
            {
                var line = mapPackSection.GetValue(i.ToString(), null);
                if (line == null)
                    break;

                sb.Append(line.Trim());
            }

            var data = Convert.FromBase64String(sb.ToString());
            var chunks = new List<byte[]>();
            var reader = new BinaryReader(new MemoryStream(data));

            try
            {
                while (true)
                {
                    var length = reader.ReadUInt32() & 0xdfffffff;
                    var dest = new byte[8192];
                    var src = reader.ReadBytes((int)length);

                    LCWCompression.DecodeInto(src, dest);

                    chunks.Add(dest);
                }
            }
            catch (EndOfStreamException) { }

            var ms = new MemoryStream();
            foreach (var chunk in chunks)
                ms.Write(chunk, 0, chunk.Length);

            ms.Position = 0;

            return ms;
        }
        /// <summary>
        /// Writes build information into the specified file path.
        /// Erases the file first if it already exists.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public void Write(string filePath)
        {
            File.Delete(filePath);

            var iniFile = new IniFile(filePath);

            var versionSection = new IniSection(VERSION_SECTION);

            iniFile.AddSection(versionSection);
            ProductVersionInfo.Write(versionSection);

            var filesSection = new IniSection(FILES_SECTION);

            iniFile.AddSection(filesSection);

            for (int i = 0; i < FileInfos.Count; i++)
            {
                filesSection.SetStringValue(i.ToString(), FileInfos[i].GetString());
            }

            iniFile.WriteIniFile();
        }
Exemple #50
0
        public void IndexerGet_IndexNames_SectionsAreIndexed()
        {
            // Arrange
            IniFile    file     = new IniFile();
            IniSection section1 = new IniSection("testSection1");
            IniSection section2 = new IniSection("testSection2");
            IniSection section3 = new IniSection("testSection3");

            file.Sections.Add(section1);
            file.Sections.Add(section2);
            file.Sections.Add(section3);

            // Act
            IniSection indexedSection1 = file["testSection1"];
            IniSection indexedSection2 = file["testSection2"];
            IniSection indexedSection3 = file["testSection3"];

            // Assert
            Assert.AreSame(section1, indexedSection1);
            Assert.AreSame(section2, indexedSection2);
            Assert.AreSame(section3, indexedSection3);
        }
        private void ReadGlobalVariables(IniFile campaignsIni)
        {
            const string GlobalVariablesSectionName = "GlobalVariables";
            IniSection   globalVariablesSection     = campaignsIni.GetSection(GlobalVariablesSectionName);

            if (globalVariablesSection == null)
            {
                Logger.Log($"{nameof(CampaignHandler)}: [{GlobalVariablesSectionName}] not found from campaign config INI!");
                return;
            }

            int i = 0;

            while (true)
            {
                string variableInternalName = globalVariablesSection.GetStringValue(i.ToString(), null);
                if (string.IsNullOrWhiteSpace(variableInternalName))
                {
                    break;
                }

                var globalVariable = new CampaignGlobalVariable(i, variableInternalName);
                var section        = campaignsIni.GetSection(variableInternalName);

                if (section != null)
                {
                    globalVariable.InitFromIniSection(section);
                }
                else
                {
                    Logger.Log($"Section for defined global variable [{variableInternalName}] not found from campaign config INI!");
                }

                GlobalVariables.Add(globalVariable);

                i++;
            }
        }
Exemple #52
0
        public void Load()
        {
            _sections.Clear();
            _sectionNames.Clear();
            if (string.IsNullOrEmpty(_fileName)) return;

            //Log.Write("Loading INI file '{0}'.", _fileName);
            using (StreamReader sr = new StreamReader(_fileName))
            {
                IniSection curSection = null;

                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine().Trim();
                    if (line.StartsWith("#") || line.StartsWith(";")) continue;

                    Match match = _rxSection.Match(line);
                    if (match.Success)
                    {
                        string sectionName = match.Groups[1].Value;
                        //Log.Write("Found section '{0}'.", sectionName);
                        if (!_sections.TryGetValue(sectionName.ToLower(), out curSection))
                        {
                            curSection = new IniSection();
                            _sections[sectionName.ToLower()] = curSection;
                            _sectionNames.Add(sectionName);
                        }
                    }
                    else if (curSection != null && (match = _rxValue.Match(line)).Success)
                    {
                        //Log.Write("Found key '{0}' with value '{1}'.", match.Groups[1].Value, match.Groups[2].Value);
                        curSection.values[match.Groups[1].Value.ToLower()] = match.Groups[2].Value;
                    }
                }
            }

            //Log.Write("Finished loading INI file.");
        }
        /// <summary>
        /// DB로부터 작업지시 목록을 가져와 ComboBox에 할당하는 함수
        /// 완료되지 않은 품목에 대해서만 출력한다
        /// (생산이 일부만 이뤄진 경우에 대해서 구분할 수단을 추가해야함)
        /// </summary>
        private void LoadOrders()
        {
            DBConnect dbConnect = new DBConnect();
            IniFile   ini       = new IniFile();

            ini.Load(IniData.SettingIniFile);
            IniSection dbSection = ini[DBConnect.IniSectionName];

            string cmdText = $@"Select Orders.{dbSection["OrderTB_No"]},
                                       Orders.{dbSection["OrderTB_Date"]},
                                       Items.{dbSection["ItemTB_Name"]},
                                       Orders.{dbSection["OrderTB_Amount"]}
                                  from {dbSection["OrderTB"]} as Orders
                                  Inner Join {dbSection["ItemTB"]} as Items
                                          On Orders.{dbSection["OrderTB_Item"]} = Items.{dbSection["ItemTB_No"]}
                                       Where Orders.{dbSection["OrderTB_No"]} NOT IN 
                                                (Select {dbSection["OutputTB_Order"]} from {dbSection["OutputTB"]})";

            DataSet orderSet;
            bool    result = dbConnect.Search(cmdText, out orderSet);

            if (!result || orderSet == null)
            {
                return;
            }

            Dictionary <string, string> orderList = new Dictionary <string, string>();

            foreach (DataRow row in orderSet.Tables[0].Rows)
            {
                orderList.Add($"{row[0].ToString()} - {row[1].ToString().Substring(0, 10)} {row[2].ToString()} {row[3].ToString()}개",
                              row[0].ToString());
            }

            Cmb_Order.DataSource    = new BindingSource(orderList, null);
            Cmb_Order.DisplayMember = "Key";    // 일자 + 생산품목 및 그 개수에 대한 정보를 Display한다
            Cmb_Order.ValueMember   = "Value";  // 작업지시 코드를 Value로 한다
        }
 // Returns placeholder pairs as KeyValuePair<IniKey, string>:
 //       Key  =  IniKey in which value's the placeholder resides
 //     Value  =  Placeholder, e.g. @{Placeholder}
 private IEnumerable<KeyValuePair<IniKey, string>> GetPlaceholderPairs(IniSection section)
 {
     if (section != null)
     {
         foreach (IniKey key in section.Keys)
             if (key.Value != null)
             {
                 int matchStartat = key.Value.IndexOf("@{");
                 if (matchStartat != -1)
                     foreach (Match match in placeholderPattern.Matches(key.Value, matchStartat))
                         yield return new KeyValuePair<IniKey, string>(key, match.Value);
             }
     }
     else
     {
         foreach (IniSection iniSection in this.iniFile.Sections)
             foreach (var placeholderPair in this.GetPlaceholderPairs(iniSection))
                 yield return placeholderPair;
     }
 }
        void cmdMnuControl_TrimFileDialogPressed(object sender, TrimCommandMenu.TrimFileDialogEventsArgs e)
        {
            if (e.Filedialog == "Open")
            {
                string _fileName = string.Empty;
                this.openFD.Title = "Open a Robot Trim File";
                this.openFD.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                this.openFD.FileName = string.Empty;
                this.openFD.Filter = "Robot Trim files|*.rcb|All files|*.*";
                if (this.openFD.ShowDialog() != DialogResult.Cancel)
                {
                    trimFile = new IniFile(this.openFD.FileName);
                    if (trimFile.Exists())
                    {
                        if (trimFile.Load())
                        {
                            try
                            {
                                // Load the selected trim file
                                saServo = trimFile["Trim"]["Prm"].Split(',');
                                // Position the sliders on the UI
                                trimservosSlider(saServo);
                                // Send the servo trim values to the server
                                trimservos.changeAllChannels(saServo);
                            }
                            catch
                            {
                                MessageBox.Show("No Trim file...");
                            }
                        }
                    }
                }

            }
            else if (e.Filedialog == "Save")
            {
                string str = string.Empty;
                string[] strArray = new string[StaticUtilities.numberOfServos];
                for (int i = 0; i < StaticUtilities.numberOfServos; i++)
                {
                    strArray[i] = horizontalSliderArray[i].sliderValue.ToString();
                }
                str = string.Join(",", strArray);
                this.saveFD.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                this.saveFD.Title = "Save the Robot Trim File";
                this.saveFD.Filter = "Robot Trim Files|*.rcb|All files|*.*";
                this.saveFD.AddExtension = true;
                if (this.saveFD.ShowDialog() != DialogResult.Cancel)
                {
                    trimFile = new IniFile(this.saveFD.FileName);
                    IniSection section = new IniSection();
                    section.Add("Prm", str);
                    trimFile.Add("Trim", section);
                    trimFile.Save();
                }
            }
        }
        private void saveConfigFile()
        {
            string currentPath = Directory.GetCurrentDirectory();
            IniFile ini = new IniFile(currentPath + "\\config.ini");

            foreach (ListViewItem lsti in HostListView.Items)
            {
                IniSection section = new IniSection();
                section.Add("HostName", lsti.SubItems[0].Text);
                section.Add("Port", lsti.SubItems[1].Text);
                section.Add("Community", lsti.SubItems[2].Text);
                section.Add("Version", lsti.SubItems[3].Text);
                section.Add("User", lsti.SubItems[4].Text);
                section.Add("Password", lsti.SubItems[5].Text);
                ini.Add(lsti.SubItems[0].Text, section);
            }
            ini.Save();
        }
Exemple #57
0
        static MemoryStream ReadPackedSection(IniSection mapPackSection)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 1; ; i++)
            {
                string line = mapPackSection.GetValue(i.ToString(), null);
                if (line == null)
                    break;

                sb.Append(line.Trim());
            }

            byte[] data = Convert.FromBase64String(sb.ToString());
            List<byte[]> chunks = new List<byte[]>();
            BinaryReader reader = new BinaryReader(new MemoryStream(data));

            try
            {
                while (true)
                {
                    uint length = reader.ReadUInt32() & 0xdfffffff;
                    byte[] dest = new byte[8192];
                    byte[] src = reader.ReadBytes((int)length);

                    /*int actualLength =*/ Format80.DecodeInto(src, dest);

                    chunks.Add(dest);
                }
            }
            catch (EndOfStreamException) { }

            MemoryStream ms = new MemoryStream();
            foreach (byte[] chunk in chunks)
                ms.Write(chunk, 0, chunk.Length);

            ms.Position = 0;

            return ms;
        }
Exemple #58
0
 public static void Load(object self, IniSection ini)
 {
     foreach (var x in ini)
         LoadField(self, x.Key, x.Value);
 }
 private static string GetTargetedValue(IniSection targetedSection, string targetedKeyName)
 {
     IniKey targetedKey = targetedSection.Keys[targetedKeyName];
     return targetedKey != null ? targetedKey.Value : null;
 }
Exemple #60
0
	   public static TemplateProvider Build(IniSection[] sections) {
		  Category[] categories = BuildCategories(sections);
		  TemplateProvider template = new TemplateProvider(categories);
		  KnownCategories.Instance.AddRange(template.ToStringArray());
		  return template;
	   }