Inheritance: System.Collections.ICollection, System.Collections.IEnumerable
        /// <include file='doc\RepeaterDesigner.uex' path='docs/doc[@for="RepeaterDesigner.PreFilterProperties"]/*' />
        /// <devdoc>
        ///   Filter the properties to replace the runtime DataSource property
        ///   descriptor with the designer's.
        /// </devdoc>
        protected override void PreFilterProperties(IDictionary properties)
        {
            base.PreFilterProperties(properties);

            PropertyDescriptor prop;

            prop = (PropertyDescriptor)properties["DataSource"];
            Debug.Assert(prop != null);

            // we can't create the designer DataSource property based on the runtime property since theie
            // types do not match. Therefore, we have to copy over all the attributes from the runtime
            // and use them that way.
            AttributeCollection runtimeAttributes = prop.Attributes;

            Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];

            runtimeAttributes.CopyTo(attrs, 0);
            attrs[runtimeAttributes.Count] = new TypeConverterAttribute(typeof(DataSourceConverter));
            prop = TypeDescriptor.CreateProperty(this.GetType(), "DataSource", typeof(string),
                                                 attrs);
            properties["DataSource"] = prop;

            prop = (PropertyDescriptor)properties["DataMember"];
            Debug.Assert(prop != null);
            prop = TypeDescriptor.CreateProperty(this.GetType(), prop,
                                                 new Attribute[] {
                new TypeConverterAttribute(typeof(DataMemberConverter))
            });
            properties["DataMember"] = prop;
        }
 private static void OutputAttributes(AttributeCollection attributeCollection)
 {
     foreach (Attribute attribute in attributeCollection)
     {
         Console.WriteLine("Attribute: {0}", attribute.ToString());
     }
 }
        internal static void AddAttributesToPropertiesOfDifferentType(
            Type designerType,
            Type newType,
            IDictionary properties,
            String propertyName,
            Attribute newAttribute)
        {
            Debug.Assert(propertyName != null &&
                         propertyName.Length != 0);

            PropertyDescriptor prop = (PropertyDescriptor)properties[propertyName];

            Debug.Assert(prop != null);

            // we can't create the designer DataSource property based on the runtime property since their
            // types do not match. Therefore, we have to copy over all the attributes from the runtime
            // and use them that way.
            System.ComponentModel.AttributeCollection runtimeAttributes = prop.Attributes;
            Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];
            runtimeAttributes.CopyTo(attrs, 0);

            attrs[runtimeAttributes.Count] = newAttribute;
            prop = TypeDescriptor.CreateProperty(
                designerType,
                propertyName,
                newType,
                attrs);

            properties[propertyName] = prop;
        }
Beispiel #4
0
        protected override void PreFilterProperties(IDictionary properties)
        {
            base.PreFilterProperties(properties);

            PropertyDescriptor propertyDescriptor = (PropertyDescriptor)properties["DataSource"];

            if (null != propertyDescriptor)
            {
                System.ComponentModel.AttributeCollection runtimeAttributes = propertyDescriptor.Attributes;
                Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];

                runtimeAttributes.CopyTo(attrs, 0);
                attrs[runtimeAttributes.Count] = new TypeConverterAttribute(typeof(DataSourceConverter));
                propertyDescriptor             = TypeDescriptor.CreateProperty(this.GetType(), "DataSource", typeof(string),
                                                                               attrs);
                properties["DataSource"] = propertyDescriptor;
            }

            propertyDescriptor = (PropertyDescriptor)properties["DataMember"];
            if (null != propertyDescriptor)
            {
                System.ComponentModel.AttributeCollection runtimeAttributes = propertyDescriptor.Attributes;
                Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];

                runtimeAttributes.CopyTo(attrs, 0);
                attrs[runtimeAttributes.Count] = new TypeConverterAttribute(typeof(DataMemberConverter));
                propertyDescriptor             = TypeDescriptor.CreateProperty(this.GetType(), "DataMember", typeof(string),
                                                                               attrs);
                properties["DataMember"] = propertyDescriptor;
            }
        }
		AttributeCollection ICustomTypeDescriptor.GetAttributes()
		{
			if (_attributes == null)
				_attributes = _typeDescriptionProvider.GetAttributes();

			return _attributes;
		}
        private List <PropertyDescriptor> GetPropertyDescriptor(SearchHelper helper)
        {
            List <PropertyDescriptor> returnProp = new List <PropertyDescriptor>();

            var properties = TypeDescriptor.GetProperties(helper.SearchType);

            foreach (PropertyDescriptor propDes in properties)
            {
                PropertyDescriptor property = propDes;
                if (helper.HideColumns.Contains(propDes.Name))
                {
                    if (property != null)
                    {
                        System.ComponentModel.AttributeCollection runtimeAttributes = property.Attributes;
                        // make a copy of the original attributes
                        // but make room for one extra attribute
                        Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];
                        runtimeAttributes.CopyTo(attrs, 0);
                        attrs[runtimeAttributes.Count] = new BrowsableAttribute(false);

                        // makes this Property hidden in PropertyGrid
                        property = TypeDescriptor.CreateProperty(this.GetType(), property.Name, property.PropertyType, attrs);
                    }
                }

                returnProp.Add(property);
            }
            return(returnProp);
        }
        protected override void PreFilterProperties(IDictionary properties)
        {
            int num2;

            base.PreFilterProperties(properties);
            PropertyDescriptor oldPropertyDescriptor = (PropertyDescriptor)properties["DataSource"];

            System.ComponentModel.AttributeCollection attributes = oldPropertyDescriptor.Attributes;
            int    index      = -1;
            int    count      = attributes.Count;
            string dataSource = this.DataSource;

            if (dataSource.Length > 0)
            {
                this._keepDataSourceBrowsable = true;
            }
            for (int i = 0; i < attributes.Count; i++)
            {
                if (attributes[i] is BrowsableAttribute)
                {
                    index = i;
                    break;
                }
            }
            if (((index == -1) && (dataSource.Length == 0)) && !this._keepDataSourceBrowsable)
            {
                num2 = count + 2;
            }
            else
            {
                num2 = count + 1;
            }
            Attribute[] array = new Attribute[num2];
            attributes.CopyTo(array, 0);
            array[count] = new TypeConverterAttribute(typeof(DataSourceConverter));
            if ((dataSource.Length == 0) && !this._keepDataSourceBrowsable)
            {
                if (index == -1)
                {
                    array[count + 1] = BrowsableAttribute.No;
                }
                else
                {
                    array[index] = BrowsableAttribute.No;
                }
            }
            oldPropertyDescriptor      = TypeDescriptor.CreateProperty(base.GetType(), "DataSource", typeof(string), array);
            properties["DataSource"]   = oldPropertyDescriptor;
            oldPropertyDescriptor      = (PropertyDescriptor)properties["DataMember"];
            oldPropertyDescriptor      = TypeDescriptor.CreateProperty(base.GetType(), oldPropertyDescriptor, new Attribute[] { new TypeConverterAttribute(typeof(DataMemberConverter)) });
            properties["DataMember"]   = oldPropertyDescriptor;
            oldPropertyDescriptor      = (PropertyDescriptor)properties["DataKeyField"];
            oldPropertyDescriptor      = TypeDescriptor.CreateProperty(base.GetType(), oldPropertyDescriptor, new Attribute[] { new TypeConverterAttribute(typeof(DataFieldConverter)) });
            properties["DataKeyField"] = oldPropertyDescriptor;
            oldPropertyDescriptor      = (PropertyDescriptor)properties["DataSourceID"];
            oldPropertyDescriptor      = TypeDescriptor.CreateProperty(base.GetType(), oldPropertyDescriptor, new Attribute[] { new TypeConverterAttribute(typeof(DataSourceIDConverter)) });
            properties["DataSourceID"] = oldPropertyDescriptor;
        }
        public SettingsForm()
        {
            InitializeComponent();

            pgSettings.SelectedObject = _appSettings;
            System.Configuration.UserScopedSettingAttribute userAttr = new System.Configuration.UserScopedSettingAttribute();
            System.ComponentModel.AttributeCollection       attrs    = new System.ComponentModel.AttributeCollection(userAttr);
            pgSettings.BrowsableAttributes = attrs;
        }
Beispiel #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AttributesContainer"/> class.
        /// </summary>
        /// <param name="attributes">The collection of attributes.</param>
        public AttributesContainer(AttributeCollection attributes)
        {
            if (attributes == null) throw new ArgumentNullException("attributes");

            this.attributes = attributes;

            foreach (Type type in from Attribute attr in this.attributes select attr.GetType())
                RegisterAttribute(type.Name, type);
        }
		public void CanGetEditorAttributeFromCollection()
		{
			BindableAttribute bindableAttribute = new BindableAttribute(false);
			EditorAttribute editorAttribute = new EditorAttribute();
			
			Attribute[] attributes = new Attribute[] { bindableAttribute, editorAttribute };
			AttributeCollection attributeCollection = new AttributeCollection(attributes);
			
			Assert.AreSame(editorAttribute, WixBindingTestsHelper.GetEditorAttribute(attributeCollection));
		}
		public static AttributeCollection FromExisting (AttributeCollection existing, params Attribute [] newAttributes)
		{
			if (existing == null)
				throw new ArgumentNullException ("existing");
			AttributeCollection ret = new AttributeCollection ();
			ret.attrList.AddRange (existing.attrList);
			if (newAttributes != null)
				ret.attrList.AddRange (newAttributes);
			return ret;
		}
Beispiel #12
0
        private void frmSettings_Load(object sender, EventArgs e)
        {
            System.Configuration.UserScopedSettingAttribute userAttr = new System.Configuration.UserScopedSettingAttribute();
              System.ComponentModel.AttributeCollection attrs = new System.ComponentModel.AttributeCollection(userAttr);

              propertyGrid1.BrowsableAttributes = attrs;
              propertyGrid1.SelectedObject = Properties.Settings.Default;

              cboCompany.Items.AddRange(hc.getAllCompanies());
        }
Beispiel #13
0
 internal static bool IsEnabled(Type type)
 {
     if (!_viewStateIdTypes.ContainsKey(type))
     {
         System.ComponentModel.AttributeCollection attrs = TypeDescriptor.GetAttributes(type);
         ViewStateModeByIdAttribute attr = (ViewStateModeByIdAttribute)attrs[typeof(ViewStateModeByIdAttribute)];
         _viewStateIdTypes[type] = (attr != null);
     }
     return((bool)_viewStateIdTypes[type]);
 }
		/// <summary>
		/// Returns the EditorAttribute in the AttributeCollection.
		/// </summary>
		public static EditorAttribute GetEditorAttribute(AttributeCollection attributes)
		{
			foreach (Attribute attribute in attributes) {
				EditorAttribute editorAttribute = attribute as EditorAttribute;
				if (editorAttribute != null) {
					return editorAttribute;
				}
			}
			return null;
		}
Beispiel #15
0
 private static EditorOptions GetEditorOptionsAttribute(System.ComponentModel.AttributeCollection attribCollection)
 {
     foreach (Attribute attrib in attribCollection)
     {
         if (attrib is EditorOptions)
         {
             return(attrib as EditorOptions);
         }
     }
     return(null);
 }
        /// <summary>
        /// Constructs a description based on the specified <see cref="DomainServiceDescription"/>.
        /// </summary>
        /// <param name="baseDescription">The base <see cref="DomainServiceDescription"/></param>
        internal DomainServiceDescription(DomainServiceDescription baseDescription)
        {
            if (baseDescription == null)
            {
                throw new ArgumentNullException("baseDescription");
            }

            this._domainServiceType = baseDescription._domainServiceType;
            this._attributes = baseDescription._attributes;
            this._operationEntries.AddRange(baseDescription._operationEntries);
        }
Beispiel #17
0
 private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attributes, ref PropertyDescriptorCollection returnValue)
 {
     using (typeDescriptor.TraceScope("Checking property \"{0}\".", new object[] { propertyInfo.Name }))
     {
         if (!propertyInfo.IsGettable)
         {
             typeDescriptor.WriteLine("Property \"{0}\" is write-only so it has been skipped.", new object[] { propertyInfo.Name });
         }
         else
         {
             AttributeCollection propertyAttributes = null;
             Type propertyType = typeof(object);
             if ((attributes != null) && (attributes.Length != 0))
             {
                 PSProperty property = propertyInfo as PSProperty;
                 if (property != null)
                 {
                     DotNetAdapter.PropertyCacheEntry adapterData = property.adapterData as DotNetAdapter.PropertyCacheEntry;
                     if (adapterData == null)
                     {
                         typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", new object[] { property.Name });
                     }
                     else if (property.isDeserialized)
                     {
                         typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it has been deserialized.", new object[] { property.Name });
                     }
                     else
                     {
                         propertyType = adapterData.propertyType;
                         propertyAttributes = adapterData.Attributes;
                         foreach (Attribute attribute in attributes)
                         {
                             if (!propertyAttributes.Contains(attribute))
                             {
                                 typeDescriptor.WriteLine("Property \"{0}\" does not contain attribute \"{1}\" so it has been skipped.", new object[] { property.Name, attribute });
                                 return;
                             }
                         }
                     }
                 }
             }
             if (propertyAttributes == null)
             {
                 propertyAttributes = new AttributeCollection(new Attribute[0]);
             }
             typeDescriptor.WriteLine("Adding property \"{0}\".", new object[] { propertyInfo.Name });
             PSObjectPropertyDescriptor descriptor = new PSObjectPropertyDescriptor(propertyInfo.Name, propertyType, !propertyInfo.IsSettable, propertyAttributes);
             descriptor.SettingValueException += this.SettingValueException;
             descriptor.GettingValueException += this.GettingValueException;
             returnValue.Add(descriptor);
         }
     }
 }
        /// <summary>
        /// Used to modify the Attributes of the 'Data' related fields such that
        /// the correct TypeConverters are added to the Attributes. For some reason
        /// adding the attributes directly doesn't work.
        /// </summary>
        /// <param name="properties">The dictionary</param>
        protected override void PreFilterProperties(IDictionary properties)
        {
            base.PreFilterProperties(properties);
            PropertyDescriptor prop = (PropertyDescriptor)properties["DataSource"];

            if (prop != null)
            {
                System.ComponentModel.AttributeCollection runtimeAttributes = prop.Attributes;
                // make a copy of the original attributes but make room for one extra attribute ie the TypeConverter attribute
                Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];
                runtimeAttributes.CopyTo(attrs, 0);
                attrs[runtimeAttributes.Count] = new TypeConverterAttribute(typeof(DataSourceConverter));
                prop = TypeDescriptor.CreateProperty(this.GetType(), "DataSource", typeof(string), attrs);
                properties["DataSource"] = prop;
            }

            prop = (PropertyDescriptor)properties["DataMember"];
            if (prop != null)
            {
                System.ComponentModel.AttributeCollection runtimeAttributes = prop.Attributes;
                Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];
                // make a copy of the original attributes but make room for one extra attribute ie the TypeConverter attribute
                runtimeAttributes.CopyTo(attrs, 0);
                attrs[runtimeAttributes.Count] = new TypeConverterAttribute(typeof(DataMemberConverter));
                prop = TypeDescriptor.CreateProperty(this.GetType(), "DataMember", typeof(string), attrs);
                properties["DataMember"] = prop;
            }

            prop = (PropertyDescriptor)properties["DataValueField"];
            if (prop != null)
            {
                System.ComponentModel.AttributeCollection runtimeAttributes = prop.Attributes;
                Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];
                // make a copy of the original attributes but make room for one extra attribute ie the TypeConverter attribute
                runtimeAttributes.CopyTo(attrs, 0);
                attrs[runtimeAttributes.Count] = new TypeConverterAttribute(typeof(DataFieldConverter));
                prop = TypeDescriptor.CreateProperty(this.GetType(), "DataValueField", typeof(string), attrs);
                properties["DataValueField"] = prop;
            }

            prop = (PropertyDescriptor)properties["DataTextField"];
            if (prop != null)
            {
                System.ComponentModel.AttributeCollection runtimeAttributes = prop.Attributes;
                Attribute[] attrs = new Attribute[runtimeAttributes.Count + 1];
                // make a copy of the original attributes but make room for one extra attribute ie the TypeConverter attribute
                runtimeAttributes.CopyTo(attrs, 0);
                attrs[runtimeAttributes.Count] = new TypeConverterAttribute(typeof(DataFieldConverter));
                prop = TypeDescriptor.CreateProperty(this.GetType(), "DataTextField", typeof(string), attrs);
                properties["DataTextField"] = prop;
            }
        }
Beispiel #19
0
        private void InitializePanelControls()
        {
            this._selectLabel.Text = System.Design.SR.GetString("CreateDataSource_SelectType");
            this._idLabel.Text     = System.Design.SR.GetString("CreateDataSource_ID");
            base.OKButton.Enabled  = false;
            this.Text = System.Design.SR.GetString("CreateDataSource_Title");
            this._descriptionBox.Text  = System.Design.SR.GetString("CreateDataSource_SelectTypeDesc");
            base.AccessibleDescription = System.Design.SR.GetString("CreateDataSource_Description");
            base.CaptionLabel.Text     = System.Design.SR.GetString("CreateDataSource_Caption");
            this.UpdateFonts();
            ISite site = this.GetSite();

            if (site != null)
            {
                IComponentDiscoveryService service = (IComponentDiscoveryService)site.GetService(typeof(IComponentDiscoveryService));
                IDesignerHost designerHost         = (IDesignerHost)site.GetService(typeof(IDesignerHost));
                if (service != null)
                {
                    ICollection componentTypes = service.GetComponentTypes(designerHost, this._dataSourceType);
                    if (componentTypes != null)
                    {
                        ImageList list = new ImageList {
                            ColorDepth = ColorDepth.Depth32Bit
                        };
                        System.Type[] array = new System.Type[componentTypes.Count];
                        componentTypes.CopyTo(array, 0);
                        foreach (System.Type type in array)
                        {
                            System.ComponentModel.AttributeCollection attributes = TypeDescriptor.GetAttributes(type);
                            Bitmap image = null;
                            if (attributes != null)
                            {
                                ToolboxBitmapAttribute attribute = attributes[typeof(ToolboxBitmapAttribute)] as ToolboxBitmapAttribute;
                                if ((attribute != null) && !attribute.Equals(ToolboxBitmapAttribute.Default))
                                {
                                    image = attribute.GetImage(type, true) as Bitmap;
                                }
                            }
                            if (image == null)
                            {
                                image = new Bitmap(base.GetType(), "CustomDataSource.bmp");
                            }
                            list.ImageSize = new Size(0x20, 0x20);
                            list.Images.Add(type.FullName, image);
                            this._dataSourceTypesListView.Items.Add(new DataSourceListViewItem(type));
                        }
                        this._dataSourceTypesListView.Sort();
                        this._dataSourceTypesListView.LargeImageList = list;
                    }
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Перевести атрибуты заданного типа
        /// </summary>
        /// <remarks>Используется словарь с ключём, совпадающим с полным именем типа</remarks>
        public void TranslateAttrs(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            string dictKey = type.FullName;

            Localization.Dict dict;

            if (Localization.Dictionaries.TryGetValue(dictKey, out dict))
            {
                Dictionary <string, PropAttrs>  propAttrsDict = GetPropAttrsDict(dict);
                CM.PropertyDescriptorCollection allProps      = CM.TypeDescriptor.GetProperties(type);

                foreach (CM.PropertyDescriptor prop in allProps)
                {
                    PropAttrs propAttrs;

                    if (propAttrsDict.TryGetValue(prop.Name, out propAttrs))
                    {
                        CM.AttributeCollection attrs = prop.Attributes;

                        foreach (Attribute attr in attrs)
                        {
                            if (attr is DisplayNameAttribute)
                            {
                                if (!string.IsNullOrEmpty(propAttrs.DisplayName))
                                {
                                    ((DisplayNameAttribute)attr).DisplayNameValue = propAttrs.DisplayName;
                                }
                            }
                            else if (attr is CategoryAttribute)
                            {
                                if (!string.IsNullOrEmpty(propAttrs.Category))
                                {
                                    ((CategoryAttribute)attr).CategoryName = propAttrs.Category;
                                }
                            }
                            else if (attr is DescriptionAttribute)
                            {
                                if (!string.IsNullOrEmpty(propAttrs.Description))
                                {
                                    ((DescriptionAttribute)attr).DescriptionValue = propAttrs.Description;
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #21
0
 public string GetDescriptionText()
 {
     System.ComponentModel.AttributeCollection attributes = TypeDescriptor.GetAttributes(this._dataSourceType);
     if (attributes != null)
     {
         DescriptionAttribute attribute = attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
         if (attribute != null)
         {
             return(attribute.Description);
         }
     }
     return(string.Empty);
 }
        internal static AttributeCollection AddDisplayName(string name, AttributeCollection attributes) {
            var displayNameAttrib = attributes.OfType<DisplayNameAttribute>().FirstOrDefault();

            // If there is already a display name attribute, don't change anything
            if (displayNameAttrib != null) {
                return attributes;
            }

            // Add a friendlier display name attribute
            return AttributeCollection.FromExisting(
                attributes,
                new DisplayNameAttribute(MakeFriendlyName(name)));
        }
Beispiel #23
0
    private void LoadIndexes()
    {
        if ((_Indexes == null) || (_Indexes.Count == 0))
        {
            IRepository <IIndexDefinition> rep = EntityFactory.GetRepository <IIndexDefinition>();
            IQueryable         qry             = (IQueryable)rep;
            IExpressionFactory ef        = qry.GetExpressionFactory();
            ICriteria          crit      = qry.CreateCriteria();
            IExpression        accessExp = ef.Le("UserAccess", _UserType);
            crit.Add(ef.And(accessExp, ef.Eq("Enabled", true)));
            crit.AddOrder(ef.Asc("IndexName"));
            IList <IIndexDefinition> tempIndexes = crit.List <IIndexDefinition>();

            //c.Add(NHibernate.Expression.Expression.Eq("Enabled", true));
            //c.Add(Expression.Le("UserAccess", _UserType));
            //c.AddOrder(Order.Asc("IndexName"));
            //List<IndexDefinition> tempIndexes = (List<IndexDefinition>)c.List<IndexDefinition>();

            Assembly interfaceAsm = Assembly.GetAssembly(typeof(IIndexDefinition));
            Type[]   types        = interfaceAsm.GetTypes();
            _TablesEntities = new Dictionary <string, Type>();
            foreach (Type entity in types)
            {
                AttributeCollection attrs = TypeDescriptor.GetAttributes(entity);
                foreach (Attribute attr in attrs)
                {
                    ActiveRecordAttribute activeRecord = attr as ActiveRecordAttribute;
                    if (activeRecord != null)
                    {
                        _TablesEntities.Add(activeRecord.Table.ToUpper(), entity);
                    }
                }
            }
            _Indexes = new List <IIndexDefinition>();
            foreach (IIndexDefinition index in tempIndexes)
            {
                if (index.Type == 1) // database index
                {
                    DBIndexDefinition dbid = DBIndexDefinition.SetFromString(index.MetaData);
                    if (_TablesEntities.ContainsKey(dbid.MainTable.ToUpper()))
                    {
                        _Indexes.Add(index);
                    }
                }
                else
                {
                    _Indexes.Add(index);
                }
            }
        }
    }
        public static void Main()
        {
            System.ComponentModel.AttributeCollection myAttributes =
                TypeDescriptor.GetAttributes(typeof(SimpleWebControl));

            DataBindingHandlerAttribute myDataBindingHandlerAttribute =
                myAttributes[typeof(DataBindingHandlerAttribute)] as DataBindingHandlerAttribute;

            if (myDataBindingHandlerAttribute != null)
            {
                Console.Write("DataBindingHandlerAttribute's HandlerTypeName is : " +
                              myDataBindingHandlerAttribute.HandlerTypeName);
            }
        }
Beispiel #25
0
        protected override void PreFilterProperties(IDictionary properties)
        {
            int num2;

            base.PreFilterProperties(properties);
            PropertyDescriptor descriptor = (PropertyDescriptor)properties["DataSource"];

            System.ComponentModel.AttributeCollection attributes = descriptor.Attributes;
            int    index      = -1;
            int    count      = attributes.Count;
            string dataSource = this.DataSource;
            bool   flag       = (dataSource != null) && (dataSource.Length > 0);

            if (flag)
            {
                this._keepDataSourceBrowsable = true;
            }
            for (int i = 0; i < attributes.Count; i++)
            {
                if (attributes[i] is BrowsableAttribute)
                {
                    index = i;
                    break;
                }
            }
            if (((index == -1) && !flag) && !this._keepDataSourceBrowsable)
            {
                num2 = count + 1;
            }
            else
            {
                num2 = count;
            }
            Attribute[] array = new Attribute[num2];
            attributes.CopyTo(array, 0);
            if (!flag && !this._keepDataSourceBrowsable)
            {
                if (index == -1)
                {
                    array[count] = BrowsableAttribute.No;
                }
                else
                {
                    array[index] = BrowsableAttribute.No;
                }
            }
            descriptor = TypeDescriptor.CreateProperty(base.GetType(), "DataSource", typeof(string), array);
            properties["DataSource"] = descriptor;
        }
Beispiel #26
0
        /// <summary>
        /// 添加标签属性时的触发事件函数.用于设置自身的某些属性值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnAddingAttribute(object sender, AttributeCollection.AttributeAddingEventArgs e)
        {
            string name = e.Item.Name.ToLower();

            switch (name)
            {
                case "id":
                    this.Id = e.Item.Text.Trim();
                    break;
                case "name":
                    this.Name = e.Item.Text.Trim();
                    break;
            }
            OnAddingAttribute(name, e.Item);
        }
        public static AttributeCollection DeleteNonRelevatAttributes(AttributeCollection collection)
        {
            ArrayList attributes = GetAttributes(collection);

            ArrayList newAttributes = new ArrayList();
            foreach (Attribute attr in attributes)
            {
                if (acceptableAttributes.ContainsKey(attr.GetType())
                    || acceptableAttributes.ContainsKey(attr.GetType().BaseType))
                {
                    newAttributes.Add(attr);
                }
            }
            return GetAttributes(newAttributes);
        }
Beispiel #28
0
 public static bool IsPropertyFilterable(PropertyDescriptor propDesc)
 {
     System.ComponentModel.AttributeCollection attributes = propDesc.Attributes;
     if (attributes.Count != 0)
     {
         foreach (Attribute attrib in attributes)
         {
             if (attrib is FilterableAttribute)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Beispiel #29
0
        /// <summary>
        /// 设置对象的只读属性
        /// </summary>
        /// <param name="myobj">需设置的属性表</param>
        /// <param name="Readonly">只读为true,可写为false</param>f
        void SetClassReadonly(ReflectoreTest myobj, bool Readonly)
        {
            if (myobj == null)
            {
                return;           //myobj就是类TaoNei的一个实例
            }
            var readOnlyAttribute = myobj.GetType().GetCustomAttribute <ReadOnlyAttribute>();

            Type readonlyType = typeof(ReadOnlyAttribute);

            FieldInfo fld = readonlyType.GetField("isReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

            System.ComponentModel.AttributeCollection attrs = TypeDescriptor.GetAttributes(myobj);

            fld.SetValue(attrs[typeof(ReadOnlyAttribute)], Readonly);
        }
 public static AttributeCollection FromExisting(AttributeCollection existing, params Attribute[] newAttributes)
 {
     if (existing == null)
     {
         throw new ArgumentNullException("existing");
     }
     if (newAttributes == null)
     {
         newAttributes = new Attribute[0];
     }
     Attribute[] array = new Attribute[existing.Count + newAttributes.Length];
     int count = existing.Count;
     existing.CopyTo(array, 0);
     for (int i = 0; i < newAttributes.Length; i++)
     {
         if (newAttributes[i] == null)
         {
             throw new ArgumentNullException("newAttributes");
         }
         bool flag = false;
         for (int j = 0; j < existing.Count; j++)
         {
             if (array[j].TypeId.Equals(newAttributes[i].TypeId))
             {
                 flag = true;
                 array[j] = newAttributes[i];
                 break;
             }
         }
         if (!flag)
         {
             array[count++] = newAttributes[i];
         }
     }
     Attribute[] destinationArray = null;
     if (count < array.Length)
     {
         destinationArray = new Attribute[count];
         Array.Copy(array, 0, destinationArray, 0, count);
     }
     else
     {
         destinationArray = array;
     }
     return new AttributeCollection(destinationArray);
 }
        /// <summary>
        /// Initializes a new instance of the DomainOperationParameter class
        /// </summary>
        /// <param name="name">The name of the parameter</param>
        /// <param name="parameterType">The Type of the parameter</param>
        /// <param name="attributes">The set of attributes for the parameter</param>
        public DomainOperationParameter(string name, Type parameterType, AttributeCollection attributes)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (parameterType == null)
            {
                throw new ArgumentNullException("parameterType");
            }

            if (attributes == null)
            {
                throw new ArgumentNullException("attributes");
            }

            this._name = name;
            this._parameterType = parameterType;
            this._attributes = attributes;
        }
 public SYNamePropertyDescriptor(PropertyDescriptor descr):base(descr)
 {
     _d = descr;
     int count = _d.Attributes.Count;
     Attribute[] attrs = new Attribute[count];
     Attribute vis_att = new System.ComponentModel.BrowsableAttribute(true);
     for (int i = 0; i < count; ++i)
     {
         if (_d.Attributes[i].TypeId == vis_att.TypeId)
         {
             attrs[i] = vis_att;
         }
         else
         {
             attrs[i] = _d.Attributes[i];
         }
     }
     _ac = new AttributeCollection(attrs);
     //Array.Resize(attrs, attrs.Length + 1);
     //attrs[attrs.Length - 1] = new System.ComponentModel.BrowsableAttribute(true);
 }
        public override AttributeCollection GetAttributes()
        {
            if (_finalAttributeCollection == null)
            {
                lock (_lockAttributeGetter)
                {
                    if (_finalAttributeCollection == null)
                    {
                        bool metadataModified;
                        Type reflectedType = TypeDescriptor.GetReflectionType(_configuration.ComponentType);
                        Attribute[] originalAttributes =
                            reflectedType.GetCustomAttributes(true).Cast<Attribute>().ToArray();
                        Attribute[] finalAttributes = GetAttributes(originalAttributes, _configuration,
                                                                    out metadataModified);

                        _finalAttributeCollection = new AttributeCollection(finalAttributes);
                    }
                }
            }
            return _finalAttributeCollection;
        }
Beispiel #34
0
 public string GetDisplayName()
 {
     if (this._displayName == null)
     {
         System.ComponentModel.AttributeCollection attributes = TypeDescriptor.GetAttributes(this._dataSourceType);
         this._displayName = string.Empty;
         if (attributes != null)
         {
             DisplayNameAttribute attribute = attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute;
             if (attribute != null)
             {
                 this._displayName = attribute.DisplayName;
             }
         }
         if (string.IsNullOrEmpty(this._displayName))
         {
             this._displayName = this._dataSourceType.Name;
         }
     }
     return(this._displayName);
 }
        public static bool IsTypeFilterable(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            object result = _filterableTypes[type];

            if (result != null)
            {
                return((bool)result);
            }

            System.ComponentModel.AttributeCollection attrs = TypeDescriptor.GetAttributes(type);
            FilterableAttribute attr = (FilterableAttribute)attrs[typeof(FilterableAttribute)];

            result = (attr != null) && attr.Filterable;
            _filterableTypes[type] = result;

            return((bool)result);
        }
        public WrappedProperty(MemberDescriptor descr, PropertyView propertyView, Attribute[] attrs)
            : base(descr, attrs)
        {
            this.realPropertyDescriptor = (PropertyDescriptor) descr;
            this.name = propertyView.Name;
            this.displayName = propertyView.DisplayName;

            Attribute[] attribs = new Attribute[descr.Attributes.Count + 4];

            int i = 0;
            foreach (Attribute attrib in descr.Attributes)
            {
                attribs[i] = attrib;
                i++;
            }
            attribs[i] = new DescriptionAttribute(propertyView.Description);
            attribs[i + 1] = new CategoryAttribute(propertyView.Category);
            attribs[i + 2] = new DescriptionAttribute(propertyView.Description);
            attribs[i + 3] = new ReadOnlyAttribute(propertyView.IsReadOnly);

            attributes = new AttributeCollection(attribs);
        }
        public ObjectPropertyDescriptor(MemberDescriptor descr, IContext context, IPropertyMap propertyMap, object obj, Attribute[] attrs)
            : base(descr, attrs)
        {
            this.realPropertyDescriptor = (PropertyDescriptor) descr;
            this.name = propertyMap.Name;
            this.displayName = propertyMap.Name;

            Attribute[] attribs = new Attribute[descr.Attributes.Count + 4];

            int i = 0;
            foreach (Attribute attrib in descr.Attributes)
            {
                attribs[i] = attrib;
                i++;
            }
            attribs[i] = new DescriptionAttribute(propertyMap.Name + " is a property.");
            attribs[i + 1] = new CategoryAttribute("");
            attribs[i + 2] = new DefaultValueAttribute(context.ObjectManager.GetOriginalPropertyValue(obj, propertyMap.Name));
            attribs[i + 3] = new ReadOnlyAttribute(propertyMap.IsReadOnly);

            attributes = new AttributeCollection(attribs);
        }
        protected static AttributeCollection AddDefaultAttributes(ColumnProvider columnProvider, AttributeCollection attributes) {
            List<Attribute> extraAttributes = new List<Attribute>();

            // If there is no required attribute and the Provider says required, add one
            var requiredAttribute = attributes.FirstOrDefault<RequiredAttribute>();
            if (requiredAttribute == null && !columnProvider.Nullable) {
                extraAttributes.Add(new RequiredAttribute());
            }

            // If there is no StringLength attribute and it's a string, add one
            var stringLengthAttribute = attributes.FirstOrDefault<StringLengthAttribute>();
            int maxLength = columnProvider.MaxLength;
            if (stringLengthAttribute == null && columnProvider.ColumnType == typeof(String) && maxLength > 0) {
                extraAttributes.Add(new StringLengthAttribute(maxLength));
            }

            // If we need any extra attributes, create a new collection
            if (extraAttributes.Count > 0) {
                attributes = AttributeCollection.FromExisting(attributes, extraAttributes.ToArray());
            }

            return attributes;
        }
        // In the future, we may want to add Color, Date, etc.
        private bool CanEditProperty(PropertyDescriptor property)
        {
            // Don't show readonly properties
            if (property.IsReadOnly)
            {
                return(false);
            }

            // Don't show Shared personalizable properties in User mode
            if (WebPartManager != null &&
                WebPartManager.Personalization != null &&
                WebPartManager.Personalization.Scope == PersonalizationScope.User)
            {
                AttributeCollection attributes = property.Attributes;
                if (attributes.Contains(PersonalizableAttribute.SharedPersonalizable))
                {
                    return(false);
                }
            }

            // Only show properties that can be converted to/from string
            return(Util.CanConvertToFrom(property.Converter, typeof(string)));
        }
        public static AttributeCollection GetAttributes(object component, bool noCustomTypeDesc) 
        {
            if (component == null) 
            {
                Debug.Fail("COMPAT:  Returning an empty collection, but you should not pass null here");
                return new AttributeCollection((Attribute[])null);
            }

            // We create a sort of pipeline for mucking with metadata.  The pipeline
            // goes through the following process:
            //
            // 1.  Merge metadata from extenders.
            // 2.  Allow services to filter the metadata
            // 3.  If an attribute filter was specified, apply that.
            // 
            // The goal here is speed.  We get speed by not copying or
            // allocating memory.  We do this by allowing each phase of the
            // pipeline to cache its data in the object cache.  If
            // a phase makes a change to the results, this change must cause
            // successive phases to recompute their results as well.  "Results" is
            // always a collection, and the various stages of the pipeline may
            // replace or modify this collection (depending on if it's a
            // read-only IList or not).  It is possible for the orignal
            // descriptor or attribute collection to pass through the entire
            // pipeline without modification.
            // 
            ICustomTypeDescriptor typeDesc = GetDescriptor(component, noCustomTypeDesc);
            ICollection results = typeDesc.GetAttributes();

            // If we are handed a custom type descriptor we have several choices of action
            // we can take.  If noCustomTypeDesc is true, it means that the custom type
            // descriptor is trying to find a baseline set of properties.  In this case
            // we should merge in extended properties, but we do not let designers filter
            // because we're not done with the property set yet.  If noCustomTypeDesc
            // is false, we don't do extender properties because the custom type descriptor
            // has already added them.  In this case, we are doing a final pass so we
            // want to apply filtering.  Finally, if the incoming object is not a custom
            // type descriptor, we do extenders and the filter.
            //
            if (component is ICustomTypeDescriptor)
            {
                if (noCustomTypeDesc)
                {
                    ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component);
                    if (extDesc != null)
                    {
                        ICollection extResults = extDesc.GetAttributes();
                        results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, component, null);
                    }
                }
                else
                {
                    results = PipelineFilter(PIPELINE_ATTRIBUTES, results, component, null);
                }
            }
            else
            {
                IDictionary cache = GetCache(component);

                results = PipelineInitialize(PIPELINE_ATTRIBUTES, results, cache);
                
                ICustomTypeDescriptor extDesc = GetExtendedDescriptor(component);
                if (extDesc != null)
                {
                    ICollection extResults = extDesc.GetAttributes();
                    results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, component, cache);
                }

                results = PipelineFilter(PIPELINE_ATTRIBUTES, results, component, cache);
            }

            AttributeCollection attrs = results as AttributeCollection;
            if (attrs == null)
            {
                Trace("Attributes : Allocated new attribute collection for {0}", component.GetType().Name);
                Attribute[] attrArray = new Attribute[results.Count];
                results.CopyTo(attrArray, 0);
                attrs = new AttributeCollection(attrArray);
            }

            DebugValidate(attrs, component, noCustomTypeDesc);
            return attrs;
        }
        /// <devdoc>
        ///     Metdata filtering is the third stage of our pipeline.  
        ///     In this stage we check to see if the given object is a
        ///     sited component that provides the ITypeDescriptorFilterService
        ///     object.  If it does, we allow the TDS to filter the metadata.
        ///     This will use the cache, if available, to store filtered
        ///     metdata.
        /// </devdoc>
        private static ICollection PipelineFilter(int pipelineType, ICollection members, object instance, IDictionary cache)
        {
            IComponent component = instance as IComponent;
            ITypeDescriptorFilterService componentFilter = null;

            if (component != null)
            {
                ISite site = component.Site;
                if (site != null)
                {
                    componentFilter = site.GetService(typeof(ITypeDescriptorFilterService)) as ITypeDescriptorFilterService;
                }
            }

            // If we have no filter, there is nothing for us to do.
            //
            IList list = members as ArrayList;

            if (componentFilter == null)
            {
                Debug.Assert(cache == null || list == null || !cache.Contains(_pipelineFilterKeys[pipelineType]), "Earlier pipeline stage should have removed our cache");
                return members;
            }

            // Now, check our cache.  The cache state is only valid
            // if the data coming into us is read-only.  If it is read-write,
            // that means something higher in the pipeline has already changed
            // it so we must recompute anyway.
            //
            if (cache != null && (list == null || list.IsReadOnly))
            {
                FilterCacheItem cacheItem = cache[_pipelineFilterKeys[pipelineType]] as FilterCacheItem;
                if (cacheItem != null && cacheItem.IsValid(componentFilter)) {
                    return cacheItem.FilteredMembers;
                }
            }

            // Cache either is dirty or doesn't exist.  Re-filter the members.
            // We need to build an IDictionary of key->value pairs and invoke
            // Filter* on the filter service.
            //
            OrderedDictionary filterTable = new OrderedDictionary(members.Count);
            bool cacheResults;

            switch(pipelineType)
            {
                case PIPELINE_ATTRIBUTES:
                    foreach(Attribute attr in members)
                    {
                        filterTable[attr.TypeId] = attr;
                    }
                    cacheResults = componentFilter.FilterAttributes(component, filterTable);
                    break;

                case PIPELINE_PROPERTIES:
                case PIPELINE_EVENTS:
                    foreach(MemberDescriptor desc in members)
                    {
                        string descName = desc.Name;
                        // We must handle the case of duplicate property names
                        // because extender providers can provide any arbitrary
                        // name.  Our rule for this is simple:  If we find a
                        // duplicate name, resolve it back to the extender
                        // provider that offered it and append "_" + the
                        // provider name.  If the provider has no name,
                        // then append the object hash code.
                        //
                        if (filterTable.Contains(descName)) 
                        {
                            // First, handle the new property.  Because
                            // of the order in which we added extended
                            // properties earlier in the pipeline, we can be 
                            // sure that the new property is an extender.  We
                            // cannot be sure that the existing property
                            // in the table is an extender, so we will 
                            // have to check.
                            //
                            string suffix = GetExtenderCollisionSuffix(desc);
                            Debug.Assert(suffix != null, "Name collision with non-extender property.");
                            if (suffix != null) 
                            {
                                filterTable[descName + suffix] = desc;
                            }

                            // Now, handle the original property.
                            //
                            MemberDescriptor origDesc = (MemberDescriptor)filterTable[descName];
                            suffix = GetExtenderCollisionSuffix(origDesc);
                            if (suffix != null) 
                            {
                                filterTable.Remove(descName);
                                filterTable[origDesc.Name + suffix] = origDesc;
                            }
                        }
                        else 
                        {
                            filterTable[descName] = desc;
                        }
                    }
                    if (pipelineType == PIPELINE_PROPERTIES)
                    {
                        cacheResults = componentFilter.FilterProperties(component, filterTable);
                    }
                    else
                    {
                        cacheResults = componentFilter.FilterEvents(component, filterTable);
                    }
                    break;

                default:
                    Debug.Fail("unknown pipeline type");
                    cacheResults = false;
                    break;
            }

            // See if we can re-use the IList were were passed.  If we can,
            // it is more efficient to re-use its slots than to generate new ones.
            //
            if (list == null || list.IsReadOnly)
            {
                Trace("Pipeline : Filter needs to create member list for {0}", instance.GetType().Name);
                list = new ArrayList(filterTable.Values);
            }
            else
            {
                list.Clear();
                foreach(object obj in filterTable.Values)
                {
                    list.Add(obj);
                }
            }

            // Component filter has requested that we cache these
            // new changes.  We store them as a correctly typed collection
            // so on successive invocations we can simply return.  Note that
            // we always return the IList so that successive stages in the
            // pipeline can modify it.
            //
            if (cacheResults && cache != null)
            {
                ICollection cacheValue;

                switch(pipelineType)
                {
                    case PIPELINE_ATTRIBUTES:
                        Attribute[] attrArray = new Attribute[list.Count];
                        try
                        {
                            list.CopyTo(attrArray, 0);
                        }
                        catch(InvalidCastException)
                        {
                            throw new ArgumentException(SR.GetString(SR.TypeDescriptorExpectedElementType, typeof(Attribute).FullName));
                        }
                        cacheValue = new AttributeCollection(attrArray);
                        break;

                    case PIPELINE_PROPERTIES:
                        PropertyDescriptor[] propArray = new PropertyDescriptor[list.Count];
                        try
                        {
                            list.CopyTo(propArray, 0);
                        }
                        catch(InvalidCastException)
                        {
                            throw new ArgumentException(SR.GetString(SR.TypeDescriptorExpectedElementType, typeof(PropertyDescriptor).FullName));
                        }
                        cacheValue = new PropertyDescriptorCollection(propArray, true);
                        break;

                    case PIPELINE_EVENTS:
                        EventDescriptor[] eventArray = new EventDescriptor[list.Count];
                        try
                        {
                            list.CopyTo(eventArray, 0);
                        }
                        catch(InvalidCastException)
                        {
                            throw new ArgumentException(SR.GetString(SR.TypeDescriptorExpectedElementType, typeof(EventDescriptor).FullName));
                        }
                        cacheValue = new EventDescriptorCollection(eventArray, true);
                        break;

                    default:
                        Debug.Fail("unknown pipeline type");
                        cacheValue = null;
                        break;
                }

                Trace("Pipeline : Filter results being cached for {0}", instance.GetType().Name);

                FilterCacheItem cacheItem = new FilterCacheItem(componentFilter, cacheValue);
                cache[_pipelineFilterKeys[pipelineType]] = cacheItem;
                cache.Remove(_pipelineAttributeFilterKeys[pipelineType]);
            }

            return list;
        }
            /// <devdoc>
            ///     Helper method to return an editor attribute of the correct base type.
            /// </devdoc>
            private static EditorAttribute GetEditorAttribute(AttributeCollection attributes, Type editorBaseType)
            {
                foreach(Attribute attr in attributes)
                {
                    EditorAttribute edAttr = attr as EditorAttribute;
                    if (edAttr != null)
                    {
                        Type attrEditorBaseType = Type.GetType(edAttr.EditorBaseTypeName);

                        if (attrEditorBaseType != null && attrEditorBaseType == editorBaseType) 
                        {
                            return edAttr;
                        }
                    }
                }

                return null;
            }
 /// <devdoc>
 ///     Refreshes the contents of this type descriptor.  This does not
 ///     actually requery, but it will clear our state so the next
 ///     query re-populates.
 /// </devdoc>
 internal void Refresh()
 {
     _attributes = null;
     _events = null;
     _properties = null;
     _converter = null;
     _editors = null;
     _editorTypes = null;
     _editorCount = 0;
 }
 public AttributeListTest()
 {
     _testAttributes = new Attribute[] { new TestAttribute(), new DerivedAttribute(), new DerivedDerivedAttribute() };
     _collection     = new AttributeCollection(_testAttributes);
     _list           = new AttributeList(_collection);
 }
            /// <devdoc>
            ///     Retrieves custom attributes.
            /// </devdoc>
            internal AttributeCollection GetAttributes()
            {
                // Worst case collision scenario:  we don't want the perf hit
                // of taking a lock, so if we collide we will query for
                // attributes twice.  Not a big deal.
                //
                if (_attributes == null)
                {
                    TypeDescriptor.Trace("Attributes : Building collection for {0}", _type.Name);

                    // Obtaining attributes follows a very critical order: we must take care that
                    // we merge attributes the right way.  Consider this:
                    //
                    // [A4]
                    // interface IBase;
                    //
                    // [A3]
                    // interface IDerived;
                    //
                    // [A2]
                    // class Base : IBase;
                    //
                    // [A1]
                    // class Derived : Base, IDerived
                    //
                    // Calling GetAttributes on type Derived must merge attributes in the following
                    // order:  A1 - A4.  Interfaces always lose to types, and interfaces and types
                    // must be merged in the same order.  At the same time, we must be careful
                    // that we don't always go through reflection here, because someone could have
                    // created a custom provider for a type.  Because there is only one instance
                    // of ReflectTypeDescriptionProvider created for typeof(object), if our code
                    // is invoked here we can be sure that there is no custom provider for
                    // _type all the way up the base class chain.
                    // We cannot be sure that there is no custom provider for
                    // interfaces that _type implements, however, because they are not derived
                    // from _type.  So, for interfaces, we must go through TypeDescriptor
                    // again to get the interfaces attributes.  

                    // Get the type's attributes. This does not recurse up the base class chain.
                    // We append base class attributes to this array so when walking we will
                    // walk from Length - 1 to zero.
                    //
                    Attribute[] attrArray = ReflectTypeDescriptionProvider.ReflectGetAttributes(_type);
                    Type baseType = _type.BaseType;

                    while (baseType != null && baseType != typeof(object))
                    {
                        Attribute[] baseArray = ReflectTypeDescriptionProvider.ReflectGetAttributes(baseType);
                        Attribute[] temp = new Attribute[attrArray.Length + baseArray.Length];
                        Array.Copy(attrArray, 0, temp, 0, attrArray.Length);
                        Array.Copy(baseArray, 0, temp, attrArray.Length, baseArray.Length);
                        attrArray = temp;
                        baseType = baseType.BaseType;
                    }

                    // Next, walk the type's interfaces.  We append these to
                    // the attribute array as well.
                    //
                    int ifaceStartIdx = attrArray.Length;
                    Type[] interfaces = _type.GetInterfaces(); 
                    TypeDescriptor.Trace("Attributes : Walking {0} interfaces", interfaces.Length);
                    for(int idx = 0; idx < interfaces.Length; idx++)
                    {
                        Type iface = interfaces[idx];

                        // only do this for public interfaces.
                        //
                        if ((iface.Attributes & (TypeAttributes.Public | TypeAttributes.NestedPublic)) != 0) {
                            // No need to pass an instance into GetTypeDescriptor here because, if someone provided a custom
                            // provider based on object, it already would have hit.
                            AttributeCollection ifaceAttrs = TypeDescriptor.GetAttributes(iface);
                            if (ifaceAttrs.Count > 0) {
                                Attribute[] temp = new Attribute[attrArray.Length + ifaceAttrs.Count];
                                Array.Copy(attrArray, 0, temp, 0, attrArray.Length);
                                ifaceAttrs.CopyTo(temp, attrArray.Length);
                                attrArray = temp;
                            }
                        }
                    }

                    // Finally, put all these attributes in a dictionary and filter out the duplicates.
                    //
                    OrderedDictionary attrDictionary = new OrderedDictionary(attrArray.Length);

                    for (int idx = 0; idx < attrArray.Length; idx++)
                    {
                        bool addAttr = true;
                        if (idx >= ifaceStartIdx) {
                            for (int ifaceSkipIdx = 0; ifaceSkipIdx < _skipInterfaceAttributeList.Length; ifaceSkipIdx++)
                            {
                                if (_skipInterfaceAttributeList[ifaceSkipIdx].IsInstanceOfType(attrArray[idx]))
                                {
                                    addAttr = false;
                                    break;
                                }
                            }

                        }

                        if (addAttr && !attrDictionary.Contains(attrArray[idx].TypeId)) {
                            attrDictionary[attrArray[idx].TypeId] = attrArray[idx];
                        }
                    }

                    attrArray = new Attribute[attrDictionary.Count];
                    attrDictionary.Values.CopyTo(attrArray, 0);
                    _attributes = new AttributeCollection(attrArray);
                }

                return _attributes;
            }
        private static void DebugValidate(AttributeCollection attributes, AttributeCollection debugAttributes)
        {
            #if DEBUG

            if (attributes.Count >= debugAttributes.Count)
            {
                foreach(Attribute a in attributes)
                {
                    if (!(a is GuidAttribute) && !(a is ComVisibleAttribute))
                    {
                        bool found = false;
                        bool typeFound = false;
    
                        // Many attributes don't implement .Equals correctly,
                        // so they will fail an equality check.  But we want to 
                        // make sure that common ones like Browsable and ReadOnly
                        // were correctly picked up.  So only check the ones in
                        // component model.
                        if (!a.GetType().FullName.StartsWith("System.Component"))
                        {
                            found = true;
                            break;
                        }
    
                        if (!found)
                        {
                            foreach(Attribute b in debugAttributes)
                            {
                                if (!typeFound && a.GetType() == b.GetType())
                                {
                                    typeFound = true;
                                }
    
                                // Semitrust may throw here.  
                                try
                                {
                                    if (a.Equals(b))
                                    {
                                        found = true;
                                        break;
                                    }
                                }
                                catch
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }
    
                        if (!found && !a.IsDefaultAttribute())
                        {
                            if (typeFound)
                            {
                                Debug.Fail(string.Format(CultureInfo.InvariantCulture, "TypeDescriptor engine Validation Failure. Attribute {0} was found but failed equality.  Perhaps attribute .Equals is not implemented correctly?", a.GetType().Name));
                            }
                            else
                            {
                                Debug.Fail(string.Format(CultureInfo.InvariantCulture, "TypeDescriptor engine Validation Failure. Attribute {0} should not exist", a.GetType().Name));
                            }
                        }
                    }
                }
            }
            else
            {
                foreach(Attribute b in debugAttributes)
                {
                    // We skip all interop attributes because interface merging has changed on purpose.  
                    if (!(b is GuidAttribute) && !(b is ComVisibleAttribute) && !(b is InterfaceTypeAttribute) && !(b is ReadOnlyAttribute))
                    {
                        bool found = false;
                        bool typeFound = false;
    
                        // Many attributes don't implement .Equals correctly,
                        // so they will fail an equality check.  But we want to 
                        // make sure that common ones like Browsable and ReadOnly
                        // were correctly picked up.  So only check the ones in
                        // component model.
                        if (!b.GetType().FullName.StartsWith("System.Component"))
                        {
                            found = true;
                            break;
                        }
    
                        if (!found)
                        {
                            foreach(Attribute a in attributes)
                            {
                                if (!typeFound && a.GetType() == b.GetType())
                                {
                                    typeFound = true;
                                }
    
                                // Semitrust may throw here.  
                                try
                                {
                                    if (b.Equals(a))
                                    {
                                        found = true;
                                        break;
                                    }
                                }
                                catch
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }
    
                        if (!found && !b.IsDefaultAttribute())
                        {
                            if (!typeFound)
                            {
                                Debug.Fail(string.Format(CultureInfo.InvariantCulture, "TypeDescriptor engine Validation Failure. Attribute {0} should exist", b.GetType().Name));
                            }
                        }
                    }
                }
            }
#endif
        }
 private static void DebugValidate(AttributeCollection attributes, object instance, bool noCustomTypeDesc)
 {
     #if DEBUG
     if (!DebugShouldValidate(instance)) return;
     AttributeCollection debugAttributes = DebugTypeDescriptor.GetAttributes(instance, noCustomTypeDesc);
     DebugValidate(attributes, debugAttributes);
     #endif
 }
        /// <devdoc>
        ///     Metadata merging is the second stage of our metadata pipeline.  This stage
        ///     merges extended metdata with primary metadata, and stores it in 
        ///     the cache if it is available.
        /// </devdoc>
        private static ICollection PipelineMerge(int pipelineType, ICollection primary, ICollection secondary, object instance, IDictionary cache)
        {
            // If there is no secondary collection, there is nothing to merge.
            //
            if (secondary == null || secondary.Count == 0)
            {
                return primary;
            }

            // Next, if we were given a cache, see if it has accurate data.
            //
            if (cache != null)
            {
                ICollection mergeCache = cache[_pipelineMergeKeys[pipelineType]] as ICollection;
                if (mergeCache != null && mergeCache.Count == (primary.Count + secondary.Count))
                {
                    // Walk the merge cache.
                    IEnumerator mergeEnum = mergeCache.GetEnumerator();
                    IEnumerator primaryEnum = primary.GetEnumerator();
                    bool match = true;

                    while(primaryEnum.MoveNext() && mergeEnum.MoveNext())
                    {
                        if (primaryEnum.Current != mergeEnum.Current)
                        {
                            match = false;
                            break;
                        }
                    }

                    if (match)
                    {
                        IEnumerator secondaryEnum = secondary.GetEnumerator();

                        while(secondaryEnum.MoveNext() && mergeEnum.MoveNext())
                        {
                            if (secondaryEnum.Current != mergeEnum.Current)
                            {
                                match = false;
                                break;
                            }
                        }
                    }

                    if (match)
                    {
                        return mergeCache;
                    }
                }
            }

            // Our cache didn't match.  We need to merge metadata and return
            // the merged copy.  We create an array list here, rather than
            // an array, because we want successive sections of the 
            // pipeline to be able to modify it.
            //
            ArrayList list = new ArrayList(primary.Count + secondary.Count);
            foreach(object obj in primary)
            {
                list.Add(obj);
            }
            foreach(object obj in secondary)
            {
                list.Add(obj);
            }

            if (cache != null)
            {
                ICollection cacheValue;

                switch(pipelineType)
                {
                    case PIPELINE_ATTRIBUTES:
                        Attribute[] attrArray = new Attribute[list.Count];
                        list.CopyTo(attrArray, 0);
                        cacheValue = new AttributeCollection(attrArray);
                        break;

                    case PIPELINE_PROPERTIES:
                        PropertyDescriptor[] propArray = new PropertyDescriptor[list.Count];
                        list.CopyTo(propArray, 0);
                        cacheValue = new PropertyDescriptorCollection(propArray, true);
                        break;

                    case PIPELINE_EVENTS:
                        EventDescriptor[] eventArray = new EventDescriptor[list.Count];
                        list.CopyTo(eventArray, 0);
                        cacheValue = new EventDescriptorCollection(eventArray, true);
                        break;

                    default:
                        Debug.Fail("unknown pipeline type");
                        cacheValue = null;
                        break;
                }

                Trace("Pipeline : Merge results being cached for {0}", instance.GetType().Name);
                cache[_pipelineMergeKeys[pipelineType]] = cacheValue;
                cache.Remove(_pipelineFilterKeys[pipelineType]);
                cache.Remove(_pipelineAttributeFilterKeys[pipelineType]);
            }

            return list;
        }
Beispiel #49
0
        public static void DescribeComponent(object instance, ScriptComponentDescriptor descriptor, IUrlResolutionService urlResolver, IControlResolver controlResolver)
        {
            // validate preconditions
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }
            if (urlResolver == null)
            {
                urlResolver = instance as IUrlResolutionService;
            }
            if (controlResolver == null)
            {
                controlResolver = instance as IControlResolver;
            }

            // describe properties
            // PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);

            PropertyInfo[] properties = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (PropertyInfo prop in properties)
            {
                ScriptControlPropertyAttribute propAttr  = null;
                ScriptControlEventAttribute    eventAttr = null;
                string propertyName = prop.Name;

                System.ComponentModel.AttributeCollection attribs = new System.ComponentModel.AttributeCollection(Attribute.GetCustomAttributes(prop, false));

                // Try getting a property attribute
                propAttr = (ScriptControlPropertyAttribute)attribs[typeof(ScriptControlPropertyAttribute)];
                if (propAttr == null || !propAttr.IsScriptProperty)
                {
                    // Try getting an event attribute
                    eventAttr = (ScriptControlEventAttribute)attribs[typeof(ScriptControlEventAttribute)];
                    if (eventAttr == null || !eventAttr.IsScriptEvent)
                    {
                        continue;
                    }
                }

                // attempt to rename the property/event
                ClientPropertyNameAttribute nameAttr = (ClientPropertyNameAttribute)attribs[typeof(ClientPropertyNameAttribute)];
                if (nameAttr != null && !string.IsNullOrEmpty(nameAttr.PropertyName))
                {
                    propertyName = nameAttr.PropertyName;
                }

                // determine whether to serialize the value of a property.  readOnly properties should always be serialized
                //bool serialize = true;// prop.ShouldSerializeValue(instance) || prop.IsReadOnly;
                //if (serialize)
                //{
                // get the value of the property, skip if it is null
                Control c     = null;
                object  value = prop.GetValue(instance, new object[0] {
                });
                if (value == null)
                {
                    continue;
                }

                // convert and resolve the value
                if (eventAttr != null && prop.PropertyType != typeof(String))
                {
                    throw new InvalidOperationException("ScriptControlEventAttribute can only be applied to a property with a PropertyType of System.String.");
                }
                else
                {
                    if (!prop.PropertyType.IsPrimitive && !prop.PropertyType.IsEnum)
                    {
                        if (prop.PropertyType == typeof(Color))
                        {
                            value = ColorTranslator.ToHtml((Color)value);
                        }
                        else
                        {
                            // TODO: Determine if we should let ASP.NET AJAX handle this type of conversion, as it supports JSON serialization
                            //TypeConverter conv = prop.Converter;
                            //value = conv.ConvertToString(null, CultureInfo.InvariantCulture, value);

                            //if (prop.PropertyType == typeof(CssStyleCollection))
                            //    value = (new CssStyleCollectionJSCoverter()).Serialize(value, new JavaScriptSerializer());
                            //if (prop.PropertyType == typeof(Style))
                            //    value = (new CssStyleCollectionJSCoverter()).Serialize(((Style)value).GetStyleAttributes(null), new JavaScriptSerializer());

                            Type valueType = value.GetType();

                            JavaScriptConverterAttribute attr      = (JavaScriptConverterAttribute)attribs[typeof(JavaScriptConverterAttribute)];
                            JavaScriptConverter          converter = attr != null ?
                                                                     (JavaScriptConverter)TypeCreator.CreateInstance(attr.ConverterType) :
                                                                     JSONSerializerFactory.GetJavaScriptConverter(valueType);

                            if (converter != null)
                            {
                                value = converter.Serialize(value, JSONSerializerFactory.GetJavaScriptSerializer());
                            }
                            else
                            {
                                value = JSONSerializerExecute.PreSerializeObject(value);
                            }

                            //Dictionary<string, object> dict = value as Dictionary<string, object>;
                            //if (dict != null && !dict.ContainsKey("__type"))
                            //    dict["__type"] = valueType.AssemblyQualifiedName;
                        }
                    }
                    if (attribs[typeof(IDReferencePropertyAttribute)] != null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (attribs[typeof(UrlPropertyAttribute)] != null && urlResolver != null)
                    {
                        value = urlResolver.ResolveClientUrl((string)value);
                    }
                }

                // add the value as an appropriate description
                if (eventAttr != null)
                {
                    if (!string.IsNullOrEmpty((string)value))
                    {
                        descriptor.AddEvent(propertyName, (string)value);
                    }
                }
                else if (attribs[typeof(ElementReferenceAttribute)] != null)
                {
                    if (c == null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (c != null)
                    {
                        value = c.ClientID;
                    }
                    descriptor.AddElementProperty(propertyName, (string)value);
                }
                else if (attribs[typeof(ComponentReferenceAttribute)] != null)
                {
                    if (c == null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (c != null)
                    {
                        //ExtenderControlBase ex = c as ExtenderControlBase;
                        //if (ex != null && ex.BehaviorID.Length > 0)
                        //    value = ex.BehaviorID;
                        //else
                        value = c.ClientID;
                    }
                    descriptor.AddComponentProperty(propertyName, (string)value);
                }
                else
                {
                    if (c != null)
                    {
                        value = c.ClientID;
                    }
                    descriptor.AddProperty(propertyName, value);
                }
            }
            //}

            // determine if we should describe methods
            foreach (MethodInfo method in instance.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public))
            {
                ScriptControlMethodAttribute methAttr = (ScriptControlMethodAttribute)Attribute.GetCustomAttribute(method, typeof(ScriptControlMethodAttribute));
                if (methAttr == null || !methAttr.IsScriptMethod)
                {
                    continue;
                }

                // We only need to support emitting the callback target and registering the WebForms.js script if there is at least one valid method
                Control control = instance as Control;
                if (control != null)
                {
                    // Force WebForms.js
                    control.Page.ClientScript.GetCallbackEventReference(control, null, null, null);

                    // Add the callback target
                    descriptor.AddProperty("_callbackTarget", control.UniqueID);
                }
                break;
            }
        }
Beispiel #50
0
        /// <devdoc>
        ///     Creates a new AttributeCollection from an existing AttributeCollection
        /// </devdoc>
        public static AttributeCollection FromExisting(AttributeCollection existing, params Attribute[] newAttributes)
        {
            // VSWhidbey #75418
            // This method should be a constructor, but making it one introduces a breaking change.
            //
            if (existing == null)
            {
                throw new ArgumentNullException("existing");
            }

            if (newAttributes == null)
            {
                newAttributes = new Attribute[0];
            }

            Attribute[] newArray    = new Attribute[existing.Count + newAttributes.Length];
            int         actualCount = existing.Count;

            existing.CopyTo(newArray, 0);

            for (int idx = 0; idx < newAttributes.Length; idx++)
            {
                if (newAttributes[idx] == null)
                {
                    throw new ArgumentNullException("newAttributes");
                }

                // We must see if this attribute is already in the existing
                // array.  If it is, we replace it.
                bool match = false;
                for (int existingIdx = 0; existingIdx < existing.Count; existingIdx++)
                {
                    if (newArray[existingIdx].TypeId.Equals(newAttributes[idx].TypeId))
                    {
                        match = true;
                        newArray[existingIdx] = newAttributes[idx];
                        break;
                    }
                }

                if (!match)
                {
                    newArray[actualCount++] = newAttributes[idx];
                }
            }

            // Now, if we collapsed some attributes, create a new array.
            //

            Attribute[] attributes = null;
            if (actualCount < newArray.Length)
            {
                attributes = new Attribute[actualCount];
                Array.Copy(newArray, 0, attributes, 0, actualCount);
            }
            else
            {
                attributes = newArray;
            }

            return(new AttributeCollection(attributes));
        }
        /// <summary>
        /// Gets an editor of the specified type.
        /// </summary>
        public virtual object GetEditor(Type editorBaseType)
        {
            object editor = null;

            // Always grab the attribute collection first here, because if the metadata version
            // changes it will invalidate our editor cache.
            AttributeCollection attrs = Attributes;

            // Check the editors we've already created for this type.
            if (_editorTypes != null)
            {
                for (int i = 0; i < _editorCount; i++)
                {
                    if (_editorTypes[i] == editorBaseType)
                    {
                        return _editors[i];
                    }
                }
            }

            // If one wasn't found, then we must go through the attributes.
            if (editor == null)
            {
                for (int i = 0; i < attrs.Count; i++)
                {
                    if (!(attrs[i] is EditorAttribute attr))
                    {
                        continue;
                    }

                    Type editorType = GetTypeFromName(attr.EditorBaseTypeName);

                    if (editorBaseType == editorType)
                    {
                        Type type = GetTypeFromName(attr.EditorTypeName);
                        if (type != null)
                        {
                            editor = CreateInstance(type);
                            break;
                        }
                    }
                }

                // Now, if we failed to find it in our own attributes, go to the
                // component descriptor.
                if (editor == null)
                {
                    editor = TypeDescriptor.GetEditor(PropertyType, editorBaseType);
                }

                // Now, another slot in our editor cache for next time
                if (_editorTypes == null)
                {
                    _editorTypes = new Type[5];
                    _editors = new object[5];
                }

                if (_editorCount >= _editorTypes.Length)
                {
                    Type[] newTypes = new Type[_editorTypes.Length * 2];
                    object[] newEditors = new object[_editors.Length * 2];
                    Array.Copy(_editorTypes, newTypes, _editorTypes.Length);
                    Array.Copy(_editors, newEditors, _editors.Length);
                    _editorTypes = newTypes;
                    _editors = newEditors;
                }

                _editorTypes[_editorCount] = editorBaseType;
                _editors[_editorCount++] = editor;
            }

            return editor;
        }
 public AttributeList(AttributeCollection attributes)
 {
     Contract.Assert(attributes != null);
     _attributes = attributes;
 }
 private static void DebugValidate(Type type, AttributeCollection attributes, AttributeCollection debugAttributes)
 {
     #if DEBUG
     if (!DebugShouldValidate(type)) return;
     DebugValidate(attributes, debugAttributes);
     #endif
 }
            /// <summary>
            ///     Retrieves custom attributes.
            /// </summary>
            internal AttributeCollection GetAttributes()
            {
                // Worst case collision scenario:  we don't want the perf hit
                // of taking a lock, so if we collide we will query for
                // attributes twice.  Not a big deal.
                //
                if (_attributes == null)
                {
                    // Obtaining attributes follows a very critical order: we must take care that
                    // we merge attributes the right way.  Consider this:
                    //
                    // [A4]
                    // interface IBase;
                    //
                    // [A3]
                    // interface IDerived;
                    //
                    // [A2]
                    // class Base : IBase;
                    //
                    // [A1]
                    // class Derived : Base, IDerived
                    //
                    // Calling GetAttributes on type Derived must merge attributes in the following
                    // order:  A1 - A4.  Interfaces always lose to types, and interfaces and types
                    // must be merged in the same order.  At the same time, we must be careful
                    // that we don't always go through reflection here, because someone could have
                    // created a custom provider for a type.  Because there is only one instance
                    // of ReflectTypeDescriptionProvider created for typeof(object), if our code
                    // is invoked here we can be sure that there is no custom provider for
                    // _type all the way up the base class chain.
                    // We cannot be sure that there is no custom provider for
                    // interfaces that _type implements, however, because they are not derived
                    // from _type.  So, for interfaces, we must go through TypeDescriptor
                    // again to get the interfaces attributes.

                    // Get the type's attributes. This does not recurse up the base class chain.
                    // We append base class attributes to this array so when walking we will
                    // walk from Length - 1 to zero.
                    //
                    Attribute[] attrArray = ReflectTypeDescriptionProvider.ReflectGetAttributes(_type);
                    Type        baseType  = _type.BaseType;

                    while (baseType != null && baseType != typeof(object))
                    {
                        Attribute[] baseArray = ReflectTypeDescriptionProvider.ReflectGetAttributes(baseType);
                        Attribute[] temp      = new Attribute[attrArray.Length + baseArray.Length];
                        Array.Copy(attrArray, 0, temp, 0, attrArray.Length);
                        Array.Copy(baseArray, 0, temp, attrArray.Length, baseArray.Length);
                        attrArray = temp;
                        baseType  = baseType.BaseType;
                    }

                    // Next, walk the type's interfaces.  We append these to
                    // the attribute array as well.
                    //
                    int    ifaceStartIdx = attrArray.Length;
                    Type[] interfaces    = _type.GetInterfaces();
                    for (int idx = 0; idx < interfaces.Length; idx++)
                    {
                        Type iface = interfaces[idx];

                        // only do this for public interfaces.
                        //
                        if ((iface.Attributes & (TypeAttributes.Public | TypeAttributes.NestedPublic)) != 0)
                        {
                            // No need to pass an instance into GetTypeDescriptor here because, if someone provided a custom
                            // provider based on object, it already would have hit.
                            AttributeCollection ifaceAttrs = TypeDescriptor.GetAttributes(iface);
                            if (ifaceAttrs.Count > 0)
                            {
                                Attribute[] temp = new Attribute[attrArray.Length + ifaceAttrs.Count];
                                Array.Copy(attrArray, 0, temp, 0, attrArray.Length);
                                ifaceAttrs.CopyTo(temp, attrArray.Length);
                                attrArray = temp;
                            }
                        }
                    }

                    // Finally, put all these attributes in a dictionary and filter out the duplicates.
                    //
                    OrderedDictionary attrDictionary = new OrderedDictionary(attrArray.Length);

                    for (int idx = 0; idx < attrArray.Length; idx++)
                    {
                        bool addAttr = true;
                        if (idx >= ifaceStartIdx)
                        {
                            for (int ifaceSkipIdx = 0; ifaceSkipIdx < s_skipInterfaceAttributeList.Length; ifaceSkipIdx++)
                            {
                                if (s_skipInterfaceAttributeList[ifaceSkipIdx].IsInstanceOfType(attrArray[idx]))
                                {
                                    addAttr = false;
                                    break;
                                }
                            }
                        }

                        if (addAttr && !attrDictionary.Contains(attrArray[idx].TypeId))
                        {
                            attrDictionary[attrArray[idx].TypeId] = attrArray[idx];
                        }
                    }

                    attrArray = new Attribute[attrDictionary.Count];
                    attrDictionary.Values.CopyTo(attrArray, 0);
                    _attributes = new AttributeCollection(attrArray);
                }

                return(_attributes);
            }
 private static void DebugValidate(AttributeCollection attributes, Type type)
 {
     #if DEBUG
     if (!DebugShouldValidate(type)) return;
     AttributeCollection debugAttributes = DebugTypeDescriptor.GetAttributes(type);
     DebugValidate(attributes, debugAttributes);
     #endif
 }
Beispiel #56
0
            internal AttributeCollection GetAttributes()
            {
                // Worst case collision scenario:  we don't want the perf hit
                // of taking a lock, so if we collide we will query for
                // attributes twice. Not a big deal.
                if (_attributes == null)
                {
                    // Obtaining attributes follows a very critical order: we must take care that
                    // we merge attributes the right way. Consider this:
                    //
                    // [A4]
                    // interface IBase;
                    //
                    // [A3]
                    // interface IDerived;
                    //
                    // [A2]
                    // class Base : IBase;
                    //
                    // [A1]
                    // class Derived : Base, IDerived
                    //
                    // Calling GetAttributes on type Derived must merge attributes in the following
                    // order:  A1 - A4. Interfaces always lose to types, and interfaces and types
                    // must be merged in the same order. At the same time, we must be careful
                    // that we don't always go through reflection here, because someone could have
                    // created a custom provider for a type. Because there is only one instance
                    // of ReflectTypeDescriptionProvider created for typeof(object), if our code
                    // is invoked here we can be sure that there is no custom provider for
                    // _type all the way up the base class chain.
                    // We cannot be sure that there is no custom provider for
                    // interfaces that _type implements, however, because they are not derived
                    // from _type. So, for interfaces, we must go through TypeDescriptor
                    // again to get the interfaces attributes.

                    // Get the type's attributes. This does not recurse up the base class chain.
                    // We append base class attributes to this array so when walking we will
                    // walk from Length - 1 to zero.
                    //

                    var  attributes = new List <Attribute>(ReflectGetAttributes(_type));
                    Type baseType   = _type.BaseType;

                    while (baseType != null && baseType != typeof(object))
                    {
                        attributes.AddRange(ReflectGetAttributes(baseType));
                        baseType = baseType.BaseType;
                    }

                    // Next, walk the type's interfaces. We append these to
                    // the attribute array as well.
                    int    ifaceStartIdx = attributes.Count;
                    Type[] interfaces    = _type.GetInterfaces();
                    for (int idx = 0; idx < interfaces.Length; idx++)
                    {
                        // Only do this for public interfaces.
                        Type iface = interfaces[idx];
                        if ((iface.Attributes & (TypeAttributes.Public | TypeAttributes.NestedPublic)) != 0)
                        {
                            // No need to pass an instance into GetTypeDescriptor here because, if someone provided a custom
                            // provider based on object, it already would have hit.
                            attributes.AddRange(TypeDescriptor.GetAttributes(iface).Attributes);
                        }
                    }

                    // Finally, filter out duplicates.
                    if (attributes.Count != 0)
                    {
                        var filter = new HashSet <object>(attributes.Count);
                        int next   = 0;

                        for (int idx = 0; idx < attributes.Count; idx++)
                        {
                            Attribute attr = attributes[idx];

                            bool addAttr = true;
                            if (idx >= ifaceStartIdx)
                            {
                                for (int ifaceSkipIdx = 0; ifaceSkipIdx < s_skipInterfaceAttributeList.Length; ifaceSkipIdx++)
                                {
                                    if (s_skipInterfaceAttributeList[ifaceSkipIdx].IsInstanceOfType(attr))
                                    {
                                        addAttr = false;
                                        break;
                                    }
                                }
                            }

                            if (addAttr && filter.Add(attr.TypeId))
                            {
                                attributes[next++] = attributes[idx];
                            }
                        }

                        attributes.RemoveRange(next, attributes.Count - next);
                    }

                    _attributes = new AttributeCollection(attributes.ToArray());
                }

                return(_attributes);
            }
 public static bool ContainsAttributeType <TAttribute>(this AttributeCollection attributes) where TAttribute : Attribute
 {
     return(attributes.Cast <Attribute>().Any(a => a.GetType() == typeof(TAttribute)));
 }
 public override AttributeCollection GetAttributes()
 {
     ArrayList collection = new ArrayList();
     foreach (Attribute attribute in base.GetAttributes())
     {
         //should not have any editor attribute and only one readonly attribute
         if (!(attribute is EditorAttribute || attribute is ReadOnlyAttribute))
             collection.Add(attribute);
     }
     collection.Add(new ReadOnlyAttribute(true));
     AttributeCollection newCollection = new AttributeCollection((Attribute[])collection.ToArray(typeof(Attribute)));
     return newCollection;
 }