private void DictionaryToMap(object obj, YamlMapping mapping) { var accessor = ObjectMemberAccessor.FindFor(obj.GetType()); var iter = ((IEnumerable)obj).GetEnumerator(); // When this is a pure dictionary, we can directly add key,value to YamlMapping var dictionary = accessor.IsPureDictionary ? mapping : map(); Func <object, object> key = null, value = null; while (iter.MoveNext()) { if (key == null) { var keyvalue = iter.Current.GetType(); var keyprop = keyvalue.GetProperty("Key"); var valueprop = keyvalue.GetProperty("Value"); key = o => keyprop.GetValue(o, new object[0]); value = o => valueprop.GetValue(o, new object[0]); } dictionary.Add( ObjectToNode(key(iter.Current), accessor.KeyType), ObjectToNode(value(iter.Current), accessor.ValueType) ); } if (!accessor.IsPureDictionary && dictionary.Count > 0) { mapping.Add(MapKey("~Items"), dictionary); } }
/// <summary> /// Create a mapping node. /// </summary> /// <param name="nodes">Sequential list of key/value pairs.</param> /// <param name="tag">Tag for the mapping.</param> /// <returns>Created mapping node.</returns> protected static YamlMapping map_tag(string tag, params YamlNode[] nodes) { var map = new YamlMapping(nodes); map.Tag = tag; return(map); }
protected YamlMapping CreateKeyValue(string key, string value) { var kv = new YamlMapping(); kv[key] = new YamlValue(value); return(kv); }
protected static YamlMapping SetSequence(YamlMapping m, string key, params YamlElement[] values) { var seq = new YamlSequence(); seq.AddRange(values); m[key] = seq; return(m); }
private void VerifyPerson(YamlMapping mapping, string name, string reason) { Assert.That(mapping, Is.Not.Null); Assert.That(mapping.ContainsKey("name"), Is.True); Assert.That(mapping["name"].ToString(), Is.EqualTo(name)); Assert.That(mapping.ContainsKey("reason"), Is.True); Assert.That(mapping["reason"].ToString(), Is.EqualTo(reason)); }
protected static YamlMapping EnsureSequence(YamlMapping m, string key) { if (m[key] == null) { m[key] = new YamlSequence(); } return(m); }
static Texts() { scripts = ParseYamlScripts("Text.Scripts.General.yaml") as YamlMapping; blind = ParseTextScript("Text.Scripts.Blind.txt"); ganon = ParseTextScript("Text.Scripts.Ganon.txt"); tavernMan = ParseTextScript("Text.Scripts.TavernMan.txt"); triforceRoom = ParseTextScript("Text.Scripts.TriforceRoom.txt"); }
public void CustomActivator() { var brush = new YamlMapping("Color", "Blue"); brush.Tag = "!System.Drawing.SolidBrush"; Assert.Throws<MissingMethodException>(()=>constructor.NodeToObject(brush, YamlNode.DefaultConfig)); var config = new YamlConfig(); config.AddActivator<System.Drawing.SolidBrush>(() => new System.Drawing.SolidBrush(System.Drawing.Color.Black)); Assert.AreEqual(System.Drawing.Color.Blue, ((System.Drawing.SolidBrush)constructor.NodeToObject(brush, config)).Color); }
static void EnsureDefaultBranches(YamlMapping firstMapping) { YamlElement branches = firstMapping["branches"]; if (branches == null) { firstMapping["branches"] = SetSequence(new YamlMapping(), "only", new YamlValue("master"), new YamlValue("develop")); } }
static void Main(string[] args) { // yaml file을 열고, database name 등 사용자의 설정을 읽는다. string dbName; string CSVFilter; string serverName; string userID; string password; try { // look for yaml file var n = YamlMapping.FromYamlFile("csv-to-db-config.yaml"); var m = (YamlMapping)n[0]; dbName = ((YamlScalar)m["Database"]).Value; CSVFilter = ((YamlScalar)m["CSV-Filter"]).Value; serverName = ((YamlScalar)m["Server"]).Value; userID = ((YamlScalar)m["User-ID"]).Value; password = ((YamlScalar)m["Password"]).Value; } catch (Exception e) { Console.WriteLine("** Open csv-to-db-config.yaml failed."); Console.WriteLine(e.ToString()); return; } // 조건에 맞는 파일들을 찾아서, DB record에 넣는다. var files = Directory.GetFiles(".", CSVFilter); foreach (var fileName in files) { var pureName = Path.GetFileNameWithoutExtension(fileName); CsvToRecord v = new CsvToRecord(); v.m_DBName = dbName; v.m_tableName = pureName; v.m_serverName = serverName; v.m_userID = userID; v.m_password = password; v.Process(); // 에러가 났으면 if (v.m_error != null) { // 에러를 출력하자. Console.WriteLine($"**Failed to write to DB for {v.m_tableName}. {v.m_error.ToString()}"); } else { Console.WriteLine($"DB write ok: {v.m_tableName}"); } } }
public static object GetValue(this YamlMapping mapping, Type asType, string key) { object value = GetValue(mapping, key); if (value != null) { return(System.Convert.ChangeType(value, asType)); } return(null); }
public void TestChangingMappingKey() { var key = (YamlScalar)"def"; var map = new YamlMapping(key, 3); key.Value = "ghi"; Assert.IsTrue(map.ContainsKey(key)); Assert.IsTrue(map.Remove(key)); map[map] = 4; Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); var map2 = new YamlMapping(key, 3); map2[map2] = 2; map2[map] = 4; Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); map[map2] = 2; Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); map.Tag = YamlNode.DefaultTagPrefix + "map"; Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); Assert.IsTrue(map.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map[map2]); var seq = new YamlSequence(map); map.Add(seq, 4); Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); Assert.IsTrue(map.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map[map2]); seq.Add(map); Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); Assert.IsTrue(map.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map[map2]); }
public void CustomActivator() { var brush = new YamlMapping("Color", "Blue"); brush.Tag = "!System.Drawing.SolidBrush"; Assert.Throws <MissingMethodException>(() => constructor.NodeToObject(brush, YamlNode.DefaultConfig)); var config = new YamlConfig(); config.AddActivator <System.Drawing.SolidBrush>(() => new System.Drawing.SolidBrush(System.Drawing.Color.Black)); Assert.AreEqual(System.Drawing.Color.Blue, ((System.Drawing.SolidBrush)constructor.NodeToObject(brush, config)).Color); }
public void TrackerAssignmentTest() { var tracker = new YamlNodeTracker(); var stream = new YamlStream(tracker); var document = new YamlDocument(); var sequence = new YamlSequence(); document.Contents = sequence; var mapping = new YamlMapping(); sequence.Add(mapping); var key = new YamlValue("key"); var value = new YamlValue("value"); var eventList = new List <TrackerEventArgs>(); tracker.TrackerEvent += (sender, args) => eventList.Add(args); mapping[key] = value; Assert.IsNull(document.Tracker); Assert.IsNull(sequence.Tracker); Assert.IsNull(mapping.Tracker); Assert.IsNull(key.Tracker); Assert.IsNull(value.Tracker); stream.Add(document); Assert.AreEqual(tracker, document.Tracker); Assert.AreEqual(tracker, sequence.Tracker); Assert.AreEqual(tracker, mapping.Tracker); Assert.AreEqual(tracker, key.Tracker); Assert.AreEqual(tracker, value.Tracker); Assert.AreEqual(4, eventList.Count); Assert.IsTrue(eventList[0] is MappingPairAdded); Assert.IsTrue(eventList[1] is SequenceElementAdded); Assert.IsTrue(eventList[2] is DocumentContentsChanged); Assert.IsTrue(eventList[3] is StreamDocumentAdded); eventList.Clear(); var key2 = new YamlValue("key2"); var value2 = new YamlValue("value2"); mapping[key2] = value2; Assert.AreEqual(1, eventList.Count); Assert.IsTrue(eventList[0] is MappingPairAdded); }
public static string Save() { YamlMapping Map = new YamlMapping(); YamlSerializer Serializer = new YamlSerializer(); ForeachSetting((F, A) => { // HAX Map.Add(F.Name, YamlNode.FromYaml(Serializer.Serialize(F.GetValue(null)))[0]); }); return Map.ToYaml(); }
void EnsureDefaultBranches(YamlMapping firstMapping) { YamlElement branches = firstMapping["branches"]; if (branches == null) { firstMapping["branches"] = branches = new YamlMapping(); } if (branches is YamlMapping m) { SetSequence(m, "only", new YamlValue(GitFolder.World.MasterBranchName), new YamlValue(GitFolder.World.DevelopBranchName)); } }
public static T GetValue <T>(this YamlMapping mapping, string key) { object value = GetValue(mapping, key); if (value is T typed) { return(typed); } if (value is YamlMapping childMapping) { return(Convert <T>(childMapping)); } return(default(T)); }
public void CustomActivator() { var brush = new YamlMapping("Color", "Blue"); brush.Tag = "!System.Drawing.SolidBrush"; var config = new YamlConfig(); config.Register(new LegacyTypeConverterFactory()); config.LookupAssemblies.Add(typeof(System.Drawing.SolidBrush).Assembly); Assert.Throws <MissingMethodException>(() => constructor.NodeToObject(brush, new SerializerContext(config))); config.AddActivator <System.Drawing.SolidBrush>(() => new System.Drawing.SolidBrush(System.Drawing.Color.Black)); Assert.AreEqual(System.Drawing.Color.Blue, ((System.Drawing.SolidBrush)constructor.NodeToObject(brush, new SerializerContext(config))).Color); }
public static object GetValue(this YamlMapping mapping, string key, object ifKeyNotPresent = null) { if (!mapping.ContainsKey(key)) { return(ifKeyNotPresent); } object value = mapping[key]; if (value is YamlScalar scalar) { return(scalar.Value); } return(value); }
public static YamlNode ToYamlNode(this object val) { Type type = val.GetType(); YamlMapping node = new YamlMapping(); List <PropertyInfo> properties = new List <PropertyInfo>(type.GetProperties()); properties.Sort((l, r) => l.MetadataToken.CompareTo(r.MetadataToken)); foreach (PropertyInfo property in properties) { object propVal = property.GetValue(val); if (propVal != null) { if (property.IsEnumerable()) { YamlSequence yamlSequence = new YamlSequence(); node.Add(property.Name, yamlSequence); foreach (object v in ((IEnumerable)propVal)) { yamlSequence.Add(v.ToYamlNode()); } } else { if (property.PropertyType == typeof(bool) || property.PropertyType == typeof(bool?) || property.PropertyType == typeof(int) || property.PropertyType == typeof(int?) || property.PropertyType == typeof(long) || property.PropertyType == typeof(long?) || property.PropertyType == typeof(decimal) || property.PropertyType == typeof(decimal?) || property.PropertyType == typeof(double) || property.PropertyType == typeof(double?) || property.PropertyType == typeof(string) || property.PropertyType == typeof(byte[]) || property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?)) { node.Add(property.Name, new YamlScalar(propVal.ToString())); } else { node.Add(property.Name, propVal.ToYamlNode()); } } } } return(node); }
private void MappingToYaml(YamlMapping node, string pres, Context c) { var tag = TagToYaml(node, "!!map"); if (node.Count > 0) { if (tag != "" || c == Context.Map) { WriteLine(tag); c = Context.Normal; } string press = pres + " "; foreach (var item in node) { if (c != Context.List) { Write(pres); } c = Context.Normal; if (WriteImplicitKeyIfPossible(item.Key, press, Context.NoBreak)) { Write(": "); NodeToYaml(item.Value, press, Context.Map); } else { // explicit key Write("? "); NodeToYaml(item.Key, press, Context.List); Write(pres); Write(": "); NodeToYaml(item.Value, press, Context.List); } } } else { if (tag != "" && tag != "!!map") { Write(tag + " "); } Write("{}"); if (c != Context.NoBreak) { WriteLine(); } } }
private bool Save(FATabStripItem tab) { var tb = (tab.Controls[0] as RegexTesterTab); YamlNode pnode = new YamlMapping( "regex", new YamlScalar(tb.RegexText.Text), "text", new YamlScalar(tb.TesterText.Text) ); if (tab.Tag == null) { if (sfdMain.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return(false); } tab.Title = Path.GetFileName(sfdMain.FileName); tab.Tag = sfdMain.FileName; if (!RecentFiles.Contains(sfdMain.FileName)) { RecentFiles.Add(sfdMain.FileName); } } try { File.WriteAllText(tab.Tag as string, pnode.ToYaml()); tb.RegexText.IsChanged = false; tb.TesterText.IsChanged = false; } catch (Exception ex) { if (MessageBox.Show(ex.Message, "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry) { return(Save(tab)); } else { return(false); } } tb.Invalidate(); return(true); }
public void ApplySettings(IActivityMonitor m) { if (!this.CheckCurrentBranch(m)) { return; } YamlMapping firstMapping = GetFirstMapping(m, true); if (firstMapping == null) { m.Error("First mapping should not return null !"); return; } // We don't use GitLab for public repositories if (GitFolder.IsPublic || GitFolder.KnownGitProvider != KnownGitProvider.GitLab) { if (TextContent != null) { m.Log(LogLevel.Info, "The project is public or the repository is not on GitLab, so we don't use GitLab and the .gitlab-ci.yml is not needed."); Delete(m); } return; } // We use GitLab when the repository is private. YamlMapping codeCakeJob = FindOrCreateYamlElement(m, firstMapping, "codecakebuilder"); SetSequence(codeCakeJob, "tags", new YamlValue("windows")); SetSequence(codeCakeJob, "script", new YamlValue("dotnet run --project CodeCakeBuilder -nointeraction") ); codeCakeJob["artifacts"] = new YamlMapping() { ["paths"] = new YamlSequence() { new YamlValue(@"'**\*.log'"), new YamlValue(@"'**\*.trx'"), new YamlValue(@"'**\Tests\**\TestResult*.xml'"), new YamlValue(@"'**Tests\**\Logs\**\*'"), }, ["when"] = new YamlValue("always"), ["expire_in"] = new YamlValue("6 month") }; CreateOrUpdate(m, YamlMappingToString(m)); }
private void SaveConfig() { var sec = new YamlSequence(); foreach (var rf in RecentFiles) { sec.Add(new YamlScalar(rf)); } YamlNode pnode = new YamlMapping( "recentfiles", sec ); var path = Path.Combine(GetExecPath(), "cache.yml"); pnode.ToYamlFile(path); }
public object ReadYaml(ref ObjectContext objectContext) { if (objectContext.Descriptor.Type == typeof(YamlNode)) { if (objectContext.Reader.Accept <MappingStart>()) { return(YamlMapping.Load(objectContext.Reader, new YamlNodeTracker())); } if (objectContext.Reader.Accept <SequenceStart>()) { return(YamlSequence.Load(objectContext.Reader, new YamlNodeTracker())); } if (objectContext.Reader.Accept <Scalar>()) { return(YamlValue.Load(objectContext.Reader, new YamlNodeTracker())); } } if (objectContext.Descriptor.Type == typeof(YamlMapping)) { if (objectContext.Reader.Accept <MappingStart>()) { return(YamlMapping.Load(objectContext.Reader, new YamlNodeTracker())); } throw new YamlException($"Expected {nameof(MappingStart)} but did not find it"); } if (objectContext.Descriptor.Type == typeof(YamlSequence)) { if (objectContext.Reader.Accept <SequenceStart>()) { return(YamlSequence.Load(objectContext.Reader, new YamlNodeTracker())); } throw new YamlException($"Expected {nameof(SequenceStart)} but did not find it"); } if (objectContext.Descriptor.Type == typeof(YamlValue)) { if (objectContext.Reader.Accept <Scalar>()) { return(YamlValue.Load(objectContext.Reader, new YamlNodeTracker())); } throw new YamlException($"Expected {nameof(Scalar)} but did not find it"); } throw new YamlException($"{objectContext.Descriptor.Type} is not a supported {nameof(YamlNode)} type"); }
private void ValidatePersonYaml(YamlMapping map, string name, string age, string[] phones) { Assert.That(map, Is.Not.Null); Assert.That(map.ContainsKey("name"), Is.True); Assert.That(map.ContainsKey("age"), Is.True); Assert.That(map.ContainsKey("phones"), Is.True); Assert.That(map["name"].ToString(), Is.EqualTo(name)); Assert.That(map["age"].ToString(), Is.EqualTo(age)); var phoneSeq = map["phones"] as YamlSequence; Assert.That(phoneSeq, Is.Not.Null); Assert.That(phoneSeq.Count, Is.EqualTo(phones.Length)); for (int i = 0; i < phones.Length; i++) { Assert.That(phoneSeq[i].ToString(), Is.EqualTo(phones[i])); } }
protected YamlMapping FindOrCreateYamlElement(IActivityMonitor m, YamlMapping mapping, string elementName) ///Too similar with AppveyorFile.FindOrCreateEnvironement. We should mutualise these. { YamlMapping jobMapping; YamlElement job = mapping[elementName]; if (job != null) { jobMapping = job as YamlMapping; if (jobMapping == null) { m.Error($"Unable to parse Yaml file. Expecting job mapping but found '{job.GetType()}'."); } } else { mapping[elementName] = jobMapping = new YamlMapping(); } return(jobMapping); }
public static object Convert(this YamlMapping mapping, Type type) { object result = type.Construct(); foreach (PropertyInfo property in type.GetProperties()) { if (mapping.ContainsKey(property.Name)) { YamlNode node = mapping[property.Name]; if (node is YamlScalar value) { result.Property(property.Name, System.Convert.ChangeType(value.Value, property.PropertyType)); } else if (node is YamlMapping childMapping) { result.Property(property.Name, childMapping.Convert(property.PropertyType)); } } } return(result); }
protected YamlMapping GetFirstMapping(IActivityMonitor m, bool autoCreate) { if (_firstMapping == null) { var input = TextContent; if (input == null && autoCreate) { input = String.Empty; } if (input != null) { _yamlStream = YamlStream.Load(new StringReader(input)); if (_yamlStream.Count > 0) { _doc = _yamlStream[0]; } else { _yamlStream.Add((_doc = new YamlDocument())); } if (_doc.Contents == null) { _doc.Contents = (_firstMapping = new YamlMapping()); } else { _firstMapping = _doc.Contents as YamlMapping; if (_firstMapping == null) { m.Error($"Unable to parse Yaml file. Missing a first mapping object as the first document content."); } } } } return(_firstMapping); }
object MappingToObject(YamlMapping map, Type type, object obj, Dictionary<YamlNode, object> appeared) { // 1) Give a chance to deserialize through a IYamlSerializable interface var serializable = config.Serializable.FindSerializable(context, obj, type); if (serializable != null) { return serializable.Deserialize(context, map, type); } // 2) Naked !!map is constructed as Dictionary<object, object>. if ( ( ( map.ShorthandTag() == "!!map" && type == null ) || type == typeof(Dictionary<object,object>) ) && obj == null ) { var objectDictionary = new Dictionary<object, object>(); appeared.Add(map, objectDictionary); foreach ( var entry in map ) objectDictionary.Add(NodeToObjectInternal(entry.Key, null, appeared), NodeToObjectInternal(entry.Value, null, appeared)); return objectDictionary; } if (type == null) { throw new FormatException("Unable to find type for {0}]".DoFormat(map.ToString())); } // 3) Give a chance to config.Activator if ( obj == null ) { obj = config.Activator.Activate(type); appeared.Add(map, obj); } else { if ( appeared.ContainsKey(map) ) throw new InvalidOperationException("This member is not writeable: {0}".DoFormat(obj.ToString())); } var dictionary = obj as IDictionary; var access = ObjectMemberAccessor.FindFor(type); foreach (var entry in map) { if (obj == null) throw new InvalidOperationException("Object is not initialized"); // If this is a pure dictionary, we can directly add key,value to it if (dictionary != null && access.IsPureDictionary) { dictionary.Add(NodeToObjectInternal(entry.Key, access.KeyType, appeared), NodeToObjectInternal(entry.Value, access.ValueType, appeared)); continue; } // Else go the long way var name = (string)NodeToObjectInternal(entry.Key, typeof(string), appeared); if (name == "~Items") { if (entry.Value is YamlSequence) { SequenceToObject((YamlSequence)entry.Value, obj.GetType(), obj, appeared); } else if (entry.Value is YamlMapping) { if (!access.IsDictionary || dictionary == null) throw new FormatException("{0} is not a dictionary type.".DoFormat(type.FullName)); dictionary.Clear(); foreach (var child in (YamlMapping)entry.Value) dictionary.Add(NodeToObjectInternal(child.Key, access.KeyType, appeared), NodeToObjectInternal(child.Value, access.ValueType, appeared)); } else { throw new InvalidOperationException("Member {0} of {1} is not serializable.".DoFormat(name, type.FullName)); } } else { if (!access.ContainsKey(name)) throw new FormatException("{0} does not have a member {1}.".DoFormat(type.FullName, name)); switch (access[name].SerializeMethod) { case YamlSerializeMethod.Assign: access[obj, name] = NodeToObjectInternal(entry.Value, access[name].Type, appeared); break; case YamlSerializeMethod.Content: MappingToObject((YamlMapping)entry.Value, access[name].Type, access[obj, name], appeared); break; case YamlSerializeMethod.Binary: access[obj, name] = ScalarToObject((YamlScalar)entry.Value, access[name].Type); break; default: throw new InvalidOperationException( "Member {0} of {1} is not serializable.".DoFormat(name, type.FullName)); } } } return obj; }
object MappingToObject(YamlMapping map, Type type, object obj, Dictionary <YamlNode, object> appeared) { // Naked !!map is constructed as Dictionary<object, object>. if (((map.ShorthandTag() == "!!map" && type == null) || type == typeof(Dictionary <object, object>)) && obj == null) { var dict = new Dictionary <object, object>(); appeared.Add(map, dict); foreach (var entry in map) { dict.Add(NodeToObjectInternal(entry.Key, null, appeared), NodeToObjectInternal(entry.Value, null, appeared)); } return(dict); } if (obj == null) { obj = config.Activator.Activate(type); appeared.Add(map, obj); } else { if (appeared.ContainsKey(map)) { throw new InvalidOperationException("This member is not writeable: {0}".DoFormat(obj.ToString())); } } var access = ObjectMemberAccessor.FindFor(type); foreach (var entry in map) { if (obj == null) { throw new InvalidOperationException("Object is not initialized"); } var name = (string)NodeToObjectInternal(entry.Key, typeof(string), appeared); switch (name) { case "ICollection.Items": if (access.CollectionAdd == null) { throw new FormatException("{0} is not a collection type.".DoFormat(type.FullName)); } access.CollectionClear(obj); foreach (var item in (YamlSequence)entry.Value) { access.CollectionAdd(obj, NodeToObjectInternal(item, access.ValueType, appeared)); } break; case "IDictionary.Entries": if (!access.IsDictionary) { throw new FormatException("{0} is not a dictionary type.".DoFormat(type.FullName)); } var dict = obj as IDictionary; dict.Clear(); foreach (var child in (YamlMapping)entry.Value) { dict.Add(NodeToObjectInternal(child.Key, access.KeyType, appeared), NodeToObjectInternal(child.Value, access.ValueType, appeared)); } break; default: if (!access.ContainsKey(name)) { // ignoring non existing properties //throw new FormatException("{0} does not have a member {1}.".DoFormat(type.FullName, name)); continue; } switch (access[name].SerializeMethod) { case YamlSerializeMethod.Assign: access[obj, name] = NodeToObjectInternal(entry.Value, access[name].Type, appeared); break; case YamlSerializeMethod.Content: MappingToObject((YamlMapping)entry.Value, access[name].Type, access[obj, name], appeared); break; case YamlSerializeMethod.Binary: access[obj, name] = ScalarToObject((YamlScalar)entry.Value, access[name].Type); break; default: throw new InvalidOperationException( "Member {0} of {1} is not serializable.".DoFormat(name, type.FullName)); } break; } } return(obj); }
public void Example2_27_YAML1_2() { var invoice = new YamlMapping( "invoice", 34843, "date", new DateTime(2001, 01, 23), "bill-to", new YamlMapping( "given", "Chris", "family", "Dumars", "address", new YamlMapping( "lines", "458 Walkman Dr.\nSuite #292\n", "city", "Royal Oak", "state", "MI", "postal", 48046 ) ), "product", new YamlSequence( new YamlMapping( "sku", "BL394D", "quantity", 4, "description", "Basketball", "price", 450.00 ), new YamlMapping( "sku", "BL4438H", "quantity", 1, "description", "Super Hoop", "price", 2392.00 ) ), "tax", 251.42, "total", 4443.52, "comments", "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338." ); invoice["ship-to"] = invoice["bill-to"]; invoice.Tag = "tag:clarkevans.com,2002:invoice"; var yaml = invoice.ToYaml(); Assert.AreEqual( MultiLineText( @"%YAML 1.2 --- !<tag:clarkevans.com,2002:invoice> bill-to: &A address: city: Royal Oak lines: ""458 Walkman Dr.\n\ Suite #292\n"" postal: 48046 state: MI family: Dumars given: Chris comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338. date: 2001-01-23 invoice: 34843 product: - description: Basketball price: !!float 450 quantity: 4 sku: BL394D - description: Super Hoop price: !!float 2392 quantity: 1 sku: BL4438H ship-to: *A tax: 251.42 total: 4443.52 ..."), yaml); // Doesn't really make sense to test Row //Assert.AreEqual(27, invoice["invoice"].Row); Assert.AreEqual(10, invoice["invoice"].Column); //Assert.AreEqual(22, invoice["date"].Row); Assert.AreEqual(7, invoice["date"].Column); //Assert.AreEqual(4, invoice["bill-to"].Row); Assert.AreEqual(10, invoice["bill-to"].Column); //Assert.AreEqual(11, ( (YamlMapping)invoice["bill-to"] )["given"].Row); Assert.AreEqual(10, ( (YamlMapping)invoice["bill-to"] )["given"].Column); //Assert.AreEqual(4, invoice["ship-to"].Row); Assert.AreEqual(10, invoice["ship-to"].Column); }
public void MergeKey() { var map = new YamlMapping("existing", "value"); var mergeKey = new YamlScalar("!!merge", "<<"); map.Add(mergeKey, new YamlMapping("existing", "new value")); map.OnLoaded(); Assert.AreEqual(1, map.Count); Assert.IsTrue(map.ContainsKey("existing")); Assert.AreEqual((YamlNode) "value", map["existing"]); map.Add(mergeKey, new YamlMapping("not existing", "new value")); map.OnLoaded(); Assert.AreEqual(2, map.Count); Assert.IsTrue(map.ContainsKey("existing")); Assert.AreEqual((YamlNode) "value", map["existing"]); Assert.IsTrue(map.ContainsKey("not existing")); Assert.AreEqual((YamlNode) "new value", map["not existing"]); map.Add(mergeKey, new YamlMapping("key1", "value1", 2, 2, 3.0, 3.0)); map.OnLoaded(); Assert.AreEqual(5, map.Count); Assert.IsTrue(map.ContainsKey("existing")); Assert.AreEqual((YamlNode) "value", map["existing"]); Assert.IsTrue(map.ContainsKey("not existing")); Assert.AreEqual((YamlNode) "new value", map["not existing"]); Assert.IsTrue(map.ContainsKey(2)); Assert.AreEqual((YamlNode) 2, map[2]); Assert.IsTrue(map.ContainsKey(3.0)); Assert.AreEqual((YamlNode) 3.0, map[3.0]); map = new YamlMapping( "existing", "value", mergeKey, new YamlMapping("not existing", "new value")); map.OnLoaded(); Assert.AreEqual(2, map.Count); Assert.IsTrue(map.ContainsKey("existing")); Assert.AreEqual((YamlNode) "value", map["existing"]); Assert.IsTrue(map.ContainsKey("not existing")); Assert.AreEqual((YamlNode) "new value", map["not existing"]); map = (YamlMapping) YamlNode.FromYaml( "key1: value1\r\n" + "key2: value2\r\n" + "<<: \r\n" + " key2: value2 modified\r\n" + " key3: value3\r\n" + " <<: \r\n" + " key4: value4\r\n" + " <<: value5\r\n" + "key6: <<\r\n")[0]; var mapBack = map.ToYaml(); Assert.AreEqual(@"%YAML 1.2 --- <<: value5 key1: value1 key2: value2 key3: value3 key4: value4 key6: << ... ", mapBack); Assert.IsTrue(map.ContainsKey(mergeKey)); Assert.AreEqual(mergeKey, map["key6"]); map.Remove(mergeKey); map.Add(mergeKey, map); // recursive map.OnLoaded(); // nothing has been changed mapBack = map.ToYaml(); Assert.AreEqual(@"%YAML 1.2 --- key1: value1 key2: value2 key3: value3 key4: value4 key6: << ... ", mapBack); }
public void TestChangingMappingKey() { var key = (YamlScalar)"def"; var map = new YamlMapping(key, 3); key.Value = "ghi"; Assert.IsTrue(map.ContainsKey(key)); Assert.IsTrue(map.Remove(key)); map[map] = 4; Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); var map2 = new YamlMapping(key, 3); map2[map2] = 2; map2[map] = 4; Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); map[map2] = 2; Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); map.Tag = YamlNode.DefaultTagPrefix + "map"; Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); Assert.IsTrue(map.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map[map2]); var seq = new YamlSequence(map); map.Add(seq, 4); Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); Assert.IsTrue(map.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map[map2]); seq.Add(map); Assert.IsTrue(map2.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map2[map2]); Assert.AreEqual((YamlNode)4, map2[map]); Assert.IsTrue(map.ContainsKey(map)); Assert.AreEqual((YamlNode)4, map[map]); Assert.IsTrue(map.ContainsKey(map2)); Assert.AreEqual((YamlNode)2, map[map2]); }
private void DictionaryToMap(object obj, YamlMapping mapping) { var accessor = ObjectMemberAccessor.FindFor(obj.GetType()); var iter = ((IEnumerable)obj).GetEnumerator(); // When this is a pure dictionary, we can directly add key,value to YamlMapping var dictionary = accessor.IsPureDictionary ? mapping : map(); Func<object, object> key = null, value = null; while (iter.MoveNext()) { if (key == null) { var keyvalue = iter.Current.GetType(); var keyprop = keyvalue.GetProperty("Key"); var valueprop = keyvalue.GetProperty("Value"); key = o => keyprop.GetValue(o, new object[0]); value = o => valueprop.GetValue(o, new object[0]); } dictionary.Add( ObjectToNode(key(iter.Current), accessor.KeyType), ObjectToNode(value(iter.Current), accessor.ValueType) ); } if (!accessor.IsPureDictionary && dictionary.Count > 0) mapping.Add(MapKey("~Items"), dictionary); }
public void Example2_27_YAML1_2() { var invoice = new YamlMapping( "invoice", 34843, "date", new DateTime(2001, 01, 23), "bill-to", new YamlMapping( "given", "Chris", "family", "Dumars", "address", new YamlMapping( "lines", "458 Walkman Dr.\nSuite #292\n", "city", "Royal Oak", "state", "MI", "postal", 48046 ) ), "product", new YamlSequence( new YamlMapping( "sku", "BL394D", "quantity", 4, "description", "Basketball", "price", 450.00 ), new YamlMapping( "sku", "BL4438H", "quantity", 1, "description", "Super Hoop", "price", 2392.00 ) ), "tax", 251.42, "total", 4443.52, "comments", "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338." ); invoice["ship-to"] = invoice["bill-to"]; invoice.Tag = "tag:clarkevans.com,2002:invoice"; var yaml = invoice.ToYaml(); Assert.AreEqual( MultiLineText( @"%YAML 1.2", @"---", @"!<tag:clarkevans.com,2002:invoice>", @"ship-to: &A ", @" address: ", @" city: Royal Oak", @" postal: 48046", @" lines: ""458 Walkman Dr.\n\", @" Suite #292\n""", @" state: MI", @" given: Chris", @" family: Dumars", @"product: ", @" - quantity: 4", @" sku: BL394D", @" price: !!float 450", @" description: Basketball", @" - quantity: 1", @" sku: BL4438H", @" price: !!float 2392", @" description: Super Hoop", @"date: 2001-01-23", @"tax: 251.42", @"bill-to: *A", @"comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.", @"total: 4443.52", @"invoice: 34843", @"..." ), yaml); Assert.AreEqual(27, invoice["invoice"].Raw); Assert.AreEqual(10, invoice["invoice"].Column); Assert.AreEqual(22, invoice["date"].Raw); Assert.AreEqual(7, invoice["date"].Column); Assert.AreEqual(4, invoice["bill-to"].Raw); Assert.AreEqual(10, invoice["bill-to"].Column); Assert.AreEqual(11, ((YamlMapping)invoice["bill-to"])["given"].Raw); Assert.AreEqual(10, ((YamlMapping)invoice["bill-to"])["given"].Column); Assert.AreEqual(4, invoice["ship-to"].Raw); Assert.AreEqual(10, invoice["ship-to"].Column); }
public static T Convert <T>(this YamlMapping mapping) { return((T)Convert(mapping, typeof(T))); }
private Config() { top = YamlNode.FromYamlFile("config.yml").topMap(); }
public void CustomActivator() { var brush = new YamlMapping("Color", "Blue"); brush.Tag = "!System.Drawing.SolidBrush"; var config = new YamlConfig(); config.Register(new LegacyTypeConverterFactory()); config.LookupAssemblies.Add(typeof(System.Drawing.SolidBrush).Assembly); Assert.Throws<MissingMethodException>(() => constructor.NodeToObject(brush, new SerializerContext(config))); config.AddActivator<System.Drawing.SolidBrush>(() => new System.Drawing.SolidBrush(System.Drawing.Color.Black)); Assert.AreEqual(System.Drawing.Color.Blue, ((System.Drawing.SolidBrush)constructor.NodeToObject(brush, new SerializerContext(config))).Color); }
public void MergeKey() { var map = new YamlMapping("existing", "value"); var mergeKey = new YamlScalar("!!merge", "<<"); map.Add(mergeKey, new YamlMapping("existing", "new value")); map.OnLoaded(); Assert.AreEqual(1, map.Count); Assert.IsTrue(map.ContainsKey("existing")); Assert.AreEqual((YamlNode)"value", map["existing"]); map.Add(mergeKey, new YamlMapping("not existing", "new value")); map.OnLoaded(); Assert.AreEqual(2, map.Count); Assert.IsTrue(map.ContainsKey("existing")); Assert.AreEqual((YamlNode)"value", map["existing"]); Assert.IsTrue(map.ContainsKey("not existing")); Assert.AreEqual((YamlNode)"new value", map["not existing"]); map.Add(mergeKey, new YamlMapping("key1", "value1", 2, 2, 3.0, 3.0)); map.OnLoaded(); Assert.AreEqual(5, map.Count); Assert.IsTrue(map.ContainsKey("existing")); Assert.AreEqual((YamlNode)"value", map["existing"]); Assert.IsTrue(map.ContainsKey("not existing")); Assert.AreEqual((YamlNode)"new value", map["not existing"]); Assert.IsTrue(map.ContainsKey(2)); Assert.AreEqual((YamlNode)2, map[2]); Assert.IsTrue(map.ContainsKey(3.0)); Assert.AreEqual((YamlNode)3.0, map[3.0]); map = new YamlMapping( "existing", "value", mergeKey, new YamlMapping("not existing", "new value")); map.OnLoaded(); Assert.AreEqual(2, map.Count); Assert.IsTrue(map.ContainsKey("existing")); Assert.AreEqual((YamlNode)"value", map["existing"]); Assert.IsTrue(map.ContainsKey("not existing")); Assert.AreEqual((YamlNode)"new value", map["not existing"]); map = (YamlMapping)YamlNode.FromYaml( "key1: value1\r\n" + "key2: value2\r\n" + "<<: \r\n" + " key2: value2 modified\r\n" + " key3: value3\r\n" + " <<: \r\n" + " key4: value4\r\n" + " <<: value5\r\n" + "key6: <<\r\n")[0]; Assert.AreEqual( "%YAML 1.2\r\n" + "---\r\n" + "<<: value5\r\n" + "key6: <<\r\n" + "key3: value3\r\n" + "key2: value2\r\n" + "key4: value4\r\n" + "key1: value1\r\n" + "...\r\n", map.ToYaml() ); Assert.IsTrue(map.ContainsKey(mergeKey)); Assert.AreEqual(mergeKey, map["key6"]); map.Remove(mergeKey); map.Add(mergeKey, map); // recursive map.OnLoaded(); Assert.AreEqual( // nothing has been changed "%YAML 1.2\r\n" + "---\r\n" + "key6: <<\r\n" + "key3: value3\r\n" + "key2: value2\r\n" + "key4: value4\r\n" + "key1: value1\r\n" + "...\r\n", map.ToYaml() ); }
/// <summary> /// Create a mapping node. /// </summary> /// <param name="nodes">Sequential list of key/value pairs.</param> /// <param name="tag">Tag for the mapping.</param> /// <returns>Created mapping node.</returns> protected static YamlMapping map_tag(string tag, params YamlNode[] nodes) { var map = new YamlMapping(nodes); map.Tag = tag; return map; }
public void saveYaml() { if (string.IsNullOrEmpty(Global.projectName)) { MessageBox.Show("Please check the project", "Project Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } //네비 시작점 확인 if (!checkStart()) { MessageBox.Show("Please check the starting point.", "Start Point Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } //종점 확인 if (!checkend()) { MessageBox.Show("Please check the end point.", "End Point Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } saveNaviTemp.Clear(); var startshape = NavinObsDiagram.Instance.Navidiagram.Items.OfType <NaviShape>().Where(x => x.PointType == "0").ToList(); saveNaviTemp.Add(startshape[0]); SetNaviPoistion(startshape[0]); //리스트에 시작 끝점이 존재하는지 체크 if (!checkStartEnd(saveNaviTemp)) { MessageBox.Show("It is not connected from start point to end point.", "End Point Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } //저장을 시작한다. System.Windows.Forms.SaveFileDialog save = new System.Windows.Forms.SaveFileDialog(); save.Title = ""; save.Filter = "Yaml file|*.yaml"; if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using (new WaitCursor()) { string filePath = save.FileName; YamlMapping map = new YamlMapping(); //point 갯수 map.Add("size_points", saveNaviTemp.Count); //장애물 갯수 List <ObsShape> obsdata = NavinObsDiagram.Instance.Navidiagram.Items.OfType <ObsShape>().ToList(); map.Add("size_objects", obsdata.Count); //네비포인트 갯수 for (int i = 0; i < saveNaviTemp.Count; i++) { //points0_x string Xkey = "points" + i + "_x"; string Ykey = "points" + i + "_y"; map.Add(Xkey, saveNaviTemp[i].NaviPointX); map.Add(Ykey, saveNaviTemp[i].NaviPointY); } //장애물 갯수 for (int i = 0; i < obsdata.Count; i++) { //x y name comment type //objects0_pos_x string Xkey = "objects" + obsdata[i].Index.ToString() + "_pos_x"; string Ykey = "objects" + obsdata[i].Index.ToString() + "_pos_y"; string NameKey = "objects" + obsdata[i].Index.ToString() + "_name"; string commKey = "objects" + obsdata[i].Index.ToString() + "_comment"; string typeKey = "objects" + obsdata[i].Index.ToString() + "_type"; map.Add(Xkey, obsdata[i].ObsPointX); map.Add(Ykey, obsdata[i].ObsPointY); map.Add(NameKey, Global.getObsCodeName(int.Parse(obsdata[i].PointType))); map.Add(commKey, obsdata[i].Description); map.Add(typeKey, int.Parse(obsdata[i].PointType)); } map.Add("wayWidth", float.Parse("2.5000000000000000e+00")); map.Add("nextDirDist", float.Parse("10.00000")); map.Add("nextDirThres", float.Parse("20.00000")); YamlNode node = map; node.ToYamlFile(filePath); MessageBox.Show("yaml file creation is complete.", "Yaml Create.", MessageBoxButton.OK, MessageBoxImage.Information); } } }