Exemplo n.º 1
0
        public Search(Dictionary<string, string> searchTerms, System.Type type, FormStorage<bool> storage)
        {
            _searchTerms = searchTerms;
            _storage = storage;
            _searchList = new BindingList<string>();

            InitializeComponent();

            List<string> list = type.GetProperties().Select(p => p.Name).ToList();

            this.comboCriteria.DataSource = type.GetProperties().Select(p => p.Name).ToList();
            this.listSearchTerms.DataSource = _searchList;
            this.buttonRemove.Enabled = false;
        }
Exemplo n.º 2
0
 public static IEnumerable<DeclaredPersistentProperty> PersistentInfo(System.Type @class, IEnumerable<Property> properties, bool includeEmbedded)
 {
     // a persistent property can be anything including a noop "property" declared in the mapping
     // for query only. In this case I will apply some trick to get the MemberInfo.
     var candidateMembers =
         @class.GetFields(DefaultBindingFlags).Concat(@class.GetProperties(DefaultBindingFlags).Cast<MemberInfo>()).ToList();
     var candidateMembersNames = candidateMembers.Select(m => m.Name).ToList();
     foreach (var property in properties)
     {
         if(includeEmbedded && property.PropertyAccessorName=="embedded")
             yield return new DeclaredPersistentProperty(property, DeclaredPersistentProperty.NotAvailableMemberInfo);
         var exactMemberIdx = candidateMembersNames.IndexOf(property.Name);
         if (exactMemberIdx >= 0)
         {
             // No metter which is the accessor the audit-attribute should be in the property where available and not
             // to the member used to read-write the value. (This method work even for access="field").
             yield return new DeclaredPersistentProperty(property, candidateMembers[exactMemberIdx]);
         }
         else
         {
             // try to find the field using field-name-strategy
             //
             // This part will run for:
             // 1) query only property (access="none" or access="noop")
             // 2) a strange case where the element <property> is declared with a "field.xyz" but only a field is used in the class. (Only God may know way)
             var exactFieldIdx = GetMemberIdxByFieldNamingStrategies(candidateMembersNames, property);
             if (exactFieldIdx >= 0)
             {
                 yield return new DeclaredPersistentProperty(property, candidateMembers[exactFieldIdx]);
             }
         }
     }
 }
 private static List<PropertyInfo> GetInterfaceProperties(System.Type interfaceToReflect, List<PropertyInfo> properties)
 {
     var interfaces = interfaceToReflect.GetInterfaces();
     foreach (var inter in interfaces)
     {
         properties.AddRange(GetInterfaceProperties(inter, properties));
     }
     properties.AddRange(interfaceToReflect.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList());
     return properties.Distinct().OrderBy(i => i.Name).ToList();
 }
        private void searchForRevisionInfoCfgInProperties(System.Type t, ref bool revisionNumberFound, 
                        ref bool revisionTimestampFound, String accessType) {
           
            foreach (PropertyInfo property in t.GetProperties()) {
                //RevisionNumber revisionNumber = property.getAnnotation(RevisionNumber.class);
                RevisionNumberAttribute revisionNumber = (RevisionNumberAttribute)Attribute.GetCustomAttribute(property, typeof(RevisionNumberAttribute));
                RevisionTimestampAttribute revisionTimestamp = (RevisionTimestampAttribute)Attribute.GetCustomAttribute(property, typeof(RevisionTimestampAttribute));

                if (revisionNumber != null) {
                    if (revisionNumberFound) {
                        throw new MappingException("Only one property may have the attribute [RevisionNumber]!");
                    }

                    System.Type revNrType = property.PropertyType;
                    if (revNrType.Equals( typeof(int)) || revNrType.Equals( typeof(Int16)) || revNrType.Equals( typeof(Int32)) || revNrType.Equals( typeof(Int64))) {
                        revisionInfoIdData = new PropertyData(property.Name, property.Name, accessType, ModificationStore._NULL);
                        revisionNumberFound = true;
                    } else if (revNrType.Equals(typeof(long))) {
                        revisionInfoIdData = new PropertyData(property.Name, property.Name, accessType, ModificationStore._NULL);
                        revisionNumberFound = true;

                        // The default is integer
                        revisionPropType = "long";
                    } else {
                        throw new MappingException("The field decorated with [RevisionNumberAttribute] must be of type " +
                                "int, Int16, Int32, Int64 or long");
                    }

                    // Getting the @Column definition of the revision number property, to later use that info to
                    // generate the same mapping for the relation from an audit table's revision number to the
                    // revision entity revision number.
                    ColumnAttribute revisionPropColumn = (ColumnAttribute)Attribute.GetCustomAttribute(property,typeof(ColumnAttribute));
                    if (revisionPropColumn != null) {
                        revisionPropSqlType = revisionPropColumn.columnDefinition;
                    }
                }

                if (revisionTimestamp != null) {
                    if (revisionTimestampFound) {
                        throw new MappingException("Only one property may be decorated with [RevisionTimestampAttribute]!");
                    }

                    System.Type revisionTimestampType = property.GetType();
                    if (typeof(DateTime).Equals(revisionTimestampType)) {
                        revisionInfoTimestampData = new PropertyData(property.Name, property.Name, accessType, ModificationStore._NULL);
                        revisionTimestampFound = true;
                    } else {
                        throw new MappingException("The field decorated with @RevisionTimestamp must be of type DateTime");
                    }
                }
            }
        }
	    private void AddPropertiesFromClass(System.Type clazz)  {
            //No need to go to base class, the .NET GetProperty method can bring the base properties also
            //System.Type superclazz = clazz.BaseType;
            //if (!"System.Object".Equals(superclazz.FullName))
            //{
            //    AddPropertiesFromClass(superclazz);
            //}

            //ORIG: addFromProperties(clazz.getDeclaredProperties("field"), "field", fieldAccessedPersistentProperties);
            //addFromProperties(clazz.getDeclaredProperties("property"), "property", _propertyAccessedPersistentProperties);

            //only one call is needed, .NET does not differentiate between field and property
            //AddFromProperties(clazz.GetProperties(BindingFlags.GetField), "field", _fieldAccessedPersistentProperties);
            AddFromProperties(clazz.GetProperties(), "property", _propertyAccessedPersistentProperties);
	    }
Exemplo n.º 6
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;
            }
        }
Exemplo n.º 7
0
        protected override IList<Newtonsoft.Json.Serialization.JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization)
        {
            var props = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            List<Newtonsoft.Json.Serialization.JsonProperty> jsonProps = new List<Newtonsoft.Json.Serialization.JsonProperty>();

            foreach (var prop in props)
            {
                jsonProps.Add(base.CreateProperty(prop, memberSerialization));
            }

            foreach (var field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
            {
                jsonProps.Add(base.CreateProperty(field, memberSerialization));
            }

            jsonProps.ForEach(p => { p.Writable = true; p.Readable = true; });
            return jsonProps;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Configures the display of the list view control based upon the attributes exposed by the object
        /// </summary>
        /// <param name="ObjType"></param>
        public void SetDisplayType(System.Type ObjType)
        {
            List<string> ColumnList = new List<String>();
            PropertyInfo[] Properties = ObjType.GetProperties();
            List<PropertyInfo> listPropInfoForColumn = new List<PropertyInfo>();
            foreach(PropertyInfo Property in Properties)
            {
                ColumnAttribute[] Attributes = Property.GetCustomAttributes(typeof(ColumnAttribute), true) as ColumnAttribute[];
                foreach (ColumnAttribute Attrib in Attributes)
                {
                    ColumnList.Add(Attrib.ColumnName);
                    listPropInfoForColumn.Add(Property);
                }

                if (Property.GetCustomAttributes(typeof(ThisToOneRelationAttribute), true).Length > 0)
                {
                    ColumnList.Add(Property.Name);
                    listPropInfoForColumn.Add(Property);
                }
            }

            Trace.WriteLineIf(ColumnList.Count == 0, "No columns defined for type: " + ObjType.ToString(), "UI");

            this.BeginUpdate();

            this.Items.Clear();
            this.Columns.Clear();

            this.Columns.Add("Name", 150, HorizontalAlignment.Left);

            foreach(string ColumnName in ColumnList)
            {
                this.Columns.Add(ColumnName, _ColumnDefaultWidth, HorizontalAlignment.Left);
            }

            this.EndUpdate();

            this.ColumnProperties = listPropInfoForColumn.ToArray();
            /*
            this.ColumnProperties = new PropertyInfo[ColumnList.Count];
            for(int iColumn = 0; iColumn < ColumnList.Count; iColumn++)
            {
                ColumnHeader Column = this.Columns[iColumn + 1];
                ColumnProperties[iColumn] = ObjType.GetProperty(listPropInfoForColumn[iColumn].Name);
                Debug.Assert(ColumnProperties[iColumn] != null);
            }
             */

            LoadColumnVisibilitySettings();
        }
Exemplo n.º 9
0
		private void CreateControlContentForSingleEntry (CVM.TableLayoutDefinition ContentInstance,
									System.Type ContentClass, Grid Parent)
			{
			Parent.Children.Clear ();
			Parent.RowDefinitions.Clear ();
			Parent.ColumnDefinitions.Clear ();
			PropertyInfo [] Properties = ContentClass.GetProperties ();
			GridLengthConverter GLConverter = new GridLengthConverter ();

			int RowIndex = 0;
			foreach (PropertyInfo PropInfo in Properties)
				{
				String LabePropertyName = PropInfo.Name;
				String OptionStringName = LabePropertyName + "_Option";
				FieldInfo OptionField = (FieldInfo)ContentClass.GetField (OptionStringName);
				String Options;
				if (OptionField != null)
					{
					Options = (String)OptionField.GetValue (ContentInstance);
					if (Options.IndexOf ("NoUpdate") != -1)
						continue;
					}
				String HelpStringName = LabePropertyName + "_Help";
				FieldInfo HelpField = (FieldInfo) ContentClass.GetField (HelpStringName);
				RowDefinition MainRow = new RowDefinition ();
				Parent.RowDefinitions.Add (MainRow);
				Grid SubGrid = new Grid ();
				Parent.Children.Add (SubGrid);
				Grid.SetRow (SubGrid, RowIndex++);
				Grid.SetColumn (SubGrid, 0);
				Label PropertyNameLabel = new Label ();
				PropertyNameLabel.Content = LabePropertyName;
				SubGrid.Children.Add (PropertyNameLabel);
				Grid.SetRow (PropertyNameLabel, 0);
				SubGrid.ColumnDefinitions.Add (new ColumnDefinition ());
				SubGrid.ColumnDefinitions [0].Width = (GridLength)GLConverter.ConvertFromString ("6" + "*");
				SubGrid.ColumnDefinitions.Add (new ColumnDefinition ());
				SubGrid.ColumnDefinitions [1].Width = (GridLength)GLConverter.ConvertFromString ("8" + "*");
				SubGrid.RowDefinitions.Add (new RowDefinition ());
				SubGrid.RowDefinitions [0].Height = (GridLength)GLConverter.ConvertFromString ("*");
				if (PropInfo.PropertyType == typeof (int))
					{
					TextBox ContentBox = CreateSimpleLine (ContentInstance, PropInfo, MainRow, SubGrid, HelpField);
					}
				if (PropInfo.PropertyType == typeof (double))
					{
					TextBox ContentBox = CreateSimpleLine (ContentInstance, PropInfo, MainRow, SubGrid, HelpField);
					}
				if (PropInfo.PropertyType == typeof (Size))
					{
					TextBox [] ContentBoxes = CreateTwoSubLines (ContentInstance, PropInfo, MainRow, SubGrid,
						new String [] { "Weite", "Höhe" }, HelpField);
					}
				if (PropInfo.PropertyType == typeof (Point))
					{
					TextBox [] ContentBoxes = CreateTwoSubLines (ContentInstance, PropInfo, MainRow, SubGrid,
						new String [] { "Links", "Oben" }, HelpField);
					}
				if (PropInfo.PropertyType == typeof (String))
					{
					TextBox ContentBox = CreateSimpleLine (ContentInstance, PropInfo, MainRow, SubGrid, HelpField);
					}
				if (PropInfo.PropertyType == typeof (bool))
					{
					RadioButton [] Buttons = CreateBoolLine (ContentInstance, PropInfo, MainRow, SubGrid,
						new String [] { "Ja", "Nein" }, HelpField);
					}
				}

			}
 private static PropertyInfo GetTypedIndexer(System.Type type)
 {
     if ((!typeof(IList).IsAssignableFrom(type) && !typeof(ITypedList).IsAssignableFrom(type)) && !typeof(IListSource).IsAssignableFrom(type))
     {
         return null;
     }
     PropertyInfo info = null;
     PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
     for (int i = 0; i < properties.Length; i++)
     {
         if ((properties[i].GetIndexParameters().Length > 0) && (properties[i].PropertyType != typeof(object)))
         {
             info = properties[i];
             if (info.Name == "Item")
             {
                 return info;
             }
         }
     }
     return info;
 }
Exemplo n.º 11
0
        private void ListProperties(System.Type objType)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            ed.WriteMessage("\nReadable Properties for: " + objType.Name + " : ");

            PropertyInfo[] propInfos = objType.GetProperties();
            foreach (PropertyInfo propInfo in propInfos)
            {
                if (propInfo.CanRead)
                {
                    ed.WriteMessage("\n " + propInfo.Name + " : " + propInfo.PropertyType);
                }
            }
            ed.WriteMessage(System.Environment.NewLine); // "\n";
        }
Exemplo n.º 12
0
        private void BindClass(System.Type entity, PersistentClass pclass)
        {
            pclass.IsLazy = true;
            pclass.EntityName = entity.FullName;
            pclass.ClassName = entity.AssemblyQualifiedName;
            pclass.ProxyInterfaceName = entity.AssemblyQualifiedName;
            string tableName = GetClassTableName(pclass);
            Table table = mappings.AddTable(null, null, tableName, null, pclass.IsAbstract.GetValueOrDefault(), null);
            ((ITableOwner) pclass).Table = table;
            pclass.IsMutable = true;
            PropertyInfo[] propInfos = entity.GetProperties();

            PropertyInfo toExclude = new IdBinder(this, propInfos).Bind(pclass, table);

            pclass.CreatePrimaryKey(dialect);
            BindProperties(pclass, propInfos.Where(x => x != toExclude));
            mappings.AddClass(pclass);

            string qualifiedName = pclass.MappedClass == null ? pclass.EntityName : pclass.MappedClass.AssemblyQualifiedName;
            mappings.AddImport(qualifiedName, pclass.EntityName);
            if (mappings.IsAutoImport && pclass.EntityName.IndexOf('.') > 0) {
                mappings.AddImport(qualifiedName, StringHelper.Unqualify(pclass.EntityName));
            }
        }
		/// <summary>
		/// Resolves mapping type in target type without caching and returning with Exception
		/// if Mapping does not exists
		/// </summary>
		/// <param name="aTarget">
		/// Object type to resolve property from <see cref="System.Type"/>
		/// </param>
		/// <param name="aMapping">
		/// Property name <see cref="System.String"/>
		/// </param>
		/// <param name="aThrowException">
		/// Set true if throwing exception on non success is needed <see cref="System.Boolean"/>
		/// </param>
		/// <returns>
		/// Property info if successful, null if not <see cref="PropertyInfo"/>
		/// </returns>
		public static PropertyInfo ResolveMappingPropertyByType (System.Type aTarget, string aMapping, bool aThrowException)
		{
			if ((aMapping == "") || (aTarget == null))
				return (null);
			
/*			if (TypeValidator.IsCompatible(aTarget, TypeValidator.typeIVirtualObject) == true)
				throw new Exception ("Searching property by type for VirtualObject is not possible! Check and correct implementation!");*/
			foreach (PropertyInfo pInfo in aTarget.GetProperties ())
				if (pInfo.Name == aMapping)
					return (pInfo);

			if (aThrowException == true)
				throw new ExceptionPropertyNotFound (aMapping);
			return (null);
		}
 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);
         }
     }
 }
		protected bool MatchComponentPattern(System.Type subject)
		{
			const BindingFlags flattenHierarchyMembers =
				BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

			if (declaredModel.IsEntity(subject))
			{
				return false;
			}
			var modelInspector = (IModelInspector) this;
			return !subject.IsEnum && (subject.Namespace == null || !subject.Namespace.StartsWith("System")) /* hack */
							&& !modelInspector.IsEntity(subject)
							&& !subject.GetProperties(flattenHierarchyMembers).Cast<MemberInfo>().Concat(
			       		subject.GetFields(flattenHierarchyMembers)).Any(m => modelInspector.IsPersistentId(m));
		}
