I use the following methods to serialize and deserialize .NET objects:
public static string SerializeToBase64(object data) { var stream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(stream, data); stream.Position = 0; return Convert.ToBase64String(stream.ToArray()); } public static object DeserializeFromBase64(string data) { var stream = new MemoryStream(Convert.FromBase64String(data)); stream.Position = 0; var formatter = new BinaryFormatter(); return formatter.Deserialize(stream); }
These methods seem to work just fine when dealing with simple classes marked with the [Serializable] attribute.
But I need to use this code to serialize entity classes (also made as Serializable) created by the ORM framework, with each entity class coming from a base class for which I don't have source code.
When working with instances of an entity class, it completes serialization with no exceptions, but deserialization always throws a reference zero of exception when excecuting formatter.Deserialize ().
I am not very familiar with the serialization process, but I assume that this problem should be caused by something abnormal in the state of the target. Is there a standard set of criteria that an object must meet before serialization?
Any other debugging suggestions would be appreciated.
Thanks Tim
UPDATE:
After further experimentation, I think I discovered the cause of the problem. The target has events that are handled by another class that is not marked as serializable, as described in this post .
Interestingly, serialaztion works correctly, even with attached event handlers - this is deserialization that fails.
But I tested by temporarily removing event handlers, and serialization and deserialization work correctly, so I assume this is a problem. However, since I do not have access to the code in which the events are declared, I cannot immediately see how to implement the solution described above. Perhaps I need to modify the serialization process to remove and then restore event handlers.