How can I write reflection code that goes through my project and looks for classes with special attribute and able to collection 2 pieces of information: ClassName.PropertyName and string that is being passed into ResourceManager.GetValue inside the property. My code is as follows. Please help. Thanks
[TestMethod]
public void TestMethod1()
{
Dictionary<string, string> mydictionary = new Dictionary<string, string>();
mydictionary = ParseAllClassesWithAttribute("MyAttribute");
Assert.AreEqual(mydictionary["MyClass.FirstNameIsRequired"].ToString(), "First Name is Required");
}
private Dictionary<string, string> ParseAllClassesWithAttribute(string p)
{
Dictionary<string,string> dictionary = new Dictionary<string, string>();
// use reflection to go through the class that is decorated by attribute MyAttribute
// and is able to extract ClassName.PropertyName along with what is Inside
// GetValue method parameter.
// In the following I am artificially populating the dictionary object.
dictionary.Add("MyClass.FirstNameIsRequired", "First Name is Required");
return dictionary;
}
[MyAttribute]
public class MyClass
{
public string FirstNameIsRequired
{
get
{
return ResourceManager.GetValue("First Name is required");
}
}
}
public static class ResourceManager
{
public static string GetValue(string key)
{
return String.Format("some value from the database based on key {0}",key);
}
}
Reflection can’t extract the
"First Name is Required"value, unless you take the IL bytes and parse them. Here’s one potential solution:Now you can read all properties with
MyAttributeand see the expected values. (if you have trouble with this part, be sure to follow the advice of the comments on your question)