I
wrote an entry on serialization about a week ago. After two days I saw that only a handful of people accessed the blog post. Since I had spent a few hours writing up that post I felt a little bad that my contribution didn't get exposed. :-)
So I decided to
post it on CodeProject as well. That was one week ago. Want to take a guess on the number of hits for that article? Just read the following reversed text: derdnuHeviFdnasuohTowT
I am in the belief that there's a decent amount of exhibitionism involved in blogging and that made me feel really good. The rating isn't great, only 3.25 out of 5, but only 9 out of 2440 readers have rated it. So since the articles on CodeProject are sorted by default by popularity I concluded that there were a few interested objective readers giving it between 4-5 and a few authors of other articles who gave it a 1 to boost the position of their own article. (To tell the truth, I didn't come up with that theory, a friend of mine did) But after what I've heard lately regarding biased reviews on Amazon, I'm not blown away if there's some truth in his (my friends') reasoning. Besides that with only 9 votes it's a waste of time spending energy on the number. If you have a CodeProject account AND you liked the article please vote. If you didn't like it just forget about it. :-)
On a project we're working on here at Renaissance we were in the need of serialization en mass. A lot of classes had to be serializable. Following are the requirements, the stages towards a solution and a proposed solution. See a better solution? Please let me know.
Requirements:
- It must be simple for the application programmer.
- The serialization output should be xml.
- Future changes in the serialization code must not involve making changes to client code. Eg. We may have to encrypt the serialized object representation.
Since this was my first date with serialization I naturally went googling to get a feeling for whom I'm dating. It quickly seemed that serialization wasn't that hard. Many people suggested using the following wherever you need to serialize.
Dim serializedObj As String
Dim serializer As New XmlSerializer(Me.GetType)
Dim writer As New StringWriter
serializer.Serialize(writer, Me)
serializedObj = writer.ToString()
Not so bad. You decorate your class with the <Serializable()> attribute and maybe hide a few public properties with XmlIgnore and there you go.
It was immediately ruled out to have the client code contain this code in every class. So what about a utility method that will serialize/deserialize an object?
There are a few challenges here. The utility function must be able to handle any type of object. Until .NET 2.0 the answer would probably have been something along:
Public Shared Function Serialize(obj as Object) As String
That looks OK. Lets have a look at the deserialize method as well and see if there are any surprises hiding there. In order to Deserialize we need another piece of information that we had when serializing. We need to know what type to deserialize to. The following signature should give us enough information to get the job done.
Public Shared Function Deserialize(xml As String, obj As Object) As Object
The client code would then look something like
' serialize
Dim instance1 As New TestClass
Dim serializedInstance As String = SharedLib.Serialize(instance1)
' deserialize
Dim instance2 As New TestClass
instance2 = CType(SharedLib.DeSerialize(serializedInstance, instance2), _
TestClass)
At this point I was in doubt. Should I stop here and accept something that I didn't feel very good about, or should I spend some more time to try to find a better solution. I had two problems with the above code. The client code was not intuitive enough and there was still too much code needed to get the job done. From an object oriented perspective I would much more like to have the methods on the class itself.
I decided to look for something else.
I hear you shout Generics, so here it comes, but with a twist.
We'll leave the concept of utility functions all together. In a normal object model you have objects that contain state and do actions. Most of us don't write helperLib.Drive(myCar), but rather myCar.Drive(). How can we apply that to the serialization problem at hand?
Lets first look at how we want the calling code to look like and then on how to implement our serialization to match that.
' serialize
Dim instance1 As New TestClass
Dim serializedInstance As String = instance1.Serialize()
' deserialize
Dim instance2 As TestClass1
instance2 = TestClass1.Deserialize(serializedInstance)
That's what I want the calling code to look like.
Just to make things even between VB.NET and C#, I'll do the remaining part in C#.
We want to add a Serialize() and Deserialize() method to any class that needs to be serialized. In order to minimize the coding effort of the classes that will use this functionality we will write a generic base class with the implementation of the two methods.
Here is the base class implementation.
[Serializable()]
public abstract class ContractBase<T>
{
/// <summary>
/// Must have default constructor for xml serialization
/// </summary>
public ContractBase()
{
}
/// <summary>
/// Create an xml representation of this instance
/// </summary>
/// <returns></returns>
public string Serialize()
{
XmlSerializer serializer = new XmlSerializer(this.GetType());
using (StringWriter stream = new StringWriter())
{
serializer.Serialize(stream, this);
stream.Flush();
return stream.ToString();
}
}
/// <summary>
/// Creata a new instance from an xml string.
/// The client is responsible for deserialization of the correct type
/// </summary>
/// <param name="xml"></param>
/// <returns>new object of type T</returns>
public static T Deserialize(string xml)
{
if (string.IsNullOrEmpty(xml))
{
throw new ArgumentNullException("xml");
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader stream = new StringReader(xml))
{
try
{
return (T)serializer.Deserialize(stream);
}
catch (Exception ex)
{
// The serialization error messages are cryptic at best.
// Give a hint at what happened
throw new InvalidOperationException("Failed to create object from xml string", ex);
}
}
}
}
Here is a sample class using the serialization base class we just wrote.
[Serializable()]
public class TestClass : ContractBase< TestClass >
{
private string m_firstName;
public string FirstName
{
get
{
return m_firstName;
}
set
{
if (m_firstName == value)
return;
m_firstName = value;
}
}
Note that the TestClass inherits from a generic base class passing in its own type as the generic type.
The calling code now looks like what we wanted.
//serialize
TestClass instance1 = new TestClass();
string serializedInstance = instance1.Serialize();
//deserialize
TestClass instance2;
instance2 = TestClass.Deserialize(serializedInstance);
Like many of you I spend about an hour every day commuting to work. Until sometime early last year I used to spend my time in the car listening to the radio. That changed when I was first introduced to PodCasts. I've met a lot of people lately who were not aware of this way of distributing information. Since I have found that I really enjoy and actually learn something from these PodCasts, I thought I'll share my favorites.
The one I enjoy the most is TWiT. This is a tech related PodCast with Leo Laporte, John C. Dvorak (From PC Mag.) and a few other knowledgeable people in the tech industry. They spend about an hour every week talking about tech related stuff.
Number two on my list is DotNetRocks. In this show Carl Franklin and Richard Campbell interview .NET experts on a different topic every week.
Next is Engadget. The Engadget duo has an active Blog which they cover in this weekly PodCast. Maybe a little too much on Cell Phone technology, but a fun show.
Mondays isn't really tech related at all, but I love it. For those next to me on the plane back from Tech-Ed who wondered why is that guy sitting their laughing to himself? That must have been during the Dumber than me section that Mark Miller does. Hilarious!
In HanselMinutes, a high speed show,
Scott Hanselman (who writes one of my favorite Blogs) covers useful tools mostly for developers. The home page for the show has all the links mentioned in the show.
Just to keep the post short I'll list a few other PodCasts that I listen to regularly.
So I mostly have my commuting time covered.
If you know of any high quality tech PodCasts I would love to hear about it
On one project I'm currently working on in .NET 2.0 we have a solution with multiple projects. There's main GUI project and several class libraries and web services. Every now and then (a few times a day) we would get the following error:

Pressing OK would be followed by a myriad of the following dialog:

Eventually Visual Studio would shut down.
A few quick moves that may help until you get the hotfix.
- Turn off Edit and Continue
- Don't abort running code by pressing the Stop button
This has been driving me crazy for some time and I have been following this thread at Microsoft forums. Obviously I'm not the only one pulling my hair out.
Finally there's a cure: http://support.microsoft.com/default.aspx?scid=kb;en-us;915038
I stumbled over a blog entry by Mike Gunderloy on what else you can do with version control in addition to track the history of your source code. It's worth a peek.
His post made me think about a side effect that comes with source control that is sometimes overseen. Side note: A few years ago, maybe more than a few... I read a paper on how switching from a typewriter or hand writing to a word processor created better writers. You don't have to worry about typing something wrong or miss-placing a paragraph. Select the text drag it to a new position and that's it. This may seem almost ridiculously obvious today where even my eight year old son use Word, PowerPoint, and IM etc. But I believe it's correct. Spend your brain power on the content and don't constrain yourself with what will happen if you miss-spell a word.
So how is this related to version control? I believe that once your code is under source control you have additional freedom to "play" with the code. Especially when you use today's enormous dev environments where there's a fair amount of magic going on behind the scenes when you make changes through the different designers. You don't have to be afraid to screw things up. You can always revert to a previous version. You can always compare what you had with what you have. On more than one occasion have I seen the VS designers make erroneous "corrections" to the source code. Sure you say, of course I use source control. But the following scenarios aren't science fiction: Q:"Can you please show me the last revisions of this code (that doesn't work anymore)" – A:"No, I keep only a single backup copy while I work". Or Q:"How do you ensure that you don't overwrite each others source files?" A:"We don't work on the same files" (Sure)
So even if you work alone on a single project, version control is an important tool to allow you to spend your brain power on cranking out great code.
For small to medium sized projects and teams SourceSafe is a decent choice. For larger projects and teams Team System might be a better choice.
If you spend any significant time writing or reading code you know that the Font is of real importance to keep your eyes from burning. Microsoft has a new font specifically designed for use in programming environments. The font is Consolas and it is included with Windows Vista. This font is superior to any font I know of, but until now it was only available in Vista.

Scott Hanselman recently blogged that the font is now available for public download.
In order to get full benefit of this font, you should have your graphics settings set to use ClearType.
Open the display settings and chose "Effects..." from the Appearance tab.

Let me know after 12 hours of coding if it helped or not. :-)