Exemplo n.º 16
0
        private IEnumerable<PropertyInfo> GetTypeProperties(System.Type type)
        {
            IEnumerable<PropertyInfo> props;
            if (!_typePropertyCache.TryGetValue(type, out props))
            {
                props = type.GetProperties()
                            .Where(p => p.GetSetMethod() != null);

                _typePropertyCache.Add(type, props);
            }

            return props;
        }
Exemplo n.º 17
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++;
				}
			}
		}
Exemplo n.º 18
0
 private object InternalParseParam(System.Type type, object data)
 {
   if (data == null)
     return (object) null;
   IList list;
   if ((list = data as IList) != null)
   {
     if (!type.IsArray)
       throw new InvalidOperationException("Not an array " + type.FullName);
     System.Type elementType = type.GetElementType();
     ArrayList arrayList = new ArrayList();
     for (int index = 0; index < list.Count; ++index)
     {
       object obj = this.InternalParseParam(elementType, list[index]);
       arrayList.Add(obj);
     }
     return (object) arrayList.ToArray(elementType);
   }
   IDictionary dictionary;
   if ((dictionary = data as IDictionary) != null)
   {
     if (!type.IsClass)
       throw new InvalidOperationException("Not a class " + type.FullName);
     ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, (Binder) null, CallingConventions.Any, new System.Type[0], (ParameterModifier[]) null);
     if (constructor == null)
       throw new InvalidOperationException("Cannot find a default constructor for " + type.FullName);
     object obj1 = constructor.Invoke(new object[0]);
     using (List<System.Reflection.FieldInfo>.Enumerator enumerator = ((IEnumerable<System.Reflection.FieldInfo>) type.GetFields(BindingFlags.Instance | BindingFlags.Public)).ToList<System.Reflection.FieldInfo>().GetEnumerator())
     {
       while (enumerator.MoveNext())
       {
         System.Reflection.FieldInfo current = enumerator.Current;
         try
         {
           object obj2 = this.InternalParseParam(current.FieldType, dictionary[(object) current.Name]);
           current.SetValue(obj1, obj2);
         }
         catch (KeyNotFoundException ex)
         {
         }
       }
     }
     using (List<PropertyInfo>.Enumerator enumerator = ((IEnumerable<PropertyInfo>) type.GetProperties(BindingFlags.Instance | BindingFlags.Public)).ToList<PropertyInfo>().GetEnumerator())
     {
       while (enumerator.MoveNext())
       {
         PropertyInfo current = enumerator.Current;
         try
         {
           object obj2 = this.InternalParseParam(current.PropertyType, dictionary[(object) current.Name]);
           MethodInfo setMethod = current.GetSetMethod();
           if (setMethod != null)
             setMethod.Invoke(obj1, new object[1]{ obj2 });
         }
         catch (KeyNotFoundException ex)
         {
         }
         catch (TargetInvocationException ex)
         {
         }
       }
     }
     return Convert.ChangeType(obj1, type);
   }
   string str;
   if ((str = data as string) != null)
     return (object) str;
   if (data is bool)
     return (object) (bool) data;
   if (data is double)
     return (object) (double) data;
   if (data is int || data is short || (data is int || data is long) || data is long)
     return Convert.ChangeType(data, type);
   throw new InvalidOperationException("Cannot parse " + Json.Serialize(data));
 }
