public void Run(string[] args)
        {
            // Setup the input
            var input = new StringReader(Document);

            // Load the stream
            //var yaml = new YamlStream();
            //yaml.Load(input);

            var serializer = new YamlSerializer<Product>();
            var result = serializer.Deserialize(input);

            var dumpSerializer = new Serializer();
            dumpSerializer.Serialize(Console.Out, result);

            //Console.WriteLine(result);
            //// Examine the stream
            //var mapping =
            //    (YamlMappingNode)yaml.Documents[0].RootNode;

            //foreach (var entry in mapping.Children)
            //{
            //    Console.WriteLine(((YamlScalarNode)entry.Key).Value);
            //}
        }
示例#2
0
 public void TestBlockStrings()
 {
     Assert.AreEqual(
         "multiline: |\n" +
         "  just\n" +
         "  multiple\n" +
         "  lines\n" +
         "blankLine: |\n" +
         "  first\n" +
         "\n" +
         "  third\n" +
         "noFinalNewLine: |-\n" +
         "  ends\n" +
         "  right\n" +
         "  here\n" +
         "someLineWhitespace: |\n" +
         "  function hello() {\n" +
         "    return \"hi\";\n" +
         "  }\n" +
         "firstLineWhitespace: |2\n" +
         "    function hello() {\n" +
         "      return \"hi\";\n" +
         "    }\n" +
         "bothIndicators: |-2\n" +
         "    hi\n" +
         "  there\n" +
         "forcedBlock: |-\n" +
         "  unnecessary\n" +
         "empty: |-\n",
         YamlSerializer.Serialize(
             new DummyBlockStrings()));
 }
示例#3
0
        public void TestThat_YamlCanBeLoadedIntoModel()
        {
            var key        = JsonPasswordCrypto.GenerateKey(256);
            var serializer = new YamlSerializer <ConDepEnvConfig>(new YamlConfigCrypto(key));

            var condepConfig = serializer.DeSerialize(_yml);
        }
        public FullObjectGraphTraversalStrategy(YamlSerializer serializer, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention)
        {
            if (maxRecursion <= 0)
            {
                throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1");
            }

            Serializer = serializer;

            if (typeDescriptor == null)
            {
                throw new ArgumentNullException("typeDescriptor");
            }

            _typeDescriptor = typeDescriptor;

            if (typeResolver == null)
            {
                throw new ArgumentNullException("typeResolver");
            }

            _typeResolver = typeResolver;

            _maxRecursion     = maxRecursion;
            _namingConvention = namingConvention;
        }
示例#5
0
        private void LoadConfigFile()
        {
            var serializer = new YamlSerializer();

            if (File.Exists(_settingsFile))
            {
                var obj = serializer.DeserializeFromFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\Settings.cfg");
                _config        = (Config)obj[0];
                configFilepath = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + _config.LastMapFile + ".cfg";
            }
            else
            {
                _config             = new Config();
                _config.LastMapFile = "Default";
            }


            if (File.Exists(configFilepath))
            {
                var obj = serializer.DeserializeFromFile(configFilepath);
                mapPoints = (List <MapPoint>)obj[0];
            }
            else
            {
                mapPoints = new List <MapPoint>();
            }


            this.Text = "Salt Charts - " + _config.LastMapFile;
        }
        public void TestCustomActivator()
        {
            var serializer = new YamlSerializer();
            var yaml       =
                @"%YAML 1.2
---
!System.Drawing.SolidBrush
Color: Red
...
";

            SolidBrush b = null;

            try {
                b = (SolidBrush)serializer.Deserialize(yaml)[0];
            } catch (MissingMethodException) {
                // SolidBrush has no default constructor!
            }

            var config = new YamlConfig();

            config.AddActivator <SolidBrush>(() => new SolidBrush(Color.Black));
            serializer = new YamlSerializer(config);

            // Now the serializer knows how to activate an instance of SolidBrush.
            b = (SolidBrush)serializer.Deserialize(yaml)[0];

            Assert.AreEqual(b.Color, Color.Red);
        }
        public void CultureTest()
        {
            var config = new YamlConfig();

            config.Culture = new System.Globalization.CultureInfo("da-DK");
            var    serializer = new YamlSerializer(config);
            object obj        = new System.Drawing.PointF(1.2f, 3.1f);
            var    yaml       = serializer.Serialize(obj);

            Assert.AreEqual(
                BuildResult(
                    "!System.Drawing.PointF",
                    "Y: 3,1",
                    "X: 1,2"
                    ),
                yaml
                );
            var restore = serializer.Deserialize(yaml)[0];

            Assert.AreEqual(obj, restore);

            obj  = new System.Drawing.Point(1, 3);
            yaml = serializer.Serialize(obj);
            Assert.AreEqual(
                BuildResult(
                    "!System.Drawing.Point 1; 3"
                    ),
                yaml
                );
            restore = serializer.Deserialize(yaml)[0];
            Assert.AreEqual(obj, restore);

            YamlNode.DefaultConfig.Culture = System.Globalization.CultureInfo.CurrentCulture;
        }
