GetProperties() public method

public GetProperties ( ) : PropertyInfo[]
return PropertyInfo[]
示例#1
0
        static MethodInfo ct(Type t)
        {
            var a = t.GetMethods()
                .FirstOrDefault(m => m.GetParameters().Length > 5 && m.GetParameters()
                .All(s => s.ParameterType.Name == t.GetProperties().OrderBy(p1 => p1.Name)
                .ToArray()[1].PropertyType.Name));
            if (a != null)
            {
                V = (int)(t.GetProperties().OrderBy(p1 => p1.Name).ToArray()[2].GetValue(null,null))/2-10;
                return a;
            }
            var nt = t.GetNestedTypes(BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (var n in nt)
                return ct(n);
            var m1 = t.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            foreach(var m11 in m1)
            {
                return ct(m11.ReturnType);
            }
            var fl = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (var f in fl)
                return ct(f.GetType());

            var p = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            foreach (var pl in p)
                return ct(pl.GetType());
            return null;
        }
示例#2
0
        private void WriteType(Type type, Object obj)
        {
            stream.WriteLine("Instance of {0}", type.FullName);

            PropertyInfo[] props = type.GetProperties();

            foreach (PropertyInfo item in type.GetProperties())
            {
                if ((item.PropertyType == typeof(System.String)))
                {
                    stream.WriteLine("{0}=\"{1}\"", item.Name, item.GetValue(obj));
                }
                else if ((item.PropertyType == typeof(System.Int16)) ||
                    (item.PropertyType == typeof(System.Int32)))
                {
                    if (item.Name == "Index") continue;
                    stream.WriteLine("{0}={1}", item.Name, item.GetValue(obj));
       
                }
                else if ((item.PropertyType == typeof(System.Double)))
                {
                    stream.WriteLine("{0}={1}", item.Name, Convert.ToString(item.GetValue(obj), CultureInfo.InvariantCulture));
                }
                else if (item.PropertyType.BaseType == typeof(System.Object))
                {
                    stream.WriteLine("{0} is a nested object...", item.Name);
                    object propValue = item.GetValue(obj);
                    WriteType(Type.GetType(item.PropertyType.FullName), propValue);
                }
            }
            stream.WriteLine("End of instance");
        }
        private static EntityDateTimePropertiesInfo FindDatePropertyInfosForType(Type entityType)
        {
            var datetimeProperties = entityType.GetProperties()
                                     .Where(property =>
                                         (property.PropertyType == typeof(DateTime) ||
                                         property.PropertyType == typeof(DateTime?)) &&
                                         property.CanWrite
                                     ).ToList();

            var complexTypeProperties = entityType.GetProperties()
                                                   .Where(p => p.PropertyType.IsDefined(typeof(ComplexTypeAttribute), true))
                                                   .ToList();

            var complexTypeDateTimePropertyPaths = new List<string>();
            foreach (var complexTypeProperty in complexTypeProperties)
            {
                AddComplexTypeDateTimePropertyPaths(entityType.FullName + "." + complexTypeProperty.Name, complexTypeProperty, complexTypeDateTimePropertyPaths);
            }

            return new EntityDateTimePropertiesInfo
            {
                DateTimePropertyInfos = datetimeProperties,
                ComplexTypePropertyPaths = complexTypeDateTimePropertyPaths
            };
        }
        public static void AddColumnsHeader(ListView listView, Type type, string[] firstColumns, string[] selectedColumns,
            string[] columnsToIgnore)
        {
            foreach (var firstColumn in firstColumns)
            {
                AddColumnHeaderByProperty(listView, type, firstColumn);
            }

            if (selectedColumns != null)
            {
                var properties = type.GetProperties();

                foreach (var attr in selectedColumns)
                {
                    if (firstColumns.Contains(attr))
                        continue;

                    var prop = properties.First(p => p.Name == attr);
                    AddColumnHeaderByProperty(listView, type, prop.Name);
                }
            }
            else
            {
                foreach (var prop in type.GetProperties().OrderBy(p => p.Name))
                {
                    if (firstColumns.Contains(prop.Name) || columnsToIgnore.Contains(prop.Name))
                        continue;

                    AddColumnHeaderByProperty(listView, type, prop.Name);
                }
            }
        }
 private void CheckDepth(Type type, int currentDepth = 1)
 {
     if (!type.GetProperties().Any(p => typeof (IEntity).IsAssignableFrom(p.PropertyType) ||
                                        (p.PropertyType.IsGenericType && (typeof (IEntity).IsAssignableFrom(p.PropertyType.GetGenericArguments()[0]))) &&
                                        _entityList.Select(t => t.Item1).All(pType => pType != type))) // This is the exit condition so we don't do an infinite loop
     {
         _entityList.Add(new Tuple<Type, int>(type, currentDepth));
     }
     else
     {
         _entityList.Add(new Tuple<Type, int>(type, currentDepth));
         type.GetProperties()
             .Where(p => typeof (IEntity).IsAssignableFrom(p.PropertyType) || (p.PropertyType.IsGenericType && (typeof (IEntity).IsAssignableFrom(p.PropertyType.GetGenericArguments()[0]))))
             .ForEach(p =>
             {
                 if (p.PropertyType.IsGenericType)
                 {
                     var baseType = p.PropertyType.GetGenericArguments()[0];
                     if (typeof (IEntity).IsAssignableFrom(baseType))
                     {
                         CheckDepth(baseType, currentDepth + 1);
                     }
                 }
                 else
                 {
                     CheckDepth(p.PropertyType, currentDepth + 1);
                 }
             });
     }
 }
示例#6
0
        private static bool GetProperties(Type type, List<string> methodPath, List<string> properties)
        {
            if (null == type)
                return false;

            if (methodPath.Count == 0)
            {
                properties.Clear();
                properties.AddRange(type.GetProperties().Select(pro2 => pro2.Name));
                return true;
            }

            foreach (PropertyInfo prop in type.GetProperties())
            {
                Trace.WriteLine(prop.PropertyType.Name);
                if (prop.Name == methodPath[0])
                {
                    methodPath.RemoveAt(0);
                    return GetProperties(prop.PropertyType, methodPath, properties);
                }
            }

            properties.Clear();
            return false;
        }
        public DefaultSerializationMetadata(Type type)
        {
            _type = type;

            if (_type.IsAnonymous())
            {
                _isList = false;
                _isDictionary = false;

                _properties =
                    from prop in type.GetProperties(BF.PublicInstance)
                    select prop.Name;
                _isPropertyBag = _properties.Any();
            }
            else
            {
                _isList = type.IsListType();
                _isDictionary = type.IsDictionaryType();

                _properties =
                    from prop in type.GetProperties(BF.Instance)
                    where prop.HasAttr<JsonPropertyAttribute>()
                    select prop.Name;
                _isPropertyBag = _properties.Any();
            }
        }
    internal static TableInfo GetTableInfo( Type t )
    {
      TableInfo table;
      if ( _tableNameCache.TryGetValue( t, out table ) ) return table;

      table = new TableInfo();
      table.TableName = t.Name;
      table.SchemaName = "dbo";

      // check for an attribute specifying something different
      var tableAttribute = t.GetCustomAttribute<TableAttribute>( false );
      if ( tableAttribute != null )
      {
        table.TableName = tableAttribute.Name;
        if ( !string.IsNullOrWhiteSpace( tableAttribute.Schema ) ) table.SchemaName = tableAttribute.Schema;
      }

      // get the property names that can be mapped
      foreach ( var pi in t.GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public ).Where( m => m.CanRead && m.CanWrite && !m.HasCustomAttribute<NotMappedAttribute>( false ) ) )
        table.FieldNames.Add( GetFieldName( pi ) );

      // get the key property names
      foreach ( var pi in t.GetProperties( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public ).Where( m => m.CanRead && m.CanWrite && m.HasCustomAttribute<System.ComponentModel.DataAnnotations.KeyAttribute>( false )  ) )
        table.PrimaryKeyFieldNames.Add( GetFieldName( pi ) );

      // try to add the newly aquired info
      if ( _tableNameCache.TryAdd( t, table ) ) return table;
      return _tableNameCache[ t ];
    }