Exemplo n.º 19
0
        /// <summary> 
        /// Gets the best matching property info for the given name on the given type if the same property is defined on 
        /// multiple levels in the object hierarchy. 
        /// </summary> 
        private static PropertyInfo GetBestMatchingProperty(string propertyName, System.Type type)
        {
            PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

            PropertyInfo bestMatch = null;
            int bestMatchDistance = int.MaxValue;
            for (int i = 0; i < propertyInfos.Length; i++)
            {
                PropertyInfo info = propertyInfos[i];
                if (info.Name == propertyName)
                {
                    int distance = CalculateDistance(type, info.DeclaringType);
                    if (distance == 0)
                    {
                        // as close as we're gonna get... 
                        return info;
                    }
                    if (distance > 0 && distance < bestMatchDistance)
                    {
                        bestMatch = info;
                        bestMatchDistance = distance;
                    }
                }
            }
            return bestMatch;
        }
Exemplo n.º 20
0
        static void AddProperties(GType gtype, System.Type t, bool register_instance_prop, ref bool handlers_overridden)
        {
            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++;
            }

            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));
                    }
                }
            }
        }
 private static object[] GetConstants(System.Type enumType)
 {
     MethodAttributes attributes = MethodAttributes.Static | MethodAttributes.Public;
     PropertyInfo[] properties = enumType.GetProperties();
     ArrayList list = new ArrayList();
     for (int i = 0; i < properties.Length; i++)
     {
         PropertyInfo info = properties[i];
         if (info.PropertyType == typeof(Color))
         {
             MethodInfo getMethod = info.GetGetMethod();
             if ((getMethod != null) && ((getMethod.Attributes & attributes) == attributes))
             {
                 object[] index = null;
                 list.Add(info.GetValue(null, index));
             }
         }
     }
     return list.ToArray();
 }
