Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Created February 13, 2019 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottoffen/20f6bf3596ade5b1a31b4ffeb113e94b to your computer and use it in GitHub Desktop.
Save scottoffen/20f6bf3596ade5b1a31b4ffeb113e94b to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Sandbox
{
[Serializable]
public class HeaderCollection : Dictionary<string, string>, IXmlSerializable, ISerializable
{
public HeaderCollection() { }
public HeaderCollection(IDictionary<string, string> dictionary) : base(dictionary) { }
public HeaderCollection(IEqualityComparer<string> comparer) : base(comparer) { }
public HeaderCollection(int capacity) : base(capacity) { }
public HeaderCollection(IDictionary<string, string> dictionary, IEqualityComparer<string> comparer) : base(dictionary, comparer) { }
public HeaderCollection(int capacity, IEqualityComparer<string> comparer) : base(capacity, comparer) { }
protected HeaderCollection(SerializationInfo info, StreamingContext context) : base(info, context)
{
int itemCount = info.GetInt32("itemsCount");
for (int i = 0; i < itemCount; i++)
{
var kvp = (KeyValuePair<string, string>)info.GetValue(String.Format(CultureInfo.InvariantCulture, "Item{0}", i), typeof(KeyValuePair<string, string>));
Add(kvp.Key, kvp.Value);
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("itemsCount", Count);
int itemIdx = 0;
foreach (KeyValuePair<string, string> kvp in this)
{
info.AddValue(String.Format(CultureInfo.InvariantCulture, "Item{0}", itemIdx), kvp, typeof(KeyValuePair<string, string>));
itemIdx++;
}
}
XmlSchema IXmlSerializable.GetSchema() => null;
void IXmlSerializable.ReadXml(XmlReader reader)
{
if (reader.IsEmptyElement) return;
if (reader.NodeType == XmlNodeType.Element && !reader.Read())
throw new XmlException("Error in Deserialization of HeaderCollection");
while (reader.NodeType != XmlNodeType.EndElement)
{
object key = reader.GetAttribute("Name");
object value = reader.GetAttribute("Value");
this.Add((string)key, (string)value);
reader.Read();
}
if (reader.NodeType == XmlNodeType.EndElement)
{
reader.ReadEndElement();
}
else
{
throw new XmlException("Error in Deserialization of HeaderCollection");
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
foreach (var key in this.Keys)
{
writer.WriteStartElement("Header");
writer.WriteAttributeString("Name", key);
writer.WriteAttributeString("Value", this[key]);
writer.WriteEndElement();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment