protected override object GetValueFromXml(XElement root, XName name, PropertyInfo prop) { var isAttribute = false; // Check for the DeserializeAs attribute on the property var options = prop.GetAttribute<DeserializeAsAttribute>(); if (options != null) { name = options.Name ?? name; isAttribute = options.Attribute; } if (isAttribute) { var attributeVal = GetAttributeByName(root, name); if (attributeVal != null) { return attributeVal.Value; } } return base.GetValueFromXml(root, name, prop); }
static ElementInit PropertyToElementInit(PropertyInfo propertyInfo, Expression instance) { return Expression.ElementInit(DictionaryAddMethod, Expression.Constant(propertyInfo.Name), Expression.Call(ToStringOrNullMethod, Expression.Convert(Expression.Property(instance, propertyInfo), typeof(object)))); }
public static string ExpressionToString(Expression expr) { if (propertyDebugView == null) propertyDebugView = typeof(Expression).GetTypeInfo().FindDeclaredProperty("DebugView", ReflectionFlag.NoException | ReflectionFlag.NonPublic | ReflectionFlag.Instance); return (string)propertyDebugView.GetValue(expr, null); }
public static bool ArePropertiesEqual(PropertyInfo property, object object1, object object2) { bool result = true; object object1Value = null; object object2Value = null; if (object1 != null) { object1Value = property.GetValue(object1, null); } if (object2 != null) { object2Value = property.GetValue(object2, null); } if (object1Value != null) { if (object1Value.Equals(object2Value) == false) { result = false; } } else { if (object2Value != null) { result = false; } } return result; }
private void BindToProperty(PropertyInfo property) { if (property.GetSetMethod(true) == null) { this.MemberAccess = MemberAccess.Create(AccessStrategy.NoSetter, TryToFindFieldNamingStrategy(property)); } }
public DynamicPropertyAccessor(PropertyInfo propertyInfo) { // target: (object)((({TargetType})instance).{Property}) // preparing parameter, object type ParameterExpression instance = Expression.Parameter( typeof(object), "instance"); // ({TargetType})instance Expression instanceCast = Expression.Convert( instance, propertyInfo.ReflectedType); // (({TargetType})instance).{Property} Expression propertyAccess = Expression.Property( instanceCast, propertyInfo); // (object)((({TargetType})instance).{Property}) UnaryExpression castPropertyValue = Expression.Convert( propertyAccess, typeof(object)); // Lambda expression Expression<Func<object, object>> lambda = Expression.Lambda<Func<object, object>>( castPropertyValue, instance); this.m_getter = lambda.Compile(); MethodInfo setMethod = propertyInfo.GetSetMethod(); if (setMethod != null) { this.m_dynamicSetter = new DynamicMethodExecutor(setMethod); } }
protected MvxBasePropertyInfoSourceBinding(object source, string propertyName) : base(source) { _propertyName = propertyName; if (Source == null) { MvxBindingTrace.Trace( MvxTraceLevel.Warning, "Unable to bind to source is null" , propertyName); return; } _propertyInfo = source.GetType().GetProperty(propertyName); if (_propertyInfo == null) { MvxBindingTrace.Trace( MvxTraceLevel.Warning, "Unable to bind: source property source not found {0} on {1}" , propertyName, source.GetType().Name); } var sourceNotify = Source as INotifyPropertyChanged; if (sourceNotify != null) sourceNotify.PropertyChanged += new PropertyChangedEventHandler(SourcePropertyChanged); }
/// <summary> /// Inidcates whether the specified property should be validated. /// </summary> /// <param name="property">The property.</param> /// <returns> /// true if should be validated; otherwise false /// </returns> public bool ShouldValidate(PropertyInfo property) { var validator = GetValidator(GetUnproxiedType(property.DeclaringType)); return validator != null && validator.CreateDescriptor() .GetValidatorsForMember(property.Name).Any(); }
protected IList<IPropertyInterceptor> GetPropertyInterceptors(PropertyInfo Property) { if (this.PropertyInterceptorRegistrations.ContainsKey(Property)) return this.PropertyInterceptorRegistrations[Property]; else return null; }
/// <summary> /// Dispatches the call to the extensions. /// </summary> /// <param name="pi">The property info reflection object.</param> /// <param name="belongsToModel">The belongs to model.</param> /// <param name="model">The model.</param> public void ProcessBelongsTo(PropertyInfo pi, BelongsToModel belongsToModel, ActiveRecordModel model) { foreach(IModelBuilderExtension extension in extensions) { extension.ProcessBelongsTo(pi, belongsToModel, model); } }
private TypeReference GetDefaultType(PropertyInfo property) { if (IsSqlTimestamp(property)) return new TypeReference("BinaryBlob"); return new TypeReference(property.PropertyType); }
/// <summary> /// Gets or creates an injector for the specified property. /// </summary> /// <param name="property">The property.</param> /// <returns>The created injector.</returns> public PropertyInjector Create(PropertyInfo property) { #if NO_SKIP_VISIBILITY var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) }); #else var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) }, true); #endif ILGenerator il = dynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); EmitUnboxOrCast(il, property.DeclaringType); il.Emit(OpCodes.Ldarg_1); EmitUnboxOrCast(il, property.PropertyType); #if !SILVERLIGHT bool injectNonPublic = Settings.InjectNonPublic; #else const bool injectNonPublic = false; #endif // !SILVERLIGHT EmitMethodCall(il, property.GetSetMethod(injectNonPublic)); il.Emit(OpCodes.Ret); return (PropertyInjector) dynamicMethod.CreateDelegate(typeof(PropertyInjector)); }
internal static GenericGetter CreateGetMethod(Type type, PropertyInfo propertyInfo) { MethodInfo getMethod = propertyInfo.GetGetMethod(); if (getMethod == null) return null; DynamicMethod getter = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type); ILGenerator il = getter.GetILGenerator(); if (!type.IsClass) // structs { var lv = il.DeclareLocal(type); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Unbox_Any, type); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloca_S, lv); il.EmitCall(OpCodes.Call, getMethod, null); if (propertyInfo.PropertyType.IsValueType) il.Emit(OpCodes.Box, propertyInfo.PropertyType); } else { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType); il.EmitCall(OpCodes.Callvirt, getMethod, null); if (propertyInfo.PropertyType.IsValueType) il.Emit(OpCodes.Box, propertyInfo.PropertyType); } il.Emit(OpCodes.Ret); return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter)); }
/// <summary> /// Configures the specified property info. /// </summary> /// <param name="propertyInfo">The property info.</param> /// <param name="config">The config.</param> public void Configure(PropertyInfo propertyInfo, SitecoreInfoConfiguration config) { config.Type = Type; config.UrlOptions = UrlOptions; config.MediaUrlOptions = MediaUrlOptions; base.Configure(propertyInfo, config); }
private static void InitializeTypes(Action<string> errorHandler) { if (_typesInitialized) { return; } try { Assembly extensionManagerAssembly = AppDomain.CurrentDomain.GetAssemblies() .First(a => a.FullName.StartsWith("Microsoft.VisualStudio.ExtensionManager,")); _sVsExtensionManagerType = extensionManagerAssembly.GetType("Microsoft.VisualStudio.ExtensionManager.SVsExtensionManager"); _iVsExtensionManagerType = extensionManagerAssembly.GetType("Microsoft.VisualStudio.ExtensionManager.IVsExtensionManager"); _iInstalledExtensionType = extensionManagerAssembly.GetType("Microsoft.VisualStudio.ExtensionManager.IInstalledExtension"); _tryGetInstalledExtensionMethod = _iVsExtensionManagerType.GetMethod("TryGetInstalledExtension", new[] { typeof(string), _iInstalledExtensionType.MakeByRefType() }); _installPathProperty = _iInstalledExtensionType.GetProperty("InstallPath", typeof(string)); if (_installPathProperty == null || _tryGetInstalledExtensionMethod == null || _sVsExtensionManagerType == null) { throw new Exception(); } _typesInitialized = true; } catch { // if any of the types or methods cannot be loaded throw an error. this indicates that some API in // Microsoft.VisualStudio.ExtensionManager got changed. errorHandler(VsResources.PreinstalledPackages_ExtensionManagerError); } }
/// <summary> /// Creates one instance of the Relation Object from the PropertyInfo object of the reflected class /// </summary> /// <param name="propInfo"></param> /// <returns></returns> public static Relation CreateRelationObject(PropertyInfo propInfo) { Relation result = new VSPlugin.Relation(); // get's the Relation Attribute in the class RelationAttribute relationAttribute = propInfo.GetCustomAttribute<RelationAttribute>(); if (relationAttribute== null) return result; Type elementType = null; //we need to discover the id of the relation and if it's a collection if (propInfo.PropertyType.IsArray) { result.Collection = true; elementType = propInfo.PropertyType.GetElementType(); } else if(propInfo.PropertyType.IsGenericType && propInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>)) { result.Collection = true; elementType = propInfo.PropertyType.GetGenericArguments().Single(); } else elementType = propInfo.PropertyType; result.Type = GetResourceType(elementType); result.Required = relationAttribute.Required; result.Requirement = relationAttribute.Requirement; result.Allocate = relationAttribute.Allocate.ToString(); return result; }
/// <summary> /// 获取对象的属性名或者描述和值的键值对列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="isToDesc"></param> /// <returns></returns> public static Dictionary <string, string> GetPropOrDescKeyValueDict <T>(this T obj, bool isToDesc = false) where T : class { Dictionary <string, string> dict = new Dictionary <string, string>(); var allProoKeys = obj.GetAllPropKeys(); foreach (var propKeyName in allProoKeys) { Type type = obj.GetType(); //获取类型 Reflection.PropertyInfo propertyInfo = type.GetProperty(propKeyName); //获取指定名称的属性 var value = propertyInfo.GetValue(obj, null).ToString(); //获取属性值 string desc = ""; if (isToDesc) { object[] objs = typeof(T).GetProperty(propKeyName).GetCustomAttributes(typeof(DescriptionAttribute), true); if (objs.Length > 0) { desc = ((DescriptionAttribute)objs[0]).Description; } else { desc = propKeyName; } } else { desc = propKeyName; } dict.Add(desc, value); } return(dict); }
public virtual object GetValueOnField(object valueOnDomain, object value, PropertyInfo propertyInfo) { object valueOnField = value; if (valueOnDomain != null && typeof (CustomEnum).IsAssignableFrom(propertyInfo.PropertyType)) valueOnField = CustomEnum.ValueOf(propertyInfo.PropertyType, value.ToString()); return valueOnField; }
public OppositeAttribute(Type oppositeType, string propertyName) { if (oppositeType == null) throw new ArgumentNullException("oppositeType"); if (propertyName == null) throw new ArgumentNullException("propertyName"); Property = oppositeType.GetProperty(propertyName); }
public DocumentedProperty(Identifier name, XmlNode xml, PropertyInfo property, Type targetType) { Property = property; Xml = xml; Name = name; TargetType = targetType; }
private static LocalizationInfo GetLocalizationInfo(PropertyInfo prop) { var attr = prop.GetCustomAttribute<LocalizeAttribute>(); if(attr == null) { return null; } var info = new LocalizationInfo { ResourceName = attr.ResourceName ?? (prop.DeclaringType.Name + "_" + prop.Name) }; if(info.ResourceType != null) { info.ResourceType = attr.ResourceType; } else { var parent = prop.DeclaringType.GetTypeInfo().GetCustomAttribute<LocalizeAttribute>(); if(parent == null || parent.ResourceType == null) { throw new ArgumentException(String.Format( "The property '{0}' or its parent class '{1}' must define a ResourceType in order to be localized.", prop.Name, prop.DeclaringType.Name)); } info.ResourceType = parent.ResourceType; } return info; }
public MatchResult MatchTest(PropertyInfo property) { if (property.PropertyType.Equals(typeof(DateTime))) return MatchResult.Match; else return MatchResult.NotMatch; }
public ValidationResult IsValid(PropertyInfo propertyToValidate, object value) { // enable to be empty if (value == null) return ValidationResult.Success; if (!(value is DateTime)) { return ValidationResult.CreateError(propertyToValidate, "Adf.Business.AttributeInRangeInvalid", propertyToValidate.Name); } // double newValue; // try // { // newValue = (double)value; // } // catch // { // return ValidationResult.CreateError(propertyToValidate, "Adf.Business.AttributeInRangeInvalid", propertyToValidate.Name); // } DateTime newValue = (DateTime) value; if (min >= newValue || max <= newValue) { return ValidationResult.CreateError(propertyToValidate, "Adf.Business.AttributeInRangeInvalidRange", propertyToValidate.Name, min, max); } // if (!NumberHelper.CheckRange(newValue, min, max)) // return ValidationResult.CreateError(propertyToValidate, "Adf.Business.AttributeInRangeInvalidRange", propertyToValidate.Name, min, max); return ValidationResult.Success; }
public OptionPropertyValue(PropertyInfo propertyInfo, object owner) { _propertyInfo = propertyInfo; _owner = owner; _displayName = _propertyInfo.GetCustomAttribute<DisplayNameAttribute>(); _description = _propertyInfo.GetCustomAttribute<DescriptionAttribute>(); }
public static PropertyAccessor Get(PropertyInfo propertyInfo) { PropertyAccessor propertyAccessor = null; try { propertyAccessorsCacheLock.AcquireReaderLock(-1); if (propertyAccessorsCache.ContainsKey(propertyInfo)) { return (PropertyAccessor)propertyAccessorsCache[propertyInfo]; } } finally { propertyAccessorsCacheLock.ReleaseReaderLock(); } try { propertyAccessorsCacheLock.AcquireWriterLock(-1); if (propertyAccessorsCache.ContainsKey(propertyInfo)) { return (PropertyAccessor)propertyAccessorsCache[propertyInfo]; } propertyAccessor = NewInstance(propertyInfo); propertyAccessorsCache[propertyInfo] = propertyAccessor; } finally { propertyAccessorsCacheLock.ReleaseWriterLock(); } return propertyAccessor; }
public static ConstantUpdate Create(PropertyInfo property, ConstantExpression constantExpr) { Debug.Assert(property != null, "property should not be null"); Debug.Assert(constantExpr != null, "constantExpr should not be null"); return new ConstantUpdate(property, constantExpr.Value); }
/// <summary> /// Dispatches the call to the extensions. /// </summary> /// <param name="pi">The property info reflection object.</param> /// <param name="model">The model.</param> public void ProcessProperty(PropertyInfo pi, ActiveRecordModel model) { foreach(IModelBuilderExtension extension in extensions) { extension.ProcessProperty(pi, model); } }
public void Save(object obj, XmlWriter writer) { Type t = obj.GetType(); // writer.WriteStartElement(GetTypeName(t)); // System.Console.WriteLine("\tSave <{0}>",GetTypeName(t)); writer.WriteStartElement(obj.GetType().Name); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj); PropertyInfo [] propertyInfos = new PropertyInfo[properties.Count]; for (int i = 0;i < properties.Count ; i ++){ propertyInfos[i] = t.GetProperty(properties[i].Name); } foreach (PropertyInfo info in propertyInfos) { if (info == null){ continue; } if (!info.CanRead) continue; if (info.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Length != 0) continue; object val = info.GetValue(obj, null); if (val == null) continue; if (val is ICollection) { // PropertyInfo pinfo = t.GetProperty(info.Name); // Console.WriteLine("pinfo {0}",pinfo.Name); if (info.Name.StartsWith("Contr")) { writer.WriteStartElement("Items"); } else { writer.WriteStartElement(info.Name); } foreach (object element in (ICollection)val) { Save(element, writer); } writer.WriteEndElement(); } else { if (!info.CanWrite) continue; TypeConverter c = TypeDescriptor.GetConverter(info.PropertyType); if (c.CanConvertFrom(typeof(string)) && c.CanConvertTo(typeof(string))) { try { writer.WriteElementString(info.Name, c.ConvertToInvariantString(val)); } catch (Exception ex) { writer.WriteComment(ex.ToString()); } } else if (info.PropertyType == typeof(Type)) { writer.WriteElementString(info.Name, ((Type)val).AssemblyQualifiedName); } else { // System.Diagnostics.Trace.WriteLine("Serialize Pagelayout"); // writer.WriteStartElement(info.Name); // Save(val, writer); // writer.WriteEndElement(); } } } writer.WriteEndElement(); }
//Supports getters of the form `return field;` private static FieldInfo GetBackingFieldInternal(PropertyInfo property) { if (property == null) throw new ArgumentNullException("property"); MethodInfo getter = property.GetGetMethod(true); if (getter == null) return null; byte[] il = getter.GetMethodBody().GetILAsByteArray(); if (il.Length != 7 || il[0] != 0x02//ldarg.0 || il[1] != 0x7b//ldfld <field> || il[6] != 0x2a//ret ) return null; int metadataToken = il[2] | il[3] << 8 | il[4] << 16 | il[5] << 24; Type type = property.ReflectedType; do { foreach (FieldInfo fi in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (fi.MetadataToken == metadataToken) return fi; } type = type.BaseType; } while (type != null); throw new Exception("Field not found"); }
private static void CheckAndCopyGenericType <T>(T result, Reflection.PropertyInfo tp, object value) { if (tp.PropertyType.IsGenericType) { var lst = tp.GetValue(result, null); if (lst != null) { if (lst is IList) { foreach (var item in value as IList) { (lst as IList).Add(item.CopyProperties(true)); } } } } }
/// <summary> Creates a PropertySignature of a property represented by System.Reflection type </summary> public static PropertySignature FromReflection(R.PropertyInfo prop) { prop = MethodSignature.SanitizeDeclaringTypeGenerics(prop); var declaringType = TypeSignature.FromType(prop.DeclaringType); var get = prop.GetMethod?.Apply(MethodSignature.FromReflection); var set = prop.SetMethod?.Apply(MethodSignature.FromReflection); var m = get ?? set; var resultType = TypeReference.FromType(prop.PropertyType); return(PropertySignature.Create(prop.Name, declaringType, resultType, get?.Accessibility, set?.Accessibility, m.IsStatic, m.IsVirtual, m.IsOverride, m.IsAbstract)); }
static StackObject *Equals_25(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, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Object @obj = (System.Object) typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Reflection.PropertyInfo instance_of_this_method = (System.Reflection.PropertyInfo) typeof(System.Reflection.PropertyInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Equals(@obj); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return(__ret + 1); }
public object GetCurrentlyBoundId() { System.Windows.Forms.Binding binding = GetSelectedValueBinding(); if (binding == null) { return(null); } if (((System.Windows.Forms.BindingSource)binding.DataSource).Count == 0) { return(null); } object obj = ((System.Windows.Forms.BindingSource)binding.DataSource)[0]; System.Type type = obj.GetType(); System.Windows.Forms.BindingMemberInfo bindingMemberInfo = binding.BindingMemberInfo; string s = bindingMemberInfo.BindingMember; System.Reflection.PropertyInfo propertyInfo = type.GetProperty(s); return(propertyInfo.GetValue(obj, null)); }
/// <summary> /// 设置指定对象的指定属性的值 /// </summary> /// <param name="o">需要获取属性的对象</param> /// <param name="propertyName">对象的属性名</param> /// <param name="propertyValue">对象的属性值</param> /// <returns></returns> public static bool SetProperty(object o, string propertyName, object propertyValue, ref string err) { try { Type type = o.GetType(); //获取类型 System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName); //获取指定名称的属性 if (propertyInfo == null) { throw new Exception("获取指定属性失败,请检查该对象是否有这个属性?"); } propertyInfo.SetValue(o, propertyValue, null); return(true); } catch (Exception ex) { err = ex.Message; return(false); } }
static StackObject *GetRawConstantValue_24(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, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Reflection.PropertyInfo instance_of_this_method = (System.Reflection.PropertyInfo) typeof(System.Reflection.PropertyInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetRawConstantValue(); object obj_result_of_this_method = result_of_this_method; if (obj_result_of_this_method is CrossBindingAdaptorType) { return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance, true)); } return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method, true)); }
public static java.lang.Class getClass(this System.Object t) { Type runtimeType = t.GetType(); Reflection.PropertyInfo propInfo = runtimeType.GetProperty("UnderlyingSystemType"); Type type = null == propInfo ? runtimeType : (Type)propInfo.GetValue(t, null); java.lang.Class clazz = null; if (loadedClasses.containsKey(type)) { clazz = loadedClasses.get(type); } else { clazz = new java.lang.Class(type); loadedClasses.put(type, clazz); } return(clazz); }
public DataBinderBase(object target, System.Reflection.PropertyInfo property) { Target = target; Property = property; Label = new Label(); Label.AutoSize = false; Label.TextAlign = ContentAlignment.MiddleRight; Label.Width = 80; Label.Text = property.Name + ":"; Control = new CONTROL(); Control.Left = 90; mLabelAttribute = property.GetCustomAttribute <PropertyLabelAttribute>(); Control.Width = 500; if (mLabelAttribute != null) { Label.Text = mLabelAttribute.Name + ":"; } Height = 30; }
public static Func <object, object> CreatePropertyGetter(System.Reflection.PropertyInfo propertyInfo) { var getMethod = propertyInfo.GetGetMethod(); if (getMethod == null) { return(x => propertyInfo.GetValue(x, null)); } var type = propertyInfo.DeclaringType; var instance = Expression.Parameter(typeof(object)); var typedInstance = Expression.Convert(instance, type); var res = Expression.Call(typedInstance, getMethod); var result = Expression.Convert(res, typeof(object)); var lambda = Expression.Lambda <Func <object, object> >(result, instance); return(lambda.Compile()); }
/// <summary> /// 得到一个属性中列类型 /// </summary> /// <param name="attri">要得到的类型Col定义</param> /// <param name="property">属性</param> /// <returns></returns> public String GetColName(ColumnAttribute attri, System.Reflection.PropertyInfo property) { var table = GetTableAttribute(property.ReflectedType); var index = attri.PreIndex; var len = attri.PreLen; if (index == -1 || String.IsNullOrEmpty(table.ColPreStr) || attri.OverideParent == true) { return(attri.ColumnName); } else { var str = table.ColPreStr; if (len != 0) { str = str.Substring(0, len); } return(attri.ColumnName.Insert(index, str)); } }
/***************************************************/ public static bool SetPropertyValue(this object obj, string propName, object value) { System.Reflection.PropertyInfo prop = obj.GetType().GetProperty(propName); if (prop != null) { if (value.GetType() != prop.PropertyType && value.GetType().GenericTypeArguments.Length > 0 && prop.PropertyType.GenericTypeArguments.Length > 0) { value = Modify.CastGeneric(value as dynamic, prop.PropertyType.GenericTypeArguments[0]); } if (value.GetType() != prop.PropertyType) { ConstructorInfo constructor = prop.PropertyType.GetConstructor(new Type[] { value.GetType() }); if (constructor != null) { value = constructor.Invoke(new object[] { value }); } } prop.SetValue(obj, value); return(true); } else if (obj is IBHoMObject) { IBHoMObject bhomObj = obj as IBHoMObject; if (bhomObj == null) { return(false); } if (!(bhomObj is CustomObject)) { Compute.RecordWarning("The objects does not contain any property with the name " + propName + ". The value is being set as custom data"); } bhomObj.CustomData[propName] = value; return(true); } return(false); }
/// <summary> /// Map property value from source to target /// </summary> /// <param name="source">DataSource object</param> /// <param name="target">Target object</param> public void Map(Object dataSource, Object target) { // Get value of the property Object propertyValue = GetPropertyValue(dataSource); // Property info of target object System.Reflection.PropertyInfo targetPropertyInfo = target.GetType().GetProperty(MemberName); // Nullable<InnerType> Type innerTypeOfNullableProperty; if (!IsNullable(targetPropertyInfo.PropertyType, out innerTypeOfNullableProperty)) { // Convert 'the type of the property value of source' to 'the type of the property value of target' if (!targetPropertyInfo.PropertyType.Equals(typeof(Brush))) { if (propertyValue != null) { propertyValue = Convert.ChangeType(propertyValue, targetPropertyInfo.PropertyType, System.Globalization.CultureInfo.CurrentCulture); } } } else if (innerTypeOfNullableProperty != null) { // Convert 'the type of the property value of source' to 'the type of the property value of target' if (propertyValue != null) { propertyValue = Convert.ChangeType(propertyValue, innerTypeOfNullableProperty, System.Globalization.CultureInfo.CurrentCulture); } } if (targetPropertyInfo.PropertyType == typeof(Double) && propertyValue == null) { propertyValue = Double.NaN; } // Set value of the property of target target.GetType().GetProperty(MemberName).SetValue(target, propertyValue, null); }
/***************************************************/ public static bool SetPropertyValue(this object obj, string propName, object value) { if (propName.Contains(".")) { string[] props = propName.Split('.'); for (int i = 0; i < props.Length - 1; i++) { obj = obj.PropertyValue(props[i]); if (obj == null) { break; } } propName = props[props.Length - 1]; } System.Reflection.PropertyInfo prop = obj.GetType().GetProperty(propName); if (prop != null) { if (value.GetType() != prop.PropertyType && value.GetType().GenericTypeArguments.Length > 0 && prop.PropertyType.GenericTypeArguments.Length > 0) { value = Modify.CastGeneric(value as dynamic, prop.PropertyType.GenericTypeArguments[0]); } if (value.GetType() != prop.PropertyType) { ConstructorInfo constructor = prop.PropertyType.GetConstructor(new Type[] { value.GetType() }); if (constructor != null) { value = constructor.Invoke(new object[] { value }); } } prop.SetValue(obj, value); return(true); } else { return(SetValue(obj as dynamic, propName, value)); } }
public static T DataRowToObjectKS <T>(DataRow row, List <int> lstDaiLyID, List <long> lstDaiLyLuyKe) 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 "KhachSan": index = lstDaiLyID.IndexOf(int.Parse(row[c].ToString())); break; case "GiaNet": lstDaiLyLuyKe[index] -= long.Parse(row[c].ToString()); break; case "TaiKhoanCo": lstDaiLyLuyKe[index] += long.Parse(row[c].ToString()); break; case "SoTienBaoLuu": lstDaiLyLuyKe[index] += long.Parse(row[c].ToString()); break; } if (p.Name == "LuyKe") { p.SetValue(obj, lstDaiLyLuyKe[index], null); } else { p.SetValue(obj, row[c], null); } } } return(obj); }
static ScriptInspector() { var assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); var spotlightAssembly = assemblies.FirstOrDefault(a => a.FullName.StartsWith("Spotlight,")); if (spotlightAssembly == null) { spotlightAssembly = assemblies.FirstOrDefault(a => a.FullName.StartsWith("Assembly-CSharp-Editor,")); } if (spotlightAssembly != null) { spotlightWindowType = spotlightAssembly.GetType("TakionStudios.Spotlight.Helper"); if (spotlightWindowType != null) { currentSpotlightWindowProperty = spotlightWindowType.GetProperty("CurrentWindow", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); } } inspectorWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.InspectorWindow"); if (inspectorWindowType != null) { currentInspectorWindowField = inspectorWindowType.GetField("s_CurrentInspectorWindow", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); } guiViewType = typeof(EditorWindow).Assembly.GetType("UnityEditor.GUIView"); if (guiViewType != null) { guiViewCurrentProperty = guiViewType.GetProperty("current"); } hostViewType = typeof(EditorWindow).Assembly.GetType("UnityEditor.HostView"); if (hostViewType != null) { hostViewActualViewProperty = hostViewType.GetProperty("actualView", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); } }
public int Compare(T x, T y) { Type t = x.GetType(); System.Reflection.PropertyInfo prop = t.GetProperty(_FieldName); object a = null; object b = null; if (prop != null) { a = prop.GetValue(x, null); b = prop.GetValue(y, null); } else { System.Reflection.FieldInfo field = t.GetField(_FieldName); if (field == null) { throw new Exception(string.Format("There is no \"{0}\" property or field in {1}.", _FieldName, t.ToString())); } a = field.GetValue(x); b = field.GetValue(y); } if (a != null && b == null) { return(Result(1)); } if (a == null && b != null) { return(Result(-1)); } if (a == null && b == null) { return(0); } return(Result(((IComparable)a).CompareTo(b))); }
public static PropInfo[] GetProps(object obj) { System.Reflection.BindingFlags bindingAttr = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public; System.Type type = obj.GetType(); System.Collections.Generic.List <PropInfo> list = new System.Collections.Generic.List <PropInfo>(); System.Reflection.PropertyInfo[] properties = type.GetProperties(bindingAttr); for (int i = 0; i < properties.Length; i++) { System.Reflection.PropertyInfo prop = properties[i]; list.Add(new PropInfo(obj, prop)); } System.Reflection.FieldInfo[] fields = type.GetFields(bindingAttr); for (int i = 0; i < fields.Length; i++) { System.Reflection.FieldInfo field = fields[i]; list.Add(new PropInfo(obj, field)); } PropInfo[] array = new PropInfo[list.Count]; list.CopyTo(array); return(array); }
private object GetNullItem() { if (Oranikle.Studio.Controls.CtrlNullableComboBox.NullItemMap.ContainsKey(_ItemType)) { return(Oranikle.Studio.Controls.CtrlNullableComboBox.NullItemMap[_ItemType]); } if (_ItemType == typeof(Oranikle.Studio.Controls.EnumDisplay)) { Oranikle.Studio.Controls.EnumDisplay enumDisplay = new Oranikle.Studio.Controls.EnumDisplay(0, NullDisplay, ""); Oranikle.Studio.Controls.CtrlNullableComboBox.NullItemMap.Add(typeof(Oranikle.Studio.Controls.EnumDisplay), enumDisplay); return(enumDisplay); } object obj = System.Activator.CreateInstance(_ItemType); System.Reflection.PropertyInfo propertyInfo1 = _ItemType.GetProperty(DisplayMember); propertyInfo1.SetValue(obj, Oranikle.Studio.Controls.Util.Translate(NullDisplay), null); System.Reflection.PropertyInfo propertyInfo2 = _ItemType.GetProperty(ValueMember); propertyInfo2.SetValue(obj, null, null); Oranikle.Studio.Controls.CtrlNullableComboBox.NullItemMap.Add(_ItemType, obj); return(obj); }
public DataTable FillDataTable(System.Collections.Generic.List <T> modelList) { if (modelList == null || modelList.Count == 0) { return(null); } DataTable dataTable = this.CreateData(modelList[0]); foreach (T current in modelList) { DataRow dataRow = dataTable.NewRow(); System.Reflection.PropertyInfo[] properties = typeof(T).GetProperties(); for (int i = 0; i < properties.Length; i++) { System.Reflection.PropertyInfo propertyInfo = properties[i]; dataRow[propertyInfo.Name] = propertyInfo.GetValue(current, null); } dataTable.Rows.Add(dataRow); } return(dataTable); }
public Indexer(Class declaringType, SR.PropertyInfo tinfo) { this.declaringType = declaringType; ModifierEnum mod = (ModifierEnum)0; modifiers = mod; this.FullyQualifiedName = tinfo.Name; returnType = new ReturnType(tinfo.PropertyType); this.region = Class.GetRegion(); this.bodyRegion = Class.GetRegion(); LoadXml(declaringType); // Add parameters foreach (SR.ParameterInfo pinfo in tinfo.GetIndexParameters()) { parameters.Add(new Parameter(this, pinfo, node)); } }
private static object ConverValue(System.Reflection.PropertyInfo p, object obj) { var propertyType = p.PropertyType; switch (propertyType.Name) { case "Boolean": obj = Convert.ToBoolean(obj); break; case "Image": obj = GetImage(obj); break; default: obj = Convert.ChangeType(obj, p.PropertyType); break; } return(obj); }
private float EquipmentStatSum(string StatName) { float sum = 0.0f; System.Reflection.PropertyInfo prop = typeof(Equipment).GetProperty(StatName); foreach (Equipment equip in getEquipmetList()) { var thisStat = prop.GetValue(equip, null); if (thisStat is int) { sum += (int)thisStat; } else if (thisStat is float) { sum += (float)thisStat; } } return(sum); }
public static KeyValuePair <string, int?> PrimaryKey(this IOrmModel me) { string _primaryKeyFieldName = string.Empty; int? Id = 0; try { foreach (System.Web.Mvc.ModelMetadata field in System.Web.Mvc.ModelMetadataProviders.Current.GetMetadataForProperties(me, me.GetType())) { if (field.AdditionalValues.Contains(new KeyValuePair <string, object>("ORM_PrimaryKey", true))) { _primaryKeyFieldName = field.PropertyName; break; // TODO: might not be correct. Was : Exit For } } System.Reflection.PropertyInfo _PrimaryKey = me.GetType().GetProperty(_primaryKeyFieldName); Id = (int?)_PrimaryKey.GetValue(me, null); } catch (Exception ex) { } return(new KeyValuePair <string, int?>(_primaryKeyFieldName, Id)); }
/// <summary>Initializes a new instance of OpmlHead</summary> public OpmlHead(System.Xml.XmlReader xmlTextReader) : this() { bool supressRead = false; System.Reflection.PropertyInfo propertyInfo = null; while (!(xmlTextReader.Name == "head" && xmlTextReader.NodeType == XmlNodeType.EndElement)) { // Continue read if (!supressRead) { xmlTextReader.Read(); } xmlTextReader.MoveToContent(); // find related property by name propertyInfo = GetType().GetProperty(xmlTextReader.Name, System.Reflection.BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (propertyInfo != null) { supressRead = XmlSerializationUtil.DecodeXmlTextReaderValue(this, xmlTextReader); } } }
/// <summary> /// Using reflection to apply optional parameters to the request. /// /// If the optonal parameters are null then we will just return the request as is. /// </summary> /// <param name="request">The request. </param> /// <param name="optional">The optional parameters. </param> /// <returns></returns> public static object ApplyOptionalParms(object request, object optional) { if (optional == null) { return(request); } System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties(); foreach (System.Reflection.PropertyInfo property in optionalProperties) { // Copy value from optional parms to the request. They should have the same names and datatypes. System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name); if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null { piShared.SetValue(request, property.GetValue(optional, null), null); } } return(request); }
/// <summary> /// Returns false if the property isn't readable or if it's an indexer, setting 'result' to null in the process. /// Otherwise true while setting result to a new RuntimeMember wrapping the specified property /// using the appropriate method of building the [s|g]etters (delegates in case of editor/standalone, reflection otherwise) /// Note that readonly properties (getter only) are fine, as the setter will just be an empty delegate doing nothing. /// </summary> public static bool TryWrapProperty(System.Reflection.PropertyInfo property, object target, out RuntimeMember result) { if (!property.CanRead || property.IsIndexer()) { result = null; return(false); } result = new RuntimeMember(property, property.PropertyType, target); if (property.CanWrite) { result._setter = (x, y) => property.SetValue(x, y, null); } else { result._setter = (x, y) => { } }; result._getter = x => property.GetValue(x, null); return(true); }
public FieldEditInfo(FieldEditInfo info) { m_name = info.m_name; m_nicifiedName = info.m_nicifiedName; m_fieldInfo = info.m_fieldInfo; m_propertyInfo = info.m_propertyInfo; m_kind = info.m_kind; m_objectValue = info.m_objectValue; m_valueType = info.m_valueType; m_intValue = info.m_intValue; m_floatValue = info.m_floatValue; m_longValue = info.m_longValue; m_boolValue = info.m_boolValue; m_stringValue = info.m_stringValue; m_v2value = info.m_v2value; m_v3value = info.m_v3value; m_v4value = info.m_v4value; m_curveValue = info.m_curveValue; m_colorValue = info.m_colorValue; }
public static System.Reflection.PropertyInfo getPublicProperty(System.Reflection.PropertyInfo property) { System.Type clazz = property.DeclaringType; // TODO: return(property); /* * Short circuit for (hopefully the majority of) cases where the declaring * class is public. */ if (clazz.IsPublic) { return(property); } //TODO return(null); // return getPublicMethod(clazz, method.Name, GetMethodParameterTypes(method)); }
//将泛型类转换成DataTable public static DataTable Fill <T>(IList <T> objlist) { if (objlist == null || objlist.Count <= 0) { return(null); } DataTable dt = new DataTable(typeof(T).Name); DataColumn column; DataRow row; System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (T t in objlist) { if (t == null) { continue; } row = dt.NewRow(); for (int i = 0, j = myPropertyInfo.Length; i < j; i++) { System.Reflection.PropertyInfo pi = myPropertyInfo[i]; string name = pi.Name; if (dt.Columns[name] == null) { column = new DataColumn(name, pi.PropertyType); dt.Columns.Add(column); } row[name] = pi.GetValue(t, null); } dt.Rows.Add(row); } return(dt); }
private KeyValuePair<string, object> CreateKeyValuePair(object target, PropertyInfo property) { object value; if (property.PropertyType.IsEnum) value = (int) property.GetValue(target, null); else value = property.GetValue(target, null); return new KeyValuePair<string, object>(property.Name, value); }
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(); }