Geeks With Blogs

News My Blog has been MOVED to
Michael Freidgeim's OLD Blog My Blog has been MOVED to
When creating a new data class, it’s a good idea to override ToString() method to output most of the data.
It will help to see details in logs.

The only exception if the class has a sensitive data like CreditCard number or password.
For DataContract classes just use

public override string ToString()
                      //Use JSON as the simplest serializer
                      string sRet = this.ToExtJsJsonItem();
                      return sRet;
Sometimes it is useful to create extensions to standard .Net classes.
E.g. In CookieHelper class I've created
  public static string ToJsonString( this HttpCookie httpCookie)
            string sRet = httpCookie.ToExtJsJsonItem();
            return sRet;
The actual extension we are using was written by Nikita Pinchuk
      public static string ToExtJsJsonItem( this object item)
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
            using ( MemoryStream ms = new MemoryStream ())
                serializer.WriteObject(ms, item);
                StringBuilder sb = new StringBuilder ();

                sb.Append( Encoding.UTF8.GetString(ms.ToArray()));

                return sb.ToString();
For non DataContract classes the extension method may not work-it could cause an error: 
A first chance exception of type 'System.Runtime.Serialization.InvalidDataContractException' occurred in System.Runtime.Serialization.dll

In this case you can try  JSON.NET or the JsonValue types (nuget package JsonValue).

Sometimes I am using
 string sRet = this.XmlSerializeSafe();
But it is also not working for all types, e.g. 
MyClass cannot be serialized because it does not have a parameterless constructor.

In some places we are using LinqPad's Dump an arbitrary object To Html String, but we found it is too heavy for logs, plain text is easier to read than HTML.

I haven't tried yet ServiceStack.Text  C# .NET Extension method: T.Dump();
Posted on Saturday, May 4, 2013 1:18 PM Testing/Debugging/Logging | Back to top

Comments on this post: Override ToString() using Json serialization or something else.

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Michael Freidgeim | Powered by: