public async Task WriteAsync_GivenGivenExistingFileAndExistingSectionAndExistingPropertyWithDifferentValueDontUpdateProperty_ShouldAddPropertyAsync() { var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "tmp.unit-test-file_7.ini"); var doc = GenerateIniObject(GenerateIniDocument(1)); await doc.WriteAsync(file); //Assert.True(File.Exists(file)); //Assert.True(new FileInfo(file).Length > 0); await IniDocument.WriteAsync(file, "Person", "Age", "90"); //Assert.True(File.Exists(file)); var sec = await IniDocument.ReadSectionAsync(file, "Person"); Assert.Collection(sec.Properties(), s => Assert.Equal("FirstName", s.Key), s => Assert.Equal("LastName", s.Key), s => Assert.Equal("Age", s.Key), s => Assert.Equal("Age", s.Key)); File.Delete(file); Assert.False(File.Exists(file)); }
private static async Task<bool> GetChangeLog(String fileUrl) { UpdateLog.Clear(); String filePath; IniDocument document = null; try { filePath = await Request.HttpDownload(fileUrl); document = new IniDocument(filePath); if(document != null) { IniKeyValue pair = document["setting"]["slogan"]; String str = pair == null ? "" : pair.Value; UpdateLog.Add("slogan", str); pair = pair = document["setting"]["content"]; str = pair == null ? "" : pair.Value; UpdateLog.Add("content", str); pair = document["update"]["sjh"]; str = pair == null ? "" : pair.Value; UpdateLog.Add("sjhs", str); } return true; } catch { return false; } }
public Config() { #if CONFIG_NINI m_ConfigPath = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), "smuxi"); if (!Directory.Exists(m_ConfigPath)) { Directory.CreateDirectory(m_ConfigPath); } m_IniFilename = Path.Combine(m_ConfigPath, "smuxi-engine.ini"); if (!File.Exists(m_IniFilename)) { #if LOG4NET _Logger.Debug("creating file: " + m_IniFilename); #endif File.Create(m_IniFilename).Close(); m_IsCleanConfig = true; } m_IniDocument = new IniDocument(m_IniFilename); //m_IniConfigSource = new IniConfigSource(m_IniFilename); #endif }
private async void FormatButton_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(tbInput.Text) || string.IsNullOrWhiteSpace(tbOutput.Text)) { return; } var btn = sender as Button; btn.IsEnabled = false; btn.Content = "正在处理"; try { using var input = new FileStream(tbInput.Text, FileMode.Open, FileAccess.Read, FileShare.Read); var ini = await IniDocument.ParseAsync(input); using var output = new FileStream(tbOutput.Text, FileMode.Create, FileAccess.Write, FileShare.Read); using var sw = new StreamWriter(output); var options = new SortOptions { Digit = string.IsNullOrWhiteSpace(tbDigit.Text) ? (int?)null : int.Parse(tbDigit.Text), First = string.IsNullOrWhiteSpace(tbDigit.Text) ? 0 : int.Parse(tbFirst.Text), Prefix = tbPrefix.Text, Sort = cbSort.IsChecked, SortTargetKey = tbSortTargetKey.Text, SummaryKey = tbSummaryKey.Text, KeyConstraint = tbKeyConstraint.Text, ValueConstraint = tbValueConstraint.Text }; var result = SortHelper.Sort(ini, options); if (!string.IsNullOrEmpty(tbTargetSectionName.Text)) { await sw.WriteLineAsync($"[{tbTargetSectionName.Text}]"); } result.ToList().ForEach(i => sw.WriteLine(i)); await sw.FlushAsync(); } #if !DEBUG catch (Exception ex) { using var logfs = new FileStream("program.err.log", FileMode.Create, FileAccess.Write, FileShare.Read); using var sw = new StreamWriter(logfs); await sw.WriteLineAsync(ex.ToString()); await sw.WriteLineAsync("全部堆栈跟踪"); await sw.WriteLineAsync(ex.StackTrace); await sw.FlushAsync(); MessageBox.Show(ex.ToString(), "发生异常:"); } #endif finally { btn.IsEnabled = true; btn.Content = "开始格式化"; } }
public void SaveAsMysqlStyle() { string filePath = "Save.ini"; FileStream stream = new FileStream(filePath, FileMode.Create); // Create a new document and save to stream IniDocument doc = new IniDocument(); doc.FileType = IniFileType.MysqlStyle; IniSection section = new IniSection("Pets"); section.Set("my comment"); section.Set("dog", "rover"); doc.Sections.Add(section); doc.Save(stream); stream.Close(); StringWriter writer = new StringWriter(); writer.WriteLine("[Pets]"); writer.WriteLine("# my comment"); writer.WriteLine("dog = rover"); StreamReader reader = new StreamReader(filePath); Assert.AreEqual(writer.ToString(), reader.ReadToEnd()); reader.Close(); IniDocument iniDoc = new IniDocument(); iniDoc.FileType = IniFileType.MysqlStyle; iniDoc.Load(filePath); File.Delete(filePath); }
private void WriteLauncher(string launcherFile) { IniDocument iniDocument = new IniDocument("iniDocument", "", ""); iniDocument.Add(this._buttons.Launch.Write2File(), true); iniDocument.Add(this._buttons.Activate.Write2File(), true); iniDocument.Add(this._buttons.LiveMode.Write2File(), true); iniDocument.Add(this._buttons.Environment.Write2File(), true); iniDocument.Add(this._buttons.RegistryKeys.Write2File(), true); iniDocument.Add(this._buttons.RegistryValueWrite.Write2File(), true); iniDocument.Add(this._buttons.RegistryCleanup.Write2File(), true); iniDocument.Add(this._buttons.FileWriteN.Write2File(), true); iniDocument.Add(this._buttons.FilesMove.Write2File(), true); iniDocument.Add(this._buttons.DirectoriesMove.Write2File(), true); iniDocument.Add(this._buttons.DirectoriesCleanup.Write2File(), true); iniDocument.Add(this._buttons.Language.Write2File(), true); iniDocument.Add(this._buttons.LanguageStrings.Write2File(), true); iniDocument.Add(this._buttons.LanguageFile.Write2File(), true); iniDocument.Add(this._buttons.Custom.Write2File(), true); iniDocument.Remove(Descendants.Empty); foreach (Section section in iniDocument.get_Sections()) { section.Remove(Descendants.Empty); } iniDocument.Footer = "Generated with PAF Launcher Editor 5"; iniDocument.SpaceOutSections = true; File.WriteAllLines(launcherFile, iniDocument.Lines(), Encoding.Default); }
protected internal static object DeserializeType(Type type, IniDocument ini) { var obj = Activator.CreateInstance(type); foreach(var target in Targets[type]) { var propType = target.Property.PropertyType; object val; var containerAttr = target.Attribute as IniValueContainerAttribute; var valAttr = target.Attribute as IniValueAttribute; // if this property is a container, recurse to deserialize it if(containerAttr != null) val = DeserializeType(propType, ini); // otherwise, extract this property's value from the ini else if(valAttr != null) { var valString = ini[valAttr.Section][valAttr.Key].Value; if (string.IsNullOrEmpty(valString)) valString = valAttr.DefaultValue; var typeConverter = TypeDescriptor.GetConverter(propType); val = typeConverter.ConvertFromString(valString); } // ??? internal error! else throw new Exception(); // set the property to whichever value was computed target.Property.SetValue(obj, val, BindingFlags.SetProperty, null, null, null); } return obj; }
public IniDocument LoadDataIni() { string iniContent = "[post]" + Environment.NewLine + "Title:Learn .NET 0" + Environment.NewLine + "StartDate:${today}" + Environment.NewLine + "StartTime:9:30pm" + Environment.NewLine + "IsFree:yes" + Environment.NewLine + "Location.Street:100 Broadway0" + Environment.NewLine + "Location.City:Queens0" + Environment.NewLine + "Location.State:New York0" + Environment.NewLine + "Location.Country:USA0" + Environment.NewLine + "Location.Zip:11240" + Environment.NewLine + "MaxSeats:850" + Environment.NewLine + "Cost:$250" + Environment.NewLine + "Url:http://www.comlib0.com" + Environment.NewLine + Environment.NewLine + "[post]" + Environment.NewLine + "Title:Learn .NET 1" + Environment.NewLine + "StartDate:${t+1}" + Environment.NewLine + "StartTime:11:30 a.m" + Environment.NewLine + "IsFree:no" + Environment.NewLine + "Location.Street:100 Broadway1" + Environment.NewLine + "Location.City:Queens1" + Environment.NewLine + "Location.State:New York1" + Environment.NewLine + "Location.Country:USA1" + Environment.NewLine + "Location.Zip:11241" + Environment.NewLine + "MaxSeats:851" + Environment.NewLine + "Cost:251" + Environment.NewLine + "Url:http://www.comlib1.com" + Environment.NewLine + Environment.NewLine; IniDocument doc = new IniDocument(iniContent, false); return(doc); }
public DevAnalogGrp(IniDocument docIni, int index) { string name = docIni.GetString("模拟量类型", (index+1).ToString()); if (string.IsNullOrEmpty(name)) return; this.Name = name; int type = docIni.GetInt(name, "类型",0); if (type <= 0) return; this.Type = type; this.Unit = docIni.GetString(name, "单位"); int analogNum = docIni.GetInt(name, "数目", 0); float val = docIni.GetFloat(name, "AD最小", float.NaN); this.ADMin = float.IsNaN(val) ? 0 : val; val = docIni.GetFloat(name, "AD最大", float.NaN); this.ADMax = float.IsNaN(val) ? 0 : val; for (int i = 0; i < analogNum; i++) { DevAnalog analog = new DevAnalog(docIni,this,i); if (analog.IsValid) { if (dicAnalog.ContainsKey(analog.Name) == false) { dicAnalog.Add(analog.Name, analog); } } } if (dicAnalog.Count <= 0) return; this.IsValid = true; }
public void SambaLoadAsStandard() { IniDocument doc = new IniDocument(); Assert.Throws <IniException>(() => { var filePath = "Save.ini"; var stream = new FileStream(filePath, FileMode.Create); // Create a new document and save to stream doc.FileType = IniFileType.SambaStyle; var section = new IniSection("Pets"); section.Set("my comment"); section.Set("dog", "rover"); doc.Sections.Add(section); doc.Save(stream); stream.Close(); var iniDoc = new IniDocument { FileType = IniFileType.Standard }; iniDoc.Load(filePath); File.Delete(filePath); }); }
public void SaveAsPythonStyle() { const string filePath = "Save.ini"; var stream = new FileStream(filePath, FileMode.Create); // Create a new document and save to stream var doc = new IniDocument { FileType = IniFileType.PythonStyle }; var section = new IniSection("Pets"); section.Set("my comment"); section.Set("dog", "rover"); doc.Sections.Add(section); doc.Save(stream); stream.Close(); var writer = new StringWriter(); writer.WriteLine("[Pets]"); writer.WriteLine("# my comment"); writer.WriteLine("dog : rover"); var reader = new StreamReader(filePath); Assert.AreEqual(writer.ToString(), reader.ReadToEnd()); reader.Close(); File.Delete(filePath); }
public static async Task ScreeningAsync(SectionScreenOptions options, IConsole console) { IniDocument ini, result; try { // 0. 判断程序是否具备执行条件 if (options.Sections is null || options.Sections.Length < 1)// 未设置目标键或目标键为空 { console.Error.WriteLine($"{nameof(options.Sections)} are NULL or Empty"); return; } // 1. 读入文件 ini = await IniDocument.ParseAsync(options.Input); // 2. 筛选并保留目标键 // 输出 result.Sections = options.MatchCase ? ini.Sections.Where(section => options.Sections.Contains(section.Name)).ToArray() : ini.Sections.Where(section => options.Sections.Contains(section.Name, StringComparer.OrdinalIgnoreCase)).ToArray(); await result.DeparseAsync(options.Output); } finally { console.Out.WriteLine("All Done!"); } }
public HHDevice(IniDocument ini, int index, HHDeviceGrp devGrp) { this.DevGroup = devGrp; string sectionName = devGrp.Name + "\\设备" + (index + 1); this.Name = ini.GetString(sectionName, "设备名称"); if (string.IsNullOrEmpty(this.Name)) { return; } IList <HHDeviceProperty> props = devGrp.Properties; for (int i = 0; i < props.Count; i++) { string propName = props[i].Name; string bindName = ini.GetString(sectionName, propName); listProp.Add(props[i].Bind(bindName)); } this.IsValid = true; for (int i = 0; i < listProp.Count; i++) { if (listProp[i].IsBind == false) { this.IsValid = false; break; } } }
private void LoadConfig() { if (configLoaded) { return; } if (Path.GetExtension(mFile).ToUpper() == ".INI") { if (!File.Exists(mFile)) { mSource = new IniConfigSource(); } else { IniDocument doc = new IniDocument(mFile, IniFileType.WindowsStyle); mSource = new IniConfigSource(doc); } } else if (Path.GetExtension(mFile).ToUpper() == ".CONFIG") { if (!File.Exists(mFile)) { mSource = new DotNetConfigSource(); } else { mSource = new DotNetConfigSource(mFile); } } //mSource = Init.AddFile(mArgConfig, mFile); configLoaded = true; }
public void WithFooter_ShouldReplaceExistingFooter() { var doc = IniDocument .Builder() .Build(); Assert.True(doc.Footer.IsEmpty); Assert.Equal(CommentType.Footer, doc.Footer.Type); doc = IniDocument .Builder(doc) .WithFooter(Comment .Builder() .AppendLine("CommentLine1") .Build()) .Build(); Assert.False(doc.Footer.IsEmpty); var doc1 = IniDocument .Builder(doc) .WithFooter(null) .Build(); Assert.True(doc1.Footer.IsEmpty); var doc2 = IniDocument .Builder(doc) .WithFooter(Comment.Builder().Build()) .Build(); Assert.True(doc2.Footer.IsEmpty); Assert.Equal(CommentType.Footer, doc2.Footer.Type); }
public void SaveToStream() { const string filePath = "SaveToStream.ini"; var stream = new FileStream(filePath, FileMode.Create); // Create a new document and save to stream var doc = new IniDocument(); var section = new IniSection("Pets"); section.Set("dog", "rover"); section.Set("cat", "muffy"); doc.Sections.Add(section); doc.Save(stream); stream.Close(); var newDoc = new IniDocument(new FileStream(filePath, FileMode.Open)); section = newDoc.Sections["Pets"]; Assert.IsNotNull(section); Assert.AreEqual(2, section.GetKeys().Length); Assert.AreEqual("rover", section.GetValue("dog")); Assert.AreEqual("muffy", section.GetValue("cat")); stream.Close(); File.Delete(filePath); }
/// <summary> /// POS AppConfig.ini setting /// </summary> /// <param name="section"></param> /// <param name="config"></param> /// <returns></returns> string GetPOSConfig(string section, string config) { string configFilePath = Path.Combine(m_posConfigFolder, "AppConfig.ini"); IniDocument doc = new IniDocument(configFilePath); return(doc.Sections[section].GetValue(config)); }
public void SaveDocumentWithComments() { StringWriter writer = new StringWriter(); writer.WriteLine("; some comment"); writer.WriteLine(""); // empty line writer.WriteLine("[new section]"); writer.WriteLine(" dog = rover"); writer.WriteLine(""); // Empty line writer.WriteLine("; a comment"); writer.WriteLine(" cat = muffy"); IniDocument doc = new IniDocument(new StringReader(writer.ToString())); StringWriter newWriter = new StringWriter(); doc.Save(newWriter); StringReader reader = new StringReader(newWriter.ToString()); Assert.AreEqual("; some comment", reader.ReadLine()); Assert.AreEqual("", reader.ReadLine()); Assert.AreEqual("[new section]", reader.ReadLine()); Assert.AreEqual("dog = rover", reader.ReadLine()); Assert.AreEqual("", reader.ReadLine()); Assert.AreEqual("; a comment", reader.ReadLine()); Assert.AreEqual("cat = muffy", reader.ReadLine()); writer.Close(); }
public HHDevice(IniDocument ini, int index, HHDeviceGrp devGrp) { this.DevGroup = devGrp; string sectionName = devGrp.Name + "\\设备" + (index + 1); this.Name = ini.GetString(sectionName, "设备名称"); if (string.IsNullOrEmpty(this.Name)) return; IList<HHDeviceProperty> props = devGrp.Properties; for (int i = 0; i < props.Count; i++) { string propName = props[i].Name; string bindName = ini.GetString(sectionName, propName); listProp.Add(props[i].Bind(bindName)); } this.IsValid = true; for (int i = 0; i < listProp.Count; i++) { if (listProp[i].IsBind==false) { this.IsValid = false; break; } } }
/// <summary> /// Map objects from the source and convert to list of type T. Collect errors into the IErrors. /// </summary> /// <param name="filepath"></param> /// <param name="errors"></param> /// <returns></returns> public IList <T> MapFromFile(string filepath, IErrors errors) { IniDocument doc = new IniDocument(filepath, true); _data = doc; return(Map(errors)); }
public void CanParseMultilineValueWithSingleGroup() { string iniContent = "[globalSettings]" + Environment.NewLine + "Title:Learn painting" + Environment.NewLine + "Description:\"Learn to paint" + Environment.NewLine + " using oil\"" + Environment.NewLine + "[post1]" + Environment.NewLine + "title:Build a website" + Environment.NewLine + "CreatedBy: user1"; IniDocument document = new IniDocument(iniContent, false); string title = document.Get <string>("globalSettings", "Title"); string desc = document.Get <string>("globalSettings", "Description"); Assert.AreEqual(title, "Learn painting"); Assert.AreEqual(desc, "Learn to paint" + Environment.NewLine + " using oil"); Assert.AreEqual(document["post1", "title"], "Build a website"); Assert.AreEqual(document["post1", "CreatedBy"], "user1"); //Assert.IsTrue(groupedDict.ContainsKey("globalSettings")); //Assert.AreEqual(groupedDict["globalSettings"]["category"], "Art,Drawing"); //Assert.IsTrue(groupedDict.ContainsKey("post1")); //Assert.AreEqual(groupedDict["post1"]["title"], "Build a website"); //Assert.AreEqual(groupedDict["post1"]["CreatedBy"], "user1"); }
/// <summary> /// Map objects from the source and convert to list of type T. Collect errors into the IErrors. /// </summary> /// <param name="content"></param> /// <param name="errors"></param> /// <returns></returns> public IList <T> MapFromText(string content, IErrors errors) { IniDocument doc = new IniDocument(content, false); _data = doc; return(Map(errors)); }
static async void Main( FileInfo input_file, string output_file, int start_num, int?digit, string prefix, bool nologo, bool sort, string sort_key, string output_section, string output_key, string constraint_key, string constraint_value) { Console.WriteLine("Hello World"); using var fs = new FileStream(input_file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); using var ofs = new FileStream(output_file, FileMode.Create, FileAccess.Write, FileShare.Read); using var sw = new StreamWriter(ofs); var options = new SortOptions { First = start_num, Digit = digit, Prefix = prefix, Sort = sort, SortTargetKey = sort_key, SummaryKey = output_key, KeyConstraint = constraint_key, ValueConstraint = constraint_value }; var result = SortHelper.Sort(await IniDocument.ParseAsync(fs), options); if (!string.IsNullOrEmpty(output_section)) { await sw.WriteLineAsync($"[{output_section}]"); } result.ToList().ForEach(i => sw.WriteLine(i)); }
public Remove(string id) { InitializeComponent(); _id = id; string metafile = Path.Combine(StaticData.PluginsDir, _id + "_pkgmeta.pkgmeta"); _metafile = metafile; if (File.Exists(metafile)) { IniDocument _ini = new IniDocument(metafile); pluginname = _ini.Sections["Package"].GetValue("plugin-name"); mainlib = _ini.Sections["Package"].GetValue("plugin-lib"); if (_ini.Sections["Package"].GetValue("referenced-libs") != "none") { reflibs = _ini.Sections["Package"].GetValue("referenced-libs").Split('|'); _isRefLibsExists = true; } plugin_name.Text = pluginname; } tip.Text = _lprov.GetValue("app.pluginmanager.remove-wizard.tip.start"); cancel.Text = _lprov.GetValue("app.pluginmanager.remove-wizard.button.cancel"); ok.Text = _lprov.GetValue("app.pluginmanager.remove-wizard.button.next"); _l_finish = _lprov.GetValue("app.pluginmanager.install-wizard.button.finish"); }
/* * 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); }
///<summary> /// Removes a member from an existing authz group. ///</summary> ///<param name="groupName">The group name which will have the member deleted.</param> ///<param name="memberNameToDelete">The name of the group member that will be removed from the group.</param> public void RemoveGroupMember(string groupName, string memberNameToDelete) { var iniDoc = new IniDocument(_authzPath, IniFileType.SambaStyle); var authzConfigFile = new IniConfigSource(iniDoc); string[] members = authzConfigFile.Configs["groups"].GetString(groupName).Split(','); var memberList = new List <string>(members.Length); memberList.AddRange(members); memberList.Remove(memberNameToDelete); members = memberList.ToArray(); string newMemberList = string.Join(",", members); authzConfigFile.Configs["groups"].Set(groupName, newMemberList); try { authzConfigFile.Save(_authzPath); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void AppendProperty_ShouldAddAPropertyToAValidSectionIfThePropertyIsUnique() { var property = Property .Builder() .WithComment(Comment .Builder() .AppendLine("property comment") .Build()) .WithKey("foo") .WithValue("bar") .Build(); Assert.False(property.IsEmpty); var doc = IniDocument .Builder() .AppendSection(Section .Builder() .WithName("section") .Build()) .Build(); Assert.True(doc.Sections()[0].IsEmpty); Assert.True(doc.IsEmpty); Assert.Single(doc.Sections()); Assert.Equal("section", doc.Sections()[0].Name); var clone = IniDocument .Builder(doc) .AppendProperty("section", property) .Build(); Assert.Equal(clone.Sections()[0].Name, doc.Sections()[0].Name); Assert.Single(clone.Sections()); Assert.Single(clone.Sections()[0].Properties()); Assert.False(clone.Sections()[0].IsEmpty); Assert.False(clone.IsEmpty); var clone2 = IniDocument .Builder(doc) .AppendProperty("section2", property) .AppendProperty("section2", property) .AppendProperty("section2", null) .AppendProperty(" ", property) .AppendProperty("", property) .AppendProperty(null, property) .AppendProperty(null, null) .AppendProperty("", null) .AppendProperty(" ", null) .AppendProperty("test", null) .Build(); Assert.Equal(clone2.Sections()[0].Name, doc.Sections()[0].Name); Assert.Equal(2, clone2.Sections().Count); Assert.Empty(clone2.Sections()[0].Properties()); Assert.True(clone2.Sections()[0].IsEmpty); Assert.Single(clone2.Sections()[1].Properties()); Assert.False(clone2.Sections()[1].IsEmpty); Assert.False(clone2.IsEmpty); }
static void Main(string[] args) { // Create a new instance of IniDocument IniDocument document = new IniDocument(); document.Load("Sample.ini"); // Make some changes document.Sections["First"].Parameters.Add( new IniParameter("Property3", 512) ); // Change syntax and formatting settings document.SyntaxDefinition = new IniSyntaxDefinition() { CommentStartChar = '#' }; // Write out document.Save(Console.Out, new IniWriterFormattingSettings { SortParameters = true }); // Wait for a key Console.ReadLine(); }
public void Parse_ShouldReturnAnIniDocumentIfTheGivenTextIsValidAndAnEmptyIniDocumentOtherwise() { var text = new StringBuilder() .AppendLine("header".AsHeader()) .AppendLine("section 1 comment".AsComment()) .AppendLine("section1".AsSection()) .AppendLine("property 1 comment".AsComment()) .AppendLine("key1=val1") .AppendLine("property 2 comment".AsComment()) .AppendLine("key2=val2") .AppendLine("section 2 comment".AsComment()) .AppendLine("section2".AsSection()) .AppendLine("property 01 comment".AsComment()) .AppendLine("key01=val01") .AppendLine("property 02 comment".AsComment()) .AppendLine("key02=val02") .AppendLine("footer".AsFooter()) .ToString().Trim(); var doc = IniDocument .Builder() .Parse(text) .Build(); Assert.False(doc.IsEmpty); Assert.Equal(text, doc.ToString()); doc = IniDocument .Builder() .Parse(null) .Build(); Assert.True(doc.IsEmpty); Assert.Equal("", doc.ToString()); }
public static async Task <IIniDocument> ParseAsync(TextReader reader) { IniDocument document = new IniDocument(); bool readHeader = true; while (reader.Peek() > 0) { string line = await reader.ReadLineAsync(); if (string.IsNullOrWhiteSpace(line)) { continue; } if (line.TrimStart()[0].Equals('[')) { readHeader = false; } if (readHeader) { document.Head.Put(IniKeyValuePairUtils.Parse(line)); } else { document.Put(await IniSectionUtils.ParseAsync(reader, line)); } } return(document); }
public async Task WriteAsync_ShouldWriteFileToNonExistingFolder() { var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "test", "tmp.unit-test-file_0.ini"); var doc = GenerateIniObject(GenerateIniDocument(1)); await doc.WriteAsync(file); await IniDocument.WriteAsync(file, "Alien", "kind", "log jaw"); var sec = await IniDocument.ReadSectionAsync(file, "Person"); Assert.Collection(sec.Properties(), s => Assert.Equal("FirstName", s.Key), s => Assert.Equal("LastName", s.Key), s => Assert.Equal("Age", s.Key)); sec = await IniDocument.ReadSectionAsync(file, "Alien"); Assert.Collection(sec.Properties(), s => Assert.Equal("kind", s.Key)); Assert.Collection(sec.Properties(), s => Assert.Equal("log jaw", s.Value)); File.Delete(file); Assert.False(File.Exists(file)); Directory.Delete(Path.GetDirectoryName(file)); Assert.False(Directory.Exists(Path.GetDirectoryName(file))); }
public DevAnalog(IniDocument ini, DevAnalogGrp grp, int index) { this.Group = grp; this.Index = index; string section = grp.Name + "\\" + (index + 1); this.Name = ini.GetString(section, "设备名称"); if (string.IsNullOrEmpty(this.Name)) { return; } if (this.Name.ToUpper() == "DUMMY") { return; } float val = ini.GetFloat(section, "AD最小", float.NaN); this.ADMin = float.IsNaN(val) ? grp.ADMin : val; val = ini.GetFloat(section, "AD最大", float.NaN); this.ADMax = float.IsNaN(val) ? grp.ADMax : val; this.IsValid = true; }
/// <include file='IniConfigSource.xml' path='//Method[@name="LoadIniDocument"]/docs/*' /> public void Load(IniDocument document) { this.Configs.Clear(); this.Merge(this); // required for SaveAll iniDocument = document; Load(); }
static void Main() { const int maxIters = 10000; var watch = new Stopwatch(); // Time how long it takes to process the INI, and estimate how much // memory the data structure takes. var startMem = GC.GetTotalMemory(false); watch.Start(); var ini = new IniDocument("test.ini"); watch.Stop(); var endMem = GC.GetTotalMemory(false); Console.WriteLine("Approx. Data Structure Mem: {0}", endMem - startMem); Console.WriteLine("{0} ms to process INI.", watch.ElapsedMilliseconds); watch.Reset(); // Time how long it takes to make many simple changes. watch.Start(); for(var i = 0; i < maxIters; ++i) { ini["User"]["Name"].Value = "md5sum"; ini["User"]["Password Hash"].Value = "e65b0dce58cbecf21e7c9ff7318f3b57"; ini["User"]["Remove This"].Value = "This shouldn'd stay."; ini["User"].Remove("Remove This"); ini["Remove This Too"].Comment = "This better not stay!"; ini.Remove("Remove This Too"); ini["User"].Comment = "These are the basic user settings.\nDon't modify them unless you know what you're doing."; } watch.Stop(); Console.WriteLine("{0} ms to make changes.", watch.ElapsedMilliseconds); watch.Reset(); // Time how long it takes to deserialize. var serializer = IniSerializer<Model2>.New(); watch.Start(); var model = serializer.Deserialize(ini); for(var i = 0; i < maxIters - 1; ++i) model = serializer.Deserialize(ini); model.Model.LastRun = DateTime.Now; watch.Stop(); Console.WriteLine("{0} ms to deserialize.", watch.ElapsedMilliseconds); watch.Reset(); // Time how long it takes to serialize. watch.Start(); for(var i = 0; i < maxIters; ++i) serializer.Serialize(model, ini); watch.Stop(); Console.WriteLine("{0} ms to serialize.", watch.ElapsedMilliseconds); watch.Reset(); // Time how long it takes to write the changes back to another file. watch.Start(); ini.Write("test2.ini"); watch.Stop(); Console.WriteLine("{0} ms write INI document to file.", watch.ElapsedMilliseconds); }
public void IniSettingsValueContainsEqualsSignParseTest() { var document = new IniDocument("IniSettingsValueContainsEqualsSignParseTestDocument.ini"); var section = document.First(); var setting = section.First(); Assert.AreEqual("ConnectionString", setting.Key); Assert.AreEqual("host=example.com;username=user;password=test123", setting.Value); }
public HHDeviceGrp(IniDocument ini, int index) { string name = ini.GetString("设备", (index + 1).ToString()); if (string.IsNullOrEmpty(name)) return; this.DevType = ini.GetInt(name, "设备类型", 0); if (this.DevType <= 0) return; this.Name = name; int propNum = ini.GetInt(name, "属性数目", 0); if (propNum <= 0) return; int devNum = ini.GetInt(name, "设备数目", 0); if (devNum <= 0) return; for (int i = 0; i < propNum; i++) { HHDeviceProperty prop = new HHDeviceProperty(ini, this, i); if (prop.IsValid) { listProperty.Add(prop); if (prop.Type == "模拟量") { listAnalogProperty.Add(prop); } else if (prop.Type == "曲线") { listCurveProperty.Add(prop); } } } if (this.DevType != 4 && this.DevType != 8) { if (listProperty.Count <= 0) return; } if (listAnalogProperty.Count > 0) { SelectProperty(0, true); } for (int i = 0; i < devNum; i++) { HHDevice device = new HHDevice(ini, i, this); if (device.IsValid) { listDevice.Add(device); } } this.BuildGroup(); this.Level = 1; this.IsValid = true; }
public void IniSettingKeyWhitespaceParseTest() { var document = new IniDocument("IniSettingKeyWhitespaceParseTestDocument.ini"); var section = document["Section"]; Assert.AreEqual(section["FirstKey"].Value, "FirstValue"); Assert.AreEqual(section["SecondKey"].Value, "SecondValue"); Assert.AreEqual(section["ThirdKey"].Value, "ThirdValue"); Assert.AreEqual(section["FourthKey"].Value, "FourthValue"); Assert.AreEqual(section["FifthKey"].Value, "FifthValue"); Assert.AreEqual(section["Sixth Key"].Value, "Sixth Value"); }
public HHDeviceProperty(IniDocument ini, HHDeviceGrp grp, int index) { this.DevGrp = grp; string sectionName = grp.Name + "\\属性" + (index + 1); this.Type = ini.GetString(sectionName, "类型"); if (string.IsNullOrEmpty(Type)) return; this.DisplayName = ini.GetString(sectionName, "显示名称"); if (string.IsNullOrEmpty(DisplayName)) return; this.Name = ini.GetString(sectionName, "名称"); if (string.IsNullOrEmpty(Name)) return; this.DataSrc = ini.GetString(sectionName, "数据来源"); if (string.IsNullOrEmpty(DataSrc)) return; string monitorType = ini.GetString(sectionName, "室外监测类型"); if (string.IsNullOrEmpty(monitorType)) return; this.MonitorType = SignalType.SignalAC; switch (monitorType) { case "直流": this.MonitorType = SignalType.SignalDC; break; case "载频": this.MonitorType = SignalType.SignalCarrier; break; case "低频": this.MonitorType = SignalType.SignalLow; break; case "直流道岔": this.MonitorType = SignalType.SignalDCCurve; break; case "交流道岔": this.MonitorType = SignalType.SignalACCurve; break; case "相位角": this.MonitorType = SignalType.SignalAngle; break; } string monitorGrp = ini.GetString(sectionName, "室外监测数据源"); if (string.IsNullOrEmpty(monitorGrp)) return; string[] grps = monitorGrp.Split(new char[]{'-'},StringSplitOptions.RemoveEmptyEntries); this.GroupIndex = int.Parse(grps[0]); this.GroupCount = 1; if (grps.Length > 1) { this.GroupCount = int.Parse(grps[1]); } this.Unit = ini.GetString(sectionName, "单位"); this.IsValid = true; }
public void LargeEqualityTest() { var ini1 = new IniDocument(); var ini2 = new IniDocument(); foreach (var ini in new[] {ini1, ini2}) { for (var i = 0; i < 1000; i++) { var section = ini[string.Format("Section{0}", i)]; for (var j = 0; j < 1000; j++) { section[string.Format("Setting{0}", j)].Value = string.Format("Value{0}", j); } } } Assert.IsTrue(ini1.Equals(ini2)); }
public void SimpleEqualityTest() { var ini1 = new IniDocument(); var ini2 = new IniDocument(); var ini3 = new IniDocument(); // the first two are constructed in the same order, and so are equal ini1["Hello"]["World"].Value = "Foo"; ini1["Second"]["Thing"].Value = "What?"; ini2["Hello"]["World"].Value = "Foo"; ini2["Second"]["Thing"].Value = "What?"; // the third has a flipped order, so it is not equal to the other two ini3["Second"]["Thing"].Value = "What?"; ini3["Hello"]["World"].Value = "Foo"; Assert.IsTrue(ini1.Equals(ini2)); Assert.IsTrue(ini2.Equals(ini1)); Assert.IsFalse(ini1.Equals(ini3)); Assert.IsFalse(ini3.Equals(ini1)); Assert.IsFalse(ini2.Equals(ini3)); Assert.IsFalse(ini3.Equals(ini2)); }
// TODO: コメント、記述順を維持した上書き public static void Format(IniDocument document, TextWriter writer) { var sections = new List<IniSection>(document.Sections); // format default section var defaultSection = sections.Find(delegate(IniSection s) { return (string.Empty.Equals(s.Name)); }); if (defaultSection != null) { FormatEntries(defaultSection, writer); sections.Remove(defaultSection); } // format other sections foreach (var section in sections) { FormatSection(section, writer); FormatEntries(section, writer); } }
public CurveGroup(IniDocument docIni, int index) { this.Name = docIni.GetString("记录曲线类型", (index + 1).ToString()); if (string.IsNullOrEmpty(Name)) return; this.Type = docIni.GetInt(this.Name, "类型", 0); if (this.Type <= 0) return; this.TimeInterval = docIni.GetFloat(this.Name, "时间间隔", 0); float limit = docIni.GetFloat(this.Name, "AD最小", float.NaN); if (float.IsNaN(limit) == false) { this.ADMin = limit; } limit = docIni.GetFloat(this.Name, "AD最大", float.NaN); if (float.IsNaN(limit) == false) { this.ADMax = limit; } int curveNum = docIni.GetInt(this.Name, "数目", 0); for (int i = 0; i < curveNum; i++) { DevCurve curve = new DevCurve(docIni, this, i); if (curve.IsValid) { if (dicCurve.ContainsKey(curve.Name) == false) { List<DevCurve> listCurve = new List<DevCurve>(); listCurve.Add(curve); dicCurve.Add(curve.Name, listCurve); } else { dicCurve[curve.Name].Add(curve); } } } if (dicCurve.Count <= 0) return; this.IsValid = true; }
private void Load(string fileName) { if (File.Exists(fileName) == false) { if (File.Exists(fileName) == false) { Assembly assembly = this.GetType().Assembly; System.IO.Stream smEmbeded = assembly.GetManifestResourceStream("ConfigManager.Config.记录曲线.rhhcfg"); byte[] data = new byte[smEmbeded.Length]; smEmbeded.Read(data, 0, data.Length); //建立目录 string dir = Path.GetDirectoryName(fileName); if (Directory.Exists(dir) == false) { Directory.CreateDirectory(dir); } File.WriteAllBytes(fileName, data); smEmbeded.Close(); } } IniDocument ini = new IniDocument(); ini.Load(fileName); int num = ini.GetInt("记录曲线类型", "数目", 0); for (int i = 0; i < num; i++) { CurveGroup grp = new CurveGroup(ini, i); if (grp.IsValid == false) continue; if (dicCurveGrp.ContainsKey(grp.Name) == false) { dicCurveGrp.Add(grp.Name, grp); } } }
public static IniDocument Parse(TextReader reader, IEqualityComparer<string> comparer) { var document = new IniDocument(comparer); var section = string.Empty; // default section name for (;;) { var line = reader.ReadLine(); if (line == null) break; // 空行は読み飛ばす if (string.Empty.Equals(line)) continue; // コメント行は読み飛ばす if (line.StartsWith(";", StringComparison.Ordinal)) continue; if (line.StartsWith("#", StringComparison.Ordinal)) continue; var matchEntry = regexEntry.Match(line); if (matchEntry.Success) { // name=valueの行 document[section][matchEntry.Groups["name"].Value.Trim()] = matchEntry.Groups["value"].Value.Trim(); continue; } var matchSection = regexSection.Match(line); if (matchSection.Success) { // [section]の行 section = matchSection.Groups["section"].Value; continue; } } return document; }
public DevCurve(IniDocument ini, CurveGroup grp, int index) { this.Group = grp; this.Index = index; string section = grp.Name + "\\" + (index + 1); this.Name = ini.GetString(section, "设备名称"); if (string.IsNullOrEmpty(this.Name)) return; if (this.Name.ToUpper() == "DUMMY") return; this.ADMax = grp.ADMax; this.ADMin = grp.ADMin; float limit = ini.GetFloat(section, "AD最小", float.NaN); if (float.IsNaN(limit) == false) { this.ADMin = limit; } limit = ini.GetFloat(section, "AD最大", float.NaN); if (float.IsNaN(limit) == false) { this.ADMax = limit; } this.Tag = ini.GetInt(grp.Name + "\\" + (index + 1), "标志", 0); this.TimeInterval = grp.TimeInterval; float interval = ini.GetFloat(grp.Name + "\\" + (index + 1), "时间间隔", float.NaN); string monitor = ini.GetString(grp.Name + "\\" + (index + 1), "室外监测类型"); this.MonitorType = SignalType.SignalACCurve; if (monitor == "直流道岔") { this.MonitorType = SignalType.SignalDCCurve; } if (float.IsNaN(interval) == false) { this.TimeInterval = interval; } this.IsValid = true; }
static void Main(string[] args) { // Create a new instance of IniDocument IniDocument document = new IniDocument(); document.Load("Sample.ini"); // Make some changes document.Sections["First"].Parameters.Add( new IniParameter("Property3", 512) ); // Change syntax and formatting settings document.SyntaxDefinition = new IniSyntaxDefinition() { CommentStartChar = '#' }; // Write out document.Save(Console.Out); // Wait for a key Console.ReadLine(); }
public void Setup() { document = IniDocument.Load(new StringReader(testDocument)); defaultSection = document.DefaultSection; }
private void Load(string fileName) { if (File.Exists(fileName) == false) { if (File.Exists(fileName) == false) { Assembly assembly = this.GetType().Assembly; System.IO.Stream smEmbeded = assembly.GetManifestResourceStream("ConfigManager.Config.设备.rhhcfg"); byte[] data = new byte[smEmbeded.Length]; smEmbeded.Read(data, 0, data.Length); //建立目录 string dir = Path.GetDirectoryName(fileName); if (Directory.Exists(dir) == false) { Directory.CreateDirectory(dir); } File.WriteAllBytes(fileName, data); smEmbeded.Close(); } } IniDocument ini = new IniDocument(); ini.Load(fileName); int num = ini.GetInt("设备", "数目", 0); for (int i = 0; i < num; i++) { HHDeviceGrp devGrp = new HHDeviceGrp(ini,i); if (devGrp.IsValid) { listGrp.Add(devGrp); } } //区间轨道电路 List<HHDeviceGrp> grpsQJ = new List<HHDeviceGrp>(); HHDeviceGrp grpQJ = null; List<HHDeviceGrp> grpsZN = new List<HHDeviceGrp>(); HHDeviceGrp grpZN = null; for (int i = 0; i < listGrp.Count; i++) { int devType=listGrp[i].DevType; switch (devType) { case 8: //区间轨道电路 grpQJ = listGrp[i]; listGrpSort.Add(grpQJ); break; case 10: //无绝缘移频 grpsQJ.Add(listGrp[i]); break; case 30: //有绝缘移频 grpsQJ.Add(listGrp[i]); break; case 208: //ZPW2000 grpsQJ.Add(listGrp[i]); break; case 4: //站内轨道电路 grpZN = listGrp[i]; listGrpSort.Add(grpZN); break; case 11: //25HZ轨道电路 grpsZN.Add(listGrp[i]); break; case 16: //480轨道电路 grpsZN.Add(listGrp[i]); break; case 17: //高压不对称 grpsZN.Add(listGrp[i]); break; case 25: //驼峰 grpsZN.Add(listGrp[i]); break; default: listGrpSort.Add(listGrp[i]); break; } if (devType != 4 && devType != 8) { listGrpUnsort.Add(listGrp[i]); } } if (grpQJ != null) { grpQJ.AddGrp(grpsQJ); } else { listGrpSort.AddRange(grpsQJ); } if (grpZN != null) { grpZN.AddGrp(grpsZN); } else { listGrpSort.AddRange(grpsZN); } }
public IDictionary GetModelSettingsAsDictionary() { var settings = Cacher.Get<IDictionary>("model.settings", true, 300, false, () => { var doc = new IniDocument(HttpContext.Current.Server.MapPath("~/config/data/models.ini.config"), true); return doc as IDictionary; }); return settings; }
public void ConfigureHandlers() { // Set up overridable image handlers so that images from the database can be handled by the MediaHelper methods // Allow the ImageHandler to handle file-system based images. ComLib.Web.HttpHandlers.ImageHandler.InitExternalHandler( (ctx) => MediaHelper.CanHandleMediaFile(ctx), (ctx) => MediaHelper.HandleMediaFile(ctx)); CommonController.SetMediaHandler(CMS.Media); CommonController.SetSettingsHandler(() => SiteSettings.Instance.Site); CommonController.SetEntitySecurityHandler(() => GetModelSettingsAsHelper()); CommonController.SetModelSettingsHandler(() => { var settings = Cacher.Get<IDictionary>("model.settings", true, 300, false, () => { var doc = new IniDocument(HttpContext.Current.Server.MapPath("~/config/data/models.ini.config"), true); return doc as IDictionary; }); return settings; }); }
protected internal static void SerializeType(Type type, object obj, IniDocument ini) { foreach (var target in Targets[type]) { var val = target.Property.GetValue(obj, BindingFlags.GetProperty, null, null, null); var containerAttr = target.Attribute as IniValueContainerAttribute; var valAttr = target.Attribute as IniValueAttribute; if(containerAttr != null) SerializeType(target.Property.PropertyType, val, ini); else if(valAttr != null) { var typeConverter = TypeDescriptor.GetConverter(target.Property.PropertyType); var valString = typeConverter.ConvertToString(val); ini[valAttr.Section][valAttr.Key].Value = valString; } // ??? internal error! else throw new Exception(); } }
public void Setup() { var reader = new StringReader(testDocument); document = IniDocument.Load(reader); }