using System.Collections.Generic;
using System.Xml.Serialization;
using System.Runtime.Serialization;
private const string OldSerializedString = "<?xml version=\"1.0\" encoding=\"utf-16\"?><CallContext xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/ContentDirect.Framework.Contract\"><_x003C_BusinessUnitId_x003E_k__BackingField>10013</_x003C_BusinessUnitId_x003E_k__BackingField><_x003C_SystemId_x003E_k__BackingField>dad1cb97-26e2-4955-b166-af54cd3aad45</_x003C_SystemId_x003E_k__BackingField></CallContext>";
public static void Main()
CallContext callContext = ReadObject<CallContext>(OldSerializedString);
Console.WriteLine("Failed with unhandled exception: ");
private static T ReadObject<T>(string serializedObject)
return (T)ReadObject(typeof(T), serializedObject);
private static object ReadObject(Type type, string serializedObject)
if (type.IsValueType || type == typeof(string))
return Convert.ChangeType(serializedObject, type);
DataContractSerializer serializer = new DataContractSerializer(type);
using (StringReader stringReader = new StringReader(serializedObject))
using (XmlReader reader = XmlReader.Create(stringReader))
return serializer.ReadObject(reader);
public int? BusinessUnitId { get; set; }
public string SystemId { get; set; }
public static partial class DataContractSerializerHelper
public static string ToContractXml<T>(this T obj, DataContractSerializer serializer, XmlWriterSettings settings)
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)
using (var textReader = new StringReader(xml ?? ""))
using (var xmlReader = XmlReader.Create(textReader))
return (T)(serializer ?? new DataContractSerializer(typeof(T))).ReadObject(xmlReader);
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, XmlSerializer serializer = null, bool omitStandardNamespaces = false)
XmlSerializerNamespaces ns = null;
if (omitStandardNamespaces)
ns = new XmlSerializerNamespaces();
using (var textWriter = new StringWriter())
var settings = new XmlWriterSettings() { Indent = true };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
(serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();