Skip to content

Instantly share code, notes, and snippets.

@mfloryan
Created June 9, 2011 10:49
Show Gist options
  • Select an option

  • Save mfloryan/1016515 to your computer and use it in GitHub Desktop.

Select an option

Save mfloryan/1016515 to your computer and use it in GitHub Desktop.

Revisions

  1. mfloryan created this gist Jun 9, 2011.
    119 changes: 119 additions & 0 deletions InitialiserFromInstance.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,119 @@
    using System;
    using System.Reflection;
    using System.Text;

    namespace Adp.Run.Mobile.Payrun
    {

    public static class InitialiserFromInstance
    {
    public static string Create(object o)
    {
    Type t = o.GetType();

    StringBuilder sb = new StringBuilder();

    sb.Append("var o = ");

    SerialiseObject(sb, t, o);

    sb.Append(";");

    return sb.ToString();
    }

    private static void SerialiseObject(StringBuilder sb, Type t, object instance)
    {
    sb.Append("new ");
    sb.Append(t.Name);
    sb.Append(" { ");
    foreach (var property in t.GetProperties())
    {
    AppendPropertyValue(sb, property, instance);
    }

    foreach (var fieldInfo in t.GetFields())
    {
    AppendFieldValue(sb, fieldInfo, instance);
    }

    sb.Remove(sb.Length - 2, 2);
    sb.Append(" }");
    }

    private static void AppendFieldValue(StringBuilder sb, FieldInfo fieldInfo, object instance)
    {
    if (!fieldInfo.IsPublic) return;

    object value = fieldInfo.GetValue(instance);

    if (value == null)
    return;

    sb.Append(fieldInfo.Name);
    sb.Append(" = ");
    OutputPropertyValue(sb, value);
    sb.Append(", ");
    }

    private static void AppendPropertyValue(StringBuilder sb, PropertyInfo property, object instance)
    {
    if (!property.CanWrite)
    return;

    var index = property.GetIndexParameters();

    if (index.Length == 0)
    {

    object value = property.GetValue(instance, null);

    if (value == null)
    return;

    sb.Append(property.Name);
    sb.Append(" = ");
    OutputPropertyValue(sb, value);
    sb.Append(", ");
    } else
    {
    foreach (var parameterInfo in index)
    {
    object value = property.GetValue(instance, new object[] { parameterInfo.Position } );

    if (value == null)
    return;

    sb.Append(property.Name);
    sb.Append(" = ");
    OutputPropertyValue(sb, value);
    sb.Append(", ");
    }
    }
    }

    private static void OutputPropertyValue(StringBuilder sb, object value)
    {
    Type t = value.GetType();

    if (t.IsPrimitive)
    {
    sb.Append(value.ToString());
    return;
    }

    if (value is string)
    {
    if (string.IsNullOrEmpty((string)value))
    {
    sb.Append("string.Empty");
    return;
    }
    sb.Append("\"" + value.ToString() + "\"");
    return;
    }

    SerialiseObject(sb, t, value);
    }
    }
    }