Setting alignment property by reflection with a string value - c#

I'd like to set align property (horizontal/vertical) of an object through reflection, with a value of type string. I use something like
private void SetPropertiesFromString(object nav, string properties)
{
Regex r = new Regex("`(?<property>[^~]*)~(?<values>[^`]*)");
MatchCollection mc = r.Matches(properties);
Type type = nav.GetType();
for (int i = 0; i < mc.Count; i++)
{
PropertyInfo prop = type.GetProperty(mc[i].Groups["property"].Value);
prop.SetValue(nav, Convert.ChangeType(mc[i].Groups["values"].Value, prop.PropertyType), null);
}
}
(Quite same like this)
My problem is, that I'm reading properties from XML, there is only HorizontalAlignment="Stretch". Than I create new entity of Control and I don't know, how to set property like HorizontalAlignment, where value is "Stretch" etc. It causes exception "Invalid cast from 'System.String' to 'System.Windows.HorizontalAlignment'."

HorizontalAlignment is an enum type. System.Enum.Parse lets you convert a string to the corresponding enum value.

Related

Invalid cast from System.Int32 to Nullable in case of Enum properties

I have the following static method:
public static cols Parse(string[] inCols, int[] dat)
{
cols c = new cols();
PropertyInfo[] properties = typeof(cols).GetProperties();
for (int i = 0; i < inCols.Length; i++)
{
PropertyInfo prop = properties.Single(a => a.Name == inCols[i]);
var t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
var safeValue = Convert.ChangeType(dat[i], t);
prop.SetValue(c, safeValue);
}
return c;
}
Here, the properties of "cols" class are nullable Enum types.
The method has two incoming parameters (inCols and dat). The inCols contains the properties names as string, the dat contains their values as int.
The method's task would be to based on the method's name, it assigns the proper values the the nullable enum type.
I receive the following error message: System.InvalidCastException: 'Invalid cast from 'System.Int32' to '<my enum type>'.'
This is strange, because the value should be 0, which is fine for the enum becuase it is its first value.
Does any of you have any idea?
Thanks!
Gabor
Because you're dealing only with Enums, you may simply change your code to this:
var safeValue = Enum.ToObject(t, dat[i]);

How to use a variable to access an object member in c#

