Last active
August 29, 2015 14:07
-
-
Save nickheppleston/a414fb76eaa7a2dc27be to your computer and use it in GitHub Desktop.
Azure Redis Cache - Cache Serialization Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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