I thought I would share these helpers for serializing objects and queries using ES. I use the BinarySerializer for querries and the XMLSerializer is for serialzing the domain objects.
BINARY:
public class BinarySerializer {
private BinarySerializer() {}
#region Serialize
/// <summary>
/// Serializes the supplied object.
/// </summary>
/// <param name="objectToSerialize">The object to serialize.</param>
/// <returns>Returns a byte array representing the object.</returns>
public static byte[] Serialize(Object objectToSerialize) {
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream()) {
bf.Serialize(ms, objectToSerialize);
return ms.ToArray();
}
}
#endregion
#region Deserialize<T>
/// <summary>
/// Deserializes the supplied byte array.
/// </summary>
/// <typeparam name="T">The type of cast to be perfomed when deserializing.</typeparam>
/// <param name="serializedObject">The serialized object.</param>
/// <returns>Returns the type T specified.</returns>
public static T Deserialize<T>(byte[] serializedObject) {
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(serializedObject)) {
return (T)bf.Deserialize(ms);
}
}
#endregion
}
XML:
public class XMLSerializer {
#region Constructors
#region XMLSerializer()
/// <summary>
/// Initializes a new instance of the <see cref="T:XMLSerializer"/> class.
/// </summary>
public XMLSerializer() { }
#endregion
#endregion
#region Static Methods
#region static string SaveToString(Object objectToSave)
/// <summary>
/// Saves or serializes the object into an XML string.
/// </summary>
/// <param name="objectToSave">The object to save.</param>
/// <returns>Returns an XML String representing the object.</returns>
public static string SaveToString(Object objectToSave) {
//Create serializer object using the type name of the Object to serialize.
XmlSerializer xmlSerializer = new XmlSerializer(objectToSave.GetType());
using (StringWriter writer = new StringWriter()) {
xmlSerializer.Serialize(writer, objectToSave);
return writer.ToString();
}
}
#endregion
#region static T LoadFromString<T>(string serializedXml)
/// <summary>
/// Loads the object T from the supplied XML string.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializedXml">The serialized XML.</param>
/// <returns>Returns the type of object T.</returns>
public static T LoadFromString<T>(string serializedXml) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(serializedXml)) {
return (T)xmlSerializer.Deserialize(reader);
}
}
#endregion
#endregion
}