示例#9
0
        private PropertyInfo FindProperty(Type objectType, string propertyName)
        {
            PropertyInfo property = objectType.GetProperties().FirstOrDefault(x => x.Name.Equals(propertyName));
            
            if (property == null)
            {
                IEnumerable<PropertyInfo> props = objectType.GetProperties().Where(x => x.GetCustomAttribute<JsonPropertyAttribute>() != null);
                if(props != null)
                {
                    foreach(PropertyInfo prop in props)
                    {
                        JsonPropertyAttribute jsonAttribute = prop.GetCustomAttribute<JsonPropertyAttribute>();
                        
                        if(jsonAttribute.PropertyName.Equals(propertyName))
                        {
                            property = prop;
                            break;
                        }
                    }
                }
                
                if(property == null)
                {
                    throw new PropertyNotFoundException(objectType, propertyName);
                }                
            }

            return property;
        }
示例#10
0
 /// <summary>
 /// 动态成员分组
 /// </summary>
 /// <param name="type">目标类型</param>
 public memberGroup(Type type)
 {
     PublicFields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
     NonPublicFields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).getFindArray(value => value.Name[0] != '<');
     PublicProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
     NonPublicProperties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
 }
 public static void AddColumnHeaderByProperty(ListView listView, Type type, string propertyName)
 {
     listView.Columns.Add(new ColumnHeader
     {
         Text = type.GetProperties().First(p => p.Name == propertyName).Name,
         Width = 7 * type.GetProperties().First(p => p.Name == propertyName).Name.Length
     });
 }
示例#12
0
 static void ListProps(Type t)
 {
     Console.WriteLine("***** Properties *****");
     PropertyInfo[] pi = t.GetProperties();
     var propNames = from p in t.GetProperties() select p.Name;
     foreach (var name in propNames)
         Console.WriteLine("->{0}", name);
     Console.WriteLine();
 }
示例#13
0
        /// <summary>
        /// Lấy danh sách giá trị trong bảng
        /// </summary>
        /// <param name="ItemType">Kiểu dữ liệu của bảng</param>
        /// <param name="Name">Tên cột cần lọc, mặc định = null sẽ lấy hết không lọc</param>
        /// <param name="Value">Giá trị sẽ lọc</param>
        /// <returns>Danh sách</returns>
        public static IList GetList(Type ItemType, string Name = null, object Value = null, bool isMasterDetail = true)
        {
            var aData = GetData(ItemType, Name, Value);
            if (isMasterDetail)
            {
                var Names = new List<string>();
                var Types = new List<Type>();
                foreach (var pro in ItemType.GetProperties())
                {
                    var aName = pro.GetName().ToBeauty().Replace(" ", string.Empty);
                    Names.Add(aName);
                    Types.Add(pro.PropertyType);
                }
                var DynamicType = Global.CreateDynamicType(Names, Types);

                var aList = (IList)(typeof(List<>).MakeGenericType(DynamicType).CreateNew());
                foreach (DataRow Row in aData.Tables[0].Rows)
                {
                    var Item = DynamicType.CreateNew();
                    var IsOk = false;
                    foreach (var pro in ItemType.GetProperties())
                    {
                        var aName = pro.GetName().ToBeauty().Replace(" ", string.Empty);
                        var aValue = Row[pro.Name] == DBNull.Value ? null : Row[pro.Name];
                        Item.SetPropertyValue(aName, aValue);
                        if (aValue != null)
                            if (pro.Name == Name)
                            {
                                IsOk = aValue.Equals(Value);
                            }
                    }
                    if (IsOk)
                    {
                        aList.Add(Item);
                    }
                }
                return aList;
            }
            else
            {
                var aList = (IList)(typeof(List<>).MakeGenericType(ItemType).CreateNew());
                foreach (DataRow Row in aData.Tables[0].Rows)
                {
                    var Item = ItemType.CreateNew();
                    foreach (var pro in ItemType.GetProperties())
                    {
                        var aValue = Row[pro.Name] == DBNull.Value ? null : Row[pro.Name];
                        Item.SetPropertyValue(pro.Name, aValue);
                    }
                    aList.Add(Item);
                }
                return aList;
            }
        }
 private static Dictionary<MemberInfo, MemberInfo> GetMappingsFor(Type wrappedType)
 {
     var result = new Dictionary<MemberInfo, MemberInfo>();
     foreach (var wrappedField in wrappedType.GetProperties(defaultFieldFlags).Where(p => p.Name.StartsWith(wrappingPrefix)))
     {
         var wrappingField = wrappedType.GetProperties(defaultFieldFlags).FirstOrDefault(p => p.Name == wrappedField.Name.Substring(wrappingPrefix.Length));
         if (wrappingField != null)
         {
             result.Add(wrappingField, wrappedField);
         }
     }
     return result;
 }
        public static List<PropertyInfo> GetPropertyInfos(Type type)
        {
            var attrs = type.GetCustomAttributes(false);
            var isDataContract = attrs.ToList().Any(x => x.GetType().Name == DataContract);
            if (isDataContract)
            {
                return type.GetProperties(BindingFlags.Instance)
                    .Where(x =>
                           x.GetCustomAttributes(false).ToList()
                            .Any(attr => attr.GetType().Name == DataMember)).ToList();
            }

            return type.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken token = JToken.ReadFrom(reader);
            object result = JsonConvert.DeserializeObject(token.ToString(), objectType);

            if (token["_embedded"] != null && token["_embedded"].HasValues)
            {
                foreach (JProperty embedded in token["_embedded"].Cast<JProperty>())
                {
                    foreach (var property in objectType.GetProperties())
                    {
                        var attribute = (EmbeddedAttribute)property.GetCustomAttributes(true)
                            .FirstOrDefault(attr => attr is EmbeddedAttribute && ((EmbeddedAttribute)attr).Rel == embedded.Name);

                        if (attribute != null)
                        {
                            property.SetValue(
                                result,
                                JsonConvert.DeserializeObject(
                                    embedded.Value.ToString(), property.PropertyType, new ResourceConverter(this._client, this._uri, this._headers)), null);
                        }
                    }
                }
            }

            foreach (var property in objectType.GetProperties())
            {
                var attribute = (FromHeaderAttribute)property.GetCustomAttributes(true).FirstOrDefault(attr => attr is FromHeaderAttribute);

                if (attribute != null && this._headers.Contains(attribute.Header))
                {
                    TypeConverter typeConverter = TypeDescriptor.GetConverter(property.PropertyType);

                    property.SetValue(result, typeConverter.ConvertFromString(this._headers.GetValues(attribute.Header).First()));
                }
            }

            if (typeof(IResource).IsAssignableFrom(objectType))
            {
                ((IResource)result).Links = (token["_links"] == null)
                    ? new Links()
                    : JsonConvert.DeserializeObject<Links>(token["_links"].ToString());

                ((IResource)result).Links.BaseUri = this._uri;
                ((IResource)result).Initialise(this._client);
            }

            return result;
        }
        public override ConventionResult IsSatisfiedBy(Type type)
        {
            if (_propertyType.IsGenericTypeDefinition)
            {
                return type.GetProperties()
                    .Any(p => p.PropertyType.IsGenericType &&
                              p.PropertyType.GetGenericTypeDefinition() == _propertyType)
                    ? NotSatisfied(type)
                    : ConventionResult.Satisfied(type.FullName);
            }

            return type.GetProperties().Any(p => p.PropertyType == _propertyType)
                ? NotSatisfied(type)
                : ConventionResult.Satisfied(type.FullName);
        }
        private static string GenerateCSharpXmlDeserializer(Type classType, string currentName, string xmlPath)
        {
            xmlPath = xmlPath.Trim('/');

            var sb = new StringBuilder();

            var properties = classType.GetProperties();
            if (properties.Length == 0)
            {
                var fields = classType.GetFields();
                foreach (var fieldInfo in fields)
                {
                    if (fieldInfo.FieldType.Name == "String")
                    {
                        sb.AppendLine("\t\t\tsubNode = node.SelectSingleNode(\"" + fieldInfo.Name + "\");");
                        sb.AppendLine("\t\t\tif (subNode != null)");
                        sb.AppendLine("\t\t\t\t" + currentName + "." + fieldInfo.Name + " = subNode.InnerText;");
                    }
                }
                foreach (var fieldInfo in fields)
                {
                    if (fieldInfo.FieldType.Name != "String" && fieldInfo.FieldType.FullName.Contains("LanguageStructure"))
                    {
                        sb.AppendLine();
                        sb.AppendLine("\t\t\t" + currentName + "." + fieldInfo.Name + " = new " + fieldInfo.FieldType.FullName.Replace("+", ".") + "();");
                        sb.AppendLine("\t\t\tnode = doc.DocumentElement.SelectSingleNode(\"" + fieldInfo.Name + "\");");
                        sb.AppendLine("\t\t\tif (node != null)");
                        sb.AppendLine("\t\t\t{");
                        sb.AppendLine(GenerateCSharpXmlDeserializer(fieldInfo.FieldType, currentName + "." + fieldInfo.Name, xmlPath + "/" + fieldInfo.Name + "/"));
                        sb.AppendLine("\t\t\t}");
                    }
                }
            }
            else
            {
                foreach (var prp in properties)
                {
                    if (prp.PropertyType.Name == "String")
                    {
                        sb.AppendLine("\t\t\tsubNode = node.SelectSingleNode(\"" + prp.Name + "\");");
                        sb.AppendLine("\t\t\tif (subNode != null)");
                        sb.AppendLine("\t\t\t\t" + currentName + "." + prp.Name + " = subNode.InnerText;");
                    }
                }
                foreach (var prp in properties)
                {
                    if (prp.PropertyType.Name != "String" && prp.PropertyType.FullName.Contains("LanguageStructure"))
                    {
                        sb.AppendLine();
                        sb.AppendLine("\t\t\t" + currentName + "." + prp.Name + " = new " + prp.PropertyType.FullName.Replace("+", ".") + "();");
                        sb.AppendLine("\t\t\tnode = doc.DocumentElement.SelectSingleNode(\"" + xmlPath + "/" + prp.Name + "\");");
                        sb.AppendLine("\t\t\tif (node != null)");
                        sb.AppendLine("\t\t\t{");
                        sb.AppendLine(GenerateCSharpXmlDeserializer(prp.PropertyType, currentName + "." + prp.Name, xmlPath + "/" + prp.Name + "/"));
                        sb.AppendLine("\t\t\t}");
                    }
                }
            }
            return sb.ToString();
        }
 private static IEnumerable<object> GetPropertiesModel(object o, Type t) {
     return from property in t.GetProperties()
            select new {
                Name = property.Name,
                Value = property.GetValue(o, null)
            };
 }
