// I/F public bool SetPropertyValue(object component, PropertyInfo property, string propertyValue) { var propertyType = property.PropertyType; if (propertyType == typeof(string)) { property.SetValue(component, propertyValue, null); return true; } if (propertyType.IsEnum) { var convertedValue = Enum.Parse(propertyType, propertyValue, true); property.SetValue(component, convertedValue, null); return true; } if (typeof(IConvertible).IsAssignableFrom(propertyType)) { var convertedValue = Convert.ChangeType(propertyValue, propertyType, null); property.SetValue(component, convertedValue, null); return true; } return false; }
internal static bool DecodeXmlTextReaderValue(object instance, PropertyInfo propertyInfo, XmlReader xmlTextReader) { try { // find related property by name if not provided as parameter if (propertyInfo == null) propertyInfo = instance.GetType().GetProperty(xmlTextReader.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propertyInfo == null) return false; // unescaped characters <>& if (propertyInfo.PropertyType.Equals(typeof(string))) propertyInfo.SetValue(instance, Decode(xmlTextReader.ReadInnerXml().Trim()), null); else if (propertyInfo.PropertyType.Equals(typeof(DateTime))) propertyInfo.SetValue(instance, ParseRfc822DateTime(xmlTextReader.ReadInnerXml().Trim()), null); else propertyInfo.SetValue(instance, TypeDescriptor.GetConverter(propertyInfo.PropertyType).ConvertFromString(xmlTextReader.ReadInnerXml().Trim()), null); } catch (Exception e) { Debug.WriteLine(propertyInfo.Name + ", " + propertyInfo.PropertyType.Name + " / " + instance.ToString() + " " + e.Message); return false; } return true; }
/// <summary> /// 对值类型设置初始值 /// </summary> /// <param name="properinfo"></param> /// <param name="obj"></param> /// <param name="key"></param> private static void SetValueTypeOrString(System.Reflection.PropertyInfo properinfo, object obj, string key) { string findKey = System.Web.HttpContext.Current.Request[key]; if (string.IsNullOrEmpty(findKey)) { return; } var propertyType = properinfo.PropertyType; if (propertyType.IsGenericType) { propertyType = properinfo.PropertyType.GetGenericArguments()[0]; } if (propertyType.IsEnum) { dynamic value = Enum.Parse(propertyType, findKey); properinfo.SetValue(obj, value, null); } else { dynamic value = Convert.ChangeType(findKey, propertyType); properinfo.SetValue(obj, value, null); } }
private void take_all(object sender, RoutedEventArgs e) { MenuItem mnu = sender as MenuItem; TextBox sp = null; if (mnu != null) { sp = ((ContextMenu)mnu.Parent).PlacementTarget as TextBox; if (System.Windows.MessageBox.Show("Daten wirklich für alle übernehmen?", "", MessageBoxButton.YesNo , MessageBoxImage.Question) == MessageBoxResult.Yes) { Binding myBinding = BindingOperations.GetBinding(sp, TextBox.TextProperty); string boundComponent = myBinding.Path.Path.Remove(0, 3); System.Reflection.PropertyInfo prop = typeof(ViewModels.PToshibaVM).GetProperty(boundComponent); for (int i = 0; i < m_vm.Processes.Count; i++) { if (sp.Text != "") { prop.SetValue(m_vm.Processes[i], Convert.ToDouble(sp.Text.Replace('.', ',')), null); } else { prop.SetValue(m_vm.Processes[i], null, null); } } } } }
public static void AppendValues(SerializationContext context, object obj, Reflection.PropertyInfo property, params object[] values) { var propertyType = property.PropertyType; if (propertyType.IsArray && !values[0].GetType().IsArray) { Array oldArr = (Array)property.GetValue(obj, null); int oldArrL = (oldArr != null ? oldArr.Length : 0); Array newArr = Array.CreateInstance(propertyType.GetElementType(), oldArrL + values.Length); if (oldArr != null) { Array.Copy(oldArr, newArr, oldArr.Length); } for (int v = 0; v < values.Length; ++v) { newArr.SetValue(values[v], oldArrL + v); } property.SetValue(obj, newArr, null); } else { if (values.Length > 1) { context.LogError(property.Name + " should not appear more than once!"); } property.SetValue(obj, values[0], null); } }
public static void SetKey <T>(T obj, TempDataDictionary _tempData) { System.Type type = typeof(T); // Get our Foreign Key that we want to maintain String foreignKey = _tempData["ForeignKey"].ToString(); // If we do not have a Foreign Key, we do not need to set a property if (String.IsNullOrEmpty(foreignKey)) { return; } // Get our the value that we need to set our Foreign Key to String value = _tempData[foreignKey].ToString(); // Get our property via reflection so that we can invoke methods against property System.Reflection.PropertyInfo prop = type.GetProperty(foreignKey.ToString()); // Gets what the data type is of our property (Foreign Key Property) System.Type propertyType = prop.PropertyType; // Get the type code so we can switch System.TypeCode typeCode = System.Type.GetTypeCode(propertyType); try { switch (typeCode) { case TypeCode.Int32: prop.SetValue(type, Convert.ToInt32(value), null); break; case TypeCode.Int64: prop.SetValue(type, Convert.ToInt64(value), null); break; case TypeCode.String: prop.SetValue(type, value, null); break; case TypeCode.Object: if (propertyType == typeof(Guid) || propertyType == typeof(Guid?)) { prop.SetValue(obj, Guid.Parse(value), null); return; } break; default: prop.SetValue(type, value, null); break; } return; } catch (Exception ex) { throw new Exception("Failed to set property value for our Foreign Key"); } }
public static T Copy <T>(this T obj) where T : new() { if (obj == null) { return(obj); } Object targetDeepCopyObj; Type targetType = obj.GetType(); //值类型 if(targetType.IsValueType == true) { targetDeepCopyObj = obj; } //引用类型 else { targetDeepCopyObj = System.Activator.CreateInstance(targetType); //创建引用对象 System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers(); foreach (System.Reflection.MemberInfo member in memberCollection) { if (member.MemberType == System.Reflection.MemberTypes.Field) { System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member; Object fieldValue = field.GetValue(obj); if (fieldValue is ICloneable) { field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone()); } else { field.SetValue(targetDeepCopyObj, Copy(fieldValue)); } } else if (member.MemberType == System.Reflection.MemberTypes.Property) { System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member; MethodInfo info = myProperty.GetSetMethod(false); if (info != null) { object propertyValue = myProperty.GetValue(obj, null); if (propertyValue is ICloneable) { myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null); } else { if (propertyValue != null) { myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null); } } } } } } return((T)targetDeepCopyObj); }
/// <summary> /// set setting from list /// </summary> /// <param name="settings">list of settings key-value</param> private void SetSettings(IEnumerable <KeyValuePair <string, string> > settings) { foreach (var kvp in settings) { var thisType = typeof(Settings); System.Reflection.PropertyInfo prop = thisType.GetProperty(kvp.Key); if (prop == null) { continue; } if (prop.PropertyType == typeof(string)) { prop.SetValue(this, kvp.Value, null); } else if (prop.PropertyType == typeof(bool)) { bool result = false; if (bool.TryParse(kvp.Value, out result)) { prop.SetValue(this, result, null); } } else if (prop.PropertyType == typeof(int)) { Int32 result = 1; if (Int32.TryParse(kvp.Value, out result)) { prop.SetValue(this, result, null); } } } }
public static object Copy(object obj) { System.Object targetDeepCopyObj; Type targetType = obj.GetType(); //值类型 if (targetType.IsValueType == true) { targetDeepCopyObj = obj; } //引用类型 else { targetDeepCopyObj = System.Activator.CreateInstance(targetType); //创建引用对象 System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers(); foreach (System.Reflection.MemberInfo member in memberCollection) { if (member.MemberType == System.Reflection.MemberTypes.Field) { System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member; System.Object fieldValue = field.GetValue(obj); try { if (fieldValue is ICloneable) { field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone()); } else { field.SetValue(targetDeepCopyObj, Copy(fieldValue)); } } catch (Exception e) { LogMgr.UnityError(e.ToString()); } } else if (member.MemberType == System.Reflection.MemberTypes.Property) { System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member; MethodInfo info = myProperty.GetSetMethod(false); if (info != null) { object propertyValue = myProperty.GetValue(obj, null); if (propertyValue is ICloneable) { myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null); } else { myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null); } } } } } return(targetDeepCopyObj); }
public void AssingDefaultValue(PropertyInfo prop) { var attrib = prop.GetAttribute<SerializePropertyAttribute>(); if (attrib.CreateNewAsDefaultValue) prop.SetValue(this, Activator.CreateInstance(prop.PropertyType), null); else if (attrib.DefaultValue != null) prop.SetValue(this, attrib.DefaultValue, null); }
/// <summary> /// 为对象的属性设置值 /// </summary> /// <param name="item">实体</param> /// <param name="prop">属性元数据</param> /// <param name="propvalue">属性值</param> protected void SetValue(ItemType item, System.Reflection.PropertyInfo prop, object propvalue) { if (propvalue is DBNull || propvalue == null) { return; } { try { switch (prop.PropertyType.ToString()) { case "System.String": prop.SetValue(item, propvalue.ToString().Trim(), null); break; case "System.Boolean": prop.SetValue(item, ((Convert.ToInt32(propvalue) == 0) ? false : true), null); break; case "System.Int32": prop.SetValue(item, Convert.ToInt32(propvalue), null); break; case "System.Int64": prop.SetValue(item, Convert.ToInt64(propvalue), null); break; case "System.Int16": prop.SetValue(item, Convert.ToInt16(propvalue), null); break; case "System.Decimal": prop.SetValue(item, decimal.Round(Convert.ToDecimal(propvalue), 2), null); break; case "System.DateTime": if (propvalue != null) { prop.SetValue(item, Convert.ToDateTime(propvalue), null); } else { prop.SetValue(item, null, null); } break; default: prop.SetValue(item, propvalue, null); break; } } catch { prop.SetValue(item, propvalue.ToString(), null); } } }
public static object Copy(this object obj) { if (obj == null) { return(null); } Object targetDeepCopyObj; Type targetType = obj.GetType(); if (targetType.IsValueType == true) { targetDeepCopyObj = obj; } else { targetDeepCopyObj = System.Activator.CreateInstance(targetType); //创建引用对象 System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers(); foreach (System.Reflection.MemberInfo member in memberCollection) { if (member.GetType().GetProperty("Item") != null) { continue; } if (member.MemberType == System.Reflection.MemberTypes.Field) { System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member; Object fieldValue = field.GetValue(obj); if (fieldValue is ICloneable) { field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone()); } else { field.SetValue(targetDeepCopyObj, fieldValue.Copy()); } } else if (member.MemberType == System.Reflection.MemberTypes.Property) { System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member; MethodInfo info = myProperty.GetSetMethod(false); if (info != null) { object propertyValue = myProperty.GetValue(obj, null); if (propertyValue is ICloneable) { myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null); } else { myProperty.SetValue(targetDeepCopyObj, propertyValue.Copy(), null); } } } } } return(targetDeepCopyObj); }
public static void Update(object _old, object _new) { try { System.Reflection.MemberInfo[] memberCollection = _old.GetType().GetMembers(); foreach (System.Reflection.MemberInfo member in memberCollection) { if (member.MemberType == System.Reflection.MemberTypes.Field) { System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member; Object fieldValue = field.GetValue(_old); if (fieldValue == null) { continue; } if (fieldValue is ICloneable) { field.SetValue(_new, (fieldValue as ICloneable).Clone()); } else { if ((fieldValue.GetType().IsValueType == true)) { field.SetValue(_new, fieldValue); } } } else if (member.MemberType == System.Reflection.MemberTypes.Property) { System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member; MethodInfo info = myProperty.GetSetMethod(false); if (info != null) { object propertyValue = myProperty.GetValue(_old, null); if (propertyValue == null) { continue; } if (propertyValue is ICloneable) { myProperty.SetValue(_new, (propertyValue as ICloneable).Clone(), null); } else { if ((propertyValue.GetType().IsValueType == true)) { myProperty.SetValue(_new, propertyValue); } } } } } } catch (Exception ex) { } }
void SetPropertyValue(NameValueCollection config, PropertyInfo propertyInfo) { if (!(string.IsNullOrEmpty(config[propertyInfo.Name.MakeFirstCharLower()]))) { propertyInfo.SetValue(this, XpandReflectionHelper.ChangeType(config[propertyInfo.Name.MakeFirstCharLower()], propertyInfo.PropertyType), null); } else { var defaultValueAttribute = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true).OfType<DefaultValueAttribute>().FirstOrDefault(); if (defaultValueAttribute != null) propertyInfo.SetValue(this, defaultValueAttribute.Value, null); } }
/// <summary> /// 深复制对象 /// </summary> /// <param name="obj"></param> /// <returns></returns> private object Copy(object obj) { //返回新的对象 Object targetDeepCopyObj; Type targetType = obj.GetType(); if (targetType.IsValueType) { //值类型 targetDeepCopyObj = obj; } else { //引用类型 //创建一个实例 targetDeepCopyObj = System.Activator.CreateInstance(targetType); //获取该实例的所有成员 System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers(); foreach (System.Reflection.MemberInfo member in memberCollection) { //成员类型为字段时 if (member.MemberType == System.Reflection.MemberTypes.Field) { System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member; Object fieldValue = field.GetValue(obj); if (fieldValue is ICloneable) { field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone()); } else { field.SetValue(targetDeepCopyObj, Copy(fieldValue)); } } //成员类型为属性时 else if (member.MemberType == System.Reflection.MemberTypes.Property) { System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member; MethodInfo info = myProperty.GetSetMethod(false); if (info != null) { object propertyValue = myProperty.GetValue(obj, null); if (propertyValue is ICloneable) { myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null); } else { myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null); } } } } } return(targetDeepCopyObj); }
public ActionResult PostDocument(Guid processId, int type, Guid?documentId, Guid fileId, HttpPostedFileBase files, FormCollection collection, string actionModelName, string approveDoc = "", string rejectDoc = "", string lastComment = "") { IDictionary <string, object> documentData = new Dictionary <string, object>(); Type typeActionModel = Type.GetType("RapidDoc.Models.ViewModels." + actionModelName + "_View"); var actionModel = Activator.CreateInstance(typeActionModel); foreach (var key in collection.AllKeys) { if (actionModel.GetType().GetProperty(key) != null) { System.Reflection.PropertyInfo propertyInfo = actionModel.GetType().GetProperty(key); if (propertyInfo.PropertyType.IsEnum) { var valueEnum = Enum.Parse(propertyInfo.PropertyType, collection[key].ToString(), true); propertyInfo.SetValue(actionModel, valueEnum, null); documentData.Add(key, valueEnum); } else if (propertyInfo.PropertyType == typeof(bool)) { bool valueBool = collection[key].Contains("true"); propertyInfo.SetValue(actionModel, valueBool, null); documentData.Add(key, valueBool); } else if (propertyInfo.PropertyType == typeof(DateTime?)) { DateTime?valueDate = collection[key] == "" ? null : (DateTime?)DateTime.Parse(collection[key]); propertyInfo.SetValue(actionModel, valueDate, null); documentData.Add(key, valueDate); } else { bool isRequired = actionModel.GetType().GetProperty(key) .GetCustomAttributes(typeof(RequiredAttribute), false) .Length == 1; if ((isRequired == true && !String.IsNullOrEmpty(collection[key]) && !String.IsNullOrWhiteSpace(collection[key]) && collection[key] != "<p><br></p>") || (isRequired == false)) { var value = Convert.ChangeType(collection[key], propertyInfo.PropertyType); propertyInfo.SetValue(actionModel, value, null); documentData.Add(key, value); } else { ModelState.AddModelError(string.Empty, String.Format(ValidationRes.ValidationResource.ErrorFieldisNull, key)); } } } } CheckCustomDocument(typeActionModel, actionModel); ActionResult view = RoutePostMethod(processId, actionModel, type, documentId, fileId, actionModelName, files, documentData, approveDoc, rejectDoc, lastComment); return(view); }
public List <object> ConvertTableToList(DataTable dt, EntityStructure ent, Type enttype) { List <object> retval = new List <object>(); if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { var ti = Activator.CreateInstance(enttype); foreach (EntityField col in ent.Fields) { try { System.Reflection.PropertyInfo PropAInfo = ti.GetType().GetProperty(col.fieldname); if (dr[col.fieldname] == System.DBNull.Value) { switch (col.fieldtype) { case "System.string": break; case "System.DateTime": break; } PropAInfo.SetValue(ti, null, null); } else { // TrySetProperty<enttype>(ti, dr[col.fieldname], null); PropAInfo.SetValue(ti, dr[col.fieldname], null); } } catch (Exception ex) { } // TrySetProperty<enttype>(ti, dr[col.fieldname], null); } retval.Add(ti); } } else { var ti = Activator.CreateInstance(enttype); foreach (EntityField col in ent.Fields) { System.Reflection.PropertyInfo PropAInfo = ti.GetType().GetProperty(col.fieldname); PropAInfo.SetValue(ti, null, null); } retval.Add(ti); } return(retval); }
/// <summary> /// run variable wheres /// </summary> /// <param name="newPoint"></param> /// <returns></returns> public object Run(object newPoint) { KeyValuePair <string, object> first = PublicVariables.First(); PublicVariables[first.Key] = newPoint; object result = WhereInfo.Run(newPoint); foreach (VariableInfo variableInfo in Children) { object variableValue = null; System.Reflection.PropertyInfo property = null; foreach (KeyValuePair <string, object> variable in variableInfo.PublicVariables) { if (variableInfo.PublicVariablePropertyNames.TryGetValue(variable.Key, out string name)) { string[] nameValue = name.Split('.'); if (first.Key.Equals(nameValue[0], StringComparison.OrdinalIgnoreCase)) { property = newPoint.GetType().GetProperties().FirstOrDefault(x => x.Name.Equals(nameValue.Last(), System.StringComparison.OrdinalIgnoreCase)); if (property != null) { object value = property.GetValue(newPoint); variableValue = value; break; } } } } if (variableValue is IEnumerable enumerable) { Type[] generics = property.PropertyType.GetGenericArguments(); if (generics.Length > 0) { var method = typeof(ConditionsCompiler).GetMethods(BindingFlags.NonPublic | BindingFlags.Static).Where(x => x.Name == "GenerateArrayObject" && x.GetGenericArguments().Length > 0).FirstOrDefault(); method = method.MakeGenericMethod(generics[0]); var value = method.Invoke(null, new object[] { variableValue, variableInfo }); value = typeof(Enumerable).GetMethod("ToList", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(generics[0]).Invoke(null, new object[] { value }); property.SetValue(newPoint, value); } else { var value = ConditionsCompiler.GenerateArrayObject(variableValue, variableInfo); property.SetValue(newPoint, value); } } else { object value = variableInfo.Run(variableValue); } } return(result); }
private static bool SetOption( object commandLine, PropertyInfo property, string[] optionParts, ref string errorMessage) { bool success; if(property.PropertyType == typeof(bool)) { // Last parameters for handling indexers property.SetValue( commandLine, true, null); success = true; } else { if((optionParts.Length < 2) || optionParts[1] == "" || optionParts[1] == ":") { // No setting was provided for the switch. success = false; errorMessage = string.Format( "You must specify the value for the {0} option.", property.Name); } else if( property.PropertyType == typeof(string)) { property.SetValue( commandLine, optionParts[1], null); success = true; } else if(property.PropertyType.IsEnum) { success = TryParseEnumSwitch( commandLine, optionParts, property, ref errorMessage); } else { success = false; errorMessage = string.Format( "Data type '{0}' on {1} is not supported.", property.PropertyType.ToString(), commandLine.GetType().ToString()); } } return success; }
public List <Object> SingleNodeCollection(Type typeToReturn, String xPath, XPathNavigator navigator) { XPathNodeIterator nodes = navigator.Select(xPath); List <Object> returnedList = new List <Object>(nodes.Count); while (nodes.MoveNext()) { Object newObj = Activator.CreateInstance(typeToReturn); XPathNavigator nodesNavigator = nodes.Current; XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Element, false); System.Reflection.PropertyInfo pi = null; while (nodesText.MoveNext()) { try { pi = typeToReturn.GetProperty(nodesText.Current.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); } catch (NullReferenceException ex) { continue; } //NEED TO WRITE IN AN ERROR LOG PARSER HERE. NullReferenceExcpetion will be thrown if the property sent from lala //doesn't exist in our class. That needs to be caught and handled appropriately. //-WedTM //Quick little hack for DateTime, since lala uses epoc for it's times...//-WedTM try { if (pi.PropertyType == typeof(DateTime)) { pi.SetValue(newObj, new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(nodesText.Current.ValueAsLong), null); } else { pi.SetValue(newObj, Convert.ChangeType(nodesText.Current.Value, pi.PropertyType), null); } } catch (FormatException) // Catches null values for int type properties { pi.SetValue(newObj, Convert.ChangeType(0, pi.PropertyType), null); } catch (Exception ex) { //throw; continue; } } returnedList.Add(Convert.ChangeType(newObj, typeToReturn)); } return(returnedList); }
public static T DataRowToObjectCN <T>(DataRow row, List <int> lstDaiLyID, List <long> lstDaiLyLuyKe, List <long> lstDaiLyLuyKeTong) where T : new() { T obj = new T(); int index = 0; foreach (DataColumn c in row.Table.Columns) { System.Reflection.PropertyInfo p = obj.GetType().GetProperty(c.ColumnName); if (p != null && row[c] != DBNull.Value) { switch (p.Name) { case "IDKhachHang": index = lstDaiLyID.IndexOf(int.Parse(row[c].ToString())); break; case "GiaThu": lstDaiLyLuyKe[index] -= long.Parse(row[c].ToString()); break; case "TaiKhoanCo": lstDaiLyLuyKe[index] += long.Parse(row[c].ToString()); break; case "GiaHoan": lstDaiLyLuyKe[index] += long.Parse(row[c].ToString()); lstDaiLyLuyKeTong[index] -= long.Parse(row[c].ToString()); break; case "GiaHeThong": lstDaiLyLuyKeTong[index] += long.Parse(row[c].ToString()); break; } if (p.Name == "LuyKe") { p.SetValue(obj, lstDaiLyLuyKe[index], null); } else if (p.Name == "LuyKeTong") { p.SetValue(obj, lstDaiLyLuyKeTong[index], null); } else { p.SetValue(obj, row[c], null); } } } return(obj); }
/// <summary> /// Copies value from one property to another /// </summary> /// <param name="aFromObj"> /// Source object <see cref="System.Object"/> /// </param> /// <param name="aFrom"> /// Source property <see cref="PropertyInfo"/> /// </param> /// <param name="aToObj"> /// Destination object <see cref="System.Object"/> /// </param> /// <param name="aTo"> /// Destination property <see cref="PropertyInfo"/> /// </param> /// <returns> /// true if successful <see cref="System.Boolean"/> /// </returns> public static bool CopyPropertyValueByInfo (object aFromObj, PropertyInfo aFrom, object aToObj, PropertyInfo aTo) { bool res = false; if ((aFrom == null) || (aTo == null) || (aFromObj == null) || (aToObj == null)) { Debug.Warning ("CopyPropertyValueByInfo", "One is null" + (aFrom == null) + (aTo == null) + (aFromObj == null) + (aToObj == null)); return (false); } if (aFrom.CanRead == false) throw new ExceptionGettingWriteOnlyProperty(); object val = aFrom.GetValue (aFromObj, null); if (val == null) return (false); if (aTo.CanWrite == false) throw new ExceptionAssigningReadOnlyProperty(); try { object no = System.Convert.ChangeType (val, aTo.PropertyType); if (no is IComparable) { object cval = aTo.GetValue (aToObj, null); if ((cval as IComparable).CompareTo(no) != 0) { aTo.SetValue (aToObj, no, null); res = true; } } else { res = true; aTo.SetValue (aToObj, no, null); } no = null; } catch (System.InvalidCastException) { res = false; throw new ExceptionPropertyTranslationError(); } catch (System.ArgumentNullException) { res = false; throw new ExceptionPropertyTranslationError(); } catch (System.FormatException) { res = false; throw new ExceptionPropertyTranslationError(); } catch (System.OverflowException) { res = false; throw new ExceptionPropertyTranslationError(); } val = null; return (res); }
private void DeserializeTo(System.Type type, object obj) { System.Reflection.BindingFlags bindingAttr = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public; System.Reflection.PropertyInfo[] properties = type.GetProperties(bindingAttr); System.Reflection.PropertyInfo[] array = properties; for (int i = 0; i < array.Length; i++) { System.Reflection.PropertyInfo propertyInfo = array[i]; if (propertyInfo.CanWrite) { string attrName = Serializer.GetAttrName(propertyInfo.Name); System.Type propertyType = propertyInfo.PropertyType; if (ReflectionUtils.IsPrimitiveType(propertyType)) { object value; if (this.GetAttrValue(propertyInfo, propertyType, attrName, out value)) { propertyInfo.SetValue(obj, value, null); } } else { object value = this.DeserializeObject(attrName, propertyType); propertyInfo.SetValue(obj, value, null); } } } System.Reflection.FieldInfo[] fields = type.GetFields(bindingAttr); System.Reflection.FieldInfo[] array2 = fields; for (int i = 0; i < array2.Length; i++) { System.Reflection.FieldInfo fieldInfo = array2[i]; string attrName = Serializer.GetAttrName(fieldInfo.Name); System.Type fieldType = fieldInfo.FieldType; if (ReflectionUtils.IsPrimitiveType(fieldType)) { object value; if (this.GetAttrValue(fieldInfo, fieldType, attrName, out value)) { fieldInfo.SetValue(obj, value); } } else { object value = this.DeserializeObject(attrName, fieldType); fieldInfo.SetValue(obj, value); } } }
public bool Map(object destinationObject, PropertyInfo destinationProperty, XmlElement element, XmlElement allConfig, ConfigMapper mapper) { var childElement = element.GetElementNamed(ElementName ?? destinationProperty.Name); if (childElement == null) { return false; } var elementValue = childElement.InnerText; var destinationPropertyType = destinationProperty.PropertyType; if (destinationPropertyType.IsEnum) { var value = Enum.Parse(destinationPropertyType, elementValue); destinationProperty.SetValue(destinationObject, value, null); return true; } if (destinationPropertyType.IsNullable()) { if (elementValue == "") { destinationProperty.SetValue(destinationObject, null, null); return true; } destinationPropertyType = destinationPropertyType.GetGenericArguments()[0]; } if (destinationPropertyType.IsA<IConvertible>()) { var value = Convert.ChangeType(elementValue, destinationPropertyType); destinationProperty.SetValue(destinationObject, value, null); return true; } var converter = TypeDescriptor.GetConverter(destinationPropertyType); if (converter.CanConvertFrom(typeof (string))) { var value = converter.ConvertFromString(elementValue); destinationProperty.SetValue(destinationObject, value, null); return true; } return false; }
public static T DataRowToModel <T>(DataRow objReader) where T : new() { T result; if (objReader != null) { System.Type typeFromHandle = typeof(T); int count = objReader.Table.Columns.Count; T t = (default(T) == null) ? System.Activator.CreateInstance <T>() : default(T); for (int i = 0; i < count; i++) { if (!ReaderConvert.IsNullOrDBNull(objReader[i])) { try { System.Reflection.PropertyInfo property = typeFromHandle.GetProperty(objReader.Table.Columns[i].ColumnName.Replace("_", ""), System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty); if (property != null) { System.Type type = property.PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(System.Nullable <>))) { NullableConverter nullableConverter = new NullableConverter(type); type = nullableConverter.UnderlyingType; } if (type.IsEnum) { object value = System.Enum.ToObject(type, objReader[i]); property.SetValue(t, value, null); } else { property.SetValue(t, ReaderConvert.CheckType(objReader[i], type), null); } } } catch { } } } result = t; } else { result = default(T); } return(result); }
/// <summary> /// 给实例对象属性赋值 /// </summary> /// <param name="InstanceObject">对象实例</param> /// <param name="valueObj">值</param> /// <param name="t">类型</param> /// <param name="propertyName">属性的名字</param> private static void SetProperty(object InstanceObject, object valueObj, Type t, string propertyName) { //依据类型获得类型属性 System.Reflection.PropertyInfo pi = t.GetProperty(propertyName, BindingFlags.Public); //给实例对象属性赋值 pi.SetValue(InstanceObject, valueObj, null); }
internal static bool SetPropertyValues(this object instance, PropertyInfo property, object value) { var container = (IEnumerable)property.GetValue(instance); var itemType = property.PropertyType.FindItemType(); if (property.PropertyType.IsArray) { return property.SetPropertyArrayValue(instance, container, value); } if ((container != null) && (container.GetType().GetImplementationOfAny(typeof(ICollection<>), typeof(ICollection)) != null)) { container.GetType().GetMethod("Add", BindingFlags.Instance | BindingFlags.Public).Invoke(container, new[] { value }); return true; } if (!property.CanWrite) { return false; } var list = (IList)typeof(List<>).MakeGenericType(itemType).GetConstructor(new Type[0]).Invoke(null); property.SetValue(instance, list); container.ForEach(item => list.Add(item)); list.Add(value); return true; }
void BindNamed(object commando, PropertyInfo property, List<CommandLineParameter> parameters, NamedArgumentAttribute attribute, BindingContext context) { var name = attribute.Name; var shortHand = attribute.ShortHand; var parameter = parameters.Where(p => p is NamedCommandLineParameter) .Cast<NamedCommandLineParameter>() .SingleOrDefault(p => p.Name == name || p.Name == shortHand); var value = parameter != null ? Mutate(parameter, property) : attribute.Default != null ? Mutate(attribute.Default, property) : null; if (value == null) { context.Report.PropertiesNotBound.Add(property); if (!attribute.Required) return; throw Ex("Could not find parameter matching required parameter named {0}", name); } property.SetValue(commando, value, null); context.Report.PropertiesBound.Add(property); }
/// <summary>Initializes a new instance of OpmlOutline</summary> public OpmlOutline(System.Xml.XmlReader xmlTextReader) : this() { if (!xmlTextReader.HasAttributes) { return; } // get attributes System.Reflection.PropertyInfo propertyInfo = null; for (int i = 0; i < xmlTextReader.AttributeCount; i++) { xmlTextReader.MoveToAttribute(i); // try to find some common used alias names for attributes string attributeName = xmlTextReader.Name; if (attributeName.IndexOf("url") != -1) { attributeName = "xmlUrl"; } if (attributeName.IndexOf("title") != -1) { attributeName = "text"; } // find related property by name propertyInfo = GetType().GetProperty(attributeName, System.Reflection.BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propertyInfo != null) { propertyInfo.SetValue(this, System.ComponentModel.TypeDescriptor.GetConverter(propertyInfo.PropertyType).ConvertFromString(xmlTextReader.ReadInnerXml().Trim()), null); } } }
public static void SetValue(this object self, PropertyInfo info, object value) { if (info != null) { info.SetValue(self, ChangeType(info, value)); } }
public void SetValueFor(Object instance, string key, PropertyInfo property) { if (Scope.Inputs[key] == null) return; object results = ConversionUtil.ConvertTo(property.PropertyType, Scope.Inputs[key]); if (results != null) property.SetValue(instance, results, null); }
/// <summary> /// Conviernte una colección recibida de un formulario en un objeto TEntity /// /// /// Nota: Los parámetros no incluidos se escriben en la consola /// </summary> /// <param name="tipo">Tipo de objeto que se desea convertir</param> /// <param name="collection">Coleccion recibida por desde el navegador</param> /// <returns>Instancia al objeto con los valores recibidos</returns> protected internal object CollectionToModel(Type tipo, FormCollection collection) { var entityObject = Activator.CreateInstance(tipo); foreach (string key in collection) { System.Reflection.PropertyInfo propertyInfo = tipo.GetProperty(key); try { if (propertyInfo != null) { object value = null; Type valueType = propertyInfo.PropertyType; if (valueType.GenericTypeArguments.Length > 0) { valueType = valueType.GenericTypeArguments[0]; } value = Convert.ChangeType(collection[key], valueType); this.CollectionValue(collection, key, valueType, ref value); propertyInfo.SetValue(entityObject, value, null); } else { Debug.WriteLine("Property No Found in Model: " + key); } } catch (Exception ex) { Debug.WriteLine("ConvertFormCollection WARNING" + ex.Message); } } return(entityObject); }
/// <summary> /// Method to set an object property value. /// </summary> /// <param name="obj">The object to set property value.</param> /// <param name="propertyName">The property name.</param> /// <param name="value">The property value.</param> /// <exception cref="InvalidOperationException">Occurs if the property name is not found or if the property is as read only.</exception> public static object SetPropertyValue(this object obj, string propertyName, object value) { try { object[] values = new object[] { value }; PropertyInfo prop = obj?.GetType()? .GetProperty ( propertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance ); if (prop != null && prop.CanWrite) { prop.SetValue(obj, value, null); } else { log.Error(prop.ToString()); throw new InvalidOperationException("Object property does not exists or property is lock to write."); } } catch (Exception ex) { log.Error(ex.Output(), ex); throw; } return(value); }
public override void Bind(PropertyInfo property, IBindingContext context) { var chain = context.Service<ICurrentChain>(); var resource = ResourceHash.For(new VaryByResource(chain)); property.SetValue(context.Object, resource, null); }
public void ReadBoolean(PropertyInfo property) { XElement booleanElement = this.m_Document.Element(property.Name); if (booleanElement != null) { int value = Convert.ToInt32(booleanElement.Value); if (value == 1) { property.SetValue(this.m_ObjectToWriteTo, true, null); } else { property.SetValue(this.m_ObjectToWriteTo, false, null); } } }
public List <PayDetailInfo> GetPayDetail(int id, int payid) { EntityContext context = BlueFramework.Blood.Session.CreateContext(); List <PayDetailInfo> list = context.SelectList <PayDetailInfo>("hr.pay.findPayDefaultDetail", id); Dictionary <int, Dictionary <string, decimal> > dic = GetPersionInsuranceDic(); Dictionary <int, Dictionary <string, decimal> > payDetailDic = getPayDetailDic(payid); foreach (PayDetailInfo info in list) { //填充保险 if (dic.ContainsKey(info.PersonId)) { foreach (KeyValuePair <string, decimal> kv in dic[info.PersonId]) { Type type = info.GetType(); System.Reflection.PropertyInfo propertyInfo = type.GetProperty(kv.Key); propertyInfo.SetValue(info, kv.Value); } } //填充发放表金额 if (payDetailDic.ContainsKey(info.PersonId)) { foreach (KeyValuePair <string, decimal> kv in payDetailDic[info.PersonId]) { Type type = info.GetType(); System.Reflection.PropertyInfo propertyInfo = type.GetProperty(kv.Key); propertyInfo.SetValue(info, kv.Value); } } } return(list); }
public void Bind(PropertyInfo property, IBindingContext context) { var type = property.PropertyType; var itemType = type.GetGenericArguments()[0]; if (type.IsInterface) { type = _collectionTypeProvider.GetCollectionType(type, itemType); } object collection = Activator.CreateInstance(type); var collectionType = collection.GetType(); Func<object, bool> addToCollection = obj => { if (obj != null) { var addMethod = _addMethods[collectionType]; addMethod.Invoke(collection, new[] {obj}); return true; } return false; }; var formatString = property.Name + "[{0}]"; int index = 0; string prefix; do { prefix = formatString.ToFormat(index); index++; } while (addToCollection(context.BindObject(prefix, itemType))); property.SetValue(context.Object, collection, null); }
public static void SetPropertyToUniqueValue(this object target, PropertyInfo property, object ensureDifferentFrom) { object otherValue = null; if (ensureDifferentFrom != null) otherValue = property.GetValue(ensureDifferentFrom); property.SetValue(target, CreateUniqueValueOf(property.PropertyType, otherValue)); }
private void SetPassword(object entity, EditorItem editorItem, PropertyInfo property) { if (entity.GetType().GetInterfaces().Count(t => t == typeof(IPassword)) == 0) property.SetValue(entity, editorItem.Value, null); else typeof(IPassword).GetMethod("SetPassword").Invoke(entity, new object[] { editorItem.Value }); }
static void ToggleInspectorLock() { if (!inspectorInitialized) { InitToggleInspectorLock(); } if (inspectorIsLockedPropertyInfo == null) { return; } var allInspectors = Resources.FindObjectsOfTypeAll(inspectorType); if (allInspectors.Length == 0) { return; } var inspector = allInspectors[allInspectors.Length - 1] as EditorWindow; if (inspector == null) { return; } var value = (bool)inspectorIsLockedPropertyInfo.GetValue(inspector, null); inspectorIsLockedPropertyInfo.SetValue(inspector, !value, null); inspector.Repaint(); }
/// <summary> /// Sets the new value for a specific property on an object. /// </summary> /// <param name="instance">Target object to set the property. In most cases this will be a domain object.</param> /// <param name="pi">Property info for the property to set.</param> /// <param name="newvalue">Value for the property.</param> /// <param name="culture"></param> /// <exception cref="System.InvalidCastException">Unable to convert the new value to the specified property. </exception> /// <exception cref="System.ArgumentNullException">null reference is not accept as a valid argument.</exception> public void SetValue(object instance, PropertyInfo pi, object newvalue, CultureInfo culture = null) { // else try to cast the new value to the correct type object o = Convert.ChangeType(newvalue, pi.PropertyType, culture ?? CultureInfo.CurrentCulture); if (pi.CanWrite) pi.SetValue(instance, o, null); }
/// <summary> /// 计算 /// </summary> /// <param name="expression">表达式</param> /// <returns></returns> public object Calucate(string expression) { try { if (string.IsNullOrEmpty(expression)) { return(null); } LoadParam(); string code = structure.Replace("{0}", stringBuilder.ToString()).Replace("{1}", expression.ToUpper()); CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider(); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); compilerParameters.ReferencedAssemblies.Add("System.Data.dll"); compilerParameters.ReferencedAssemblies.Add("System.Xml.dll"); compilerParameters.ReferencedAssemblies.Add("System.Xaml.dll"); compilerParameters.ReferencedAssemblies.Add("System.Xml.Linq.dll"); compilerParameters.ReferencedAssemblies.Add("SystemFunction.dll"); compilerParameters.CompilerOptions = "/t:library"; compilerParameters.GenerateInMemory = true; CompilerResults compilerResults = csharpCodeProvider.CompileAssemblyFromSource(compilerParameters, code); if (compilerResults.Errors.Count > 0) { throw new Exception(compilerResults.Errors[0].ErrorText); } else { Assembly assembly = compilerResults.CompiledAssembly; Type type = assembly.GetType("ExpressionCalculate"); object obj = Activator.CreateInstance(type); foreach (var item in paramDictionary.Keys) { FieldInfo fi = type.GetField(item.ToUpper()); if (fi != null) { System.Type type2 = fi.FieldType; object obj2 = Activator.CreateInstance(type2); if (type2.Name.Equals("OperatorOverload")) { System.Reflection.PropertyInfo propertyInfo = type2.GetProperty("Value"); if (propertyInfo != null) { propertyInfo.SetValue(obj2, paramDictionary[item], null); fi.SetValue(obj, obj2); } } } } MethodInfo method = type.GetMethod("Calculate"); return(method.Invoke(obj, null)); } } catch (Exception ex) { throw new Exception(ex.InnerException + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); } }
public void DoAction(object siteObject, PropertyInfo propertyInfo, DataGenerator dataGenerator) { if (propertyInfo.CanWrite) { propertyInfo.SetValue(siteObject, Guid.NewGuid().ToString(), null); } }
private static void SpecifyUtcKind(PropertyInfo property, object value) { //Get the datetime value var datetime = property.GetValue(value, null); //set DateTimeKind to Utc if (property.PropertyType == typeof(DateTime)) { datetime = DateTime.SpecifyKind((DateTime)datetime, DateTimeKind.Utc); } else if (property.PropertyType == typeof(DateTime?)) { var nullable = (DateTime?)datetime; if (!nullable.HasValue) return; datetime = (DateTime?)DateTime.SpecifyKind(nullable.Value, DateTimeKind.Utc); } else { return; } //And set the Utc DateTime value property.SetValue(value, datetime, null); }
private void FillProperty(object viewModel, PropertyInfo property) { object result = null; var propertyType = property.PropertyType; var baseType = propertyType.GetGenericTypeDefinition(); var innerType = propertyType.GetGenericArguments()[0]; var data = GetQueryableDataFor(innerType); var filters = FilterLocator.GetFiltersByConvention(innerType, property); foreach(var filter in filters) { data = new FilterExecutor().Execute(filter, data); } if (baseType == typeof(IPagedList<>)) { // ToDo Um how do we page a filled property? probably a bad idea result = Utilities.ToPagedList(innerType, data,new PagingCriteria()); } else if (baseType == typeof(IEnumerable<>) || baseType == typeof(IList<>)) { result = Utilities.ToList(innerType, data); } else if(baseType == typeof(IQueryable<>)) { result = data; } property.SetValue(viewModel, result, null); }
public override void Bind(PropertyInfo property, IBindingContext context) { context.Service<IRequestHeaders>().Value<string>(_headerName, val => { property.SetValue(context.Object, val, null); }); }
private object GetObjectFromWriteOnlyProperty(object parentObject, PropertyInfo destinationProperty) { var destinationObject = destinationProperty.PropertyType.CreateFromObjectOrInterface(); destinationProperty.SetValue(parentObject, destinationObject, null); return destinationObject; }
private static void PreencheURLw(URLws wsItem, string tagName, string urls, string uf) { if (urls == "") { return; } string AppPath = Propriedade.PastaExecutavel + "\\"; XmlDocument doc = new XmlDocument(); doc.LoadXml(urls); XmlNodeList urlList = doc.ChildNodes; if (urlList == null) { return; } for (int i = 0; i < urlList.Count; ++i) { for (int j = 0; j < urlList[i].ChildNodes.Count; ++j) { System.Reflection.PropertyInfo ClassProperty = wsItem.GetType().GetProperty(urlList[i].ChildNodes[j].Name); if (ClassProperty != null) { string appPath = AppPath + urlList[i].ChildNodes[j].InnerText; if (!string.IsNullOrEmpty(urlList[i].ChildNodes[j].InnerText)) { if (urlList[i].ChildNodes[j].InnerText.ToLower().EndsWith("asmx?wsdl")) { appPath = urlList[i].ChildNodes[j].InnerText; } else { if (!File.Exists(appPath)) { appPath = ""; } } } else { appPath = ""; } if (appPath == "") { Console.WriteLine(urlList[i].ChildNodes[j].InnerText + "==>" + appPath); } ClassProperty.SetValue(wsItem, appPath, null); } else { Console.WriteLine("wsItem <" + urlList[i].ChildNodes[j].Name + "> nao encontrada na classe URLws"); } } } }
public BrushDesignerWindow(object obj, PropertyInfo prop) { InitializeComponent(); (GradientGrid.Background as DrawingBrush).RelativeTransform = GGridTrans = new RotateTransform(); GGridTrans.CenterX = 0.5; GGridTrans.CenterY = 0.5; isd = new ImageSourceDesigner(); b = prop.GetValue(obj, null) as Brush; setv = (x) => prop.SetValue(obj, x, null); if (b.IsFrozen) { b = b.Clone(); setv(b); } if (b is SolidColorBrush) { cmode = Mode.Solid; } else if (b is LinearGradientBrush) { cmode = Mode.LinearGradient; } else if (b is ImageBrush) { cmode = Mode.Image; } }
public pointCoord(pointCoord pre, string tabStr) { preCoord = pre; var tmp = tabStr.Split(';'); int count = tmp.Count() / 2; Type type = this.GetType(); //获取类型 for (int i = 0; i < count; i++) { System.Reflection.PropertyInfo propertyInfo = type.GetProperty(tmp[2 * i]); propertyInfo.SetValue(this, tmp[2 * i + 1], null); //给对应属性赋值 } if (tabStr.Contains("C")) { Cstate = true; } else { Cstate = false; } }
/// <summary> /// Set value for a property. /// </summary> /// <param name="property"></param> /// <param name="value"></param> private void SetValue(PropertyInfo property, object value) { //Check for type converter.. if (Attribute.IsDefined(property, typeof(TypeConverterAttribute))) { var converterAttr = property.GetCustomAttribute<TypeConverterAttribute>(); var converter = Activator.CreateInstance(Type.GetType(converterAttr.ConverterTypeName)) as TypeConverter; property.SetValue(this, converter.ConvertFrom(value ?? String.Empty)); } else { var convert = value.TryConvertTo(property.PropertyType); if (convert.Success) property.SetValue(this, convert.Result); } }
private HttpWebRequest createRequest(Uri location, string method) { var request = (HttpWebRequest)HttpWebRequest.Create(location); var agent = ".NET FhirClient for FHIR " + Model.ModelInfo.Version; request.Method = method; try { #if PORTABLE45 System.Reflection.PropertyInfo prop = request.GetType().GetRuntimeProperty("UserAgent"); #else System.Reflection.PropertyInfo prop = request.GetType().GetProperty("UserAgent"); #endif if (prop != null) { prop.SetValue(request, agent, null); } } catch (Exception) { // platform does not support UserAgent property...too bad try { request.Headers[HttpRequestHeader.UserAgent] = agent; } catch (ArgumentException) { } } return(request); }
public static IControl TryCreate( object owner, PropertyInfo property ) { var attr = property.GetCustomAttributes( typeof( ArgumentAttribute ), true ).SingleOrDefault(); if ( attr is ConfigFileArgumentAttribute ) { return new ConfigFileControl( owner, property, (ArgumentAttribute)attr ); } if ( attr != null ) { return new GenericControl( owner, property, (ArgumentAttribute)attr ); } attr = property.GetCustomAttributes( typeof( UserControlAttribute ), true ).SingleOrDefault(); if ( attr != null ) { var instance = property.GetValue( owner, null ); if ( instance == null ) { instance = Activator.CreateInstance( property.PropertyType ); property.SetValue( owner, instance, null ); } return new UserControl( instance ); } return null; }
static StackObject *SetValue_2(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 4); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Object[] @index = (System.Object[]) typeof(System.Object[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Object @value = (System.Object) typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Object @obj = (System.Object) typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 4); System.Reflection.PropertyInfo instance_of_this_method = (System.Reflection.PropertyInfo) typeof(System.Reflection.PropertyInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0); __intp.Free(ptr_of_this_method); instance_of_this_method.SetValue(@obj, @value, @index); return(__ret); }
private static void setAgent(HttpWebRequest request, string agent) { bool userAgentSet = false; if (SetUserAgentUsingReflection) { try { System.Reflection.PropertyInfo prop = request.GetType().GetRuntimeProperty("UserAgent"); if (prop != null) { prop.SetValue(request, agent, null); } userAgentSet = true; } catch (Exception) { // This approach doesn't work on this platform, so don't try it again. SetUserAgentUsingReflection = false; } } if (!userAgentSet && SetUserAgentUsingDirectHeaderManipulation) { // platform does not support UserAgent property...too bad try { request.Headers[HttpRequestHeader.UserAgent] = agent; } catch (ArgumentException) { SetUserAgentUsingDirectHeaderManipulation = false; } } }
public static UserDefinedTypeImporter.SetterDelegate CreateSetter(Type type, PropertyInfo property) { return (Importer importer, object value) => { var fieldValue = importer.Read(property.PropertyType); property.SetValue(value, fieldValue, null); }; }
protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp) { var val = sp.GetValue(source); if (val != null) { tp.SetValue(target, val); } }
public PropertyDefinition(PropertyInfo property) { Info = property; Name = property.Name; PropertyType = property.PropertyType; Attributes = property.GetCustomAttributes(true); foreach (var a in Attributes) { if (a is IUniquelyNamed) (a as IUniquelyNamed).Name = Name; } Getter = (instance) => Info.GetValue(instance, null); Setter = (instance, value) => Info.SetValue(instance, value, null); Editable = Attributes.OfType<IEditable>().FirstOrDefault(); Displayable = Attributes.OfType<IDisplayable>().FirstOrDefault(); Persistable = Attributes.OfType<IPersistableProperty>().FirstOrDefault() ?? new PersistableAttribute { PersistAs = property.DeclaringType == typeof(ContentItem) ? PropertyPersistenceLocation.Column : Editable != null ? PropertyPersistenceLocation.Detail : PropertyPersistenceLocation.Ignore }; DefaultValue = Attributes.OfType<IInterceptableProperty>().Select(ip => ip.DefaultValue).Where(v => v != null).FirstOrDefault(); }
public static void BindFinalValue(PropertyInfo property, object parentItem, object value, XObject sourceXObject, bool definition) { sourceXObject.AddAnnotation(value); Type propertyType = property.PropertyType; if (CommonUtility.IsContainerOf(typeof(ICollection<object>), propertyType) && propertyType.GetGenericArguments()[0].IsAssignableFrom(value.GetType())) { object collection = property.GetValue(parentItem, null); MethodInfo addMethod = collection.GetType().GetMethod("Add"); addMethod.Invoke(collection, new[] { value }); } else if (propertyType.IsAssignableFrom(value.GetType())) { property.SetValue(parentItem, value, null); } else { // TODO: Message.Error("No Binding Mechanism Worked"); } var mappingProvider = value as IXObjectMappingProvider; if (mappingProvider != null && definition) { mappingProvider.BoundXObject = new XObjectMapping(sourceXObject, property.Name); } }
public GetSetGeneric(PropertyInfo info) { Name = info.Name; Info = info; CollectionType = Info.PropertyType.GetInterface ("IEnumerable", true) != null; var getMethod = info.GetGetMethod (true); var setMethod = info.GetSetMethod (true); if(getMethod == null) { Get = (o)=> { return info.GetValue(o, null); }; Set = (o,v) => { info.SetValue(o, v, null); }; return; } Get = (o) => { return getMethod.Invoke (o, null); }; Set = (o,v) => { try { setMethod.Invoke (o, new [] {v}); } catch (Exception e) { Radical.LogWarning (string.Format("When setting {0} to {1} found {2}:", o.ToString(), v.ToString(), e.ToString ())); } }; }