Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.Serialization;
- namespace Common.Caching
- {
- /// <summary>Wraps objects that aren't marked as serializable and uses Xml serialization to serialize and deserialize them</summary>
- [Serializable]
- public class SerializableObjectWrapper : ISerializable
- {
- [NonSerialized]
- object obj;
- string objxml;
- Type objType;
- public Type ObjectType
- {
- get { return objType; }
- }
- protected SerializableObjectWrapper(SerializationInfo info, StreamingContext context)
- {
- objxml = (string)info.GetValue("objxml", typeof(string));
- objType = (Type)info.GetValue("objType", typeof(Type));
- }
- public SerializableObjectWrapper(object core)
- {
- this.obj = core;
- if (core != null)
- this.objType = core.GetType();
- }
- public object GetValue()
- {
- if (obj == null)
- {
- if (string.IsNullOrWhiteSpace(objxml))
- return null;
- Type obtype = this.ObjectType;
- if (obtype == null)
- obtype = typeof(object);
- obj = Deserialize(objxml, obtype);
- }
- return obj;
- }
- public void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- info.AddValue("objxml", Serialize(obj));
- info.AddValue("objType", objType);
- }
- static string Serialize(object xmlObject, bool encodeInBase64 = false)
- {
- using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
- {
- System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(xmlObject.GetType());
- System.Xml.Serialization.XmlSerializerNamespaces xmlNamespace = new System.Xml.Serialization.XmlSerializerNamespaces();
- xmlNamespace.Add(string.Empty, string.Empty);
- xs.Serialize(memoryStream, xmlObject, xmlNamespace);
- System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
- if (encodeInBase64)
- return Convert.ToBase64String(System.Text.ASCIIEncoding.Unicode.GetBytes(encoding.GetString(memoryStream.ToArray())));
- else
- return encoding.GetString(memoryStream.ToArray());
- }
- }
- static object Deserialize(string xml, Type objtype)
- {
- bool decodeInBase64 = false;
- string data = xml;
- if (decodeInBase64)
- data = System.Text.ASCIIEncoding.Unicode.GetString(Convert.FromBase64String(xml));
- System.Xml.Serialization.XmlSerializer xs = System.Xml.Serialization.XmlSerializer.FromTypes(new Type[] { objtype })[0];
- System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
- using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(encoding.GetBytes(data)))
- {
- System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, System.Text.Encoding.UTF8);
- return xs.Deserialize(memoryStream);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment