jefffhaynes / BinarySerializer

A declarative serialization framework for controlling formatting of data at the byte and bit level using field bindings, converters, and code.
MIT License
289 stars 62 forks source link

OverflowException error using Deserialization with context #149

Closed mikedavison closed 4 years ago

mikedavison commented 4 years ago

This error might be because I am not understanding what the use of "context" is.

I have a context class that looks like this:

public class TestContext

    {
        public string fileName;
        public uint version;
        public bool versionOK = false;
        public FileAccess fileAccessMode;
        public FileStream stream;
        public Endianness endianness = Endianness.Little;
        private bool _keepOpen;
        public int headerLength;
        public int numChannels;
        public bool compressed;
        public BinarySerialization.BinarySerializer serializer = new BinarySerialization.BinarySerializer();
  }

Note the context class contains the serializer. The class to be deserialized is:

public class FileMetrics
    {
         [FieldOrder(1)] public short leader; // 0
         [FieldOrder(2)] public uint fileVersion; //2
         [FieldOrder(3)] public int headerLength; //6
         [FieldOrder(4)] public short numChannels; //10
    }

After setting up the stream and parameters I can successfully call the Deserializer method using the following:

TestContext tc = new TestContext();
tc.stream = new FileStream(fileName, FileMode.Open, fileAccessMode);
FileMetrics fm = tc.serializer.Deserialize<FileMetrics>(tc.stream);

However if I deserialize using the context: FileMetrics fm = tc.serializer.Deserialize<FileMetrics>(tc.stream, tc); It fails with OverflowException error. When I debug the code here is what I see. Looking at your class TypeNode.cs with a breakpoint on line 131 var attributes = memberInfo.GetCustomAttributes(true).ToList(); It first iterates through the members of target class FileMetrics but then for some reason tries to iterate through the members of the class TestContext and this is when the OverflowException happens.

jefffhaynes commented 4 years ago

I'm actually not able to reproduce this. However, in general the serializer needs to be able to reflect the members of the context as it is possible to bind to the context in the same way it is possible to bind to other fields in the object being serialized.

In general, I would recommend keeping the context simple and only passing the context needed for a given operation. For example, I can't think of any reason why the serializer itself would be included in the context.