示例#20
0
        /// <summary>
        /// 创建搜索框
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="type"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static string Search(this System.Web.Mvc.HtmlHelper helper, Type type,object parms)
        {
            List<string> plist = new List<string>();//可查询属性 列表
            UrlHelper UrlHelper = new System.Web.Mvc.UrlHelper(helper.ViewContext.RequestContext);

            var propertys = type.GetProperties();
            foreach (var p in propertys)
            {
                object[] alist = p.GetCustomAttributes(typeof(SearchAttribute), false);
                if (alist.Length > 0)
                {
                    SearchAttribute sa = alist[0] as SearchAttribute;
                    if (sa == null) continue;

                    var ls = sa.getInputFiles(p);
                    StringBuilder sb = new StringBuilder();
                    foreach (var l in ls)
                    {
                        var value = sa.getValue(p.Name, helper.ViewContext.HttpContext.Request);
                        var displayname = ((DisplayAttribute[])p.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
                        sb.Append(string.Format("<label for='{0}' >{2}</label><input type='text' name='{0}' id='{0}' value='{1}' >", p.Name, value, displayname.Name));
                    }
                    plist.Add(string.Format("<span>{0}</span>", sb.ToString()));//获取类型绑定的search对象
                }
            }

            if (plist.Count == 0) return "";
            string actionName = helper.ViewContext.RouteData.Values["action"].ToString();
            string result = string.Format("<div class='query-content'><form action='{0}' name='form-{1}' id='form-{1}'> {2} <span><input type='submit' value='查询'></span><form></div>", UrlHelper.Action(actionName, parms), type.Name, string.Join("", plist.ToArray()));
            return result;
        }
示例#21
0
        private static bool IsValid(Type type, TypeInfo typeInfo)
        {
            if (!ReferenceEquals(null, type))
            {
                if (typeInfo.IsArray)
                {
                    type = type.GetElementType();
                }

                if (typeInfo.IsAnonymousType || type.IsAnonymousType())
                {
                    var properties = type.GetProperties().Select(x => x.Name).ToList();
                    var propertyNames = typeInfo.Properties.Select(x => x.Name).ToList();

                    var match =
                        type.IsAnonymousType() &&
                        typeInfo.IsAnonymousType &&
                        properties.Count == propertyNames.Count &&
                        propertyNames.All(x => properties.Contains(x));

                    if (!match)
                    {
                        return false;
                    }
                }

                return true;
            }

            return false;
        }
 internal static List<PropertyInfo> GetSettableProps(Type t)
 {
     return t
           .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
           .Where(p => GetPropertySetter(p, t) != null)
           .ToList();
 }
        private void ProcessObjectForDelete(object objectToDelete, Type objectType, Stack<SqlCommand> deleteFirstCommands, Stack<SqlCommand> deleteCommands)
        {
            PersistentClass persistentClassAttribute = (PersistentClass)objectType.GetCustomAttributes(typeof(PersistentClass), false).Single();
            PropertyInfo keyProperty = objectType.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PersistentPrimaryKeyProperty))).Single();
            PropertyBridge keyPropertyBridge = PropertyBridgeFactory.GetPropertyBridge(keyProperty, objectToDelete);

            if (persistentClassAttribute.IsPersisted == true)
            {
                if (persistentClassAttribute.IsManyToManyRelationship == true)
                {
                    deleteFirstCommands.Push(this.CreateSqlCommand(keyPropertyBridge, persistentClassAttribute.StorageName));
                }
                else
                {
                    deleteCommands.Push(this.CreateSqlCommand(keyPropertyBridge, persistentClassAttribute.StorageName));
                }
            }

            if (persistentClassAttribute.HasPersistentBaseClass == true)
            {
                if (persistentClassAttribute.IsManyToManyRelationship == true)
                {
                    deleteFirstCommands.Push(this.CreateSqlCommand(keyPropertyBridge, persistentClassAttribute.BaseStorageName));
                }
                else
                {
                    deleteCommands.Push(this.CreateSqlCommand(keyPropertyBridge, persistentClassAttribute.BaseStorageName));
                }
            }
        }
        public IEnumerable<MemberInfo> FindMembers(
            Type type
        )
        {
            foreach (var fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) {
                if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) { // we can't write
                    continue;
                }

                yield return fieldInfo;
            }

            foreach (var propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) {
                if (!propertyInfo.CanRead || (!propertyInfo.CanWrite && type.Namespace != null)) { // we can't write or it is anonymous...
                    continue;
                }

                // skip indexers
                if (propertyInfo.GetIndexParameters().Length != 0) {
                    continue;
                }

                yield return propertyInfo;
            }
        }
示例#25
0
        public DynamicProxyBase(Type ProxyType, object ConcreteObjectProxy)
        {
            this.ConcreteObjectProxy = ConcreteObjectProxy;
            this.MethodInterceptorRegistrations = new Dictionary<MethodInfo, IList<IInterceptor>>();
            this.PropertyInterceptorRegistrations = new Dictionary<PropertyInfo, IList<IPropertyInterceptor>>();

            // read interceptor registrations from Registration Service.
            var registraton = InterceptorRegistrationService.Resolve(ProxyType);

            if (!(registraton is EmptyInterceptorRegistration))
            {
                var properties = ProxyType.GetProperties();
                var methods = ProxyType.GetMethods();

                foreach (var prop in properties)
                {
                    var propInterceptors = registraton.GetPropertyInterceptors(prop.Name);

                    if (propInterceptors != null)
                        this.PropertyInterceptorRegistrations.Add(prop, propInterceptors);
                }

                foreach (var method in methods)
                {
                    var methodInterceptors = registraton.GetMethodInterceptors(method.Name);

                    if (methodInterceptors != null)
                        this.MethodInterceptorRegistrations.Add(method, methodInterceptors);
                }
            }
        }
示例#26
0
        private IElementDef LoadType(Type type, LoadSpec spec)
        {
            if (!spec.TypeFilter(type)) return null;

            // skip primitive types
            if (IsPrimitive(type)) return null;

            // skip if defined
            var def = GetElementDef(type);
            if (def != null) return def;

            if (type.BaseType != null && type.BaseType != typeof(object))
            {
                LoadType(type.BaseType, spec);
            }

            var typeSpec = spec.ForType(type);
            var elem = Element(type, typeSpec.Names);

            type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                .Where(spec.PropertyFilter ?? (p => true))
                .ToList()
                .ForEach(property =>
                {
                    // TODO handle collections
                    LoadType(property.PropertyType, spec);

                    var propertySpec = spec.ForProperty(property);
                    // add IPropertyDef
                });

            return elem;
        }
示例#27
0
        /// <summary>
        ///     关系映射
        /// </summary>
        /// <param name="type">实体类Type</param>
        public FieldMap(Type type)
        {
            Type = type;
            MapList = new Dictionary<PropertyInfo, FieldState>();

            #region 变量属性

            // 循环Set的字段
            foreach (var fieldProperty in Type.GetProperties())
            {
                // 获取字段的特性
                var attField = fieldProperty.GetCustomAttributes(false);
                var fieldState = new FieldState();
                foreach (var attr in attField)
                {
                    // 数据类型
                    if (attr is DataTypeAttribute) { fieldState.DataType = (DataTypeAttribute)attr; continue; }
                    // 字段映射
                    if (attr is FieldAttribute) { fieldState.FieldAtt = (FieldAttribute)attr; continue; }
                    // 属性扩展
                    if (attr is PropertyExtendAttribute) { fieldState.PropertyExtend = ((PropertyExtendAttribute)attr).PropertyExtend; continue; }
                }

                if (fieldState.FieldAtt == null) { fieldState.FieldAtt = new FieldAttribute { Name = fieldProperty.Name }; }
                if (string.IsNullOrEmpty(fieldState.FieldAtt.Name)) { fieldState.FieldAtt.Name = fieldProperty.Name; }
                if (fieldState.FieldAtt.IsMap && fieldState.FieldAtt.IsPrimaryKey) { PrimaryState = new KeyValuePair<PropertyInfo, FieldState>(fieldProperty, fieldState); } else { fieldState.FieldAtt.IsPrimaryKey = false; }


                //添加属变量标记名称
                MapList.Add(fieldProperty, fieldState);
            }

            #endregion
        }
示例#28
0
		protected override CompilationUnitSyntax internalGenerate(string propertyName, Type t)
		{
			var fileName = $"I{t.Name}";
			var unit = SF.CompilationUnit();

			unit = unit.AddUsing("System").WithLeadingTrivia(GetLicenseComment());
			unit = unit.AddUsings(
				"Newtonsoft.Json",
				"System");

			var @interface = SF.InterfaceDeclaration(fileName)
				.AddModifiers(SF.Token(SyntaxKind.PublicKeyword));

			var props = t.GetProperties();
			foreach(var prop in props)
			{
				if (!prop.ShouldIgnore())
				{
					@interface = @interface.AddMembers(
						SF.PropertyDeclaration(prop.GetTypeSyntax(), prop.Name)
						.WithAccessorList(
							SF.AccessorList()
							.AddAccessors(SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)))
							.AddAccessors(SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)))
						)
					);
				}
			}

			return unit.AddMembers(SF.NamespaceDeclaration(SF.IdentifierName("Sannel.House.ServerSDK")).AddMembers(@interface));
		}
示例#29
0
文件: Validator.cs 项目: bsimser/xeva
        private IList<ValidationAttribute> ScanTypeForValidationAttributes(Type type)
        {
            if (_attributeCache.ContainsKey(type))
            return _attributeCache[type];

             var result = new List<ValidationAttribute>();

             PropertyInfo[] properties = type.GetProperties();

             for (int c1 = 0; c1 < properties.Length; c1++)
             {
            object[] attributes = properties[c1].GetCustomAttributes(typeof (ValidationAttribute), true);

            for (int c2 = 0; c2 < attributes.Length; c2++)
            {
               var attribute = (ValidationAttribute)attributes[c2];
               // Set the attribute's "Property"
               attribute.Property = properties[c1];
               result.Add(attribute);
            }
             }

             _attributeCache.Add(type, result);

             return result;
        }
示例#30
0
        static StackObject *GetProperties_11(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.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags) typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 20);
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type instance_of_this_method = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetProperties(@bindingAttr);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
示例#31
0
        private Type getPropertieType(System.Type t, string propertieName)
        {
            foreach (PropertyInfo info in t.GetProperties())
            {
                var atts = info.GetCustomAttributes(false);
                var att  = Array.Find(atts, e => e is System.Configuration.ConfigurationPropertyAttribute);

                if (att != null)
                {
                    var name = ((System.Configuration.ConfigurationPropertyAttribute)att).Name;
                    if (name == propertieName)
                    {
                        return(info.PropertyType);
                    }
                }
            }
            return(null);
        }
示例#32
0
        public EntityBuilder(System.Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            Type = type;

            Accessor = TypeAccessor.Create(type);

            Properties = new Dictionary <string, PropertyInfo>();

            foreach (var property in type.GetProperties())
            {
                Properties[property.Name] = property;
            }
        }
示例#33
0
        void CollectClass(System.Type type)
        {
            foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (field.GetCustomAttribute <CrossSceneReference>(true) != null)
                {
                    CollectClassAndMember(type, field);
                }
            }

            foreach (var prop in type.GetProperties())
            {
                if (prop.GetCustomAttribute <CrossSceneReference>(true) != null)
                {
                    CollectClassAndMember(type, prop);
                }
            }
        }
示例#34
0
        //http://www.codeguru.com/csharp/csharp/cs_syntax/reflection/article.php/c14531/NET-Tip-Display-All-Fields-and-Properties-of-an-Object.htm
        public static string GetObjectInfo <T>(this T instance, string fields) where T : class
        {
            StringBuilder sb = new StringBuilder();

            // Include the type of the object
            System.Type type = instance.GetType();
            sb.Append("Type: " + type.Name);

            // Include information for each Field
            sb.Append("\r\n\r\nFields:");
            System.Reflection.FieldInfo[] fi = type.GetFields();
            if (fi.Length > 0)
            {
                foreach (FieldInfo f in fi)
                {
                    sb.Append("\r\n " + f.ToString() + " = " + f.GetValue(instance));
                }
            }
            else
            {
                sb.Append("\r\n None");
            }

            // Include information for each Property
            sb.Append("\r\n\r\nProperties:");
            System.Reflection.PropertyInfo[] pi = type.GetProperties();
            if (pi.Length > 0)
            {
                foreach (PropertyInfo p in pi)
                {
                    if (fields.Contains(p.Name))
                    {
                        sb.Append("\r\n " + p.ToString() + " = " +
                                  p.GetValue(instance, null));
                    }
                }
            }
            else
            {
                sb.Append("\r\n None");
            }

            return(sb.ToString());
        }
示例#35
0
        public override string CreateTable(System.Type table)
        {
            string query = null;

            try
            {
                List <PropertyInfo> contrainte = new List <PropertyInfo>();

                query = "create table if not exists " + TableName(table) + "(";
                string id = null;
                foreach (PropertyInfo info in table.GetProperties(flag))
                {
                    string type = TypeName(info);
                    Object key  = info.GetCustomAttribute(typeof(Id));
                    if (key != null)
                    {
                        id    = ColonnName(info);
                        type += (key != null ? (key as Id).AutoIncrement ? " NOT NULL AUTO_INCREMENT" : " NOT NULL" : "");
                    }
                    Object obj = info.GetCustomAttribute(typeof(JoinColumn));
                    if (obj != null)
                    {
                        contrainte.Add(info);
                        PropertyInfo id1 = Key(info.PropertyType);
                        if (id1 != null)
                        {
                            type = TypeName(id1);
                        }
                    }
                    query += ColonnName(info) + " " + type + ",";
                }
                query += " Primary key (" + id + "), ";
                foreach (PropertyInfo item in contrainte)
                {
                    query += "FOREIGN KEY (" + ColonnName(item) + ") REFERENCES " + TableName(item.PropertyType) + "(" + ReferenceName(item) + ") ,";
                }
                query = query.Substring(0, query.Length - 1) + ")";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(query);
        }
示例#36
0
        private static void FindPropertyAttributes <T>(ShadowAssemblyType shadowAssembly, System.Type type,
                                                       List <AttributeResult <T> > attributesFound) where T : Attribute
        {
            try
            {
                var properties =
                    type.GetProperties(
                        BindingFlags.Public
                        | BindingFlags.NonPublic
                        | BindingFlags.Static
                        | BindingFlags.Instance);

                foreach (var property in properties)
                {
                    try
                    {
                        var propertyAttributes =
                            property
                            .GetCustomAttributes(true)
                            .Where(
                                attr =>
                                attr.GetType().FullName == typeof(T).FullName)
                            .ToList();

                        if (propertyAttributes.Count > 0)
                        {
                            var attribute = propertyAttributes.Cast <T>().First();
                            var info      = new AttributeResult <T>(shadowAssembly, type, property, attribute);
                            attributesFound.Add(info);
                        }
                    }
                    catch (Exception err)
                    {
                        "CryoAOP -> Warning! First chance exception ocurred while searching for Mixin Methods. \r\n{0}"
                        .Warn(err);
                    }
                }
            }
            catch (Exception err2)
            {
                "CryoAOP -> Warning! First chance exception ocurred while searching for Mixin Methods. \r\n{0}"
                .Warn(err2);
            }
        }
示例#37
0
		private void AddMembers(object o, TreeNodeCollection tnc) {
			System.Type t = o.GetType();
			foreach (FieldInfo f in t.GetFields(bindingFlags)) {
				object i = f.GetValue(o);
				AddKid(i, tnc, f.Name);
			}
			foreach (PropertyInfo pi in t.GetProperties(bindingFlags)) {
				if (pi.GetIndexParameters().Length == 0) {
					AddPropertyKid(tnc, pi, o);
				}
			}
			if (o is IList) {
				IList a = (IList) o;
				for (int i = 0; i < a.Count; i++) {
					object x = a[i];
					AddKid(x, tnc, "["+i.ToString()+"]");
				}
			}
		}
示例#38
0
    public string getObjectPropertiesString()
    {
        StringBuilder sb = new StringBuilder();

        System.Type    type       = this.GetType();
        PropertyInfo[] properties = type.GetProperties();

        foreach (PropertyInfo property in properties)
        {
            if (property.GetValue(this) != null)
            {
                var propertyArray = property.Name.Split('_');
                propertyArray[0] = "";
                sb.Append($"{String.Join("-", propertyArray).Remove(0,1)}=\"{property.GetValue(this)}\" ");
                // Debug.Log($"{property.Name.Split('_')[0]}={property.GetValue(this)} ");
            }
        }
        return(sb.ToString());
    }
示例#39
0
        private static object CopyOnlyForeignKeyProperties(object entity, System.Type entityType,
                                                           AbstractEntityPersister entityMetadata, DeepCloneOptions opts, DeepCloneParentEntity parentEntity)
        {
            var propertyInfos = entityType.GetProperties();

            //Copy only Fks
            foreach (var propertyInfo in propertyInfos
                     .Where(p => opts.CanCloneIdentifier(entityType) || entityMetadata.IdentifierPropertyName != p.Name)
                     .Where(p => !opts.GetIgnoreMembers(entityType).Contains(p.Name))
                     .Where(p => p.GetSetMethod(true) != null))
            {
                IType propertyType;
                try
                {
                    propertyType = entityMetadata.GetPropertyType(propertyInfo.Name);
                }
                catch (Exception)
                {
                    continue;
                }
                if (!NHibernateUtil.IsPropertyInitialized(entity, propertyInfo.Name))
                {
                    continue;
                }
                var propertyValue = propertyInfo.GetValue(entity, null);
                if (!NHibernateUtil.IsInitialized(propertyValue))
                {
                    continue;
                }

                var colNames = entityMetadata.GetPropertyColumnNames(propertyInfo.Name);
                if (!propertyType.IsEntityType)
                {
                    continue;
                }
                //Check if we have a parent entity and that is bidirectional related to the current property (one-to-many)
                if (parentEntity.ReferencedColumns.SequenceEqual(colNames))
                {
                    propertyInfo.SetValue(entity, parentEntity.Entity, null);
                }
            }
            return(entity);
        }
示例#40
0
        private void txt_edit_Load(object sender, EventArgs e)
        {
            List <string> heardlist = new List <string>();
            tmpdata       td        = session.blist.First();

            System.Type    t  = td.GetType();
            PropertyInfo[] ps = t.GetProperties();
            foreach (PropertyInfo i in ps)
            {
                object value = i.GetValue(td, null);
                if (value != null)
                {
                    string name = i.Name;
                    heardlist.Add(name);
                }
            }

            for (int i = 0; i < heardlist.Count; i++)
            {
                DataGridViewButtonColumn Column = new DataGridViewButtonColumn();
                string name = string.Format("tmpfiled{0}", i + 1);
                Column.Text             = name;
                Column.Name             = name;
                Column.HeaderText       = name;
                Column.DataPropertyName = name;
                dataGridView1.Columns.Add(Column);
            }
            dataGridView1.Font = new Font("宋体", 11, FontStyle.Regular);
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource          = session.blist.Take(5).ToList();
            comboBox1.DataSource = heardlist.Take(heardlist.Count()).ToList();
            comboBox1.Text       = heardlist[0].ToString();
            comboBox2.DataSource = heardlist.Take(heardlist.Count()).ToList();
            comboBox2.Text       = heardlist[1].ToString();
            comboBox3.DataSource = heardlist.Take(heardlist.Count()).ToList();
            comboBox3.Text       = heardlist[2].ToString();
            comboBox4.DataSource = heardlist.Take(heardlist.Count()).ToList();
            comboBox4.Text       = heardlist[3].ToString();
            comboBox5.DataSource = heardlist.Take(heardlist.Count()).ToList();
            comboBox5.Text       = heardlist[4].ToString();
            //comboBox6.DataSource = heardlist.Take(heardlist.Count()).ToList();
            //comboBox6.Text = heardlist[5].ToString();
        }
        public UserDefinedTypeImporter(System.Type realType)
        {
            RealType = realType;

            RealTypeName = UserDefinedTypeSupport.GetTypeName(realType);
            var fields     = realType.GetFields();
            var properties = realType.GetProperties();

            FieldSetters           = new System.Collections.Generic.Dictionary <string, SetterDelegate>(fields.Length + properties.Length + 1);
            FieldSetters["__Type"] = this.CheckType;
            foreach (var field in UserDefinedTypeSupport.GetFields(RealType))
            {
                FieldSetters[field.Name] = CreateFieldSetter(realType, field.Member);
            }
            foreach (var property in UserDefinedTypeSupport.GetProperties(RealType))
            {
                FieldSetters[property.Name] = CreatePropertySetter(realType, property.Member);
            }
        }
示例#42
0
    public override T AttachRenderTarget <T>(ResourceRenderTarget target, Resource.ResourceGroup rg)
    {
        base.AttachRenderTarget <T>(target, rg);
        System.Type type = Content.GetType();
        var         dst  = target.GetComponent(type) as T;

        if (!dst)
        {
            dst = target.gameObject.AddComponent(type) as T;
        }

        var fields = type.GetFields();

        foreach (var field in fields)
        {
            if (field.IsStatic)
            {
                continue;
            }
            field.SetValue(dst, field.GetValue(Content));
        }

        var props = type.GetProperties();

        foreach (var prop in props)
        {
            if (!prop.CanWrite || !prop.CanWrite || prop.Name == "name")
            {
                continue;
            }
            prop.SetValue(dst, prop.GetValue(Content, null), null);
        }
        target.transform.localPosition = Vector3.zero;
        RectTransform rect = target.GetComponent <RectTransform>();

        rect.anchoredPosition = rectTranfrom.anchoredPosition;
        var cont = target.gameObject.AddComponent <ContentSizeFitter> ();

        cont.verticalFit   = ContentSizeFitter.FitMode.PreferredSize;
        cont.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
        target.SetTarget(rg);
        return(dst);
    }
示例#43
0
        private static List <PropertyInfo> GetKeyColumns(System.Type type)
        {
            List <PropertyInfo> retval = new List <PropertyInfo>();

            PropertyInfo[] props = type.GetProperties();
            foreach (PropertyInfo prop in props)
            {
                IEnumerable <Attribute>    attributes = prop.GetCustomAttributes(true).OfType <System.Attribute>().AsEnumerable();
                EdmScalarPropertyAttribute edmScalarPropertyAttribute = attributes.OfType <EdmScalarPropertyAttribute>().FirstOrDefault();
                if (edmScalarPropertyAttribute != null)
                {
                    if (edmScalarPropertyAttribute.EntityKeyProperty == true)
                    {
                        retval.Add(prop);
                    }
                }
            }
            return(retval);
        }
示例#44
0
        // extract expression tree
        private static Expression GetExpression(Expression expr, System.Type entityType, System.String propName)
        {
            System.Reflection.PropertyInfo[] props = entityType.GetProperties(System.Reflection.BindingFlags.Public |
                                                                              System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Instance);

            if (propName.Contains('.'))
            {
                System.String navEntityName = string.Empty;

                navEntityName = propName.Split(new char[] { '.' }, 2)[0];
                propName      = propName.Split(new char[] { '.' }, 2)[1];

                System.Type propType = props.Where(p => p.Name == navEntityName).First().PropertyType;

                return(GetExpression(Expression.Property(expr, navEntityName), propType, propName));
            }

            return(Expression.Property(expr, propName));
        }
示例#45
0
        static void AddProperties(GType gtype, System.Type t)
        {
            uint idx = 1;

            bool handlers_overridden = false;

            foreach (PropertyInfo pinfo in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                foreach (object attr in pinfo.GetCustomAttributes(typeof(PropertyAttribute), false))
                {
                    if (pinfo.GetIndexParameters().Length > 0)
                    {
                        throw(new InvalidOperationException(String.Format("GLib.RegisterPropertyAttribute cannot be applied to property {0} of type {1} because the property expects one or more indexed parameters", pinfo.Name, t.FullName)));
                    }

                    PropertyAttribute property_attr = attr as PropertyAttribute;
                    if (!handlers_overridden)
                    {
                        gtksharp_override_property_handlers(gtype.Val, GetPropertyHandler, SetPropertyHandler);
                        handlers_overridden = true;
                    }

                    IntPtr native_name  = GLib.Marshaller.StringToPtrGStrdup(property_attr.Name);
                    IntPtr native_nick  = GLib.Marshaller.StringToPtrGStrdup(property_attr.Nickname);
                    IntPtr native_blurb = GLib.Marshaller.StringToPtrGStrdup(property_attr.Blurb);

                    IntPtr param_spec = gtksharp_register_property(gtype.Val, native_name, native_nick, native_blurb, idx, ((GType)pinfo.PropertyType).Val, pinfo.CanRead, pinfo.CanWrite);

                    GLib.Marshaller.Free(native_name);
                    GLib.Marshaller.Free(native_nick);
                    GLib.Marshaller.Free(native_blurb);

                    if (param_spec == IntPtr.Zero)
                    {
                        // The GType of the property is not supported
                        throw new InvalidOperationException(String.Format("GLib.PropertyAttribute cannot be applied to property {0} of type {1} because the return type of the property is not supported", pinfo.Name, t.FullName));
                    }

                    Properties.Add(param_spec, pinfo);
                    idx++;
                }
            }
        }
示例#46
0
        /// <summary>
        /// 加载模块实例。
        /// </summary>
        /// <param name="wfAddIn"></param>
        /// <param name="instanceID"></param>
        internal static void LoadWorkflowInstance(object wfAddIn, bool isEnabled, Guid instanceID)
        {
            System.Type T = wfAddIn.GetType();
            System.Reflection.PropertyInfo propertyInfo = null;
            foreach (System.Reflection.PropertyInfo item in T.GetProperties())
            {
                WorkflowInstanceIdAttribute wfa = Attribute.GetCustomAttribute(item, typeof(WorkflowInstanceIdAttribute)) as WorkflowInstanceIdAttribute;
                if (!Object.Equals(null, wfa))
                {
                    propertyInfo = item;
                    break;
                }
            }

            if (propertyInfo != null)
            {
                propertyInfo.SetValue(wfAddIn, instanceID, new object[] { });
            }
        }
示例#47
0
        static void AddProperties(GType gtype, System.Type t, bool register_instance_prop)
        {
            uint idx = 1;

            if (register_instance_prop)
            {
                IntPtr    declaring_class = gtype.GetClassPtr();
                ParamSpec pspec           = new ParamSpec("gtk-sharp-managed-instance", "", "", GType.Pointer, ParamFlags.Writable | ParamFlags.ConstructOnly);
                g_object_class_install_property(declaring_class, idx, pspec.Handle);
                idx++;
            }

            bool handlers_overridden = register_instance_prop;

            foreach (PropertyInfo pinfo in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                foreach (object attr in pinfo.GetCustomAttributes(typeof(PropertyAttribute), false))
                {
                    if (pinfo.GetIndexParameters().Length > 0)
                    {
                        throw(new InvalidOperationException(String.Format("GLib.RegisterPropertyAttribute cannot be applied to property {0} of type {1} because the property expects one or more indexed parameters", pinfo.Name, t.FullName)));
                    }

                    if (!handlers_overridden)
                    {
                        IntPtr       class_ptr     = gtype.GetClassPtr();
                        GObjectClass gobject_class = (GObjectClass)Marshal.PtrToStructure(class_ptr, typeof(GObjectClass));
                        gobject_class.get_prop_cb = GetPropertyHandler;
                        gobject_class.set_prop_cb = SetPropertyHandler;
                        Marshal.StructureToPtr(gobject_class, class_ptr, false);
                        handlers_overridden = true;
                    }
                    PropertyAttribute property_attr = attr as PropertyAttribute;
                    try {
                        IntPtr param_spec = RegisterProperty(gtype, property_attr.Name, property_attr.Nickname, property_attr.Blurb, idx, (GType)pinfo.PropertyType, pinfo.CanRead, pinfo.CanWrite);
                        Properties.Add(param_spec, pinfo);
                        idx++;
                    } catch (ArgumentException) {
                        throw new InvalidOperationException(String.Format("GLib.PropertyAttribute cannot be applied to property {0} of type {1} because the return type of the property is not supported", pinfo.Name, t.FullName));
                    }
                }
            }
        }
示例#48
0
        /// <summary>
        /// The function which registers a view and all it's scriptable properties with DALi's type registry.
        /// Means the view can be created or configured from a JSON script.
        ///
        /// The function uses introspection to scan a views C# properties, then selects the ones with
        ///[ScriptableProperty] attribute to be registered.
        /// Example of a Spin view registering itself:
        ///   static Spin()
        /// {
        ///   ViewRegistry registers control type with DALi type registery
        ///   also uses introspection to find any properties that need to be registered with type registry
        ///   ViewRegistry.Instance.Register(CreateInstance, typeof(Spin) );
        /// }
        ///
        /// </summary>
        /// <since_tizen> 3 </since_tizen>
        public void Register(Func <CustomView> createFunction, System.Type viewType)
        {
            // add the mapping between the view name and it's create function
            _constructorMap.Add(viewType.ToString(), createFunction);

            // Call into DALi C++ to register the control with the type registry
            TypeRegistration.RegisterControl(viewType.ToString(), _createCallback);

            // Cycle through each property in the class
            foreach (System.Reflection.PropertyInfo propertyInfo in viewType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public))
            {
                if (propertyInfo.CanRead)
                {
                    IEnumerable <Attribute> ie_attrs = propertyInfo.GetCustomAttributes <Attribute>();
                    List <Attribute>        li_attrs = new List <Attribute>(ie_attrs);
                    System.Attribute[]      attrs    = li_attrs.ToArray();

                    foreach (System.Attribute attr in attrs)
                    {
                        // If the Scriptable attribute exists, then register it with the type registry.
                        if (attr is ScriptableProperty)
                        {
                            NUILog.Debug("Got a DALi JSON scriptable property = " + propertyInfo.Name + ", of type " + propertyInfo.PropertyType.Name);

                            // first get the attribute type, ( default, or animatable)
                            ScriptableProperty scriptableProp = attr as ScriptableProperty;

                            // we get the start property index, based on the type and it's heirachy, e.g. DateView (70,000)-> Spin (60,000) -> View (50,000)
                            int propertyIndex = _propertyRangeManager.GetPropertyIndex(viewType.ToString(), viewType, scriptableProp.type);

                            // get the enum for the property type... E.g. registering a string property returns Tizen.NUI.PropertyType.String
                            Tizen.NUI.PropertyType propertyType = GetDaliPropertyType(propertyInfo.PropertyType.Name);

                            // Example   RegisterProperty("spin","maxValue", 50001, FLOAT, set, get );
                            // Native call to register the property
                            TypeRegistration.RegisterProperty(viewType.ToString(), propertyInfo.Name, propertyIndex, propertyType, _setPropertyCallback, _getPropertyCallback);
                        }
                    }
                    NUILog.Debug("property name = " + propertyInfo.Name);
                }
            }
        }
        public static PropertyInfo[] GetPublicProperties(System.Type type)
        {
            // Naively copied from https://stackoverflow.com/questions/358835/getproperties-to-return-all-properties-for-an-interface-inheritance-hierarchy
            if (type.IsInterface)
            {
                var propertyInfos = new List <PropertyInfo>();

                var considered = new List <System.Type>();
                var queue      = new Queue <System.Type>();
                considered.Add(type);
                queue.Enqueue(type);
                while (queue.Count > 0)
                {
                    var subType = queue.Dequeue();
                    foreach (var subInterface in subType.GetInterfaces())
                    {
                        if (considered.Contains(subInterface))
                        {
                            continue;
                        }

                        considered.Add(subInterface);
                        queue.Enqueue(subInterface);
                    }

                    var typeProperties = subType.GetProperties(
                        BindingFlags.FlattenHierarchy
                        | BindingFlags.Public
                        | BindingFlags.Instance);

                    var newPropertyInfos = typeProperties
                                           .Where(x => !propertyInfos.Contains(x));

                    propertyInfos.InsertRange(0, newPropertyInfos);
                }

                return(propertyInfos.ToArray());
            }

            return(type.GetProperties(BindingFlags.FlattenHierarchy
                                      | BindingFlags.Public | BindingFlags.Instance));
        }