Exemplo n.º 22
0
        private static StructureType ExploreClass(System.Type type)
        {
            StructureType ddsType = new StructureTypeImpl();

            TypeProperty typeProp = new TypePropertyImpl();
            typeProp.SetName(type.FullName);
            typeProp.SetTypeId(type.GetHashCode());
            TypeFlag flag = default(TypeFlag);
            flag |= (type.IsSealed ? TypeFlag.IS_FINAL : 0);
            typeProp.SetFlag(flag);
            ddsType.SetProperty(typeProp);

            List<Member> listMember = new List<Member>();
            var fields = type.GetFields(BindingFlags.Public |
                                        BindingFlags.Instance);
            uint lastId = 0;
            foreach (var member in fields)
            {
                Member memberInfo = new MemberImpl();
                NonFieldAttribute isField = member.GetCustomAttribute<NonFieldAttribute>();
                if (isField != null)
                    continue;

                MemberProperty memberProp = new MemberPropertyImpl();
                memberProp.SetName(member.Name);
                IDAttribute id = member.GetCustomAttribute<IDAttribute>();
                if (id != null)
                {
                    memberProp.SetMemberId(id.Value);
                    lastId = id.Value;
                }
                else
                {
                    lastId++;
                    memberProp.SetMemberId(lastId);
                }
                MemberFlag memberFlag = default(MemberFlag);
                KeyAttribute isKey = member.GetCustomAttribute<KeyAttribute>();
                if (isKey != null)
                {
                    memberFlag |= MemberFlag.IS_KEY;
                }
                OptionalAttribute isOptional = member.GetCustomAttribute<OptionalAttribute>();
                if (isOptional != null)
                {
                    memberFlag |= MemberFlag.IS_OPTIONAL;
                }

                memberProp.SetFlag(memberFlag);
                memberProp.IsProperty = false;
                memberInfo.SetProperty(memberProp);
                listMember.Add(memberInfo);
            }
            var props = type.GetProperties(BindingFlags.Public |
                                           BindingFlags.Instance);
            foreach (var member in props)
            {
                Member memberInfo = new MemberImpl();
                NonFieldAttribute isField = member.GetCustomAttribute<NonFieldAttribute>();
                if (isField != null) 
                    continue;
                MemberProperty memberProp = new MemberPropertyImpl();
                memberProp.SetName(member.Name);
                IDAttribute id = member.GetCustomAttribute<IDAttribute>();
                if (id != null)
                {
                    memberProp.SetMemberId(id.Value);
                    lastId = id.Value;
                }
                else
                {
                    continue; // TODO. Check if only process process members with ID
                    //lastId++;
                    //memberProp.SetMemberId(lastId);
                }
                MemberFlag memberFlag = default(MemberFlag);
                KeyAttribute isKey = member.GetCustomAttribute<KeyAttribute>();
                if (isKey != null)
                {
                    memberFlag |= MemberFlag.IS_KEY;
                }
                OptionalAttribute isOptional = member.GetCustomAttribute<OptionalAttribute>();
                if (isOptional != null)
                {
                    memberFlag |= MemberFlag.IS_OPTIONAL;
                }

                memberProp.SetFlag(memberFlag);
                memberProp.IsProperty = true;
                memberInfo.SetProperty(memberProp);
                listMember.Add(memberInfo);
            }
            ddsType.SetMember(listMember);

            return ddsType;
        }
		protected bool MatchEntity(System.Type subject)
		{
			const BindingFlags flattenHierarchyMembers =
				BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
			if(declaredModel.Components.Contains(subject))
			{
				return false;
			}
			var modelInspector = (IModelInspector) this;
			return subject.IsClass &&
			       subject.GetProperties(flattenHierarchyMembers).Cast<MemberInfo>().Concat(subject.GetFields(flattenHierarchyMembers)).Any(m => modelInspector.IsPersistentId(m));
		}
Exemplo n.º 24
0
        private ArrayList GetList(ManagementScope scope, System.Type t, string q)
        {
            ArrayList items = new ArrayList();

            ManagementObjectSearcher srch = new ManagementObjectSearcher(scope, new ObjectQuery(q));
            foreach (ManagementObject i in srch.Get())
            {
                object n = Activator.CreateInstance(t, true);

                foreach(PropertyInfo tp in t.GetProperties())
                {
                    if (tp.CanWrite)
                    {
                        PropertyData p = (from PropertyData x in i.Properties
                                              where x.Name.ToLower() == tp.Name.ToLower()
                                              select x).FirstOrDefault();
                        if(p != null)
                        {
                            object v = p.Value;

                            if (v != null)
                                tp.SetValue(n, v, null);
                        }
                    }
                }

                items.Add(n);
            }

            return items;
        }
		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);
			}
		}
Exemplo n.º 26
0
        /// <summary>
        /// Declare a new struct type in the current scope based on an actual class.
        /// </summary>
        /// <remarks>
        /// Used to declare predefined struct types representing existing classes in metamodel.
        /// </remarks>
        /// <param name="type">The class type.</param>
        private void Process_ModelStruct(System.Type type)
        {
            if (NameContext.Current.Scope.Model.Instances.OfType<Type>().Count(t => t.UnderlyingType == type) == 0)
            {
                StructType structType = new StructType();

                // Namespace
                structType.Namespace = (Namespace)NameContext.Current.Scope;

                // Name
                structType.Name = AttributeHelpers.GetTypeName(type);

                // Underlying type
                structType.UnderlyingType = type;

                // Hidden
                structType.AddMetaInfo(new HiddenInfo());

                // Enter scope
                using (new NameContextScope(structType))
                {
                    // Fields
                    foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                    {
                        StructField structField = new StructField();
                        structField.Name = AttributeHelpers.GetMemberName(property);
                        structField.Type = BuiltInType.GetBuiltInType(property.PropertyType);
                        structField.Struct = structType;
                        // Hidden
                        structField.AddMetaInfo(new HiddenInfo());
                    }
                }
            }
        }
 private PropertyInfo[] GetProperties(System.Type type)
 {
     List<PropertyInfo> list = new List<PropertyInfo>();
     list.AddRange(type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance));
     if (type.IsInterface)
     {
         foreach (System.Type type2 in type.GetInterfaces())
         {
             list.AddRange(type2.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance));
         }
     }
     return list.ToArray();
 }
