Friday, February 24, 2012

How to serialize and Object during debugging.

This is different. If you want to serialize an object directly in watch window, without having to goto immediate window, here is the code.

Utility.SerializeObject(quoteByIdResponse)



Code Snippet
  1. public static byte[] SerializeObject(object pObject)
  2.   {
  3.       byte[] xmlvalue = new Byte[0];
  4.  
  5.       MemoryStream memoryStream = new MemoryStream();
  6.       XmlSerializer xs = new XmlSerializer(pObject.GetType());
  7.       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
  8.       try
  9.       {
  10.           xs.Serialize(xmlTextWriter, pObject);
  11.           memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
  12.           xmlvalue = memoryStream.ToArray();
  13.       }
  14.       catch (Exception e)
  15.       {
  16.  
  17.       }
  18.       finally
  19.       {
  20.           xmlTextWriter.Close();
  21.           xmlTextWriter = null;
  22.           memoryStream.Close();
  23.           memoryStream = null;
  24.           xs = null;
  25.       }
  26.       return xmlvalue;
  27.   }
  28.  
  29.   public static string SerializeObjectString(object pObject)
  30.   {
  31.       string XmlString = null;
  32.       StringWriter sw = new StringWriter();
  33.       XmlSerializer xs = new XmlSerializer(pObject.GetType());
  34.       try
  35.       {
  36.           xs.Serialize(sw, pObject);
  37.           XmlString = sw.ToString();
  38.       }
  39.       catch (Exception e)
  40.       {
  41.           XmlString = e.Message;
  42.           if (e.InnerException != null)
  43.               XmlString += " Inner Exception:" + e.InnerException.Message;
  44.       }
  45.       finally
  46.       {
  47.           xs = null;
  48.       }
  49.       return XmlString;
  50.   }

No comments:

Post a Comment