To serialize a Business object marked with [DataContract] and properties marked with [DataMember] attributes…
public static string DataContractSerializeObject<T>(T objectToSerialize)
{
using (var output = new StringWriter())
{
using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })
{
var dataContractSerializer = new DataContractSerializer(typeof(T), EntityUtilities.GetAllKnownTypes(), int.MaxValue, true, true, null);
dataContractSerializer.WriteObject(writer, objectToSerialize);
return output.GetStringBuilder().ToString();
}
}
}
Then to deserialize back to your DataContract type, use this logic…
public static T Deserialize<T>(string xml)
{
using (Stream stream = new MemoryStream())
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
stream.Write(data, 0, data.Length);
stream.Position = 0;
var dataContractSerializer = new DataContractSerializer(typeof(T), EntityUtilities.GetAllKnownTypes(), int.MaxValue, true, true, null);
return (T)dataContractSerializer.ReadObject(stream);
}
}
So - where does EntityUtilities come from? I can find no reference to this in dotnet...
ReplyDeleteThat's custom logic for our in house application
Deleteessentially it just uses reflection to get all the types out of the assembly
Assembly assembly = AppDomain.CurrentDomain.Load("BusinessDllName");
AddKnownEntityTypes(assembly);
private static void AddKnownEntityTypes(Assembly assembly)
{
Type entityType = typeof(EntityBase);
Type collectionType = typeof(ICollectionBase);
using (new ExecutionTimer())
{
foreach (Type type in assembly.GetTypes())
{
if (!type.IsInterface && !type.IsNested && !type.IsGenericType)
{
if (!type.IsAbstract && entityType.IsAssignableFrom(type)
&& type.GetCustomAttributes(typeof(ReferenceDataAttribute), true).Length > 0)
{
lock (_knownReferenceDataTypes)
{
if (!_knownReferenceDataTypes.Contains(type))
{
_knownReferenceDataTypes.Add(type);
}
}
}
if (entityType.IsAssignableFrom(type)
&& type.GetCustomAttributes(typeof (DataContractAttribute), true).Length > 0)
{
lock (_knownEntityTypes)
{
if (!_knownEntityTypes.Contains(type))
{
_knownEntityTypes.Add(type);
}
}
#if (!NOPROXY)
Type proxyType = ProxyTypeManager.GetProxyType(type);
lock (_knownProxyTypes)
{
if (!_knownProxyTypes.Contains(proxyType))
{
_knownProxyTypes.Add(proxyType);
}
}
#endif
}
else if (collectionType.IsAssignableFrom(type)
&& type.GetCustomAttributes(typeof (CollectionDataContractAttribute), true).Length > 0)
{
lock (_knownCollectionTypes)
{
if (!_knownCollectionTypes.Contains(type))
{
_knownCollectionTypes.Add(type);
}
}
}
}
}
}
}