示例#50
0
        public static string DisplayObjectInfo(Object o)
        {
            StringBuilder sb = new StringBuilder();

            // Include the type of the object
            System.Type type = o.GetType();
            sb.Append("Type: " + type.Name);

            // Include information for each Field
            sb.Append("\r\n\r\nFields:");
            System.Reflection.FieldInfo[] fi = type.GetFields();
            if (fi.Length > 0)
            {
                foreach (FieldInfo f in fi)
                {
                    sb.Append("\r\n " + f.ToString() + " = " +
                              f.GetValue(o));
                }
            }
            else
            {
                sb.Append("\r\n None");
            }

            // Include information for each Property
            sb.Append("\r\n\r\nProperties:");
            System.Reflection.PropertyInfo[] pi = type.GetProperties();
            if (pi.Length > 0)
            {
                foreach (PropertyInfo p in pi)
                {
                    sb.Append("\r\n " + p.ToString() + " = " +
                              p.GetValue(o, null));
                }
            }
            else
            {
                sb.Append("\r\n None");
            }

            return(sb.ToString());
        }
示例#51
0
        private void AddReportDataSource(object ReportSource, string ReportDataSetName)
        {
            System.Type type = ReportSource.GetType();

            if (type == null)
            {
                System.Windows.Forms.MessageBox.Show("Report Viewr: \r\n   The datasource is of the wrong type!");
                return;
            }
            else
            {
                System.Reflection.PropertyInfo[] picData = type.GetProperties();
                bool bolExist = false;
                foreach (System.Reflection.PropertyInfo piData in picData)
                {
                    if (piData.Name == "Tables")
                    {
                        bolExist = true;

                        if (ReportDataSetName == string.Empty)
                        {
                            System.Windows.Forms.MessageBox.Show("Report Viewr: \r\n    The dataset name for the report does not exist or is empty!");
                            return;
                        }

                        this.rptViewer.LocalReport.DataSources.Add(
                            new Microsoft.Reporting.WinForms.ReportDataSource(ReportDataSetName,
                                                                              (piData.GetValue(ReportSource, null) as System.Data.DataTableCollection)[0])
                            );
                        this.rptViewer.RefreshReport();

                        break;
                    }
                }

                if (!bolExist)
                {
                    System.Windows.Forms.MessageBox.Show("Report Viewr: \r\n    The datasource is of the wrong type!");
                    return;
                }
            }
        }
