3

I'm using NetDataContractSerializer to exchange data among applications. I would like the ReadObject method throw an exception when assembly versions don't match.

Now, for example, when I serialized my object from assembly version 1.0.0.0 and later deserialize it having same assembly but now version 1.0.0.1, the NetDataContractSerializer happily swallows the stream and deserializes without problems.

Is it possible to abort the deserialization process when versions don't match?

UPDATE: I need version intolerance because of many reasons. This is both a requirement from a customer, as well as a requirement to be absolutely certain that import processes the file that was exported from the same version of the application. In case of my application, changing version makes useless the previous import process, because version change equals to more or less involved internal structure change.

Valentin V
  • 24,971
  • 33
  • 103
  • 152
  • 2
    wait... why would you want to *introduce* versioning intolerance? For most people the problem is the other way around... – Marc Gravell Mar 22 '11 at 09:27

1 Answers1

1

Ugly but effective (ideally on your root object):

[DataMember]
private string AppVersion {
    get { return CurrentAppVersion; }
    set {
        if(value != CurrentAppVersion) throw new InvalidOperationException(
            "Data from version " + value + " is not compatible");
    }
}
private const string CurrentAppVersion = "1.0.11a";
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • This is odd... I'm here because I'm having the *opposite* problem. Its throwing a FileLoadException because the strong name of the assembly has changed when I try to Deserialize(). –  Apr 20 '11 at 17:22
  • @Will: You should use `FormatterAssemblyStyle.Simple`. –  Apr 20 '11 at 17:26
  • @Will - AssemblyLoad event is useful for fixing up strig name changes – Marc Gravell Apr 20 '11 at 18:11
  • @MarcGravell: I wasn't looking forward to going that deep; besides, I'm not sure if the NDCS would respect that kind of intervention. But the FormatterAssemblyStyle works. –  Apr 20 '11 at 18:36
  • @Will I kinda gave up on type-based serializers, and NDCS is not really all that fast, truth told – Marc Gravell Apr 20 '11 at 19:16
  • @MarcGravell: I like it because it produces human-readable serialized object graphs, can handle circular references and multiple references to the same instance. –  Apr 20 '11 at 19:18
  • @Will - with my own, I can everything except the human readable, but avoid a lot of problems ;p – Marc Gravell Apr 20 '11 at 19:58