Skip to content

Instantly share code, notes, and snippets.

@nickheppleston
Last active August 29, 2015 14:07
Show Gist options
  • Save nickheppleston/a414fb76eaa7a2dc27be to your computer and use it in GitHub Desktop.
Save nickheppleston/a414fb76eaa7a2dc27be to your computer and use it in GitHub Desktop.
Azure Redis Cache - Cache Serialization Helper
/*
* A simple generic Serialization Helper allowing custom .Net types to be stored
* in the Azure Redis Cache. Inspired by the sample at:
* http://msdn.microsoft.com/en-us/library/azure/dn690524.aspx#Objects
*/
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace AzureRedisCacheSample
{
public static class CacheSerializer
{
public static byte[] Serialize(object o)
{
if (o == null)
{
return null;
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, o);
byte[] objectDataAsStream = memoryStream.ToArray();
return objectDataAsStream;
}
}
public static T Deserialize<T>(byte[] stream)
{
if (stream == null)
return (default(T));
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream(stream))
{
T result = (T)binaryFormatter.Deserialize(memoryStream);
return result;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment