Wednesday, February 2, 2011

Logging Properties of an instance object

Logging is an ongoing subject that I had some posts about it. In this post I am adding two methods to my beloved Logger class.
The first one shows the values of each property where the property is readable while the second method tries to show the signature of the method.
/// <summary>
/// Shows the public properties
/// </summary>
/// <param name="instance"></param>
public static void ShowPropertyValues(object instance)
{
var instanceType = instance.GetType();
Information(
">>> Showing Instance Properties: " + instanceType.Name);

var props = instanceType.GetProperties();
foreach (var property in props)
{
if (!property.CanRead) continue ; //'t read!
Information(
string .Format("Instance.{0} ='{1}'" , property.Name, property.GetValue(instance, null )));
}
}

/// <summary>
/// Shows the public properties
/// </summary>
/// <param name="instance"></param>
public static void ShowPropertySignature(object instance)
{
var instanceType = instance.GetType();
Information(
">>> Showing Type Properties: " + instanceType.Name);

var props = TypeDescriptor .GetProperties(instance);
foreach (PropertyDescriptor prop in props)
{
Information(
"----------------------------------------------------" );
Information(
string .Format("Name ='" , prop.Name));
Information(
string .Format("DisplayName ='" , prop.DisplayName));
Information(
string .Format("Description ='" , prop.Description));
Information(
string .Format("ComponentType ='" , prop.ComponentType.Name));
Information(
string .Format("Category ='" , prop.Category));
Information(
string .Format("IsBrowsable ='" , prop.IsBrowsable));
Information(
string .Format("IsLocalizable ='" , prop.IsLocalizable));
Information(
string .Format("IsReadOnly ='" , prop.IsReadOnly));
Information(
string .Format("PropertyType ='" , prop.PropertyType.Name));
Information(
string .Format("SerializationVisibility ='" , prop.SerializationVisibility));
Information(
string .Format("SupportsChangeEvents ='" , prop.SupportsChangeEvents));
}
}