Exemplo n.º 28
0
	private static System.Reflection.PropertyInfo[] getAccessibleProperties(System.Type clazz) {
	    System.Reflection.PropertyInfo[] properties = clazz.GetProperties();

	    //TODO
	    return properties;

	    /*
	    *  Short circuit for the (hopefully) majority of cases where the
	    *  clazz is public
	    */
	    if (clazz.IsPublic) {
		return properties;
	    }

	    /*
	    *  No luck - the class is not public, so we're going the longer way.
	    */

	    properties = new System.Reflection.PropertyInfo[0];
	    return properties;

	    // TODO
	    //	    MethodInfo[] methodInfos = new MethodInfo[methods.Length];
	    //
	    //	    for (int i = methods.Length; i-- > 0; ) {
	    //		methodInfos[i] = new MethodInfo(methods[i]);
	    //	    }
	    //
	    //	    int upcastCount = getAccessibleMethods(clazz, methodInfos, 0);
	    //
	    //	    /*
	    //	    *  Reallocate array in case some method had no accessible counterpart.
	    //	    */
	    //
	    //	    if (upcastCount < methods.Length) {
	    //		methods = new System.Reflection.MethodInfo[upcastCount];
	    //	    }
	    //
	    //	    int j = 0;
	    //	    for (int i = 0; i < methodInfos.Length; ++i) {
	    //		MethodInfo methodInfo = methodInfos[i];
	    //		if (methodInfo.upcast) {
	    //		    methods[j++] = methodInfo.method;
	    //		}
	    //	    }
	    //	    return methods;
	}
Exemplo n.º 29
0
        private List<PropertyInfo> GetGraphicProperties(System.Type type)
        {
            List<PropertyInfo> graphicProperties = new List<PropertyInfo>();
            PropertyInfo[] properties = type.GetProperties();
            foreach (var item in properties)
            {
                //Check if we have a data provider for this property type.
                IGraphicDataProvider provider = GraphicDataProvider.GetGraphicDataProviderForType(item.PropertyType);
                if (null != provider)
                    graphicProperties.Add(item);
            }

            return graphicProperties;
        }
Exemplo n.º 30
0
 public static void DisposProperties(System.Type type, Dictionary<string, ClassMethodInfo> cmfDict)
 {
     PropertyInfo[] array = type.GetProperties(BindingFlags | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
     foreach(PropertyInfo info in array){
         string key = type.Namespace + "." + type.Name + "." + info.Name;
         ClassMethodInfo cmf = !cmfDict.ContainsKey(key) ? new ClassMethodInfo() : cmfDict[key];
         cmf.fullName = key;
         cmf.className = type.Name;
         cmf.name = info.Name;
         cmf.returnName = info.PropertyType.Name;
         cmf.isStatic = false;
         cmf.isCanRead = info.CanRead;
         cmf.isCanWrite = info.CanRead;
         cmf.isPf = true;
         cmfDict[key] = cmf;
     }       
 }