I have a web service that returns a custom object (a struct type) APIStruct user.
I have a variable holding the name of the current field it is checking for currentField.
Now, in a situation where user contains first_name and last_name, I can access the value using user.first_name or user.last_name. BUT, is it possible to hold the field name in a variable and access the value through the variable? working like:
var currentField = "first_name";
var value = user.currentField;
Obviously the above is not working, so is there any way to do this? In the past with languages such as PowerShell it works just like above $currentField = "first_name"; $value = user.$currentField
I've tried user.currentField user.(currentField) user[currentField] user.$currentField
You can extend your object class to support access to a Dictionary of additional properties, accessible through an explicit indexer.
public class myClass
{
private Dictionary<string, object> Something = new Dictionary<string, object>();
public object this[string i]
{
get { return Something[i]; }
set { Something[i] = value; }
}
}
Use like this:
myClass m = new myClass();
Set value:
m["fist name"] = "Name";
m["level"] = 2;
m["birthday"] = new DateTime(2015, 1, 1);
Get value:
int level = (int)m["level"];
string firstName = (string)m["first name"];
DateTime dt = (DateTime)m["birthday"];
you must use reflection. Create a method like this:
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
and call it:
string currentField = "first_name";
GetPropValue(user, currentField);
But it must be said, it is not the way you should use for the standard reading of object values.
What you're looking for called Reflection.
var type = user.GetType(); // Get type object
var property = type.GetProperty(currentField); // get property info object
var value = property.GetValue(user); // get value from object.
Be careful - reflection is pretty slow compared to direct property access.
Another option you may have is to use a switch statement. Something like:
switch (currentField){
case "first_name":
value = user.first_name;
break;
case "last_name":
value = user.last_name;
break;
etc...

Object does not match target type with SetValue and enum

I tried adapting this tutorial from CodeProject to try and change a dynamic which will in this case be an int to a simple Enum.
If we define the Enum like so:
public Enum MyEnum { Zero = 0, One = 1, Two = 2 }
And the contents of a method to set the value of a MyObject class which contains an MyEnum:
var baseType = propertyInfo.PropertyType.BaseType; //`propertyInfo` is the `PropertyInfo` of `MyEnum`
var isEnum = baseType != null && baseType == typeof(Enum); //true in this case
dynamic d;
d = GetInt();
//For example, `d` now equals `0`
if (isEnum)
d = Enum.ToObject(propertyInfo.PropertyType, (int)d);
//I can see from debugger that `d` now equals `Zero`
propertyInfo.SetValue(myObject, d);
//Exception: Object does not match target type
Any ideas as to why this is happening?
"Object does not match target type" indicates that myObject is not an instance of the type that propertyInfo was obtained from. In other words, the property you are trying to set is on one type, and myObject is not an instance of that type.
To illustrate:
var streamPosition = typeof(Stream).GetProperty("Position");
// "Object does not match target type," because the object we tried to
// set Position on is a String, not a Stream.
streamPosition.SetValue("foo", 42);

C# how Set property dynamically by string?

First of all I'm not into programming, but could figure out the basic concept
up to my needs.
In the below code, I want to set the property by name "Gold" in something like:
_cotreport.Contract = COTReportHelper.ContractType."Blabalbal"
protected override void OnBarUpdate()
{
COTReport _cotreport = COTReport(Input);
_cotreport.Contract=COTReportHelper.ContractType.Gold;
_cotreport.OpenInterestDisplay=COTReportHelper.OpenInterestDisplayType.NetPosition;
double index = _cotreport.Commercial[0];
OwnSMA.Set(index);
}
I tried below code, but the system says: "
Object reference not set to an instance of an object"
Please help!
System.Reflection.PropertyInfo PropertyInfo = _cotreport.GetType().GetProperty("ContractType");
PropertyInfo.SetValue(_cotreport.Contract,"Gold",null);
PropertyInfo.SetValue(_cotreport.Contract,Convert.ChangeType("Gold",PropertyInfo.PropertyType),null);
You're trying to set get a property named "ContractType" on _cotreport and set it's value with on _cotreport.Contract. That's not going to work for two reasons.
The property name (from what I can tell in your code) is Contract not ContractType.
You need to set the value on _cotreport.
Try this instead
System.Reflection.PropertyInfo property = _cotreport.GetType().GetProperty("Contract");
property.SetValue(_cotreport, COTReportHelper.ContractType.Gold, new object[0]);
If you want to set the enum value by name, that's a separate issue. Try this
var enumValue = Enum.Parse(typeof(COTReportHelper.ContractType), "Gold");
property.SetValue(_cotreport, enumValue, new object[0]);
PropertyInfocould be null, and may not be if you used the property name: Contract. And you should be able to specify COTReportHelper.ContractType.Gold as the value directly. And you specify the property as the instance to be modified, but the PropertyInfo represents that, you should specify the owning instance on which the property value should be set.
Something like this:
System.Reflection.PropertyInfo PropertyInfo = _cotreport.GetType().GetProperty("Contract");
PropertyInfo.SetValue(_cotreport, COTReportHelper.ContractType.Gold, null);
This method sets value of property of any object and returns true if assignment was successfull:
public static Boolean TrySettingPropertyValue(Object target, String property, String value)
{
if (target == null)
return false;
try
{
var prop = target.GetType().GetProperty(property, DefaultBindingFlags);
if (prop == null)
return false;
if (value == null)
prop.SetValue(target,null,null);
var convertedValue = Convert.ChangeType(value, prop.PropertyType);
prop.SetValue(target,convertedValue,null);
return true;
}
catch
{
return false;
}
}

Reflection from DTO

I have 1 dto, statEMailDTO, which has a field that holds the Field Names of what I'm looking for (they are comma delimited.
var emailParams = statEmailDTO.EmailParam.ToString().Split(',');
for (int i = 0; i < emailParams.Length; i++) {
var fieldName = emailParams[i].ToString();
etc.
But, then how do I use Reflection to then get the Actual value of ``fieldName which is found in a different DTO, siDTO.
So let's say that fieldName = "SuggestionItemID", I then what to get the value of siDTO.SuggestionItemID.
I haven't done a lot of reflection in the past. Sure, I read up on PropertyInfo, but it's just not clicking.
Thoughts?
Like this:
PropertyInfo property = typeof(SomeType).GetProperty(fieldName);
object value = property.GetValue(instance, null);

Categories