示例#8
0
        public static T[] ArrayFromYaml <T>(this string yaml)
        {
            YamlSerializer ser = new YamlSerializer();

            object[] des = ser.Deserialize(yaml, typeof(T));
            return(des.Each((o) => (T)o));
        }
示例#9
0
        public void Run(string[] args)
        {
            // Setup the input
            var input = new StringReader(Document);

            // Load the stream
            //var yaml = new YamlStream();
            //yaml.Load(input);

            var serializer = new YamlSerializer <Product>();
            var result     = serializer.Deserialize(input);


            var dumpSerializer = new Serializer();

            dumpSerializer.Serialize(Console.Out, result);

            //Console.WriteLine(result);
            //// Examine the stream
            //var mapping =
            //    (YamlMappingNode)yaml.Documents[0].RootNode;

            //foreach (var entry in mapping.Children)
            //{
            //    Console.WriteLine(((YamlScalarNode)entry.Key).Value);
            //}
        }
        public void Command_ProducesCorrect_YamlString()
        {
            var yamlObj    = YamlCommandIO.Serialize(command, 0);
            var yamlString = YamlSerializer.SerializeYamlTree(yamlObj);

            Assert.AreEqual(serializedCommand, yamlString, "Strings missmatched.");
        }
示例#11
0
        /// <summary>
        /// Reloads a profile from its file, updating the value that have changed.
        /// </summary>
        /// <param name="profile">The profile to reload.</param>
        public void ReloadSettingsProfile(SettingsProfile profile)
        {
            var filePath = profile.FilePath;

            if (filePath == null)
            {
                throw new ArgumentException("profile");
            }
            if (!File.Exists(filePath))
            {
                Logger.Error("Settings file [{0}] was not found", filePath);
                throw new ArgumentException("profile");
            }

            try
            {
                var settingsFile = new SettingsFile(profile);
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    YamlSerializer.Deserialize(stream, settingsFile);
                }
            }
            catch (Exception e)
            {
                Logger.Error("Error while loading settings file [{0}]: {1}", e, filePath, e.FormatFull());
            }

            var handler = SettingsFileLoaded;

            handler?.Invoke(null, new SettingsFileLoadedEventArgs(filePath));
        }
示例#12
0
        public void TestDocumentBoundaries()
        {
            Assert.AreEqual(
                "---\n" +
                "...\n",
                YamlSerializer.Serialize(
                    null,
                    new YamlSerializationOptions
            {
                DocumentBoundaries = true
            }));

            Assert.AreEqual(
                "---\n" +
                "hello: there\n" +
                "...\n",
                YamlSerializer.Serialize(
                    new Dictionary <string, string>
            {
                { "hello", "there" }
            },
                    new YamlSerializationOptions
            {
                DocumentBoundaries = true
            }));
        }
示例#13
0
        public void Roundtrip()
        {
            YamlSerializer serializer = new YamlSerializer(typeof(X), YamlSerializerModes.Roundtrip);

            using (StringWriter buffer = new StringWriter())
            {
                X original = new X();
                serializer.Serialize(buffer, original);

                Console.WriteLine(buffer.ToString());

                X copy = (X)serializer.Deserialize(new StringReader(buffer.ToString()));

                foreach (var property in typeof(X).GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (property.CanRead && property.CanWrite)
                    {
                        Assert.AreEqual(
                            property.GetValue(original, null),
                            property.GetValue(copy, null),
                            string.Format("Property '{0}' is incorrect", property.Name)
                            );
                    }
                }
            }
        }
