/// <summary> /// Serializes the object graph using a Binary formatter, and then encodes the resulting bytes into a Base64 string that will be safe for POP attachments or Xml node data. /// </summary> /// <param name="value">The object graph to serialize. NOTE: The object must support serialization via the SerializableAttribute and optionally support the ISerializable interface.</param> /// <param name="t">The Type of the object, needed to ensure serialization is supported</param> /// <param name="base64String">A reference to a string which will receive the encoded result of the operation</param> /// <returns></returns> public static bool Base64Encode(object instance, Type t, out string base64String) { base64String = null; /// if the type supports serialization if (EncodingEngine.SupportsISerializableInterface(t) || t.IsSerializable) { BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { /// serialize the object graph bf.Serialize(ms, instance); /// retrieve the raw bytes from the serialization byte[] bytes = ms.GetBuffer(); /// encode them to a base64 string return((base64String = System.Convert.ToBase64String(bytes)) != null); } } return(false); }
/// <summary> /// Deserializes an object assuming that the string contains the base64 encoded data for the object /// </summary> /// <param name="option"></param> /// <param name="buffer"></param> /// <returns></returns> private object GetSerializedValue(XmlConfigurationOption option, string buffer) { object instance = null; try { // try and base 64 decode the string if (EncodingEngine.Base64Decode(buffer, out instance)) { return(instance); } } catch (Exception ex) { this.OnCannotReadValue(this, new XmlConfigurationReaderEventArgs(ex, option, buffer)); // Debug.WriteLine(ex); } return(instance); }
/// <summary> /// Gets the value to write using a BinaryFormatter to serialize the Object.Value property. /// </summary> /// <param name="option"></param> /// <returns></returns> private string GetSerializedValue(XmlConfigurationOption option) { string buffer = null; try { Type t = Type.GetType(option.ValueAssemblyQualifiedName); if (t != null) { if (EncodingEngine.Base64Encode(option.Value, t, out buffer)) { return(buffer); } } } catch (System.Exception systemException) { System.Diagnostics.Trace.WriteLine(systemException); this.OnCannotWriteValue(this, new XmlConfigurationWriterEventArgs(systemException, option)); } return(buffer); }