Data Versioning


The types that hold the data are always subject to the .NET rules of versioning, [4] but that doesn't really help you when it comes to reading and writing old versions of the data using new versions of the object. One way to support versioned data formats is to write a version ID into the stream as part of a custom implementation of ISerializable:

[4] The details of .NET type versioning are covered in Essential .NET (Addison-Wesley, 2003), by Don Box, with Chris Sells.

 [SerializableAttribute] class MyData :  ISerializable  {   string s = "Wahoo!";   int n = 6;  ArrayList oldStrings = new ArrayList(); // v2.0 addition   static string currentVersion = "2.0";  ... #region Implementation of ISerializable   public MyData(     SerializationInfo info, StreamingContext context) {  // Read the data based on the version   string streamVersion = info.GetString("Version");   switch( streamVersion ) {   case "1.0":  s = info.GetString("MyString");         n = s.Length;  break;   case "2.0":  s = info.GetString("MyString");         n = s.Length;  oldStrings =   (ArrayList)info.GetValue("OldStrings", typeof(ArrayList));  break;     }   }   public void GetObjectData(     SerializationInfo info, StreamingContext context) {  // Tag the data with a version   info.AddValue("Version", currentVersion);   info.AddValue("MyString", s);   info.AddValue("OldStrings", oldStrings);  } #endregion } 

This implementation writes a Version string on all the data it writes , and then it uses that string to decide which data to read back in at run time. As the data in a class changes, marking it with a version gives you a way to migrate old data forward (or to save old versions, if you'd like).

Notice also that the new hunk of data added is an ArrayList. Just like the simple types, the collection classes (along with a large number of other classes in the .NET Framework) can be serialized, making this model useful for all kinds of things, from storing user settings (as discussed in Chapter 11: Applications and Settings) to saving document state.



Windows Forms Programming in C#
Windows Forms Programming in C#
ISBN: 0321116208
EAN: 2147483647
Year: 2003
Pages: 136
Authors: Chris Sells

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net