示例#14
0
        /// <summary>
        /// Saves the given settings profile to a file at the given path.
        /// </summary>
        /// <param name="profile">The profile to save.</param>
        /// <param name="filePath">The path of the file.</param>
        /// <returns><c>true</c> if the file was correctly saved, <c>false</c> otherwise.</returns>
        public bool SaveSettingsProfile(SettingsProfile profile, UFile filePath)
        {
            if (profile == null)
            {
                throw new ArgumentNullException(nameof(profile));
            }
            try
            {
                profile.Saving = true;
                Directory.CreateDirectory(filePath.GetFullDirectory());

                var settingsFile = new SettingsFile(profile);
                using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    YamlSerializer.Serialize(stream, settingsFile);
                }
            }
            catch (Exception e)
            {
                Logger.Error("Error while saving settings file [{0}]: {1}", e, filePath, e.FormatForReport());
                return(false);
            }
            finally
            {
                profile.Saving = false;
            }
            return(true);
        }
示例#15
0
        public void TestMappings()
        {
            Assert.AreEqual(
                "",
                YamlSerializer.Serialize(
                    new Dictionary <object, object>()
            {
            }));

            Assert.AreEqual(
                "test: 123\n",
                YamlSerializer.Serialize(
                    new Dictionary <string, string>()
            {
                { "test", "123" }
            }));

            Assert.AreEqual(
                "aaa: 123\n" +
                "bbb: 456\n",
                YamlSerializer.Serialize(
                    new SortedDictionary <string, object>()
            {
                { "bbb", 456 },
                { "aaa", 123 }
            }));
        }