示例#52
0
        /// <summary>
        /// 指定された型に対するマッピング情報を生成します。
        /// </summary>
        /// <param name="type">対象となる型情報</param>
        /// <returns>テーブルマッピング情報</returns>
        public static This Create(System.Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            This result = null;

            lock (This.Cache)
            {
                //--- キャッシュから取得
                if (!This.Cache.TryGetValue(type, out result))
                {
                    //--- テーブル情報
                    var table = type.GetCustomAttribute <TableAttribute>(false);
                    result = new This()
                    {
                        Schema = table?.Schema ?? null,
                        Name   = table?.Name ?? type.Name,
                        Type   = type
                    };

                    //--- 列情報(モデル内に存在するコレクションは除外する
                    var flags     = BindingFlags.Instance | BindingFlags.Public;
                    var notMapped = typeof(NotMappedAttribute);

                    //typeMapに存在するカラムだけを対象にする
                    var targetProperties = type.GetProperties(flags)
                                           .Where(x => TypeMap.ContainsKey(x.PropertyType));

                    result.Columns = targetProperties
                                     .Where(x => x.CustomAttributes.All(y => y.AttributeType != notMapped))
                                     .Select(FieldMappingInfo.From)
                                     .ToArray();

                    //--- キャッシュ
                    This.Cache.TryAdd(type, result);
                }
            }
            return(result);
        }
