Download YamlDotNetTypeConverter.zip, last updated 01/04/2017 (27.73 KB)

Download
  • md5: 66fdcbddcff158af2b4d7d8756150c2a
  • sha1: a31655e072b0d1cebb4a03a51c3780cadaaf3d24
  • sha256: 70865eff552b26245c036320b92b2d2f010b0e62cffb0b7f9b4728e972509a6a
using System;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

// Using custom type converters with C# and YamlDotNet, part 1
// http://www.cyotek.com/blog/using-custom-type-converters-with-csharp-and-yamldotnet-part-1

// This work is licensed under the Creative Commons Attribution 4.0 International License.
// To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/.

namespace YamlDotNetTypeConverter.Serialization
{
  internal sealed class ContentCategoryYamlTypeConverter : IYamlTypeConverter
  {
    #region Constants

    private static readonly Type _contentCategoryNodeType = typeof(ContentCategory);

    #endregion

    #region Methods

    private void WriteChildren(IEmitter emitter, ContentCategory node)
    {
      emitter.Emit(new Scalar(null, "Categories"));
      emitter.Emit(new SequenceStart(null, null, false, SequenceStyle.Block));

      foreach (ContentCategory child in node.Categories)
      {
        this.WriteYaml(emitter, child, _contentCategoryNodeType);
      }

      emitter.Emit(new SequenceEnd());
    }

    private void WriteContentCategory(IEmitter emitter, object value)
    {
      ContentCategory node;

      node = (ContentCategory)value;

      emitter.Emit(new MappingStart(null, null, false, MappingStyle.Block));

      if (node.Name != null)
      {
        emitter.Emit(new Scalar(null, "Name"));
        emitter.Emit(new Scalar(null, node.Name));
      }

      if (node.Title != null)
      {
        emitter.Emit(new Scalar(null, "Title"));
        emitter.Emit(new Scalar(null, node.Title));
      }

      if (node.HasCategories)
      {
        this.WriteChildren(emitter, node);
      }

      if (node.HasTopics)
      {
        this.WriteTopics(emitter, node);
      }

      emitter.Emit(new MappingEnd());
    }

    private void WriteTopics(IEmitter emitter, ContentCategory node)
    {
      emitter.Emit(new Scalar(null, "Topics"));
      emitter.Emit(new SequenceStart(null, null, false, SequenceStyle.Block));

      foreach (string child in node.Topics)
      {
        emitter.Emit(new Scalar(null, child));
      }

      emitter.Emit(new SequenceEnd());
    }

    #endregion

    #region IYamlTypeConverter Interface

    public bool Accepts(Type type)
    {
      return type == _contentCategoryNodeType;
    }

    public object ReadYaml(IParser parser, Type type)
    {
      throw new NotImplementedException();
    }

    public void WriteYaml(IEmitter emitter, object value, Type type)
    {
      this.WriteContentCategory(emitter, value);
    }

    #endregion
  }
}

Donate

Donate