Skip to content

Instantly share code, notes, and snippets.

@budu
Created April 12, 2012 19:40
Show Gist options
  • Save budu/2370471 to your computer and use it in GitHub Desktop.
Save budu/2370471 to your computer and use it in GitHub Desktop.
Utility class to extract properties dynamically from a COM object. This provide a method that extract all of a given object properties (even those taking parameters) and generate a nice set of nested dictionnaries.
public static class ComUtils
{
public static object Get(object obj, string key, object[] args = null)
{
return obj.GetType().InvokeMember(
key,
System.Reflection.BindingFlags.GetProperty,
null,
obj,
args);
}
public static IDictionary<string, dynamic> ExtractParametrized(
dynamic obj,
PropertyInfo prop,
IEnumerable<Type> paramTypes,
List<object> args = null)
{
if (args == null) args = new List<object>();
var enumResults = new Dictionary<string, dynamic>();
foreach (var field in paramTypes.First().GetFields(BindingFlags.Public | BindingFlags.Static))
{
var nextArgs = args.Select(x => x).ToList();
nextArgs.Add(field.GetRawConstantValue());
enumResults[field.Name] = (paramTypes.Count() == 1) ?
Get(obj, prop.Name, nextArgs.ToArray<object>()) :
ExtractParametrized(obj, prop, paramTypes.Skip(1), nextArgs);
}
return enumResults;
}
public static IDictionary<string, dynamic> Extract(dynamic obj)
{
var results = new Dictionary<string, dynamic>();
var properties = obj.GetType().GetProperties();
foreach (var p in properties)
{
var prop = p as PropertyInfo;
var arity = prop.GetGetMethod().GetParameters().Length;
results[p.Name] = (arity == 0) ?
Get(obj, p.Name) :
ExtractParametrized(obj, prop, prop.GetGetMethod()
.GetParameters().Select(pi => pi.ParameterType));
}
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment