using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace dk.nsi.seal.Serializers
{
public static class IdCardSerializer
{
///
/// Serializes an IdCard to a Xml document in string form
///
/// IdCard type (either SystemIdCard or UserIdCard)
/// IdCard to serialize
/// Xml representation of IdCard as string
public static string SerializeIdCardToString(T idCard)
{
var reader = new StreamReader(Serialize2Stream(idCard));
return reader.ReadToEnd();
}
///
/// Serializes an IdCard to a Xml document in a MemoryStream
///
/// IdCard type (either SystemIdCard or UserIdCard)
/// IdCard to serialize
/// Xml representation of IdCard as MemoryStream
public static MemoryStream SerializeIdCardToStream(T idCard)
{
return Serialize2Stream(idCard);
}
///
/// Deserialize IdCard from string
///
/// IdCard type (either SystemIdCard or UserIdCard)
/// String of serialized IdCard
/// IdCard from string
public static T DeserializeIdCard(string serializedIdCard) where T : class
{
var xDoc = XDocument.Parse(serializedIdCard, LoadOptions.PreserveWhitespace);
return Deserialize(xDoc.Root);
}
///
/// Deserialize IdCard from Stream
///
/// IdCard type (either SystemIdCard or UserIdCard)
/// Stream of serialized IdCard
/// IdCard from Stream
public static T DeserializeIdCard(Stream serializedIdCard) where T : class
{
var xDoc = XDocument.Load(serializedIdCard, LoadOptions.PreserveWhitespace);
return Deserialize(xDoc.Root);
}
private static MemoryStream Serialize2Stream(T element)
{
var ms = new MemoryStream();
using (var xmlWriter = XmlWriter.Create(ms, new XmlWriterSettings { Indent = false }))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(xmlWriter, element);
}
ms.Position = 0;
return ms;
}
private static T Deserialize(XElement document) where T : class
{
var ms = new MemoryStream();
document.Save(ms);
ms.Position = 0;
var xmlSerializer = new XmlSerializer(typeof(T));
return xmlSerializer.Deserialize(ms) as T;
}
}
}