Inside a method i make a few web service calls to get data, like so:
public void SomeMethod()
{
var user = userWS.GetUsers();
var documents = documentWS.GetDocuments();
}
I also have an XML file in which a user can tell what property to map. The XML sort of looks like this:
<root>
<item id="username" mapper="user.username.value" />
<item id="document1" mapper="documents.document1.value" />
</root>
So what i basically want to do is execute to string that is inside the mapper attribute. So that i have something like this:
public void SomeMethod()
{
var user = userWS.GetUsers();
var documents = documentWS.GetDocuments();
// returns: "user.username.value"
string usernameProperty = GetMapperValueById ( "username" );
var value = Invoke(usernameProperty);
}
So it should act as if i was calling var value = user.username.value; manually in my code.
But how can i invoke this action from a string?
In general, you can't get values of local variables at runtime (see this question for reference), but based on my own answer from another question, you can use method GetPropertyValue to workaround this problem creating a local object with desired properties:
public void SomeMethod()
{
var container = new
{
user = userWS.GetUsers(),
documents = documentWS.GetDocuments()
}
// returns: "user.username.value"
string usernameProperty = GetMapperValueById ( "username" );
var value = GetPropertyValue(container, usernameProperty);
}
static object GetPropertyValue(object obj, string propertyPath)
{
System.Reflection.PropertyInfo result = null;
string[] pathSteps = propertyPath.Split('.');
object currentObj = obj;
for (int i = 0; i < pathSteps.Length; ++i)
{
Type currentType = currentObj.GetType();
string currentPathStep = pathSteps[i];
var currentPathStepMatches = Regex.Match(currentPathStep, @"(\w+)(?:\[(\d+)\])?");
result = currentType.GetProperty(currentPathStepMatches.Groups[1].Value);
if (result.PropertyType.IsArray)
{
int index = int.Parse(currentPathStepMatches.Groups[2].Value);
currentObj = (result.GetValue(currentObj) as Array).GetValue(index);
}
else
{
currentObj = result.GetValue(currentObj);
}
}
return currentObj;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With