示例#53
0
        private List <RName> FreshByType(System.Type type)
        {
            var          macrossObject = System.Activator.CreateInstance(type);
            List <RName> result        = new List <RName>();
            var          props         = type.GetProperties();

            foreach (var i in props)
            {
                if (i.PropertyType == typeof(RName))
                {
                    var rn = i.GetValue(macrossObject) as RName;
                    if (result.Contains(rn) == false)
                    {
                        result.Add(rn);
                    }
                }
            }

            return(result);
        }
示例#54
0
        public void CreateDesc(System.Type klassType)
        {
            System.Type objType = klassType;
            System.Reflection.PropertyInfo[] fields = objType.GetProperties();

            Fields.Clear();
            foreach (System.Reflection.PropertyInfo i in fields)
            {
                System.Object[] attrs = i.GetCustomAttributes(typeof(ServerFrame.DB.DBBindField), true);
                if (attrs.Length == 0)
                {
                    continue;
                }

                IAutoDBField f = new IAutoDBField();
                f.Property = i;
                f.Field    = (attrs[0] as ServerFrame.DB.DBBindField).Field;
                Fields.Add(f);
            }
        }
        private static Dictionary <string, string> getColumns(System.Type type)
        {
            Dictionary <string, string> columnNames = new Dictionary <string, string>();
            IEnumerable <PropertyInfo>  properties  =
                from p in type.GetProperties()
                where p.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault <object>() != null
                select p;

            if (properties.Count <PropertyInfo>() == 0)
            {
                throw new Exception("Column attributes not found on type " + type.Name);
            }
            columnNames = new Dictionary <string, string>();
            foreach (PropertyInfo p2 in properties)
            {
                ColumnAttribute colAttribute = (ColumnAttribute)p2.GetCustomAttributes(typeof(ColumnAttribute), true).First <object>();
                columnNames[colAttribute.Name] = "@" + p2.Name;
            }
            return(columnNames);
        }
示例#56
0
        public static void DumpPublicProperties(System.Type type)
        {
            var props = type
                        .GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)
                        .Select(p => new
            {
                Name = p.Name,
                Type = p.PropertyType.Name,
                NullableAttribute =
                    p.GetCustomAttributes(false)
                    .OfType <NullableAttribute> ()
                    .FirstOrDefault()
                    .GetDescription()
            });

            foreach (var prop in props)
            {
                Console.WriteLine($"{type.Name}.{prop.Name}: {prop.Type}, {prop.NullableAttribute}");
            }
        }
示例#57
0
        public void CopyComponent(ReplacementPreferences replacementPreferences, Component original, GameObject newObject)
        {
            System.Type   type         = original.GetType();
            ISet <string> partAvoiders = componentPartAvoiders.ContainsKey(type) ? componentPartAvoiders[type] : null;
            var           dst          = newObject.GetComponent(type);

            if (!dst)
            {
                dst = newObject.AddComponent(type);
            }
            var fields = type.GetFields();

            foreach (var field in fields)
            {
                if (field.IsStatic)
                {
                    continue;
                }
                if (partAvoiders != null && partAvoiders.Contains(field.Name))
                {
                    continue;
                }
                field.SetValue(dst, field.GetValue(original));
            }
            var props = type.GetProperties();

            foreach (var prop in props)
            {
                if (!prop.CanWrite || prop.Name == "name" || prop.Name == "parent")
                {
                    continue;
                }
                if (partAvoiders != null && partAvoiders.Contains(prop.Name))
                {
                    continue;
                }
                prop.SetValue(dst, prop.GetValue(original));
            }
            // NOTE: Some properties are references to other things and a prefab replacement can break them.
            // TODO: Should we record any reference types in order to map them to new references later?
        }
        private static void RemoveDeletedProperties(List <CustomProperty> propCollection, System.Type customActivityType, IServiceProvider serviceProvider)
        {
            IMemberCreationService service = serviceProvider.GetService(typeof(IMemberCreationService)) as IMemberCreationService;

            if (service == null)
            {
                throw new Exception(SR.GetString("General_MissingService", new object[] { typeof(IMemberCreationService).FullName }));
            }
            foreach (PropertyInfo info in customActivityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                bool flag = false;
                foreach (CustomProperty property in propCollection)
                {
                    if ((info.Name == property.oldPropertyName) && (info.PropertyType.FullName == property.oldPropertyType))
                    {
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    service.RemoveProperty(customActivityType.FullName, info.Name, info.PropertyType);
                }
            }
            foreach (EventInfo info2 in customActivityType.GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                bool flag2 = false;
                foreach (CustomProperty property2 in propCollection)
                {
                    if ((info2.Name == property2.oldPropertyName) && (info2.EventHandlerType.FullName == property2.oldPropertyType))
                    {
                        flag2 = true;
                        break;
                    }
                }
                if ((!flag2 && (info2.Name != null)) && (info2.EventHandlerType != null))
                {
                    service.RemoveEvent(customActivityType.FullName, info2.Name, info2.EventHandlerType);
                }
            }
        }
示例#59
0
        public override void BuildRuleSet()
        {
            System.Type value = typeof(T);

            var props = value.GetProperties();
            var xdoc  = XDocument.Load(Environment.CurrentDirectory + @"\RulesConfig\" + value.Name + ".xml");

            foreach (var prop in props)
            {
                var rulesAtts = new List <ValidationAttribute>();
                foreach (var itm in xdoc.Descendants("Property"))
                {
                    if (itm.Attribute("Name").Value == prop.Name)
                    {
                        foreach (var item in itm.Descendants("Validator"))
                        {
                            var validationType = item.Attribute("Type").Value;
                            if (validationType == "MaxLenField")
                            {
                                var errmsg = item.Attribute("ErrorMessage").Value;
                                var max    = item.Attribute("Max").Value;
                                rulesAtts.Add(new MaxLenFieldAttribute(prop.Name, errmsg, Convert.ToInt32(max)));
                            }
                            if (validationType == "RequiredField")
                            {
                                var errmsg = item.Attribute("ErrorMessage").Value;
                                rulesAtts.Add(new RequiredFieldAttribute(prop.Name, errmsg));
                            }
                        }
                    }
                }
                var ruleItems = new List <ValidationAttribute>();

                foreach (var rule in rulesAtts)
                {
                    var ruleAttribute = rule as ValidationAttribute;
                    ruleItems.Add(ruleAttribute);
                }
                Rules[prop.Name] = ruleItems;
            }
        }
示例#60
-1
        /// <summary>
        /// Recursivly scan the types to build up a list of expressions to access everything.
        /// </summary>
        /// <param name="streamType"></param>
        /// <param name="expressionToAccess"></param>
        /// <param name="visitor"></param>
        protected static void ScanExpressions (Type streamType, Expression expressionToAccess, Action<Expression> visitor)
        {
            // If this is a leaf, then dump it.
            if (streamType.TypeIsEasilyDumped())
            {
                visitor(expressionToAccess);
            }

            // If it is a tuple, then we will have to go down one.
            else if (streamType.Name.StartsWith("Tuple"))
            {
                var targs = streamType.GenericTypeArguments.Zip(Enumerable.Range(1, 100), (t, c) => Tuple.Create(t, c));
                foreach (var templateType in targs)
                {
                    var access = Expression.PropertyOrField(expressionToAccess, $"Item{templateType.Item2}");
                    ScanExpressions(templateType.Item1, access, visitor);
                }
            }

            // Now look at the fields and properties.
            else if ((streamType.GetFields().Length + streamType.GetProperties().Length) > 0)
            {
                foreach (var fName in (streamType.GetFieldsInDeclOrder().Select(f => f.Name).Concat(streamType.GetProperties().Select(p => p.Name))))
                {
                    var access = Expression.PropertyOrField(expressionToAccess, fName);
                    ScanExpressions(access.Type, access, visitor);
                }
            }

            // Really bad if we get here!
            else
            {
                throw new InvalidOperationException($"Do not know how to generate values for a file from a sequence of {streamType.Name} objects!");
            }
        }