public void Setup(System.Reflection.PropertyInfo propertyInfo, object parentObject) { var r = new Regex(@" (?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace); string propName = r.Replace(propertyInfo.Name.Substring(0, 1).ToUpper() + propertyInfo.Name.Substring(1), " "); var nameAttribute = propertyInfo.GetCustomAttributes(typeof(NameAttribute), true).FirstOrDefault() as NameAttribute; if (nameAttribute != null) { propName = nameAttribute.name; } SetupControls( propName, () => propertyInfo.GetValue(parentObject), (val) => { propertyInfo.SetValue(parentObject, val); onParameterModified?.Invoke(this, val); }, propertyInfo.GetCustomAttributes(false)); }
public StringFieldOptions(PropertyInfo prop) { var textFieldAttribute = prop.GetCustomAttributes(typeof(TextFieldAttribute), false).Select(d => d).FirstOrDefault() as TextFieldAttribute; var stringLengthAttr = prop.GetCustomAttributes(typeof(StringLengthAttribute), false).Select(d => d).FirstOrDefault() as StringLengthAttribute; var richTextAttr = prop.GetCustomAttributes(typeof(RichTextAttribute), false).Select(d => d).FirstOrDefault() as RichTextAttribute; if (textFieldAttribute != null) { Mask = textFieldAttribute.Mask; MaskType = textFieldAttribute.MaskType; NumberOfCharacters = textFieldAttribute.NumberOfCharacters; NumberOfRows = textFieldAttribute.NumberOfRows; } if (stringLengthAttr == null) { MinimumLength = 0; MinimumLength = 999999999; } else { MaximumLength = stringLengthAttr.MaximumLength; MinimumLength = stringLengthAttr.MinimumLength; ErrorMessage = stringLengthAttr.ErrorMessage; } if (richTextAttr != null) { IsRichText = true; } }
public ModelProperty(PropertyInfo propertyInfo) { PropertyInfo = propertyInfo; Name = PropertyInfo.Name; Type = PropertyInfo.PropertyType; DisplayAttribute = propertyInfo.GetCustomAttributes<DisplayAttribute>().FirstOrDefault(); DisplayFormatAttribute = propertyInfo.GetCustomAttributes<DisplayFormatAttribute>().FirstOrDefault(); DefaultValueAttribute = propertyInfo.GetCustomAttributes<DefaultValueAttribute>().FirstOrDefault(); var attributes = propertyInfo.CustomAttributes; //validation var maxLengthAttribute = attributes.OfType<MaxLengthAttribute>().FirstOrDefault();//use var minLengthAttribute = attributes.OfType<MinLengthAttribute>().FirstOrDefault();//use var stringLengthAttribute = attributes.OfType<StringLengthAttribute>().FirstOrDefault();//use validation var rangeAttribute = attributes.OfType<RangeAttribute>().FirstOrDefault();//use var requiredAttribute = attributes.OfType<RequiredAttribute>().FirstOrDefault();//use validation var regularExpressionAttribute = attributes.OfType<RegularExpressionAttribute>().FirstOrDefault();//use var dataTypeAttribute = attributes.OfType<DataTypeAttribute>().FirstOrDefault(); //use validation var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault();//use (name,short,description,prompt, //display var defaultValueAttribute = attributes.OfType<DefaultValueAttribute>().FirstOrDefault(); //use var displayColumnAttribute = attributes.OfType<DisplayColumnAttribute>().FirstOrDefault();//use for select en combo var displayFormatAttribute = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();//use format van date, int etc var hiddenInputAttribute = attributes.OfType<HiddenInputAttribute>().FirstOrDefault();//use hide column var scaffoldColumnAttribute = attributes.OfType<ScaffoldColumnAttribute>().FirstOrDefault();//use not on form var editableAttribute = attributes.OfType<EditableAttribute>().FirstOrDefault();//use readonly //skip var uiHintAttribute = attributes.OfType<UIHintAttribute>().FirstOrDefault();//skip var actionName = attributes.OfType<ActionNameAttribute>().FirstOrDefault(); //skip var bindingBehavior = attributes.OfType<BindingBehaviorAttribute>().FirstOrDefault();//skip var defaultMemberAttribute = attributes.OfType<DefaultMemberAttribute>().FirstOrDefault();//skip }
private static string BuildParameterDescriptionMessage(PropertyInfo propertyInfo, int maxPropertyLength) { var descriptionAttribute = propertyInfo.GetCustomAttributes<ParameterDescriptionAttribute>().FirstOrDefault(); var description = descriptionAttribute != null ? descriptionAttribute.Description : string.Empty; var exampleAttribute = propertyInfo.GetCustomAttributes<ParameterExampleAttribute>().FirstOrDefault(); var example = exampleAttribute != null ? exampleAttribute.Example : null; var defaultAttribute = propertyInfo.GetCustomAttributes<ParameterDefaultAttribute>().FirstOrDefault(); var defaultValue = defaultAttribute != null ? defaultAttribute.Value : null; var explanation = new StringBuilder(); if (string.IsNullOrWhiteSpace(description) && string.IsNullOrWhiteSpace(example) && string.IsNullOrWhiteSpace(defaultValue)) { explanation.Append("(No idea. Sorry.)"); } else { if (!string.IsNullOrWhiteSpace(description)) explanation.AppendFormat("{0} ", description); if (!string.IsNullOrWhiteSpace(example) || !string.IsNullOrWhiteSpace(defaultValue)) explanation.AppendFormat("e.g. '{0}'", example ?? defaultValue); } var sb = new StringBuilder(); sb.AppendFormat("{0}", propertyInfo.Name.PadRight(maxPropertyLength)); sb.Append("\t"); sb.Append(explanation); return sb.ToString(); }
public static IFieldOptions Create(PropertyInfo property, IEditableRoot obj) { if (property == null) { throw new ArgumentNullException("property"); } var crossRefAttr = property.GetCustomAttributes(typeof(CrossRefFieldAttribute), false).Select(d => d).FirstOrDefault() as CrossRefFieldAttribute; if (crossRefAttr == null) { throw new VeyronException("CrossRef attribute not found on Cross-reference field property"); } var result = new MultiCrossRefFieldOptions { ProcessSystemName = crossRefAttr.ReferenceTableName, FieldName = crossRefAttr.RefFieldName }; result.LinkVisibility = crossRefAttr.MultiCrAllowLinkUnlink && string.IsNullOrEmpty(crossRefAttr.LinkFieldSystemName); result.UnlinkVisibility = crossRefAttr.MultiCrAllowLinkUnlink; result.AddNewVisibility = crossRefAttr.MultiCrAllowAddNew; result.LinkFieldSystemName = crossRefAttr.LinkFieldSystemName; var recentVersionAttr = (from d in property.GetCustomAttributes(typeof(RecentVersionAttribute), true) select d).FirstOrDefault(); if (recentVersionAttr != null) { result.AllowRecentVersion = true; } var deepCopyAttr = (from d in property.GetCustomAttributes(typeof(DeepCopyAttribute), true) select d).FirstOrDefault(); if (deepCopyAttr != null) { result.AllowDeepCopy = true; } return result; }
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; }
public void PublicProperty_ThatHoldsReferenceType_MustBeTaggedWithNotNullOrCanBeNullAttributes(PropertyInfo property) { bool hasNotNullAttribute = property.GetCustomAttributes(typeof(NotNullAttribute), true).Any(); bool hasCanBeNullAttribute = property.GetCustomAttributes(typeof(CanBeNullAttribute), true).Any(); Assume.That(property.DeclaringType != null); Assert.That(hasNotNullAttribute || hasCanBeNullAttribute, "Property " + property.Name + " of type " + property.DeclaringType.Name + " must be tagged with [NotNull] or [CanBeNull]"); }
private static string GenerateRandomStringFromDataAnnotations(PropertyInfo propertyInfo, AutoBuilderConfiguration autoBuilderConfiguration) { var minLength = autoBuilderConfiguration.StringMinLength; var maxLength = autoBuilderConfiguration.StringMaxLength; var minLengthAttribute = propertyInfo.GetCustomAttributes(typeof(MinLengthAttribute)).FirstOrDefault(); if (minLengthAttribute != null) { minLength = ((MinLengthAttribute)minLengthAttribute).Length; } var maxLengthAttribute = propertyInfo.GetCustomAttributes(typeof(MaxLengthAttribute)).FirstOrDefault(); if (maxLengthAttribute != null) { maxLength = ((MaxLengthAttribute)maxLengthAttribute).Length; } if (minLengthAttribute != null || maxLengthAttribute != null) { { return NAuto.GetRandomString( minLength, maxLength, autoBuilderConfiguration.DefaultStringCharacterSetType, autoBuilderConfiguration.DefaultStringSpaces, autoBuilderConfiguration.DefaultStringCasing, autoBuilderConfiguration.DefaultLanguage); } } var stringLengthAttribute = propertyInfo.GetCustomAttributes(typeof(StringLengthAttribute)).FirstOrDefault(); if (stringLengthAttribute != null) { var minStringLength = ((StringLengthAttribute)stringLengthAttribute).MinimumLength; var maxStringLength = ((StringLengthAttribute)stringLengthAttribute).MaximumLength; if (maxStringLength == 0) { maxStringLength = minStringLength + 50; } if (maxStringLength < minStringLength) { throw new ArgumentException("Property " + propertyInfo.Name + ": the minimum string length cannot be greater than the maximum string length..."); } return NAuto.GetRandomString( minStringLength, maxStringLength, autoBuilderConfiguration.DefaultStringCharacterSetType, autoBuilderConfiguration.DefaultStringSpaces, autoBuilderConfiguration.DefaultStringCasing, autoBuilderConfiguration.DefaultLanguage); } return null; }
/// <summary> /// Initializes a new instance of the <see cref="ReflectableTaskPropertyInfo"/> class. /// </summary> /// <param name="propertyInfo">The PropertyInfo used to discover this task property.</param> internal ReflectableTaskPropertyInfo(PropertyInfo propertyInfo) : base( propertyInfo.Name, propertyInfo.PropertyType, propertyInfo.GetCustomAttributes(typeof(OutputAttribute), true).Length > 0, propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), true).Length > 0) { _propertyInfo = propertyInfo; }
private static PersistentPropertyAttribute GetPersistentAttribute(PropertyInfo p) { if (p.GetCustomAttributes(typeof(PersistentPropertyAttribute), false).Length > 0) { return (PersistentPropertyAttribute)p.GetCustomAttributes(typeof(PersistentPropertyAttribute), false)[0]; } return null; }
public static ColumnInfo FromProperty(PropertyInfo propertyInfo,bool explicitColumn=false) { var colAttrs = propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), true); var keyAttrs= propertyInfo.GetCustomAttributes(typeof(KeyAttribute), true); if (explicitColumn) { if (colAttrs.Length == 0&& keyAttrs.Length==0) return null; } else { if (propertyInfo.GetCustomAttributes(typeof(IgnoreAttribute), true).Length != 0) return null; } var ci = new ColumnInfo(); // Read attribute if (colAttrs.Length > 0) { var colattr = (ColumnAttribute)colAttrs[0]; ci.Name = colattr.Name == null ? propertyInfo.Name : colattr.Name; ci.ForceToUtc = colattr.ForceToUtc; ci.IsPrimaryKey = false; if ((colattr as ResultAttribute) != null) ci.IsResult = true; } else { if (keyAttrs.Length > 0) { var keyAttr = (KeyAttribute)keyAttrs[0]; ci.Name = keyAttr.Name == null ? propertyInfo.Name : keyAttr.Name; ci.IsPrimaryKey = true; ci.PropInfo = propertyInfo; ci.ForceToUtc = false; ci.IsResult = false; } else { ci.Name = propertyInfo.Name; ci.ForceToUtc = false; ci.IsResult = false; ci.IsPrimaryKey = false; } } return ci; }
private static bool HasIgnoreAttribute(PropertyInfo property) { var ignoreAttribute = property.GetCustomAttributes(typeof(CsvIgnoreAttribute), false); if (ignoreAttribute.Length > 0) return true; return false; }
/// <summary> /// 得到一个属性的Col标记 /// </summary> /// <param name="property"></param> /// <returns></returns> public List <ColumnAttribute> GetColNameAttributes(System.Reflection.PropertyInfo property) { ColumnAttribute colAttr; if (propertyHash.Contains(property) == false) { var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true); List <ColumnAttribute> col = new List <ColumnAttribute>(); if (attribute.Length > 0) { foreach (var attr in attribute) { col.Add(attr as ColumnAttribute); } } else { col.Add(new ColumnAttribute() { ColumnName = property.Name, NoMap = true }); } propertyHash.Add(property, col); } return(propertyHash[property] as List <ColumnAttribute>); }
private static int CompareProps(PropertyInfo a, PropertyInfo b) { OrderAttribute _a = (OrderAttribute)a.GetCustomAttributes(typeof(OrderAttribute), false)[0]; OrderAttribute _b = (OrderAttribute)b.GetCustomAttributes(typeof(OrderAttribute), false)[0]; return _a.Order - _b.Order; }
public EdiPropertyDescriptor(PropertyInfo info, IEnumerable<EdiAttribute> attributes) { _Info = info; if (attributes == null) { attributes = info.GetCustomAttributes<EdiAttribute>() .Concat(info.PropertyType.GetTypeInfo().GetCustomAttributes<EdiAttribute>()); if (info.PropertyType.IsCollectionType()) { var itemType = default(Type); if (info.PropertyType.HasElementType) { itemType = info.PropertyType.GetElementType(); } else { itemType = Info.PropertyType.GetGenericArguments().First(); } attributes = attributes.Concat(itemType.GetTypeInfo().GetCustomAttributes<EdiAttribute>()); } } _Attributes = attributes.ToList(); _PathInfo = Attributes.OfType<EdiPathAttribute>().FirstOrDefault(); _ConditionInfo = Attributes.OfType<EdiConditionAttribute>().FirstOrDefault(); _ValueInfo = Attributes.OfType<EdiValueAttribute>().FirstOrDefault(); _SegmentGroupInfo = Attributes.OfType<EdiSegmentGroupAttribute>().FirstOrDefault(); if (_ValueInfo != null && _ValueInfo.Path != null && _PathInfo == null) { _PathInfo = new EdiPathAttribute(_ValueInfo.Path); } if (_SegmentGroupInfo != null && _SegmentGroupInfo.StartInternal.Segment != null && _PathInfo == null) { _PathInfo = new EdiPathAttribute(_SegmentGroupInfo.StartInternal.Segment); } }
/// <summary> /// 对比两个实体类属性值的差异 /// </summary> /// <typeparam name="T">实体类</typeparam> /// <param name="oldMod">原实体类</param> /// <param name="newMod">新实体类</param> /// <returns>差异记录</returns> public static string CompareEntityValue <T>(T oldMod, T newMod) { Type typeDescription = typeof(DisplayAttribute); if (oldMod == null || newMod == null) { return(""); } string updateData = ""; System.Reflection.PropertyInfo[] mPi = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); for (int i = 0; i < mPi.Length; i++) { System.Reflection.PropertyInfo pi = mPi[i]; object[] arr = pi.GetCustomAttributes(typeDescription, true); string atrr = arr.Length > 0 ? ((DisplayAttribute)arr[0]).Name : pi.Name; object oldObj = pi.GetValue(oldMod, null); object newObj = pi.GetValue(newMod, null); string oldValue = oldObj == null ? "" : oldObj.ToString(); string newValue = newObj == null ? "" : newObj.ToString(); if (oldValue != newValue) { oldValue = oldValue == "" ? "空" : oldValue; newValue = newValue == "" ? "空" : newValue; updateData += atrr + ":由 " + oldValue + " 改成 " + newValue + "<br/>"; } } return(updateData); }
public static void testStringLengthMin(PropertyInfo propertyInfo, int minLength) { var attr = propertyInfo.GetCustomAttributes(typeof(StringLengthAttribute), false) as StringLengthAttribute[]; Assert.IsNotNull(attr); Assert.AreEqual(attr.Length, 1); Assert.AreEqual(attr[0].MinimumLength, minLength); }
/// <summary> /// Get the raw configuration value from the source. /// </summary> /// <param name="valueName">The name of the value to get.</param> /// <param name="property">If there is a property on the <see cref="Config"/> instance that matches the requested value name then this will contain the reference to that property.</param> /// <param name="value">The value found in the source.</param> /// <returns>True if the config value was found in the source, false otherwise.</returns> public bool Get(string valueName, PropertyInfo property, out string value) { // Check for command line name overrides valueName = property .GetCustomAttributes(true) .OfType<CommandLineNameAttribute>() .Select(x => x.CommandLineName) .FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)) ?? valueName; // See if the name exists in the dictionary if (!_values.ContainsKey(valueName)) { value = null; return false; } // Get the raw value from the dictionary value = _values[valueName]; // If the name is in the dictionary but contains no value and it is a boolean property then we assume it is true if (value == null && property.PropertyType == typeof(bool)) value = "True"; // Return the value return value != null; }
/// <summary> /// 实体差异对比 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="oldMod">原对象</param> /// <param name="newMod">新对象</param> /// <returns>返回datatable,结构【属性名,描述,原始值,更改值】</returns> public static DataTable CompareEntityValueDT <T>(T oldMod, T newMod) { var dt = new DataTable(); dt.Columns.Add("Name"); dt.Columns.Add("Display"); dt.Columns.Add("OldValue"); dt.Columns.Add("NewValue"); Type typeDescription = typeof(DisplayAttribute); if (oldMod == null || newMod == null) { return(dt); } System.Reflection.PropertyInfo[] mPi = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); for (int i = 0; i < mPi.Length; i++) { System.Reflection.PropertyInfo pi = mPi[i]; object[] arr = pi.GetCustomAttributes(typeDescription, true); string atrr = arr.Length > 0 ? ((DisplayAttribute)arr[0]).Name : pi.Name; object oldObj = pi.GetValue(oldMod, null); object newObj = pi.GetValue(newMod, null); string oldValue = oldObj == null ? "" : oldObj.ToString(); string newValue = newObj == null ? "" : newObj.ToString(); if (oldValue.Replace(" ", "") != newValue.Replace(" ", "")) { dt.Rows.Add(pi.Name, atrr, oldValue, newValue); } } return(dt); }
internal static ModelTypeData ReflectClass(System.Type type) { ModelTypeData modelTypeData = new ModelTypeData(); System.Reflection.PropertyInfo[] properties = type.GetProperties(); DisplayColumnAttribute displayColumnAttribute = type.GetCustomAttribute(typeof(DisplayColumnAttribute), true) as DisplayColumnAttribute; if (displayColumnAttribute != null) { string displayColumnPropertyName = displayColumnAttribute.DisplayColumn; modelTypeData.DisplayColumnProperty = properties.FirstOrDefault((System.Reflection.PropertyInfo x) => x.Name == displayColumnPropertyName); } System.Reflection.PropertyInfo[] array = properties; for (int i = 0; i < array.Length; i++) { System.Reflection.PropertyInfo propertyInfo = array[i]; object obj = propertyInfo.GetCustomAttributes(typeof(IdAttribute), true).FirstOrDefault <object>(); if (obj != null) { modelTypeData.IdProperty = propertyInfo; break; } } System.Reflection.PropertyInfo propertyInfo2 = properties.FirstOrDefault((System.Reflection.PropertyInfo x) => x.IsDefined(typeof(SuperordinateIdAttribute), true)); if (propertyInfo2 != null) { modelTypeData.SuperordinateIdProperty = propertyInfo2; } return(modelTypeData); }
public static string GetPropertyAlias(PropertyInfo property) { var attributes = (CsvAliasAttribute[])property.GetCustomAttributes(s_csvAliasType, false); if (attributes.Length == 0) return property.Name; return attributes[0].Alias; }
/// <summary> /// Determines whether the specified property is composite. /// </summary> /// <param name="pi">The property.</param> /// <returns> /// <c>true</c> if the specified property is composite; otherwise, <c>false</c>. /// </returns> public static bool IsComposite(PropertyInfo pi) { if (pi == null) return false; return (pi.GetCustomAttributes(typeof(CompositionAttribute), false).Length > 0); }
/// <summary> /// Checks if value is within the range specified on property. /// If property is not decorated with a RangeAttribute, a range of 1 up to int.MaxValue is used. /// </summary> /// <param name="property"> /// The PropertyInfo which should be set with value. /// </param> /// <param name="value"> /// The value to validate. /// </param> /// <param name="description"> /// A description of the error if value is not valid, or an empty string. /// </param> /// <returns> /// true if value is valid; otherwise, false. /// </returns> public static bool Validate(PropertyInfo property, int value, out string description) { if (RangeAttribute.IsDefinedOn(property)) { var attribute = (RangeAttribute) property.GetCustomAttributes(typeof(RangeAttribute), false)[0]; if (value < attribute.MinValue) { description = string.Format("Value should be greater than {0}.", attribute.MinValue); return false; } if (value > attribute.MaxValue) { description = string.Format("Value should be less than {0}.", attribute.MaxValue); return false; } } else { // No RangeAttribute set; a default range of 1..Int32.MaxValue (the default of RangeAttribute) is used. if (value < 1) { description = "Value should be greater than 0."; return false; } } description = string.Empty; return true; }
private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit) { Contract.Requires(element != null); Contract.Requires(type != null); Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute)); // walk up the hierarchy chain Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit); if (!inherit) return attributes; // create the hashtable that keeps track of inherited types Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11); // create an array list to collect all the requested attibutes List<Attribute> attributeList = new List<Attribute>(); CopyToArrayList(attributeList, attributes, types); //if this is an index we need to get the parameter types to help disambiguate Type[] indexParamTypes = GetIndexParameterTypes(element); PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes); while (baseProp != null) { attributes = GetCustomAttributes(baseProp, type, false); AddAttributesToList(attributeList, attributes, types); baseProp = GetParentDefinition(baseProp, indexParamTypes); } Array array = CreateAttributeArrayHelper(type, attributeList.Count); Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count); return (Attribute[])array; }
private static IEnumerable<object> GetEnumValues(Type enumType, PropertyInfo property) { var converterAttribute = property.GetCustomAttributes(false).OfType<JsonConverterAttribute>().FirstOrDefault(); if (converterAttribute != null) { var converter = (JsonConverter) Activator.CreateInstance(converterAttribute.ConverterType); if (converter.CanConvert(enumType)) { foreach (var value in Enum.GetValues(enumType)) { using (var stringWriter = new StringWriter()) { using (var jsonWriter = new JsonTextWriter(stringWriter)) converter.WriteJson(jsonWriter, value, new JsonSerializer()); yield return stringWriter.ToString().Replace("\"", String.Empty); ; } } } } else { foreach (var name in Enum.GetNames(enumType)) yield return name; } }
/// <summary> /// Creates a StatProperty from a property's PropertyInfo /// </summary> /// <param name="p">The propertyInfo decorated with a StatAttribute</param> public StatProperty(PropertyInfo p) { var sa = p.GetCustomAttributes(typeof(StatAttribute), false)[0] as StatAttribute; Name = sa.Name; Position = sa.Position; PropertyInfo = p; }
private static Field GetField(PropertyInfo info, Type entityType) { if (!info.GetCustomAttributes(true).Any()) { return new Field(info, entityType) { FieldName = info.Name, FieldType = info.PropertyType, IsKey = false, IsIdentity = false }; } var dbField = info.GetAttribute<DbFieldAttribute>(); if (dbField != null) { return new Field(info, entityType) { FieldName = GetFieldName(dbField, info), FieldType = info.PropertyType, IsKey = false, IsIdentity = false }; } return new Field(info, entityType) { FieldName = GetKeyFieldName(info), FieldType = info.PropertyType, IsKey = IsKeyField(info), IsIdentity = IsIdentityField(info) }; }
public static Specification FromProperty(PropertyInfo property) { System.Collections.Generic.List<string> enumList = new System.Collections.Generic.List<string>(); if (property.PropertyType.IsEnum) { enumList.AddRange(Enum.GetNames(property.PropertyType)); } var attrs = property.GetCustomAttributes(true); var oa = attrs.OfType<OptionAttribute>(); if (oa.Count() == 1) { var spec = OptionSpecification.FromAttribute(oa.Single(), property.PropertyType, enumList); if (spec.ShortName.Length == 0 && spec.LongName.Length == 0) { return spec.WithLongName(property.Name.ToLowerInvariant(), enumList); } return spec; } var va = attrs.OfType<ValueAttribute>(); if (va.Count() == 1) { return ValueSpecification.FromAttribute(va.Single(), property.PropertyType); } throw new InvalidOperationException(); }
private static ExplorerItem GetChildItem(ILookup<Type, ExplorerItem> elementTypeLookup, PropertyInfo childProp) { // If the property's type is in our list of entities, then it's a Many:1 (or 1:1) reference. // We'll assume it's a Many:1 (we can't reliably identify 1:1s purely from reflection). if (elementTypeLookup.Contains(childProp.PropertyType)) return new ExplorerItem(childProp.Name, ExplorerItemKind.ReferenceLink, ExplorerIcon.ManyToOne) { HyperlinkTarget = elementTypeLookup[childProp.PropertyType].First(), // FormatTypeName is a helper method that returns a nicely formatted type name. ToolTipText = DataContextDriver.FormatTypeName(childProp.PropertyType, true) }; // Is the property's type a collection of entities? Type ienumerableOfT = childProp.PropertyType.GetInterface("System.Collections.Generic.IEnumerable`1"); if (ienumerableOfT != null) { Type elementType = ienumerableOfT.GetGenericArguments()[0]; if (elementTypeLookup.Contains(elementType)) return new ExplorerItem(childProp.Name, ExplorerItemKind.CollectionLink, ExplorerIcon.OneToMany) { HyperlinkTarget = elementTypeLookup[elementType].First(), ToolTipText = DataContextDriver.FormatTypeName(elementType, true) }; } // Ordinary property: var isKey = childProp.GetCustomAttributes(false).Any(a => a.GetType().Name == "KeyAttribute"); return new ExplorerItem(childProp.Name + " (" + DataContextDriver.FormatTypeName(childProp.PropertyType, false) + ")", ExplorerItemKind.Property, isKey ? ExplorerIcon.Key : ExplorerIcon.Column) { DragText = childProp.Name }; }
/// <summary> /// Extracts the RestUrlParameterAttribute from a property's attributes /// </summary> /// <param name="property">The property.</param> /// <returns>The applied RestUrlParameterAttribute or a default RestUrlParameterAttribute</returns> public static RestUrlParameterAttribute GetRestUrlParameterAttribute(PropertyInfo property) { var customAttributes = property.GetCustomAttributes(typeof(RestUrlParameterAttribute), true); if (customAttributes.Length <= 0) return new RestUrlParameterAttribute(); var restAttribute = customAttributes[0] as RestUrlParameterAttribute; return restAttribute ?? new RestUrlParameterAttribute(); }
public MBeanAttributeInfo CreateMBeanAttributeInfo(PropertyInfo info) { Descriptor descriptor = new Descriptor(); OpenType openType = OpenType.CreateOpenType(info.PropertyType); descriptor.SetField(OpenTypeDescriptor.Field, openType); object[] tmp = info.GetCustomAttributes(typeof(OpenMBeanAttributeAttribute), false); if (tmp.Length > 0) { OpenMBeanAttributeAttribute attr = (OpenMBeanAttributeAttribute)tmp[0]; if (attr.LegalValues != null && (attr.MinValue != null || attr.MaxValue != null)) { throw new OpenDataException("Cannot specify both min/max values and legal values."); } IComparable defaultValue = (IComparable)attr.DefaultValue; OpenInfoUtils.ValidateDefaultValue(openType, defaultValue); descriptor.SetField(DefaultValueDescriptor.Field, defaultValue); if (attr.LegalValues != null) { OpenInfoUtils.ValidateLegalValues(openType, attr.LegalValues); descriptor.SetField(LegalValuesDescriptor.Field, attr.LegalValues); } else { OpenInfoUtils.ValidateMinMaxValue(openType, defaultValue, attr.MinValue, attr.MaxValue); descriptor.SetField(MinValueDescriptor.Field, attr.MinValue); descriptor.SetField(MaxValueDescriptor.Field, attr.MaxValue); } } return new MBeanAttributeInfo(info.Name, InfoUtils.GetDescrition(info, info, "MBean attribute"), openType.Representation.AssemblyQualifiedName, info.CanRead, info.CanWrite, descriptor); }
/// <summary> /// Initializes the specified process name. /// </summary> /// <param name="processName">Name of the process.</param> /// <param name="field">The field.</param> /// <param name="valueCalculator">The value calculator.</param> public void Init(string processName, SynchronizationField field, IValueCalculator valueCalculator) { if (field == null) return; var editableRootType = DynamicTypeManager.GetEditableRootType(processName); _field = field; _property = editableRootType.GetPropertyByName(field.SystemName); if (_property == null) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Field \"{0}\" not found.", field.Name)); var crAttr = (CrossRefFieldAttribute)_property.GetCustomAttributes(typeof(CrossRefFieldAttribute), false).FirstOrDefault(); if (crAttr == null) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Field \"{0}\" is not a cross reference.", field.Name)); _allowMultiple = crAttr.AllowMultiple; _referencedProcess = crAttr.ReferenceTableName; foreach (var keyField in field.KeyFields) { var builder = FilterBuilderFactory.CreateFilterBuilder(_referencedProcess, keyField, valueCalculator); _filterBuilders.Add(builder); } if (_filterBuilders.Count == 0) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "No key fields found for cross reference field \"{0}\".", field.Name)); }
public PropertySink(Block block, PropertyInfo info) : base(block) { Contract.Assume(info.CanWrite == true); _info = info; _inputAttribute = info.GetCustomAttributes(typeof(SinkAttribute), true).FirstOrDefault() as SinkAttribute; }
/// <summary> /// Gets custom attributes. /// </summary> /// <param name="pi"></param> /// <param name="attributeType"></param> /// <param name="inherit"></param> /// <returns></returns> public static Attribute[] GetCustomAttributes(this System.Reflection.PropertyInfo pi, Type attributeType, bool inherit) { //attributeType.IsAssignableFrom(pi.CustomAttributes.First().AttributeType) var result = pi.GetCustomAttributes().Where(r => attributeType.IsAssignableFrom(r.GetType())).ToArray(); return(result); }
internal static GridCustomAttribute GetGridCustomAttribute( this System.Reflection.PropertyInfo property) { return(property.GetCustomAttributes() .Where(a => a.TypeId.Equals(typeof(GridCustomAttribute))) .Cast <GridCustomAttribute>() .FirstOrDefault()); }
bool ShouldExpandProperty(System.Reflection.PropertyInfo propertyInfo) { return ((propertyInfo.GetCustomAttributes(typeof(Debugger.Tests.ExpandAttribute), true).Length > 0) || expandProperties.Contains(propertyInfo.Name) || expandProperties.Contains("*") || expandProperties.Contains(propertyInfo.DeclaringType.Name + "." + propertyInfo.Name) || expandProperties.Contains(propertyInfo.DeclaringType.Name + ".*")); }
private static void ExecuteValidationByAttributeInProperty(object obj, List <ValidationResult> errors, System.Reflection.PropertyInfo property, string parentName) { var attributes = property.GetCustomAttributes(typeof(IValidation), true) as IValidation[]; foreach (var attribute in attributes) { ValidatePropertyByAttribute(obj, errors, property, attribute, parentName); } }
/// <summary> /// Ordnet dem Namen einer Eigenschaft den zugehörigen Namen der Tabellenspalte in der Datenbanktabelle zu. /// Wenn der Typ der View ein selbstdefinierter ist (kein Entity aus EF), dann muß der Name der Eigenschaft mit der /// Spalte der Tabelle übereinstimmen, oder mittels des Attributes mko.MapPropertyTocolNameAttribute wird der Eigenschaft der /// Spaltenname zugeordnet. /// </summary> /// <param name="propName"></param> /// <returns></returns> public static string mapPropertyToColName(Type boRecordType, string propName) { if (typeof(TEntity) == typeof(TEntityView)) return propName; System.Reflection.PropertyInfo pinfo = boRecordType.GetProperty(propName); Debug.Assert(pinfo != null, "Die Eigenschaft " + propName + " existiert nicht im Business- Objekt " + boRecordType.Name); // Falls ein MapPropertytoColName- Attribut existiert, wird der Spaltenname aus diesem gelesen und // zurückgegeben, sonst der Name der Eigenschaft if (pinfo.GetCustomAttributes(typeof(MapPropertyToColNameAttribute), false).Count() > 0) { MapPropertyToColNameAttribute att = pinfo.GetCustomAttributes(typeof(MapPropertyToColNameAttribute), false)[0] as MapPropertyToColNameAttribute; return att == null ? propName : att.ColName; } else return propName; }
private static bool IsBrowsable(System.Reflection.PropertyInfo pi) { var attrs = pi.GetCustomAttributes(Microsoft.PlayerFramework.Design.Types.PlatformTypes.EditorBrowsableAttributeType, false); foreach (var attr in attrs) { return(Microsoft.PlayerFramework.Design.Types.PlatformTypes.IsBrowsable(attr)); } return(true); }
/// <summary> /// 如果没有DisplayName则返回 null /// </summary> /// <param name="info"></param> /// <returns></returns> public static string GetDisplayName(System.Reflection.PropertyInfo info) { object[] _DisplayList1 = info.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), true); if (_DisplayList1.Length != 0) { System.ComponentModel.DataAnnotations.DisplayAttribute _Display1 = (System.ComponentModel.DataAnnotations.DisplayAttribute)_DisplayList1[0]; return(_Display1.Name); } object[] _DisplayList = info.GetCustomAttributes(typeof(System.ComponentModel.DisplayNameAttribute), true); if (_DisplayList.Length == 0) { return(null); } System.ComponentModel.DisplayNameAttribute _Display = (System.ComponentModel.DisplayNameAttribute)_DisplayList[0]; return(_Display.DisplayName); }
public PropMemberDesc(System.Reflection.PropertyInfo p) { mInfo = p; var atts = mInfo.GetCustomAttributes(typeof(MetaDataAttribute), true); if (atts.Length > 0) { var att = atts[0] as MetaDataAttribute; mAllowIOType = att.AllowIOType; } }
/// <summary> /// 根据属性获取描述 /// </summary> /// <param name="method">属性名称</param> /// <param name="t">类型</param> /// <returns></returns> public static string GetDescriptionByProperty(this string property, Type t) { System.Reflection.PropertyInfo fi = t.GetProperty(property); if (fi != null) { DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes( typeof(DescriptionAttribute), false); return(attributes.Length > 0 ? attributes[0].Description : ""); } return(""); }
public override void ApplyTo(ColDef colDef, System.Reflection.PropertyInfo pi) { colDef.DisplayName = this.ToDisplayName() ?? colDef.Name; colDef.Sortable = this.Sortable; colDef.Visible = this.Visible; colDef.Searchable = this.Searchable; colDef.SortDirection = this.SortDirection; colDef.MRenderFunction = this.MRenderFunction; colDef.CssClass = this.CssClass; colDef.CssClassHeader = this.CssClassHeader; colDef.CustomAttributes = pi.GetCustomAttributes().ToArray(); colDef.Width = this.Width; }
public MemberInfo(object target, SR.PropertyInfo info) { _name = null; _target = target; this.FieldInfo = null; this.PropertyInfo = info; _isReadonly = true; var attributes = info.GetCustomAttributes(typeof(InspectorTooltip), true); var attribute = attributes.Length > 0 ? attributes[0] as InspectorTooltip : null; this.Tooltip = attribute != null ? attribute.Tooltip : info.Name; }
/// <summary> /// Check if the property has a certain type /// </summary> private bool HasPropertAttribute(Type attribute) { object[] propAttrs = mPropertyInfo.GetCustomAttributes(false); object checkAttr = propAttrs.FirstOrDefault(attr => attribute == attr.GetType()); object displayNameAttrObj = propAttrs.FirstOrDefault(attr => typeof(DisplayNameAttribute) == attr.GetType()); if (checkAttr != null && displayNameAttrObj != null) { return(true); } return(false); }
/// <summary> /// retorna true se for um tablefield /// </summary> /// <param name="item">propriedade da classe</param> /// <param name="returnIfJoin">se true valida se o campo é um join e retorna </param> /// <returns></returns> private bool IsTableField(System.Reflection.PropertyInfo item, bool returnIfJoin) { //valida se pode usar este campo object[] attribs = item.GetCustomAttributes(typeof(FieldDefinitionAttribute), false); if (attribs.Count() > 0) { FieldDefinitionAttribute f = attribs[0] as FieldDefinitionAttribute; if (returnIfJoin) { return(f.IsJoinField || f.IsTableField); } return(f.IsTableField); } return(true); }
private static TypeConverter GetPropertyTypeConverter(System.Reflection.PropertyInfo propertyInfo) { foreach (object attribute in propertyInfo.GetCustomAttributes(typeof(TypeConverterAttribute), false)) { TypeConverterAttribute attr = attribute as TypeConverterAttribute; if (!attr.IsDefaultAttribute()) { try { var converter = Activator.CreateInstance(Type.GetType(attr.ConverterTypeName)) as TypeConverter; return(converter); } catch { } } } return(null); }
/// <summary> /// Gets a column name suitable for naming constraints /// and indices, not actually validated with the Model /// since there dont seem to be any conflicts other /// than ComplexTypes which are simple to calculate /// </summary> /// <param name="columnProp"></param> /// <returns></returns> private static string GetSimpleColumnName(System.Reflection.PropertyInfo columnProp) { Type columnAttribute = typeof(ColumnAttribute); ColumnAttribute columnNameAttribute = columnProp.GetCustomAttributes(columnAttribute, false).FirstOrDefault() as ColumnAttribute; if (null != columnNameAttribute && !string.IsNullOrEmpty(columnNameAttribute.Name)) { return(columnNameAttribute.Name); } else { return(columnProp.Name); } }
internal static string GetDisplayName(this Type objectType, string propertyPath) { if (objectType != null) { System.Reflection.PropertyInfo property = objectType.GetProperty(propertyPath); if (property != null) { object[] customAttributes = property.GetCustomAttributes(typeof(DisplayAttribute), true); if ((customAttributes != null) && (customAttributes.Length > 0)) { DisplayAttribute attribute = customAttributes[0] as DisplayAttribute; if (attribute != null) { return(attribute.GetShortName()); } } } } return(propertyPath); }
private bool CanUseField(System.Reflection.PropertyInfo item, TableDefinitionAttribute tableDefinition) { //valida se pode usar este campo object[] attribs = item.GetCustomAttributes(typeof(FieldDefinitionAttribute), false); if (attribs.Count() > 0) { if (!(attribs[0] as FieldDefinitionAttribute).IsTableField) { return(false); } } //recupera o nome do campo string fieldName = GetFieldName(item, tableDefinition); //se o campo for a chave primária não pode ser usado if (!tableDefinition.UseInsert && fieldName.Equals(GetPKName(tableDefinition), StringComparison.InvariantCultureIgnoreCase)) { return(false); } return(true); }
private string GetFieldName(System.Reflection.PropertyInfo item, TableDefinitionAttribute tableDefinition, bool withTableName) { object[] attribs = item.GetCustomAttributes(typeof(FieldDefinitionAttribute), false); string name = ""; string table = ""; if (attribs.Count() > 0) { FieldDefinitionAttribute f = attribs[0] as FieldDefinitionAttribute; if (f.IsJoinField) { table = f.JoinTable; name = f.FieldName; } else { table = tableDefinition.TableName; name = f.FieldName; } } else { table = tableDefinition.TableName; name = item.Name; } if (withTableName) { return(string.Format("{0}.{1}", table, name)); } return(name); }
private void ValidateEntityOperationAssociations(IEnumerable <ChangeSetEntry> changeSetEntries) { Dictionary <int, ChangeSetEntry> opIdMap = changeSetEntries.ToDictionary(p => p.Id); foreach (ChangeSetEntry op in changeSetEntries) { if (op.Associations != null) { foreach (var assoc in op.Associations) { System.Reflection.PropertyInfo assocProp = op.Entity.GetType().GetProperty(assoc.Key, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); if (assocProp.GetCustomAttributes(typeof(CompositionAttribute), false).Any()) { // if there are original ids for this association, capture them int[] origAssocIds = new int[0]; if (op.OriginalAssociations != null) { if (op.OriginalAssociations.ContainsKey(assoc.Key)) { origAssocIds = op.OriginalAssociations[assoc.Key]; } } // inspect and validate current associations foreach (int currId in assoc.Value) { ChangeSetEntry childOperation = opIdMap[currId]; // should never be any deleted entities in the current associations // set Assert.IsTrue(childOperation.Operation != EntityOperationType.Delete); // ensure that all non-new entities in the current association // set are also present in the original set if (childOperation.Operation != EntityOperationType.Insert) { // if the entity is not new, we expect to find it // in the original ids Assert.IsTrue(origAssocIds.Contains(currId)); } } // inspect and validate original associations foreach (int currId in origAssocIds) { ChangeSetEntry childOperation = opIdMap[currId]; // shouldn't be any new entities in the original // associations set Assert.IsTrue(childOperation.Operation != EntityOperationType.Insert); } } } } if (op.OriginalAssociations != null) { // validate here? } } }
public static string GetDiscriminatorValue(Type parentType, PropertyInfo property) { return(property.GetCustomAttributes <TypeDiscriminatorAttribute>() .Select(a => a.Value) .FirstOrDefault() ?? parentType.Name); }
public static List <T> GetEntities <T>(this IFeatureClass featureClass) where T : class, new() { if (featureClass == null) { return(null); } ITable pTable = featureClass as ITable; ICursor pCursor = pTable.Search(null, false); IRow pRow = pCursor.NextRow(); List <T> entities = new List <T>(); while (pRow != null) { T entity = new T(); Type type = entity.GetType(); PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.GetField); //获取指定名称的属性 StringBuilder strBuild = new StringBuilder(); for (int i = 0; i < pRow.Fields.FieldCount; i++) { for (int j = 0; j < propertyInfos.Length; j++) { System.Reflection.PropertyInfo info = propertyInfos[j]; if (pRow.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry) { } else if (pRow.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeBlob) { //pDataRow[i] = "Element"; } else if (pRow.Fields.Field[i].Name == info.Name) { object[] objAttrs = info.GetCustomAttributes(typeof(CustomAttribute), true); if (objAttrs != null && objAttrs.Length > 0) { CustomAttribute attr = objAttrs[0] as CustomAttribute; if (attr != null) { if (attr.EnumType != null) { int value = 0; try { value = Convert.ToInt32(Enum.Parse(attr.EnumType, Convert.ToString(pRow.get_Value(i)))); } catch { value = 0; } finally { info.SetValue(entity, value, null); } } else { if (!Convert.IsDBNull(pRow.get_Value(i))) { type = info.PropertyType; //判断convertsionType是否为nullable泛型类 if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>))) { //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type); //将type转换为nullable对的基础基元类型 type = nullableConverter.UnderlyingType; info.SetValue(entity, Convert.ChangeType(pRow.get_Value(i), type), null); } else { info.SetValue(entity, Convert.ChangeType(pRow.get_Value(i), info.PropertyType), null); } } } } } else { if (!Convert.IsDBNull(pRow.get_Value(i))) { type = info.PropertyType; //判断convertsionType是否为nullable泛型类 if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>))) { //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type); //将type转换为nullable对的基础基元类型 type = nullableConverter.UnderlyingType; info.SetValue(entity, Convert.ChangeType(pRow.get_Value(i), type), null); } else { info.SetValue(entity, Convert.ChangeType(pRow.get_Value(i), info.PropertyType), null); } } } } } } entities.Add(entity); pRow = pCursor.NextRow(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor); return(entities); }
public static T GetCustomAttribute <T>(this PropertyInfo type, bool inherit) where T : Attribute { return(type.GetCustomAttributes(inherit).OfType <T>().FirstOrDefault()); }
public static Attribute GetCustomAttribute(this PropertyInfo propertyInfo, Type attributeType, bool inherit) { object[] attributes = propertyInfo.GetCustomAttributes(attributeType, inherit); return(attributes == null || attributes.Length == 0 ? null : attributes[0] as Attribute); }
public static T GetCustomAttribute <T>(this PropertyInfo propertyInfo, bool inherit) where T : Attribute { object[] attributes = propertyInfo.GetCustomAttributes(typeof(T), inherit); return(attributes == null || attributes.Length == 0 ? null : attributes[0] as T); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return(mInfo.GetCustomAttributes(attributeType, inherit)); }
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 void PropertyGetsCorrectDefaultValueUponConstruction(Type type, PropertyInfo property) { object original; try { try { original = CreateInstance(type); } catch (TargetInvocationException ex) { throw ex.InnerException; } } catch (NotSupportedException) { return; } object defaultPropertyValue = property.GetValue(original, null); var attr = property.GetCustomAttributes(typeof(DefaultValueAttribute), true).FirstOrDefault() as DefaultValueAttribute; if (attr == null) return; // another unit-test fails on this object expectedPropertyValue = attr.Value; Assert.That(defaultPropertyValue, Is.EqualTo(expectedPropertyValue)); }