示例#16
0
        object IConfigurationSectionHandler.Create(object parent, object configContext, XmlNode section)
        {
            TextReader yaml;

            if (section.Attributes["file"] != null)
            {
                string fileName = section.Attributes["file"].Value;
                if (!File.Exists(fileName))
                {
                    string configPath = Path.GetDirectoryName(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
                    fileName = Path.Combine(configPath, fileName);
                }

                yaml = File.OpenText(fileName);
            }
            else
            {
                yaml = GetYamlContent(section);
            }

            YamlSerializer serializer;

            if (section.Attributes["type"] != null)
            {
                serializer = new YamlSerializer(Type.GetType(section.Attributes["type"].Value, true));
            }
            else
            {
                serializer = new YamlSerializer();
            }
            return(serializer.Deserialize(yaml));
        }
示例#17
0
        public SpeakerProvider(DirectoryInfo dataFolder)
        {
            var serializer = new YamlSerializer();
            var profiles   = dataFolder.GetFiles("*.yaml");

            foreach (var profileFile in profiles)
            {
                Speaker speaker;
                try
                {
                    using (var reader = profileFile.OpenRead())
                    {
                        speaker = (Speaker)serializer.Deserialize(reader, typeof(Speaker))[0];
                    }
                }
                catch (Exception ex)
                {
                    speaker          = new Speaker();
                    speaker.FullName = "Data Error";
                    speaker.Bio      = ex.Message;
                }
                speaker.Id = Path.GetFileNameWithoutExtension(profileFile.Name);
                _speakers.Add(speaker);
            }
            _speakers.Sort((x, y) => x.FullName.CompareTo(y.FullName));
        }
    public async Task SerializesToValidNetworkDataV2()
    {
        var serializer  = new YamlSerializer();
        var networkData = new NetworkData(new Dictionary <string, object>
        {
            { "ethernets", new
              {
                  eth0 = new
                  {
                      match = new { macaddress = "00:11:22:33:44:55" },
                      dhcp4 = true
                  }
              } }
        });

        await using var resultStream = await serializer.SerializeToYaml(networkData);

        using var streamReader = new StreamReader(resultStream);
        var act = await streamReader.ReadToEndAsync();

        Assert.Equal(@"version: 2
ethernets:
  eth0:
    match:
      macaddress: 00:11:22:33:44:55
    dhcp4: true
", act);
    }
示例#19
0
        public void yaml_roundtrip()
        {
            var res = Resource.Load(Model_P5PlayerModel_Path);

            res.SaveYamlFile("test.yml");
            var newRes = YamlSerializer.LoadYamlFile <ModelPack>("test.yml");
        }
示例#20
0
        private static ConfigApplication FromYaml(FileInfo file)
        {
            var deserializer = YamlSerializer.CreateDeserializer();

            using var reader = file.OpenText();
            var application = deserializer.Deserialize <ConfigApplication>(reader);

            application.Source = file;

            // Deserialization makes all collection properties null so make sure they are non-null so
            // other code doesn't need to react
            foreach (var service in application.Services)
            {
                service.Bindings ??= new List <ConfigServiceBinding>();
                service.Configuration ??= new List <ConfigConfigurationSource>();
                service.Volumes ??= new List <ConfigVolume>();
            }

            foreach (var ingress in application.Ingress)
            {
                ingress.Bindings ??= new List <ConfigIngressBinding>();
                ingress.Rules ??= new List <ConfigIngressRule>();
            }

            return(application);
        }
        public Post Serialize(string postContent)
        {
            var sWriter        = new StringReader(postContent);
            var yamlSerializer = new YamlSerializer <Post>();

            return(yamlSerializer.Deserialize(sWriter));
        }
示例#22
0
 public void Save(Stream stream, object asset, ILogger log)
 {
     YamlSerializer.Serialize(stream, asset, null, log != null ? new SerializerContextSettings()
     {
         Logger = new YamlForwardLogger(log)
     } : null);
 }
        public void Roundtrip()
        {
            var serializer = new Serializer();

            using (StringWriter buffer = new StringWriter())
            {
                X original = new X();
                serializer.Serialize(buffer, original, SerializationOptions.Roundtrip);

                Console.WriteLine(buffer.ToString());

                var deserializer = new YamlSerializer(typeof(X), YamlSerializerModes.Roundtrip);
                X   copy         = (X)deserializer.Deserialize(new StringReader(buffer.ToString()));

                foreach (var property in typeof(X).GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (property.CanRead && property.CanWrite)
                    {
                        Assert.Equal(
                            property.GetValue(original, null),
                            property.GetValue(copy, null)
                            );
                    }
                }
            }
        }
示例#24
0
 public void TestVerticalWhitespace()
 {
     Assert.AreEqual(
         "one: 1\n" +
         "two: 2\n" +
         "\n" +
         "ten: 10\n" +
         "eleven: 11\n" +
         "\n" +
         "\n" +
         "twenty: 20\n" +
         "\n" +
         "\n" +
         "\n" +
         "forty: 40\n" +
         "\n" +
         "\n" +
         "fortyTwo: 42\n" +
         "\n" +
         "\n" +
         "\n" +
         "fifty: 50\n",
         YamlSerializer.Serialize(
             new DummyVerticalWhitespace()));
 }
        public void RoundtripList()
        {
            var serializer   = new Serializer();
            var deserializer = new YamlSerializer(typeof(List <int>), YamlSerializerModes.Roundtrip);

            using (StringWriter buffer = new StringWriter())
            {
                List <int> original = new List <int>();
                original.Add(2);
                original.Add(4);
                original.Add(6);
                serializer.Serialize(buffer, original, typeof(List <int>), SerializationOptions.Roundtrip);

                Console.WriteLine(buffer.ToString());

                List <int> copy = (List <int>)deserializer.Deserialize(new StringReader(buffer.ToString()));

                Assert.Equal(original.Count, copy.Count);

                for (int i = 0; i < original.Count; ++i)
                {
                    Assert.Equal(original[i], copy[i]);
                }
            }
        }
示例#26
0
 public object Load(Stream stream, string assetFileExtension, ILogger log, out bool aliasOccurred)
 {
     return(YamlSerializer.Deserialize(stream, null, log != null ? new SerializerContextSettings()
     {
         Logger = new YamlForwardLogger(log)
     } : null, out aliasOccurred));
 }
        public void RoundtripDictionary()
        {
            Dictionary <string, string> entries = new Dictionary <string, string>
            {
                { "key1", "value1" },
                { "key2", "value2" },
                { "key3", "value3" },
            };

            var serializer   = new Serializer();
            var deserializer = YamlSerializer.Create(entries, YamlSerializerModes.Roundtrip | YamlSerializerModes.DisableAliases);

            StringWriter buffer = new StringWriter();

            serializer.Serialize(buffer, entries);

            Console.WriteLine(buffer.ToString());

            var deserialized = deserializer.Deserialize(new StringReader(buffer.ToString()));

            foreach (var pair in deserialized)
            {
                Assert.Equal(entries[pair.Key], pair.Value);
            }
        }
示例#28
0
        /// <summary>
        /// Loads the a <see cref="ProjectTemplate"/> from the specified file path.
        /// </summary>
        /// <param name="filePath">The project template file.</param>
        /// <returns>An instance of the project template.</returns>
        /// <exception cref="System.ArgumentNullException">filePath</exception>
        public static ProjectTemplate Load(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            var             fullFilePath = Path.Combine(Environment.CurrentDirectory, filePath);
            var             projectFile  = File.ReadAllText(fullFilePath);
            ProjectTemplate template;

            // If this a project template?
            if (projectFile.StartsWith("<#@"))
            {
                template = new ProjectTemplate()
                {
                    IsDynamicTemplate = true
                };
            }
            else
            {
                using (var stream = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    template = (ProjectTemplate)YamlSerializer.Deserialize(stream);
                }
            }

            template.FilePath = fullFilePath;
            return(template);
        }
示例#29
0
        /// <summary>
        /// Saves the given settings profile to a file at the given path.
        /// </summary>
        /// <param name="profile">The profile to save.</param>
        /// <param name="filePath">The path of the file.</param>
        /// <returns><c>true</c> if the file was correctly saved, <c>false</c> otherwise.</returns>
        public static bool SaveSettingsProfile(SettingsProfile profile, UFile filePath)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile");
            }
            try
            {
                profile.Saving = true;
                Directory.CreateDirectory(filePath.GetFullDirectory());

                var settingsFile = new SettingsFile();
                foreach (var entry in profile.Settings.Values)
                {
                    settingsFile.Settings.Add(entry.Name, entry.GetSerializableValue());
                }

                using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    YamlSerializer.Serialize(stream, settingsFile);
                }
            }
            catch (Exception e)
            {
                Logger.Error("Error while saving settings file [{0}]: {1}", e, filePath, Extensions.StringExtensions.FormatExceptionForReport(e));
                return(false);
            }
            finally
            {
                profile.Saving = false;
            }
            return(true);
        }
