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();
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();
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 ())
StringBuilder sb = new StringBuilder ();
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();