locked
Binary formatter serialization not working for boolean objects in certain scenarios RRS feed

  • Question

  • Serialization using Binary fomatter is not working for boolean variables.

    The below object is serialized using binary formatter and storing in db as SqlDBType.VarBinary. While retreiving it from DB we deserialize it using the binary formatter to convert it to object. The retrieved object doesn’t seem to retain the boolean values.

    [Serializable]

    public class Sample

    {

        private List<ABC> abcList;

        private List<string> items;

    }

    [Serializable]

    public class ABC

    {

        private string code;

        private string description;

        private bool selected;

        private List<XYZ> xyzList;

    }

    [Serializable]

    public class XYZ

    {

        private string code;

        private string description;

        private bool selected;

    }

    //Saving it to DB

    using (MemoryStream serializationStream = new MemoryStream())

    {

        IFormatter formatter = new BinaryFormatter();

        formatter.Serialize(serializationStream, this); //this -> Sample object

        bytes = serializationStream.GetBuffer();

    }

    SqlParameter sdParam = new SqlParameter("@SD", SqlDbType.VarBinary, bytes.Length);

    sdParam.Value = bytes;

    //Retrieving it from DB

    bytes = (byte[])dr["SerializedData"];

    IFormatter formatter1 = new BinaryFormatter();

    using (MemoryStream stream = new MemoryStream(bytes))

    Sample obj = (LNMIProfile)formatter1.Deserialize(stream);

    Our Findings

    1. The same worked perfectly in .net 3.5 framework. It is failing after migrating the app to.net 4.0
    2. The “selected” property inside ABC object doesn’t retain its value when there is 0 count in xyzList. To fix we just tried to maintain the xyzList count  to be greater than 0. It worked perfectly. But this seems to be a criminal fix.
    3. If we use NetDataContractSerializer instead of binary formatter without any alteration in object everything works fine.

    Please help us to sort this issue.


    Tuesday, December 11, 2012 10:22 AM

All replies

  • I donot know if this will help. you can try to implement ISerializable on the class and handle the serialization and deserialization by your own.

    Sunday, December 16, 2012 4:25 PM