Manish Pansiniya's Blog

.NET, C#, Javascript, ASP.NET and lots more…:)

Versioning Serialization in .NET

leave a comment »

First let us look at what is serialization.

Assume you have created a GUI-based desktop application and wish to provide
a way for end users to save their preferences. To do so, you might define a class named UserPrefs that
encapsulates 20 or so pieces of field data. If you were to make use of a System.IO.BinaryWriter type,
you would need to manually save each field of the UserPrefs object. Likewise, when you wish to load
the data from file back into memory.
Now, say if by using something, we can save whole class into the file, how do you feel? Great huh!!! And that is done by Serialization. You can serialize any information into the stream by using Serialization.

// Assume UserPrefs has been marked [Serializable].
UserPrefs userData= new UserPrefs();
userData.WindowColor = “Yellow”
userData.FontSize = “50”
userData.IsPowerUser = false;
// Now save object to a file named user.dat.
BinaryFormatter binFormat = new BinaryFormatter();
Stream fStream = new FileStream(“user.dat”, FileMode.Create, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, userData);

You can save lot of time if serialization is used where required.

Now, what is versioning in serialization. Suppose, you are developing program where you are using serialization to store the setting of the application. You have released the version 1.0. now for 2.0 you have added 3 to 4 fields in the class that were not previously present.

[Serializable] class UserPrefs
public ConsoleColor BackgroundColor;
public ConsoleColor ForegroundColor;
// New!
[OptionalField] public int BeepFreq;
[OptionalField] public string ConsoleTitle;
public UserPrefs()
{ BeepFreq = 1000; ConsoleTitle = “My Console” BackgroundColor = ConsoleColor.Black; ForegroundColor = ConsoleColor.Red; }

That is the way we can define optional field. but this is not final solution for versioning. You can say this is workaround. but if you need proper versioning, you need to derive your class from ISerializable interface.


Written by Manish

March 6, 2007 at 3:21 pm

Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: