public static void TomlNodesAreEqual(this Assert assert, TomlNode expected, TomlNode actual, bool ignoreComments = true) { Assert.AreEqual(expected.ChildrenCount, actual.ChildrenCount); Assert.IsInstanceOfType(actual, expected.GetType()); Assert.AreEqual(expected.CollapseLevel, actual.CollapseLevel); if (!ignoreComments) { Assert.AreEqual(expected.Comment, actual.Comment, "The comments are not the same!"); } if (actual is TomlString actString && expected is TomlString expString) { Assert.AreEqual(expString.Value.Replace("\r\n", "\n"), actString.Value.Replace("\r\n", "\n")); }
/// <summary> /// Tries to parse TOML file. /// </summary> /// <param name="self">TOML parser to use.</param> /// <param name="rootNode">Parsed root node. If parsing fails, the parsed document might not contain all values.</param> /// <param name="errors">Parse errors, if any occur.</param> /// <returns>True, if parsing succeeded without errors. Otherwise false.</returns> public static bool TryParse(this TOMLParser self, out TomlNode rootNode, out IEnumerable <TomlSyntaxException> errors) { try { rootNode = self.Parse(); errors = new List <TomlSyntaxException>(); return(true); } catch (TomlParseException ex) { rootNode = ex.ParsedTable; errors = ex.SyntaxErrors; return(false); } }
private void Form1_Load(object sender, EventArgs e) { LoadConfig(); int option = _config["option"].AsInteger; _parent = _config["tables"].AsArray[option]["parent"]; _child = _config["tables"].AsArray[option]["child"]; _connection = new SqlConnection( @"Data Source = DESKTOP-CMIOIHP\SQLEXPRESS; Initial Catalog = MMORPG; Integrated Security = True"); _dataSet = new DataSet(); _daParent = new SqlDataAdapter(_parent["select"].AsString.Value, _connection); _daChild = new SqlDataAdapter(_child["select"].AsString.Value, _connection); new SqlCommandBuilder(_daChild); _bsParent = new BindingSource(); _bsChild = new BindingSource(); Fill(); string relationName = $"FK_{_parent["name"].AsString.Value}{_child["name"].AsString.Value}"; DataRelation dataRelation = new DataRelation( relationName, _dataSet.Tables[_parent["name"].AsString.Value].Columns[_parent["key"].AsString.Value], _dataSet.Tables[_child["name"].AsString.Value].Columns[_child["key"].AsString.Value] ); _dataSet.Relations.Add(dataRelation); _bsParent.DataSource = _dataSet; _bsParent.DataMember = _parent["name"].AsString.Value; _bsChild.DataSource = _bsParent; _bsChild.DataMember = relationName; ParentGrid.DataSource = _bsParent; ChildGrid.DataSource = _bsChild; ParentLabel.Text = _parent["name"].AsString.Value; ChildLabel.Text = _child["name"].AsString.Value; }
/// <summary> /// Gets node given a fully-keyed path to it. /// </summary> /// <param name="self">Node to start search from.</param> /// <param name="path">Full path to the target node. The path must follow the TOML format.</param> /// <returns>Found node. If no matching node is found, returns null.</returns> public static TomlNode FindNode(this TomlNode self, string path) {
// Method to change the Config.toml private void setConfig() { // Read the sample to get the language settings + the paths string samplePath = Directory.GetCurrentDirectory() + @"\Config.sample.toml"; using (StreamReader reader = new StreamReader(File.OpenRead(samplePath))) { TomlTable tt = TOML.Parse(reader); // Change the table in the toml file string path = Directory.GetCurrentDirectory(); string configData = path + @"\Config.toml"; int boss = 0; if (boxBossIndex.Text == "Top") { boss = 0; } if (boxBossIndex.Text == "Middle") { boss = 1; } if (boxBossIndex.Text == "Bottom") { boss = 2; } TomlTable t = new TomlTable(); t = tt; // Get all values in a string-array string[] atkPos = boxAttackPos.Text.Split(',').ToArray(); string[] atkNeut = boxAttackNeut.Text.Split(',').ToArray(); string[] atkNeg = boxAttackNeg.Text.Split(',').ToArray(); string[] speedPos = boxSpeedPos.Text.Split(',').ToArray(); string[] speedNeut = boxSpeedNeut.Text.Split(',').ToArray(); string[] speedNeg = boxSpeedNeg.Text.Split(',').ToArray(); // General Settings t["BOSS"].AsString.Value = Utils.ConvertBossNameToBossId(boxPokemon.Text); t["BASE_BALL"].AsString.Value = Utils.ConvertBallNameToBallId(boxBaseBall.Text); t["LEGENDARY_BALL"].AsString.Value = Utils.ConvertBallNameToBallId(boxLegendBall.Text); t["MODE"].AsString.Value = boxMode.Text.ToUpper(); t["FIND_PATH_WINS"].AsInteger.Value = int.Parse(boxPathWins.Text); t["COM_PORT"].AsString.Value = boxComPort.Text; t["VIDEO_INDEX"].AsInteger.Value = boxVideoCapture.SelectedIndex; t["TESSERACT_PATH"].AsString.Value = boxTesseract.Text; // Advanced Settings t["advanced"]["VIDEO_SCALE"].AsFloat.Value = float.Parse(boxVideoScale.Text); t["advanced"]["VIDEO_EXTRA_DELAY"].AsFloat.Value = float.Parse(boxVideoDelay.Text); t["advanced"]["PABOTBASE_HEX"].AsBoolean.Value = boxPABotBaseHex.Checked; t["advanced"]["BOSS_INDEX"].AsInteger.Value = boss; t["advanced"]["DYNITE_ORE"].AsInteger.Value = int.Parse(boxDyniteOre.Text); t["advanced"]["CONSECUTIVE_RESETS"].AsInteger.Value = int.Parse(boxConsecutiveResets.Text); t["advanced"]["NON_LEGEND"].AsString.Value = boxNonLegend.Text; t["advanced"]["MAXIMUM_ORE_COST"].AsInteger.Value = int.Parse(boxMaxDynite.Text); t["advanced"]["ENABLE_DEBUG_LOGS"].AsBoolean.Value = checkBoxDebugLogs.Checked; // Stat Settings t["stats"]["CHECK_ATTACK_STAT"].AsBoolean.Value = boxCheckAttack.Checked; t["stats"]["CHECK_SPEED_STAT"].AsBoolean.Value = boxCheckSpeed.Checked; // Create TomlNodes for each stat +,=,- TomlNode node = new TomlNode[] { }; TomlNode node1 = new TomlNode[] { }; TomlNode node2 = new TomlNode[] { }; TomlNode node3 = new TomlNode[] { }; TomlNode node4 = new TomlNode[] { }; TomlNode node5 = new TomlNode[] { }; // Get all values from the array into int and add it to the node for (int i = 0; i < atkPos.Length; i++) { node.Add(int.Parse(atkPos[i])); } for (int i = 0; i < atkNeut.Length; i++) { node1.Add(int.Parse(atkNeut[i])); } for (int i = 0; i < atkNeg.Length; i++) { node2.Add(int.Parse(atkNeg[i])); } for (int i = 0; i < speedPos.Length; i++) { node3.Add(int.Parse(speedPos[i])); } for (int i = 0; i < speedNeut.Length; i++) { node4.Add(int.Parse(speedNeut[i])); } for (int i = 0; i < speedNeg.Length; i++) { node5.Add(int.Parse(speedNeg[i])); } // Stats t["stats"]["ATTACK_STATS"]["positive"] = node; t["stats"]["ATTACK_STATS"]["neutral"] = node1; t["stats"]["ATTACK_STATS"]["negative"] = node2; t["stats"]["SPEED_STATS"]["positive"] = node3; t["stats"]["SPEED_STATS"]["neutral"] = node4; t["stats"]["SPEED_STATS"]["negative"] = node5; // Discord Settings t["discord"]["WEBHOOK_ID"].AsString.Value = boxWebhookID.Text; t["discord"]["WEBHOOK_TOKEN"].AsString.Value = boxWebhookToken.Text; t["discord"]["USER_ID"].AsString.Value = boxUserID.Text; t["discord"]["USER_SHORT_NAME"].AsString.Value = boxPingName.Text; t["discord"]["UPDATE_LEVELS"].AsString.Value = boxPingSettings.Text; // Game Language Settings t["language"]["LANGUAGE"].AsString.Value = boxGameLanguage.Text; using (StreamWriter writer = new StreamWriter(File.Open(configData, FileMode.Create))) { t.WriteTo(writer); writer.Flush(); } } }
/// <summary> /// Gets node given a fully-keyed path to it. /// </summary> /// <param name="self">Node to start search from.</param> /// <param name="path">Full path to the target node. The path must follow the TOML format.</param> /// <returns>Found node. If no matching node is found, returns null.</returns> public static TomlNode FindNode(this TomlNode self, string path) { bool ProcessQuotedValueCharacter(char quote, bool isNonLiteral, char c, int next, StringBuilder sb, ref bool escaped) { if (TomlSyntax.ShouldBeEscaped(c)) { throw new Exception($"The character U+{(int) c:X8} must be escaped in a string!"); } if (escaped) { sb.Append(c); escaped = false; return(false); } if (c == quote) { return(true); } if (isNonLiteral && c == TomlSyntax.ESCAPE_SYMBOL) { if (next >= 0 && (char)next == quote) { escaped = true; } } if (c == TomlSyntax.NEWLINE_CHARACTER) { throw new Exception("Encountered newline in single line string!"); } sb.Append(c); return(false); } string ReadQuotedValueSingleLine(char quote, TextReader reader, char initialData = '\0') { var isNonLiteral = quote == TomlSyntax.BASIC_STRING_SYMBOL; var sb = new StringBuilder(); var escaped = false; if (initialData != '\0' && ProcessQuotedValueCharacter(quote, isNonLiteral, initialData, reader.Peek(), sb, ref escaped)) { return(isNonLiteral ? sb.ToString().Unescape() : sb.ToString()); } int cur; while ((cur = reader.Read()) >= 0) { var c = (char)cur; if (ProcessQuotedValueCharacter(quote, isNonLiteral, c, reader.Peek(), sb, ref escaped)) { break; } } return(isNonLiteral ? sb.ToString().Unescape() : sb.ToString()); } void ReadKeyName(TextReader reader, List <string> parts) { var buffer = new StringBuilder(); var quoted = false; int cur; while ((cur = reader.Peek()) >= 0) { var c = (char)cur; if (TomlSyntax.IsWhiteSpace(c)) { break; } if (c == TomlSyntax.SUBKEY_SEPARATOR) { if (buffer.Length == 0) { throw new Exception($"Found an extra subkey separator in {".".Join(parts)}..."); } parts.Add(buffer.ToString()); buffer.Length = 0; quoted = false; goto consume_character; } if (TomlSyntax.IsQuoted(c)) { if (quoted) { throw new Exception("Expected a subkey separator but got extra data instead!"); } if (buffer.Length != 0) { throw new Exception("Encountered a quote in the middle of subkey name!"); } // Consume the quote character and read the key name buffer.Append(ReadQuotedValueSingleLine((char)reader.Read(), reader)); quoted = true; continue; } if (TomlSyntax.IsBareKey(c)) { buffer.Append(c); goto consume_character; } // If we see an invalid symbol, let the next parser handle it throw new Exception($"Unexpected symbol {c}"); consume_character: reader.Read(); } if (buffer.Length == 0) { throw new Exception($"Found an extra subkey separator in {".".Join(parts)}..."); } parts.Add(buffer.ToString()); } var pathParts = new List <string>(); using (var sr = new StringReader(path)) { ReadKeyName(sr, pathParts); } var curNode = self; foreach (var pathPart in pathParts) { if (!curNode.TryGetNode(pathPart, out var node)) { return(null); } curNode = node; } return(curNode); }
/// <summary> /// Merges the current TOML node with another node. Useful for default values. /// </summary> /// <param name="self">Node to merge into.</param> /// <param name="with">Node to merge.</param> /// <param name="mergeNewValues"> /// If true, will also merge values present in the other node that are not present in this /// node. /// </param> /// <returns>The node that the other node was merged into.</returns> public static TomlNode MergeWith(this TomlNode self, TomlNode with, bool mergeNewValues = false) { switch (self) { case TomlTable tbl when with is TomlTable withTbl: { foreach (var keyValuePair in withTbl.RawTable) { if (tbl.TryGetNode(keyValuePair.Key, out var node)) { node.MergeWith(keyValuePair.Value, mergeNewValues); } else if (mergeNewValues) { tbl[keyValuePair.Key] = node; } } } break; case TomlArray arr when with is TomlArray withArr: { if (arr.ChildrenCount != 0 && withArr.ChildrenCount != 0 && arr[0].GetType() != withArr[0].GetType()) { return(self); } for (var i = 0; i < withArr.RawArray.Count; i++) { if (i < arr.RawArray.Count) { arr.RawArray[i].MergeWith(withArr.RawArray[i], mergeNewValues); } else { arr.RawArray.Add(withArr.RawArray[i]); } } } break; case TomlBoolean bl when with is TomlBoolean withBl: bl.Value = withBl.Value; break; case TomlDateTime dt when with is TomlDateTime withDt: dt.Value = withDt.Value; break; case TomlFloat fl when with is TomlFloat withFl: fl.Value = withFl.Value; break; case TomlInteger tint when with is TomlInteger withTint: tint.Value = withTint.Value; break; case TomlString tstr when with is TomlString withTStr: tstr.Value = withTStr.Value; break; } return(self); }
private static void Traverse(JSONNode obj, TomlNode node) { if (obj is JSONArray jsonArr && node is TomlArray tomlArray) { foreach (var tomlArrayValue in tomlArray.Children) { var newNode = new JSONObject(); jsonArr.Add(newNode); Traverse(newNode, tomlArrayValue); } return; } if (node.HasValue) { switch (node) { case TomlString str: obj["type"] = "string"; obj["value"] = str.ToString(); break; case TomlInteger i: obj["type"] = "integer"; obj["value"] = i.Value.ToString(); break; case TomlFloat f: obj["type"] = "float"; obj["value"] = f.ToString(); break; case TomlDateTime dt: if (dt.OnlyDate) { obj["type"] = "date"; } else if (dt.OnlyTime) { obj["type"] = "time"; } else if (dt.Value.Kind == DateTimeKind.Local) { obj["type"] = "datetime-local"; } else { obj["type"] = "datetime"; } obj["value"] = dt.ToString(); break; case TomlBoolean b: obj["type"] = "bool"; obj["value"] = b.ToString(); break; case TomlArray arr: var jsonArray = new JSONArray(); obj["type"] = "array"; obj["value"] = jsonArray; foreach (var arrValue in arr.Children) { var o = new JSONObject(); jsonArray.Add(o); Traverse(o, arrValue); } break; } return; } foreach (var key in node.Keys) { var val = node[key]; JSONNode newNode; if (val is TomlArray arr && arr.ChildrenCount > 0 && arr[0] is TomlTable) { newNode = new JSONArray(); }