示例#30
0
        public virtual List <string> LoadPlugins()
        {
            List <string> pluginsFailedToLoad = new List <string>();

            plugins = new Dictionary <String, IPlugin>();
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
            {
                var serializer = new YamlSerializer();
                foreach (string file in store.GetFileNames("*.yml"))
                {
                    try
                    {
                        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(file, FileMode.Open, FileAccess.Read, store))
                        {
                            Plugin plugin = (Plugin)serializer.Deserialize(stream, typeof(Plugin))[0];
                            plugins.Add(Path.GetFileNameWithoutExtension(file), plugin);
                        }
                    }
                    catch
                    {
                        pluginsFailedToLoad.Add(file);
                    }
                }
                store.Close();
            }
            return(pluginsFailedToLoad);
        }
        public async Task SerializeIReadOnlyListOfClassDefaultOptions_Success()
        {
            var yamlSerializer = new YamlSerializer($"{Default}");

            var expected = _encoding.GetBytes(@"
- itemId: 7e900426dbc246bcbe100d503644b830
  itemName: alfa
  subItems:
  - bravo
  - charlie
  options: all
  createTime: 2019-01-02T03:04:05.0060007Z
- itemId: 7e900426dbc246bcbe100d503644b830
  itemName: alfa
  subItems:
  - bravo
  - charlie
  options: all
  createTime: 2019-01-02T03:04:05.0060007Z
".TrimStart());

            var actual = await yamlSerializer.Serialize(new List <Item> {
                TestItem, TestItem
            } as IReadOnlyList <Item>);

            Assert.Equal(expected, actual);
        }
示例#32
0
		public static void ToStream(IRequestContext request, object response, Stream stream)
		{
			using (var sw = new StreamWriter(stream))
			{
				var serializer = new YamlSerializer();
				serializer.Serialize(sw, response);
			}
		}
示例#33
0
        public void NotSpecifyingObjectFactoryUsesDefault()
        {
            var serializer = new YamlSerializer();
            var options = new DeserializationOptions();
            options.Mappings.Add("!foo", typeof(FooBase));
            var result = serializer.Deserialize(new StringReader("!foo {}"), options);

            Assert.IsType<FooBase>(result);
        }
示例#34
0
        public static string ToYaml(GitBinDocument document)
        {
            var sb = new StringBuilder();
            var stringWriter = new StringWriter(sb);

            var serializer = new YamlSerializer<GitBinDocument>();
            serializer.Serialize(stringWriter, document);

            return sb.ToString();
        }
示例#35
0
        public void DeserializeExplicitDictionary()
        {
            YamlSerializer serializer = new YamlSerializer();
            object result = serializer.Deserialize(YamlFile("dictionaryExplicit.yaml"));

            Assert.IsTrue(typeof(IDictionary<string, int>).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type.");

            IDictionary<string, int> dictionary = (IDictionary<string, int>)result;
            Assert.AreEqual(1, dictionary["key1"]);
            Assert.AreEqual(2, dictionary["key2"]);
        }
示例#36
0
        public void DeserializeDictionary()
        {
            YamlSerializer serializer = new YamlSerializer();
            object result = serializer.Deserialize(YamlFile("dictionary.yaml"));

            Assert.IsTrue(typeof(IDictionary<object, object>).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type.");

            IDictionary<object, object> dictionary = (IDictionary<object, object>)result;
            Assert.AreEqual("value1", dictionary["key1"]);
            Assert.AreEqual("value2", dictionary["key2"]);
        }
示例#37
0
        public YamlConfigRepository(
            IFileSystem fileSystem,
            IValidator<Config> configValidator)
        {
            this.fileSystem = fileSystem;
            this.configValidator = configValidator;

            Path = Environment.CurrentDirectory;

            serializer = new YamlSerializer<Config>();
        }
示例#38
0
        public void ObjectFactoryIsInvoked()
        {
            var serializer = new YamlSerializer();
            var options = new DeserializationOptions();
            options.Mappings.Add("!foo", typeof(FooBase));

            options.ObjectFactory = new LambdaObjectFactory(t => new FooDerived());

            var result = serializer.Deserialize(new StringReader("!foo {}"), options);

            Assert.IsType<FooDerived>(result);
        }
        public void CustomTags()
        {
            DeserializationOptions options = new DeserializationOptions();
            options.Mappings.Add("tag:yaml.org,2002:point", typeof(Point));

            YamlSerializer serializer = new YamlSerializer();
            object result = serializer.Deserialize(YamlFile("tags.yaml"), options);

            Assert.Equal(typeof(Point), result.GetType());

            Point value = (Point)result;
            Assert.Equal(10, value.X);
            Assert.Equal(20, value.Y);
        }
示例#40
0
        public void CustomTags()
        {
            DeserializationOptions options = new DeserializationOptions();
            options.Mappings.Add("tag:yaml.org,2002:point", typeof(Point));

            YamlSerializer serializer = new YamlSerializer();
            object result = serializer.Deserialize(YamlFile("tags.yaml"), options);

            Assert.AreEqual(typeof(Point), result.GetType(), "The deserializer should have used the correct type.");

            Point value = (Point)result;
            Assert.AreEqual(10, value.X, "The property X has the wrong value.");
            Assert.AreEqual(20, value.Y, "The property Y has the wrong value.");
        }
示例#41
0
        public static SiteConfiguration Load(string filePath)
        {
            var stream = File.OpenRead(filePath);
            var reader = new StreamReader(stream);
            var serializer = new YamlSerializer<SiteConfiguration>();

            try
            {
                return serializer.Deserialize(reader);
            }
            finally
            {
                reader.Close();
            }
        }
示例#42
0
        private void Button1Click(object sender, EventArgs e)
        {
            string settingsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SharpCraft");
            string settingsFile = Path.Combine(settingsFolder, "settings.yml");

            if(!Directory.Exists(settingsFolder))
                Directory.CreateDirectory(settingsFolder);

            var s = new YamlSerializer<Settings>();
            var r = new Settings {Port = 25575, WorldName = "world"};

            var sw = new StreamWriter(settingsFile);
            s.Serialize(sw, r);
            sw.Flush();
            sw.Close();
        }
示例#43
0
        public static string ToYaml(GitBinDocument document)
        {
            var sb = new StringBuilder();
            var stringWriter = new StringWriter(sb);

            var serializer = new YamlSerializer<GitBinDocument>();
            serializer.Serialize(stringWriter, document);

            if (Environment.OSVersion.Platform == PlatformID.MacOSX ||
                Environment.OSVersion.Platform == PlatformID.Unix)
            {
                sb.Replace("\n", "\r\n");
            }

            return sb.ToString();
        }
        public void DeserializationOfNullWorksInJson()
        {
            var serializer = new Serializer();
            YamlSerializer deserializer = new YamlSerializer(typeof(X), YamlSerializerModes.EmitDefaults | YamlSerializerModes.JsonCompatible | YamlSerializerModes.Roundtrip);

            using (StringWriter buffer = new StringWriter())
            {
                X original = new X { MyString = null };
                serializer.Serialize(buffer, original, typeof(X), SerializationOptions.EmitDefaults | SerializationOptions.JsonCompatible | SerializationOptions.Roundtrip);

                Console.WriteLine(buffer.ToString());

                X copy = (X)deserializer.Deserialize(new StringReader(buffer.ToString()));

                Assert.Null(copy.MyString);
            }
        }
示例#45
0
        public void CircularReference()
        {
            YamlSerializer serializer = new YamlSerializer(typeof(Y), YamlSerializerModes.Roundtrip);

            using (StringWriter buffer = new StringWriter())
            {
                Y original = new Y();
                original.Child = new Y
             	{
             		Child = original,
             		Child2 = original
             	};

                serializer.Serialize(buffer, original);

                Console.WriteLine(buffer.ToString());
            }
        }
示例#46
0
        public static GitBinDocument FromYaml(TextReader textReader )
        {
            var yaml = textReader.ReadToEnd();

            GitBinDocument document;
            var serializer = new YamlSerializer<GitBinDocument>();

            try
            {
                document = serializer.Deserialize(new StringReader(yaml));
            }
            catch (YamlDotNet.Core.SyntaxErrorException e)
            {
                GitBinConsole.WriteLine("Syntax error in YAML file: {0}\n\n File contents:{1}\n", e.Message, yaml);
                throw;
            }

            return document;
        }
 public Post Serialize(string postContent)
 {
     var sWriter = new StringReader(postContent);
     var yamlSerializer = new YamlSerializer<Post>();
     return yamlSerializer.Deserialize(sWriter);
 }
示例#48
0
        public void ExplicitType()
        {
            YamlSerializer serializer = new YamlSerializer();
            object result = serializer.Deserialize(YamlFile("explicitType.yaml"));

            Assert.IsTrue(typeof(Z).IsAssignableFrom(result.GetType()), "The deserializer should have used the correct type.");
            Assert.AreEqual("bbb", ((Z)result).aaa, "The property has the wrong value.");
        }
 public RoundtripObjectGraphTraversalStrategy(YamlSerializer serializer, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion)
     : base(serializer, typeDescriptor, typeResolver, maxRecursion, null)
 {
 }
示例#50
0
        public void DeserializeListOfDictionaries()
        {
            var serializer = new YamlSerializer<List<Dictionary<string, string>>>();
            object result = serializer.Deserialize(YamlFile("listOfDictionaries.yaml"));

            Assert.IsInstanceOfType(result, typeof(List<Dictionary<string, string>>), "The deserialized object has the wrong type.");

            var list = (List<Dictionary<string, string>>)result;
            Assert.AreEqual("conn1", list[0]["connection"]);
            Assert.AreEqual("path1", list[0]["path"]);
            Assert.AreEqual("conn2", list[1]["connection"]);
            Assert.AreEqual("path2", list[1]["path"]);
        }
示例#51
0
        public void RoundtripList()
        {
            YamlSerializer serializer = new YamlSerializer(typeof(List<int>), YamlSerializerModes.Roundtrip);

            using (StringWriter buffer = new StringWriter())
            {
                List<int> original = new List<int>();
                original.Add(2);
                original.Add(4);
                original.Add(6);
                serializer.Serialize(buffer, original);

                Console.WriteLine(buffer.ToString());

                List<int> copy = (List<int>)serializer.Deserialize(new StringReader(buffer.ToString()));

                Assert.AreEqual(original.Count, copy.Count, "The lists do not have the same number of items.");

                for(int i = 0; i < original.Count; ++i) {
                    Assert.AreEqual(original[i], copy[i]);
                }
            }
        }
示例#52
0
        public void Roundtrip()
        {
            YamlSerializer serializer = new YamlSerializer(typeof(X), YamlSerializerModes.Roundtrip);

            using (StringWriter buffer = new StringWriter())
            {
                X original = new X();
                serializer.Serialize(buffer, original);

                Console.WriteLine(buffer.ToString());

                X copy = (X)serializer.Deserialize(new StringReader(buffer.ToString()));

                foreach (var property in typeof(X).GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (property.CanRead && property.CanWrite)
                    {
                        Assert.AreEqual(
                            property.GetValue(original, null),
                            property.GetValue(copy, null),
                            string.Format("Property '{0}' is incorrect", property.Name)
                        );
                    }
                }
            }
        }
示例#53
0
        public void Overrides()
        {
            DeserializationOptions options = new DeserializationOptions();
            options.Overrides.Add(typeof(Z), "aaa", (t, reader) => ((Z)t).aaa = reader.Expect<Scalar>().Value.ToUpperInvariant());

            YamlSerializer serializer = new YamlSerializer();
            object result = serializer.Deserialize(YamlFile("explicitType.yaml"), options);

            Assert.IsTrue(typeof(Z).IsAssignableFrom(result.GetType()), "The deserializer should have used the correct type.");
            Assert.AreEqual("BBB", ((Z)result).aaa, "The property has the wrong value.");
        }
示例#54
0
        public void TestThat_YamlCanBeLoadedIntoModel()
        {
            var key = JsonPasswordCrypto.GenerateKey(256);
            var serializer = new YamlSerializer<ConDepEnvConfig>(new YamlConfigCrypto(key));

            var condepConfig = serializer.DeSerialize(_yml);
        }
        object IConfigurationSectionHandler.Create(object parent, object configContext, XmlNode section)
        {
            TextReader yaml;
            if (section.Attributes["file"] != null)
            {
                string fileName = section.Attributes["file"].Value;
                if (!File.Exists(fileName))
                {
                    string configPath = Path.GetDirectoryName(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
                    fileName = Path.Combine(configPath, fileName);
                }

                yaml = File.OpenText(fileName);
            }
            else
            {
                yaml = GetYamlContent(section);
            }

            YamlSerializer serializer;
            if (section.Attributes["type"] != null)
            {
                serializer = new YamlSerializer(Type.GetType(section.Attributes["type"].Value, true));
            }
            else
            {
                serializer = new YamlSerializer();
            }
            return serializer.Deserialize(yaml);
        }
示例#56
0
        public void DeserializeExplicitList()
        {
            YamlSerializer serializer = new YamlSerializer();
            object result = serializer.Deserialize(YamlFile("listExplicit.yaml"));

            Assert.IsTrue(typeof(IList<int>).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type.");

            IList<int> list = (IList<int>)result;
            Assert.AreEqual(3, list[0]);
            Assert.AreEqual(4, list[1]);
            Assert.AreEqual(5, list[2]);
        }
 private void LoadSections(TextReader yaml)
 {
     YamlSerializer serializer = new YamlSerializer(typeof(Dictionary<string, object>));
     sections = (IDictionary<string, object>)serializer.Deserialize(yaml);
 }
示例#58
0
        public void DeserializeList()
        {
            YamlSerializer serializer = new YamlSerializer();
            object result = serializer.Deserialize(YamlFile("list.yaml"));

            Assert.IsTrue(typeof(IList).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type.");

            IList list = (IList)result;
            Assert.AreEqual("one", list[0]);
            Assert.AreEqual("two", list[1]);
            Assert.AreEqual("three", list[2]);
        }
示例#59
0
        /// <summary>
        /// Load RtcSetting from yaml file
        /// </summary>
        /// <param name="fileName">
        /// RtcSetting file path.
        /// if not found a file name, use default setting file (./rtc.yaml).
        /// if not found a default setting file, use default setting.
        /// </param>
        /// <returns>loaded setting</returns>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="SyntaxErrorException">yaml syntax error</exception>
        public static RtcSetting Load(string fileName)
        {
            RtcSetting setting;

            var settingFile = fileName;
            if (string.IsNullOrEmpty(settingFile) || !File.Exists(settingFile))
            {
                settingFile = _defaultSettingFileNames.Where(f => File.Exists(f)).FirstOrDefault();
            }

            if (!string.IsNullOrEmpty(settingFile))
            {
                _logger.InfoFormat("parse setting file. file name = {0}", settingFile);
                using (var input = new StreamReader(settingFile, Encoding.UTF8))
                {
                    var yamlSerializer = new YamlSerializer<RtcSetting>();
                    setting = yamlSerializer.Deserialize(input);
                }
            }
            else
            {
                _logger.Info("use default setting");
                setting = new RtcSetting();
            }

            return setting;
        }
示例#60
0
        public void Enums()
        {
            YamlSerializer<StringFormatFlags> serializer = new YamlSerializer<StringFormatFlags>();

            StringFormatFlags flags = StringFormatFlags.NoClip | StringFormatFlags.NoFontFallback;

            StringWriter buffer = new StringWriter();
            serializer.Serialize(buffer, flags);

            StringFormatFlags deserialized = serializer.Deserialize(new StringReader(buffer.ToString()));

            Assert.AreEqual(flags, deserialized, "The value is incorrect.");
        }