Get Property by String Force Uppercase? - c#

I am using the C# GetPropertymethod using reflection.
obj.GetType().GetProperty("columnName")
However I cannot guarantee the exact casing of the column name as it is being based in from an external source. It maybe ColumnName or columnname
I was thinking if I could just force the string column name to uppercase, but how would I then deal with the Property on the object itself? The getProperty method looks like it needs to be the EXACT casing?

You can use
var prop = GetProperty("columnname",
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.IgnoreCase);
Note that you'll still need the Instance and Public bit (assuming that this is a public instance property) as otherwise it won't find anything.

You can ignore the case when looking up the property.
GetProperty(fieldname, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

You can always combine reflection with some Linq magic, like this:
var property = typeof (MyType).GetProperties()
.Where(p => p.Name.Equals("MyProperty", StringComparison.InvariantCultureIgnoreCase));

Try:
var yourprop = from x in obj.GetType().GetProperties()
where x.Name.ToUpper() == "a column name".ToUpper()
select x;

Related

how to prevent getmethods from retrieve a specific method

I have a static class with private functions, I want to get all functions except one. I tried using Ignorecase but i get an overload exception... I do it exactly like many examples online but I get an error and I dont know why...am I missing something?
//Example
static MethodInfo[] allFuncs ;
static Type myType = typeof(myClass);
allFuncs = myType.GetMethods("innerFunction",
BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Static);
If you want all methods except one with a particular name, you can use Enumerable.Where to filter:
allFuncs = typeof(MyClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
.Where(method => !method.Name.Equals(
"innerFunction", StringComparison.OrdinalIgnoreCase));

How set property name/value dynamically?

Hi I'm not sure if I'm describing it properly, but based on a list of strings, I want to set the values of properties that belong to an object (all properties, which are objects, that match the string names):
var _parentObject = _parentObjectService.GetParentObject(viewModel.Id);
var _listOfPropertyNames = GetPropertyNames();
foreach (var item in _listOfPropertyNames)
{
// Pseudo code, I know it's gibberish:
_parentObject.Tests.[item] = viewModel.Tests.[item];
}
Hopefully that makes sense, please let me know if not.
Thank you.
It sounds like you're looking for AutoMapper, which will do all this for you:
//Once:
Mapper.CreateMap<FromType, ToType>();
//Then:
Mapper.Map(viewModel.Tests, _parentObject.Tests);
If you want to do it yourself, you'll need reflection (slow) or compiled expression trees (fast).
Use reflection to set the property value, as per: Set object property using reflection
Really simple example:
void SetParamByName(object obj, string paramName, object value)
{
obj.GetType()
.InvokeMember(
paramName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder,
obj,
value
);
}

How can I get a list of the underlying delegates from an event using reflection?

First, GetInvocationList() won't work, because I want to be able to get to them from outside the class. I assume it will work with some reflection magic, and that's what I'm trying to figure out.
Here's what I have right now:
fooEventDispatcher.GetType().GetField("FooEvent", BindingFlags.Instance | BindingFlags.NonPublic);
var field = fieldInfo.GetValue(fooEventDispatcher);
I just don't know what to do with field. Any ideas?
This should work:
var fieldInfo = fooEventDispatcher.GetType().GetField(
"FooEvent", BindingFlags.Instance | BindingFlags.NonPublic);
var eventDelegate = fieldInfo.GetValue(fooEventDispatcher) as MulticastDelegate;
if (eventDelegate != null) // will be null if no subscribed event consumers
{
var delegates = eventDelegate.GetInvocationList();
}
Also you should use typeof(SomeFooClass) instead of fooEventDispatcher.GetType() if the type is already known at compile time (which I assume it is).

Why can't I call this method via string?

Question from a Reflection newbie. I have a method in a Windows Form:
private void handleOrderCode()
{
//...do stuff
}
Which I am trying to call in the following manner:
Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode");
if (mi != null) mi.Invoke(this, null);
I have confirmed that "this" is not null. The space where the string "handleOrderCode" has been hardcoded is to be replaced with a string variable when this works. However, at present "mi" is always null when it evaluates in the if statement in the final line.
So what am I doing wrong?
You need to specify binding flags:
using System.Reflection;
t.GetMethod("handleOrderCode", BindingFlags.Instance | BindingFlags.NonPublic)
Because overload without any flag means:
BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance
i.e. will not return any non-public (private, protected, etc) members.
The parameterless overload of Type.GetMethod only looks for public methods:
Searches for the public method with the specified name.
You need to specify an appropriate BindingFlags value to another overload instead:
MethodInfo method = t.GetMethod("handleOrderCode",
BindingFlags.Instance | BindingFlags.NonPublic);
Note that you need to specify "instance" or "static" here (or both), not just "non-public". If you want to look for public methods as well, you have to include that too.
Another alternative is just to make your method public :)
(Additionally, I'd suggest renaming it to HandleOrderCode to be more conventional, idiomatic C#.)
try:
Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode",
BindingFlags.NonPublic | BindingFlags.Instance);
if (mi != null) mi.Invoke(this, null);

Reflection class to get all properties of any object

I need to make a function that get all the properies of an object (including an children objects) This is for my error logging feature.
Right now my code always returns 0 properties.
Please let me know what I'm doing wrong, thanks!
public static string GetAllProperiesOfObject(object thisObject)
{
string result = string.Empty;
try
{
// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = thisObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Static);//By default, it will return only public properties.
// sort properties by name
Array.Sort(propertyInfos,
(propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name));
// write property names
StringBuilder sb = new StringBuilder();
sb.Append("<hr />");
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.AppendFormat("Name: {0} | Value: {1} <br>", propertyInfo.Name, "Get Value");
}
sb.Append("<hr />");
result = sb.ToString();
}
catch (Exception exception)
{
// to do log it
}
return result;
}
here's what the object looks like:
If you want all of the properties, try:
propertyInfos = thisObject.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic // Get public and non-public
| BindingFlags.Static | BindingFlags.Instance // Get instance + static
| BindingFlags.FlattenHierarchy); // Search up the hierarchy
For details, see BindingFlags.
The problem with your code is the PayPal Response types are members, NOT properties. Try:
MemberInfo[] memberInfos =
thisObject.GetMembers(BindingFlags.Public|BindingFlags.Static|BindingFlags.Instance);
Your propertyInfos array is returning 0 length for one of my classes. Changing the line to be
propertyInfos = thisObject.GetType().GetProperties();
Results in it being populated. Therefore, this line of code is your problem. It appears if you add the flag
BindingFlags.Instance
to your parameters it will return the same properties as the parameterless call. Does adding this parameter to your list fix the problem?
EDIT: Just saw your edit. Based on the code you posted, it didn't work for me either. Adding the BindingFlags.Instance made it return properties for me. I'd suggest posting the exact code you are having trouble with as your screenshot shows different code.

Categories