public string Serialize(Post post) { var writer = new StringWriter(); var yamlSerializer = new Serializer(); yamlSerializer.Serialize(writer, post); return writer.ToString(); }
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 Package(DirectoryInfo packageDirectory) { _directoryInfo = packageDirectory; var jsonFile = _directoryInfo.GetFile("metadata.json"); var yamlFile = _directoryInfo.GetFile("metadata.yml"); if (jsonFile.Exists) { var se = new Serializer(); Metadata = JsonConvert.DeserializeObject<PackageMetadata>(File.ReadAllText(_directoryInfo.GetFile("metadata.json").FullName)); using (var yamlStream = yamlFile.Open(FileMode.OpenOrCreate)) { using (var yamlWriter = new StreamWriter(yamlStream, Encoding.UTF8)) { se.Serialize(yamlWriter, Metadata); } } jsonFile.Delete(); } var dse = new Deserializer(); //Console.WriteLine("Reading YAML: {0}", yamlFile.FullName); using (var yamlStream = yamlFile.Open(FileMode.Open)) { using (var yamlReader = new StreamReader(yamlStream, Encoding.UTF8, true)) { Metadata = dse.Deserialize<PackageMetadata>(yamlReader); } } }
public void Run(string[] args) { var address = new { street = "123 Tornado Alley\nSuite 16", city = "East Westville", state = "KS" }; var receipt = new { receipt = "Oz-Ware Purchase Invoice", date = new DateTime(2007, 8, 6), customer = new { given = "Dorothy", family = "Gale" }, items = new[] { new { part_no = "A4786", descrip = "Water Bucket (Filled)", price = 1.47M, quantity = 4 }, new { part_no = "E1628", descrip = "High Heeled \"Ruby\" Slippers", price = 100.27M, quantity = 1 } }, bill_to = address, ship_to = address, specialDelivery = "Follow the Yellow Brick\n" + "Road to the Emerald City.\n" + "Pay no attention to the\n" + "man behind the curtain." }; var serializer = new Serializer(); serializer.Serialize(Console.Out, receipt); }
public void CircularReference() { var serializer = new Serializer(); using (StringWriter buffer = new StringWriter()) { Y original = new Y(); original.Child = new Y { Child = original, Child2 = original }; serializer.Serialize(buffer, original, typeof(Y), SerializationOptions.Roundtrip); Console.WriteLine(buffer.ToString()); } }
public static void WriteFactsFile(string file) { try { RubyHash common = Facter.GetFacterFacts(); RubyHash nodeSpecific = Facter.GetOpenshiftFacts(); dynamic desc = common.Merge(nodeSpecific); using (StringWriter sw = new StringWriter()) { Serializer serializer = new Serializer(); serializer.Serialize(new Emitter(sw, 2, int.MaxValue, true), desc); File.WriteAllText(file, sw.ToString()); } } catch (Exception ex) { Logger.Error("Error while generating facts file: {0} - {1}", ex.Message, ex.StackTrace); throw; } }
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); } }
static void Main(string[] args) { //シリアライズするオブジェクトを定義する var calendar = new AdventCalendar(); calendar.Year = new DateTime(2012, 12, 1); calendar.Description = "C# Advent Calender 2012"; calendar.Contents.Add(new Content() { Day = 1, Author = "gushwell", Description = ".NET Framework4.5 での非同期I/O処理 事始め", URL = @"http://gushwell.ldblog.jp/archives/52290230.html" }); calendar.Contents.Add(new Content() { Day = 2, Author = "KTZ", Description = "年末の大掃除", URL = @"http://ritalin.github.com/2012/12-02/csharp-advent-2012/" }); calendar.Contents.Add(new Content() { Day = 3, Author = "neuecc", Description = "MemcachedTranscoder – C#のMemcached用シリアライザライブラリ", URL = @"http://neue.cc/2012/12/03_389.html" }); //YAMLにシリアライズしてコンソールに表示 var serializer = new Serializer(); serializer.Serialize(Console.Out, calendar); Console.Read(); }
public static string GetCartridgeList(bool listDescriptors, bool porcelain, bool oo_debug) { string output = string.Empty; List<Cartridge> carts = new List<Cartridge>(); foreach(Manifest cartridge in CartridgeRepository.Instance.LatestVersions()) { string manifestString = cartridge.ToManifestString(); using(StringReader sr = new StringReader(manifestString)) { var desrializer = new Deserializer(); dynamic manifest = desrializer.Deserialize(sr); manifest["Version"] = cartridge.Version; carts.Add(Cartridge.FromDescriptor(manifest)); } } if (porcelain) { if (listDescriptors) { output += "CLIENT_RESULT: "; List<string> descriptors = new List<string>(); foreach (Cartridge cart in carts) { dynamic desc = cart.ToDescriptor(); StringWriter sw = new StringWriter(); Serializer serializer = new Serializer(); serializer.Serialize(new Emitter(sw, 2, int.MaxValue, true), desc); descriptors.Add(sw.ToString()); } output += JsonConvert.SerializeObject(descriptors); } else { output += "CLIENT_RESULT: "; List<string> names = new List<string>(); foreach (Cartridge cart in carts) { names.Add(cart.Name); } output += JsonConvert.SerializeObject(names); } } else { if (listDescriptors) { foreach (Cartridge cart in carts) { dynamic desc = cart.ToDescriptor(); StringWriter sw = new StringWriter(); Serializer serializer = new Serializer(SerializationOptions.JsonCompatible); serializer.Serialize(new Emitter(sw, 2, int.MaxValue, true), desc); output += string.Format("Cartridge name: {0}\n\nDescriptor:\n {1}\n\n\n", cart.Name, sw.ToString()); } } else { output += "Cartridges:\n"; foreach (Cartridge cart in carts) { output += string.Format("\t{0}\n", cart.Name); } } } return output; }
private static void WriteSampleConfigFile(string configFileName) { using (var streamWriter = File.CreateText(configFileName)) { var serializer = new Serializer(); serializer.Serialize(streamWriter, Config.SampleConfig()); } }
/// <summary> /// Write the config object to the config file /// </summary> public void WriteToConfigSettingsToFile() { StreamWriter configFile = new StreamWriter(FILE_CONFIG, false); Serializer s = new Serializer(); s.Serialize(configFile, Config); }
public void SerializationDoesNotIncludeNullWhenNotAsked() { var serializer = new Serializer(); using (StringWriter buffer = new StringWriter()) { X original = new X { MyString = null }; serializer.Serialize(buffer, original, typeof(X), SerializationOptions.None); Console.WriteLine(buffer.ToString()); Assert.False(buffer.ToString().Contains("MyString")); } }
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]); } } }
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) ); } } } }
public string ToManifestString() { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { var serializer = new Serializer(); serializer.Serialize(sw, this.ManifestSpec); } return sb.ToString(); }
public void SerializeAnonymousType() { var data = new { Key = 3 }; var serializer = new Serializer(); StringWriter buffer = new StringWriter(); serializer.Serialize(buffer, data); Console.WriteLine(buffer.ToString()); var deserializer = new YamlSerializer<Dictionary<string, string>>(); var parsed = deserializer.Deserialize(new StringReader(buffer.ToString())); Assert.NotNull(parsed); Assert.Equal(1, parsed.Count); }
public void SerializationRespectsYamlIgnoreAttribute() { var serializer = new Serializer(); var deserializer = new YamlSerializer<ContainsIgnore>(YamlSerializerModes.EmitDefaults | YamlSerializerModes.JsonCompatible | YamlSerializerModes.Roundtrip); using (StringWriter buffer = new StringWriter()) { var orig = new ContainsIgnore { IgnoreMe = "Some Text" }; serializer.Serialize(buffer, orig); Console.WriteLine(buffer.ToString()); var copy = deserializer.Deserialize(new StringReader(buffer.ToString())); Assert.Null(copy.IgnoreMe); } }
public void SerializationOfNullWorksInJson() { var serializer = new Serializer(); using (StringWriter buffer = new StringWriter()) { X original = new X { MyString = null }; serializer.Serialize(buffer, original, typeof(X), SerializationOptions.EmitDefaults | SerializationOptions.JsonCompatible); Console.WriteLine(buffer.ToString()); Assert.True(buffer.ToString().Contains("MyString")); } }
public void SerializationIncludesNullWhenAsked() { var serializer = new Serializer(); using (StringWriter buffer = new StringWriter()) { X original = new X { MyString = null }; serializer.Serialize(buffer, original, typeof(X), SerializationOptions.EmitDefaults); Console.WriteLine(buffer.ToString()); Assert.True(buffer.ToString().Contains("MyString")); } }
public string Serialize() { var yamlSerializer = new Serializer(); var stringWriter = new StringWriter(); yamlSerializer.Serialize(stringWriter, this); return stringWriter.GetStringBuilder().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); } }
public static void InstantiateCartridge(Manifest cartridge, string target, bool failureRemove = true) { Directory.CreateDirectory(target); try { bool downloadable = cartridge.ManifestPath == "url"; if (downloadable) { Uri uri = new Uri(cartridge.SourceUrl); string temporary = Path.Combine(target, Path.GetFileName(uri.LocalPath)); if (uri.Scheme == "git" || cartridge.SourceUrl.EndsWith(".git")) { // use intermediate temp directory to reset cygwin directories ACLs string tempRepo = cartridge.Name + ".temp"; string tempRepoDir = Path.Combine(new DirectoryInfo(target).Parent.FullName, tempRepo); try { string template = @"{0} clone {1} {2} set GIT_DIR=./{2}/.git {0} repack"; string file = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + "cmd.bat"); File.WriteAllText(file, string.Format(template, Path.Combine(NodeConfig.Values["SSHD_BASE_DIR"], @"bin\git.exe"), cartridge.SourceUrl, tempRepo)); ProcessResult result = ProcessExtensions.RunCommandAndGetOutput("cmd.exe", string.Format("/c {0}", file), new DirectoryInfo(target).Parent.FullName); if (result.ExitCode != 0) { throw new Exception(string.Format("Unable to clone cartridge from {0} stdout: {1} stderr {2}", cartridge.SourceUrl, result.StdOut, result.StdErr)); } DirectoryUtil.DirectoryCopy(tempRepoDir, target, true); } finally { if (Directory.Exists(tempRepoDir)) { Directory.Delete(tempRepoDir, true); } } } else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"\.zip")) { try { UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5); Extract("zip", temporary, target); } catch (Exception ex) { Logger.Error(ex.ToString()); throw ex; } finally { if (File.Exists(temporary)) { File.Delete(temporary); } } } else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"(\.tar\.gz|\.tgz)$")) { try { UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5); Extract("tgz", temporary, target); } catch (Exception ex) { Logger.Error(ex.ToString()); throw ex; } finally { if (File.Exists(temporary)) { File.Delete(temporary); } } } else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"\.tar$")) { try { UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5); Extract("tar", temporary, target); } catch(Exception ex) { Logger.Error(ex.ToString()); throw ex; } finally { if (File.Exists(temporary)) { File.Delete(temporary); } } } else if (uri.Scheme == "file") { DirectoryUtil.DirectoryCopy(uri.LocalPath, target, true); } else { throw new ArgumentException(string.Format("CLIENT_ERROR: Unsupported URL({0}) for downloading a private cartridge", cartridge.SourceUrl)); } } else { // TODO exclude usr folder and use link DirectoryUtil.DirectoryCopy(cartridge.RepositoryPath, target, true); } ValidateCartridgeHome(cartridge, target); if (downloadable) { string manifestOnDisk = Path.Combine(target, "metadata", "manifest.yml"); using (StreamWriter sw = new StreamWriter(manifestOnDisk)) { Serializer ser = new Serializer(SerializationOptions.None); ser.Serialize(sw, cartridge.ManifestSpec); } } } catch(Exception e) { if (failureRemove) { if (Directory.Exists(target)) { Directory.Delete(target); } } throw e; } }
public void Enums() { var serializer = new Serializer(); YamlSerializer<StringFormatFlags> deserializer = new YamlSerializer<StringFormatFlags>(); StringFormatFlags flags = StringFormatFlags.NoClip | StringFormatFlags.NoFontFallback; StringWriter buffer = new StringWriter(); serializer.Serialize(buffer, flags); StringFormatFlags deserialized = deserializer.Deserialize(new StringReader(buffer.ToString())); Assert.Equal(flags, deserialized); }