CSharp · Console
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using System.Reflection;
// https://stackoverflow.com/questions/50776811/can-i-create-xmlattributeoverrides-using-a-custom-attribute?noredirect=1#comment88563440_50776811
public abstract class SerializableObjectBase
{
protected int _typeIndicator;
[GenericSerializable]
public int TypeIndicator
{
get
{
return _typeIndicator;
}
set
{
_typeIndicator = value;
}
}
public SerializableObjectBase()
{
_typeIndicator = 0;
}
}
public class SerializableObjectChildOne : SerializableObjectBase
{
private int _test;
public int Test2 { get; set; }
public int Test
{
get
{
return _test;
}
set
{
_test = value;
}
}
public SerializableObjectChildOne()
: base()
{
_test = 1234;
_typeIndicator = 1;
}
}
public class SerializableObjectChildTwo : SerializableObjectChildOne
{
private List<int> _list;
public int Test3 { get; set; }
public List<int> List
{
get
{
return _list;
}
}
public SerializableObjectChildTwo()
: base()
{
_list = new List<int>();
_typeIndicator = 2;
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class GenericSerializableAttribute : System.Attribute
{
}
public static class SerializableObjectBaseExtensions
{
static readonly Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();
static readonly object padlock = new object();
public static XmlSerializer GetSerializer<TSerializable>(TSerializable obj) where TSerializable : SerializableObjectBase, new()
{
return GetSerializer(obj == null ? typeof(TSerializable) : obj.GetType());
}
public static XmlSerializer GetSerializer<TSerializable>() where TSerializable : SerializableObjectBase, new()
{
return GetSerializer(typeof(TSerializable));
}
static XmlSerializer GetSerializer(Type serializableType)
{
lock (padlock)
{
XmlSerializer serializer;
if (!serializers.TryGetValue(serializableType, out serializer))
serializer = serializers[serializableType] = CreateSerializer(serializableType);
return serializer;
}
}
static XmlSerializer CreateSerializer(Type serializableType)
{
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
for (var declaringType = serializableType; declaringType != null && declaringType != typeof(object); declaringType = declaringType.BaseType)
{
// check whether each property has the custom attribute
foreach (PropertyInfo property in declaringType.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance))
{
XmlAttributes attrbs = new XmlAttributes();
// if it has the attribute, tell the overrides to serialize this property
// property.IsDefined is faster than actually creating and returning the attribute
if (property.IsDefined(typeof(GenericSerializableAttribute), true))
{
Console.WriteLine("Adding " + property.Name + "");
attrbs.XmlElements.Add(new XmlElementAttribute(property.Name));
}
else
{
// otherwise, ignore the property
Console.WriteLine("Ignoring " + property.Name + "");
attrbs.XmlIgnore = true;
}
// add this property to the list of overrides
overrides.Add(declaringType, property.Name, attrbs);
}
}
// create the serializer
return new XmlSerializer(serializableType, overrides);
}
}
class TestClass
{
public static void Test()
{
var s = new SerializableObjectChildTwo();
var serializer = SerializableObjectBaseExtensions.GetSerializer(s);
var xml = s.GetXml(serializer);
Console.WriteLine(xml);
}
}
public static class XmlSerializationHelper
{
public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
{
serial = serial ?? new XmlSerializer(typeof(T));
using (var reader = new StringReader(xmlString))
{
return (T)serial.Deserialize(reader);
}
}
public static string GetXml<T>(this T obj, bool omitStandardNamespaces)
{
return obj.GetXml(null, omitStandardNamespaces);
}
public static string GetXml<T>(this T obj, XmlSerializer serializer = null, bool omitStandardNamespaces = false)
{
XmlSerializerNamespaces ns = null;
if (omitStandardNamespaces)
{
ns = new XmlSerializerNamespaces();
ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
}
using (var textWriter = new StringWriter())
{
var settings = new XmlWriterSettings() { Indent = true }; // For cosmetic purposes.
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
(serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
}
}
public static string GetOuterXml(this XmlNode node, bool indent = true)
{
if (node == null)
return null;
using (var textWriter = new StringWriter())
{
var settings = new XmlWriterSettings
{
Indent = indent,
OmitXmlDeclaration = true,
};
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
{
node.WriteTo(xmlWriter);
}
return textWriter.ToString();
}
}
}
public static class XmlAssert
{
// https://weblogs.asp.net/marianor/easy-way-to-compare-two-xmls-for-equality
// https://stackoverflow.com/questions/7318157/best-way-to-compare-xelement-objects
// Adapted from the answer https://stackoverflow.com/a/14463137 by https://stackoverflow.com/users/1102100/robjohnson
public static void AreEqual(
XElement expected,
XElement actual)
{
Assert.IsTrue(XNode.DeepEquals(Normalize(expected), Normalize(actual)));
}
private static XElement Normalize(XElement element)
{
if (element.HasElements)
{
return new XElement(
element.Name,
element.Attributes()
.OrderBy(a => a.Name.ToString()),
element.Elements()
.OrderBy(a => a.Name.ToString())
.Select(e => Normalize(e)));
}
if (element.IsEmpty)
{
return new XElement(
element.Name,
element.Attributes()
.OrderBy(a => a.Name.ToString()));
}
return new XElement(element.Name, element.Attributes()
.OrderBy(a => a.Name.ToString()), element.Value);
}
}
public class AssertionFailedException : System.Exception
{
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
}
public static class Assert
{
public static void IsTrue(bool value)
{
IsTrue(value, "failed");
}
public static void IsTrue(bool value, string message)
{
if (value == false)
throw new AssertionFailedException(message ?? "failed");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Uncaught exception: ");
Console.WriteLine(ex);
throw;
}
}
}