Note that there are some explanatory texts on larger screens.

plurals
  1. PONull reference exceptions during Base64 deserialization (C#)
    primarykey
    data
    text
    <p>I am using the following methods to serialize and deserialize .NET objects:</p> <pre><code>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); } </code></pre> <p>These methods seem to work fine when working with simple classes marked with the [Serializable] attribute. </p> <p>But I need to use this code to serialize entity classes (also maked as Serializable) created by an ORM framework, whereby each entity class is derived from a base class for which I do not have source code.</p> <p>When working with instances of an entity class, it completes serialization without exceptions, but deserialization always throws a null reference exception when excecuting formatter.Deserialize().</p> <p>I am not very familiar with the process of serialization, but I assume this problem must be caused by something anomalous in the state of the target object. Is there a standard set of criteria that an object must meet before serialization?</p> <p>Any other debugging suggestions would be appreciated.</p> <p>Thanks, Tim</p> <p>UPDATE:</p> <p>After further experimentation, I think I have discovered the cause of the problem. The target object has events that are handled by another class that is not marked as serializable, as described in <a href="http://quickduck.com/blog/2007/02/12/how-to-prevent-serialization-of-event-handlers/" rel="nofollow noreferrer">this post</a>.</p> <p>What's interesting is that serialaztion works correctly, even with the event handlers attached - it's deserialization that fails.</p> <p>But I have tested by temporarily removing the event handlers and both serialization and deserialization works correctly, so I assume this is the problem. However, since I don't have access to the code in which the events are declared, I can't immediately see how to implement the solution described above. It may be that I have to modify my serialization process to remove and then reinstate the event handlers.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload