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

Download
  • md5: 66fdcbddcff158af2b4d7d8756150c2a
  • sha1: a31655e072b0d1cebb4a03a51c3780cadaaf3d24
  • sha256: 70865eff552b26245c036320b92b2d2f010b0e62cffb0b7f9b4728e972509a6a
using System;
using System.Drawing;
using System.IO;
using System.Media;
using System.Windows.Forms;
using YamlDotNet.Serialization;
using YamlDotNetTypeConverter.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
{
  internal partial class MainForm : Form
  {
    #region Fields

    private ContentCategoryCollection _categories;

    private string _fileName;

    #endregion

    #region Constructors

    public MainForm()
    {
      this.InitializeComponent();
    }

    #endregion

    #region Properties

    private string DataPath
    {
      get { return Path.Combine(Application.StartupPath, "data"); }
    }

    #endregion

    #region Methods

    protected override void OnLoad(EventArgs e)
    {
      Font fixedFont;

      _categories = new ContentCategoryCollection();

      this.Font = SystemFonts.MessageBoxFont;
      fixedFont = this.GetFixedFont();
      textBox1.Font = fixedFont;
      textBox2.Font = fixedFont;

      base.OnLoad(e);
    }

    protected override void OnShown(EventArgs e)
    {
      base.OnShown(e);

      this.OpenDocument(Path.Combine(this.DataPath, "categories.yml"));
    }

    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
      using (Form dialog = new AboutDialog())
      {
        dialog.ShowDialog(this);
      }
    }

    private void addToolStripMenuItem_Click(object sender, EventArgs e)
    {
      TreeNode node;
      TreeNodeCollection nodes;

      node = new TreeNode();
      nodes = categoriesTreeView.SelectedNode?.Nodes ?? categoriesTreeView.Nodes;

      nodes.Add(node);

      categoriesTreeView.SelectedNode = node;
      node.EnsureVisible();
      node.BeginEdit();
    }

    private void categoriesTreeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
    {
      TreeNode node;

      node = e.Node;

      if (node.Tag == null)
      {
        // temporary node
        if (e.CancelEdit)
        {
          node.Remove();
        }
        else
        {
          ContentCategory item;
          TreeNode owner;

          item = new ContentCategory
                 {
                   Title = e.Label
                 };

          node.Tag = item;
          node.Text = e.Label;

          owner = node.Parent;

          if (owner == null)
          {
            _categories.Add(item);
          }
          else
          {
            ((ContentCategory)owner.Tag).Categories.Add(item);
          }
        }
      }

      this.UpdateYamlOutput();
    }

    private void categoriesTreeView_AfterSelect(object sender, TreeViewEventArgs e)
    {
      propertyGrid.SelectedObject = categoriesTreeView.SelectedCategory;
    }

    private void copyToolStripMenuItem_Click(object sender, EventArgs e)
    {
      TextBoxBase textBox;

      textBox = this.GetActiveControl();

      if (textBox != null && textBox.SelectionLength > 0)
      {
        textBox.Copy();
      }
      else
      {
        SystemSounds.Beep.Play();
      }
    }

    private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if (categoriesTreeView.Focused)
      {
        TreeNode node;

        node = categoriesTreeView.SelectedNode;

        if (node != null)
        {
          if (!node.IsEditing)
          {
            ContentCategory category;

            category = node.Tag as ContentCategory;

            if (category != null)
            {
              if (category.Parent != null)
              {
                category.Parent.Categories.Remove(category);
              }
              else
              {
                _categories.Remove(category);
              }

              this.UpdateYamlOutput();
            }

            node.Remove();
          }
        }
        else
        {
          SystemSounds.Beep.Play();
        }
      }
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private TextBoxBase GetActiveControl()
    {
      return this.GetActiveControl(this.ActiveControl);
    }

    private TextBoxBase GetActiveControl(Control activeControl)
    {
      TextBoxBase result;

      result = activeControl as TextBoxBase;

      if (result == null)
      {
        ContainerControl container;

        container = activeControl as ContainerControl;

        if (container != null)
        {
          result = this.GetActiveControl(container.ActiveControl);
        }
      }

      return result;
    }

    private Serializer GetDefaultSerializer()
    {
      return new SerializerBuilder().Build();
    }

    private Font GetFixedFont()
    {
      Font font;

      font = null;

      foreach (string fontName in new[]
                                  {
                                    "Fira Code",
                                    "Hack",
                                    "Source Code Pro",
                                    "Consolas",
                                    "Courier New"
                                  })
      {
        font = this.GetFont(fontName);

        if (font != null)
        {
          break;
        }
      }

      return font ?? SystemFonts.MessageBoxFont;
    }

    private Font GetFont(string fontFamilyName)
    {
      Font result;

      try
      {
        using (FontFamily family = new FontFamily(fontFamilyName))
        {
          result = family.IsStyleAvailable(FontStyle.Regular) ? new Font(family, 10, FontStyle.Regular) : null;
        }
      }
      catch (ArgumentException)
      {
        result = null;
      }

      return result;
    }

    private Serializer GetSerializerWithTypeConverter()
    {
      return new SerializerBuilder() // 
        .WithTypeConverter(new ContentCategoryYamlTypeConverter()) //
        .Build();
    }

    private void newToolStripMenuItem_Click(object sender, EventArgs e)
    {
      _categories.Clear();
      this.UpdateUi();
      this.SetFileName(null);
    }

    private void OpenDocument(string fileName)
    {
      Deserializer deserializer;

      deserializer = new DeserializerBuilder().Build();

      using (Stream stream = File.OpenRead(fileName))
      {
        using (TextReader reader = new StreamReader(stream))
        {
          _categories = deserializer.Deserialize<ContentCategoryCollection>(reader);
        }
      }

      this.SetParents();
      this.SetFileName(fileName);
      this.UpdateUi();
    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
      using (OpenFileDialog dialog = new OpenFileDialog
                                     {
                                       Filter = "YAML Documents (*.yml)|*.yml|All Files (*.*)|*.*",
                                       DefaultExt = "yml",
                                       InitialDirectory = this.DataPath
                                     })
      {
        if (dialog.ShowDialog(this) == DialogResult.OK)
        {
          this.OpenDocument(dialog.FileName);
        }
      }
    }

    private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
    {
      ContentCategory category;

      category = categoriesTreeView.SelectedCategory;

      if (category != null)
      {
        categoriesTreeView.SelectedNode.Text = category.Title;

        this.UpdateYamlOutput();
      }
    }

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
      this.SaveDocument();
    }

    private void SaveDocument()
    {
      using (SaveFileDialog dialog = new SaveFileDialog
                                     {
                                       Filter = "YAML Documents (*.yml)|*.yml|All Files (*.*)|*.*",
                                       DefaultExt = "yml",
                                       InitialDirectory = this.DataPath,
                                       FileName = _fileName
                                     })
      {
        if (dialog.ShowDialog(this) == DialogResult.OK)
        {
          this.SaveDocument(dialog.FileName);
        }
      }
    }

    private void SaveDocument(string fileName)
    {
      Serializer serializer;

      serializer = this.GetSerializerWithTypeConverter();

      using (Stream stream = File.Create(fileName))
      {
        using (TextWriter writer = new StreamWriter(stream))
        {
          serializer.Serialize(writer, _categories);
        }
      }

      this.SetFileName(fileName);
    }

    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if (string.IsNullOrEmpty(_fileName))
      {
        this.SaveDocument();
      }
      else
      {
        this.SaveDocument(_fileName);
      }
    }

    private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
    {
      TextBoxBase textBox;

      textBox = this.GetActiveControl();

      if (textBox != null)
      {
        textBox.SelectAll();
      }
      else
      {
        SystemSounds.Beep.Play();
      }
    }

    private void SetFileName(string fileName)
    {
      _fileName = fileName;

      this.Text = (!string.IsNullOrEmpty(fileName) ? Path.GetFileName(fileName) : "Untitled") + " - " + Application.ProductName;
    }

    private void SetParents()
    {
      foreach (ContentCategory child in _categories)
      {
        this.SetParents(child, null);
      }
    }

    private void SetParents(ContentCategory contentCategory, ContentCategory parent)
    {
      contentCategory.Parent = parent;

      if (contentCategory.HasCategories)
      {
        contentCategory.Categories.Parent = contentCategory;

        foreach (ContentCategory child in contentCategory.Categories)
        {
          this.SetParents(child, contentCategory);
        }
      }
    }

    private void UpdateUi()
    {
      categoriesTreeView.Categories = _categories;
      this.UpdateYamlOutput();
    }

    private void UpdateYamlOutput()
    {
      Serializer defaultSerializer;
      Serializer customSerializer;

      defaultSerializer = this.GetDefaultSerializer();

      textBox1.Text = defaultSerializer.Serialize(_categories);

      customSerializer = this.GetSerializerWithTypeConverter();
      textBox2.Text = customSerializer.Serialize(_categories);
    }

    #endregion
  }
}

Donate

Donate