PDF form and template-based emails often require accessing property values deep within an object graph. For example, in my current project the first name property of an employee is accessed via Employee.Person.FirstName.
The following method takes an object path as a string (such as "Employee.Person.Address.Line1") and, using recursion, returns its property value no matter how deep within the graph the desired property exists.
private static string GetObjectFromPath(string objectPath, EntityBase2 currentEntity)
{
string[] parts = objectPath.Split('.');
string firstPath = null;
object propertyValue = null;
if (parts.Length > 0)
{
firstPath = parts[0];
PropertyInfo prop = currentEntity.GetType().GetProperty(firstPath);
if (prop != null)
{
propertyValue = prop.GetValue(currentEntity, null);
}
if (propertyValue is EntityBase2)
{
objectPath = objectPath.Replace(firstPath + ".", "");
return GetObjectFromPath(objectPath, propertyValue as EntityBase2);
}
}
if (propertyValue == null)
{
return null;
}
return propertyValue.ToString();
}