using System.Collections.Generic;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
private string firstProperty;
public string FirstProperty
set => firstProperty = value;
private string firstProperty;
private string secondProperty;
public string FirstProperty
set => firstProperty = value;
public string SecondProperty
set => secondProperty = value;
public static partial class DataContractSerializerHelper
public static string ToContractXml<T>(this T obj, DataContractSerializer serializer = null, XmlWriterSettings settings = null)
serializer = serializer ?? new DataContractSerializer(obj == null ? typeof(T) : obj.GetType());
using (var textWriter = new StringWriter())
settings = settings ?? new XmlWriterSettings { Indent = true };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
serializer.WriteObject(xmlWriter, obj);
return textWriter.ToString();
public static T FromContractXml<T>(string xml, DataContractSerializer serializer = null)
using (var textReader = new StringReader(xml ?? ""))
using (var xmlReader = XmlReader.Create(textReader))
return (T)(serializer ?? new DataContractSerializer(typeof(T))).ReadObject(xmlReader);
public static void Test()
var oldToNew = DataContractSerializerHelper.FromContractXml<VNew.TestClass>(GetOldXml());
Console.WriteLine("Re-serialized {0}:", oldToNew);
var xml2 = DataContractSerializerHelper.ToContractXml(oldToNew);
var newToOld = DataContractSerializerHelper.FromContractXml<VOld.TestClass>(GetNewXmlForOld());
static string GetOldXml() => @"<TestClass xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/VNew"">
<firstProperty>first value</firstProperty>
static string GetNewXmlForOld() => @"<TestClass xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/VOld"">
<firstProperty>first value</firstProperty>
<secondProperty i:nil=""true"" />
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];