Saving Objects for Later Debugging in .NET

One of the often challenge in debugging objects in .NET is the ability to start debugging in the middle of the running application, without the need to recreate all possible scenarios (be it data entry, API inputs ) just to arrive at the transformed data or derived object. This technique could also be used for requirements like persisting objects and saving it to database for later or whatever use.

I've written a small utility that saves object to disk, and later load it back to the target object. This tool simply serializes object on save and deserialize it on load.

Here's the snippet.

namespace Generics
{
   public class Serializer<T>
   {
       public static T Load(string strPathFile)
       {
          T oBj = default(T);
          System.Xml.Serialization.XmlSerializer objDeSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
          System.IO.TextReader reader = new System.IO.StreamReader(strPathFile);
          temp = (T)objDeSerializer.Deserialize(reader);
          reader.Close();
          return oBj;
       }

       public static void Save(string strPathFile, T oObject)
       {
          System.Xml.Serialization.XmlSerializer objSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
          System.IO.TextWriter writer = new System.IO.StreamWriter(strPathFile);
          objSerializer.Serialize(writer, oObject);
          writer.Close();
       }
   }
}

Make sure to put [Serializable] attribute on top of every class you want to get serialized.

No comments:

Post a Comment