Example #1
0
    /// <summary>
    /// 判断某个 ICustomAttributeProvider 对象实例是否具有 TAttribute 类型的特性
    /// </summary>
    /// <typeparam name="TAttribute"></typeparam>
    /// <param name="provider"></param>
    /// <param name="inherit"></param>
    /// <returns></returns>
    public static bool HasAttribute <TAttribute>(this ICustomAttributeProvider provider, bool inherit = false)
        where TAttribute : Attribute
    {
        var attrs = provider.GetAttributes <TAttribute>(inherit);

        return(attrs != null && attrs.Length > 0);
    }
        private static AccessorMember MaybeSwapMetadataMember(ICustomAttributeProvider authority, AccessorMember member,
                                                              string profile)
        {
            foreach (var attribute in authority.GetAttributes <MetadataTypeAttribute>())
            {
                if (attribute.Profile != profile)
                {
                    continue;
                }

                var types = AccessorMemberTypes.None;
                types |= member.MemberType switch
                {
                    AccessorMemberType.Field => AccessorMemberTypes.Fields,
                    AccessorMemberType.Property => AccessorMemberTypes.Properties,
                    AccessorMemberType.Method => AccessorMemberTypes.Methods,
                    _ => throw new ArgumentOutOfRangeException()
                };

                var members = AccessorMembers.Create(attribute.MetadataType, types, member.Scope);
                foreach (var m in members)
                {
                    if (m.Name != member.Name)
                    {
                        continue;
                    }
                    member = m;
                    break;
                }
            }

            return(member);
        }
Example #3
0
 public IEnumerable<ValidationAttribute> GetAttributes(ICustomAttributeProvider attributeProvider)
 {
     return attributeProvider
         .GetAttributes<ValidationAttribute>()
         .Select(attr => container.BuildUp(attr.GetType(), attr))
         .Cast<ValidationAttribute>();
 }
        private ImmutableDictionary <string, object?> GetExportMetadata(ICustomAttributeProvider member)
        {
            Requires.NotNull(member, nameof(member));

            var result = ImmutableDictionary.CreateBuilder <string, object?>();
            var namesOfMetadataWithMultipleValues = new HashSet <string>(StringComparer.Ordinal);

            foreach (var attribute in member.GetAttributes <Attribute>())
            {
                var attrType = attribute.GetType().GetTypeInfo();
                var exportMetadataAttribute = attribute as ExportMetadataAttribute;
                if (exportMetadataAttribute != null)
                {
                    UpdateMetadataDictionary(result, namesOfMetadataWithMultipleValues, exportMetadataAttribute.Name, exportMetadataAttribute.Value, null);
                }
                else
                {
                    // Perf optimization, relies on short circuit evaluation, often a property attribute is an ExportAttribute
                    if (attrType != typeof(ExportAttribute).GetTypeInfo() && attrType.IsAttributeDefined <MetadataAttributeAttribute>(inherit: true))
                    {
                        var properties = attrType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                        foreach (var property in properties.Where(p => p.DeclaringType != typeof(Attribute)))
                        {
                            UpdateMetadataDictionary(result, namesOfMetadataWithMultipleValues, property.Name, property.GetValue(attribute), ReflectionHelpers.GetMemberType(property));
                        }
                    }
                }
            }

            return(result.ToImmutable());
        }
Example #5
0
        public static bool HasAttribute <TAttribute>(this ICustomAttributeProvider item)
            where TAttribute : Attribute
        {
            var attributes = item.GetAttributes <TAttribute>(true);

            return(attributes != null && attributes.Length > 0);
        }
Example #6
0
        /// <summary>
        /// Gets the first attribute and specifiy if attribute must match exactly the requested attribute type.
        /// </summary>
        /// <typeparam name="TAttribute">The type of the attribute.</typeparam>
        /// <param name="provider">The provider.</param>
        /// <param name="matchExactType">if set to <c>true</c> [match exact type].</param>
        /// <returns></returns>
        public static TAttribute GetAttribute <TAttribute>(this ICustomAttributeProvider provider, bool matchExactType) where TAttribute : Attribute
        {
            TAttribute[] tmp = provider.GetAttributes <TAttribute>(matchExactType);

            if (tmp.Length > 0)
            {
                return(tmp[0]);
            }
            return(null);
        }
        public static TAttribute?GetAttribute <TAttribute>(this ICustomAttributeProvider provider, bool inherit)
            where TAttribute : Attribute
        {
            if (provider is null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            return(provider.GetAttributes <TAttribute>(inherit).FirstOrDefault());
        }
 /// <summary>
 /// 返回<paramref name="provider"/>上定义的第一个<typeparamref name="TAttribute"/>属性。
 /// </summary>
 public static TAttribute GetAttribute <TAttribute>(
     this ICustomAttributeProvider provider,
     bool inherit = true)
     where TAttribute : Attribute
 {
     return
         (provider.IsDefined(typeof(TAttribute), inherit)
             ? provider.GetAttributes <TAttribute>(inherit)[0]
             : default(TAttribute));
 }
        /// <summary>
        /// Creates a set of import constraints for an import site.
        /// </summary>
        /// <param name="importSite">The importing member or parameter.</param>
        /// <returns>A set of import constraints.</returns>
        private static ImmutableHashSet <IImportSatisfiabilityConstraint> GetImportConstraints(ICustomAttributeProvider importSite)
        {
            Requires.NotNull(importSite, nameof(importSite));

            var constraints = ImmutableHashSet.CreateRange <IImportSatisfiabilityConstraint>(
                from importConstraint in importSite.GetAttributes <ImportMetadataConstraintAttribute>()
                select new ExportMetadataValueImportConstraint(importConstraint.Name, importConstraint.Value));

            return(constraints);
        }
        public static IEnumerable <TAttribute> GetAttributes <TAttribute>(this ICustomAttributeProvider provider, bool inherit)
            where TAttribute : Attribute
        {
            if (provider is null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            return(provider.GetAttributes(typeof(TAttribute), inherit).Cast <TAttribute>());
        }
Example #11
0
        public static T GetAttribute <T>(this ICustomAttributeProvider provider, bool inherit)
            where T : Attribute
        {
            var attrs = provider.GetAttributes <T>(inherit);

            if (attrs != null && attrs.Length > 0)
            {
                return(attrs[0]);
            }
            return(null);
        }
 /// <summary>
 /// Gets all attribute instances on a MemberInfo.
 /// </summary>
 /// <param name="member">The member.</param>
 /// <param name="inherit">If true, specifies to also search the ancestors of element for custom attributes.</param>
 public static Attribute[] GetAttributes(this ICustomAttributeProvider member, bool inherit)
 {
     try
     {
         return(member.GetAttributes <Attribute>(inherit).ToArray());
     }
     catch
     {
         return(new Attribute[0]);
     }
 }
Example #13
0
        public static A GetAttribute <A>(this ICustomAttributeProvider provider, bool inherit)
            where A : Attribute
        {
            var attributes = provider.GetAttributes <A>(inherit);

            if (attributes != null && attributes.Length > 0)
            {
                return((A)attributes[0]);
            }
            return(null);
        }
Example #14
0
        internal void TakeFromAttributes(ICustomAttributeProvider provider)
        {
            foreach (var meta in provider.GetAttributes <MetaAttribute>())
            {
                if (ContainsKey(meta.Key))
                {
                    continue;
                }

                this[meta.Key] = meta.Value;
            }
        }
Example #15
0
        public static bool TryGetAttributes <T>(this ICustomAttributeProvider provider, bool inherit,
                                                out IEnumerable <T> attributes) where T : Attribute
        {
            if (!provider.HasAttribute <T>())
            {
                attributes = Enumerable.Empty <T>();
                return(false);
            }

            attributes = provider.GetAttributes <T>(inherit);
            return(true);
        }
        public static TAttribute GetAttribute <TAttribute>(this ICustomAttributeProvider source)
            where TAttribute : Attribute
        {
            var attributes = source.GetAttributes <TAttribute>().ToList();

            if (!attributes.Any())
            {
                return(null);
            }

            return(attributes.FirstOrDefault());
        }
        public static IEnumerable <T> GetRequiredAttributes <T>(this ICustomAttributeProvider This, bool inherit = true)
        {
            var attributes = This.GetAttributes <T>(inherit).ToList();

            if (!attributes.Any())
            {
                throw new InvalidOperationException(
                          $"Missing required attribute of type {typeof(T).Name} on {This}");
            }

            return(attributes);
        }
Example #18
0
        /// <summary>
        /// Create all meta-data elements
        /// </summary>
        private void CreateMetaData(XElement parent, ICustomAttributeProvider provider)
        {
            // Create meta-data elements
            foreach (var attr in provider.GetAttributes(MetaDataAttribute))
            {
                var metaData = new XElement("meta-data");
                parent.Add(metaData);

                metaData.AddAttrIfNotEmpty("name", Namespace, attr.GetValue <string>(-1, "Name"));
                metaData.AddAttrIfNotEmpty("value", Namespace, attr.GetValue <string>(-1, "Value"));
                metaData.AddAttrIfNotEmpty("resource", Namespace, attr.GetValue <string>(-1, "Resource"), x => FormatResourceId(x, ResourceType.Unknown));
            }
        }
Example #19
0
        /// <summary>
        /// Create all meta-data elements
        /// </summary>
        private void CreateMetaData(XElement parent, ICustomAttributeProvider provider)
        {
            // Create meta-data elements
            foreach (var attr in provider.GetAttributes(MetaDataAttribute))
            {
                var metaData = new XElement("meta-data");
                parent.Add(metaData);

                metaData.AddAttrIfNotEmpty("name", Namespace, attr.GetValue<string>(-1, "Name"));
                metaData.AddAttrIfNotEmpty("value", Namespace, attr.GetValue<string>(-1, "Value"));
                metaData.AddAttrIfNotEmpty("resource", Namespace, attr.GetValue<string>(-1, "Resource"), x => FormatResourceId(x, ResourceType.Unknown));
            }
        }
Example #20
0
 private static IAttributedImport GetAttributedImport(ICustomAttributeProvider attributeProvider)
 {
     IAttributedImport[] attributes = attributeProvider.GetAttributes <IAttributedImport>(false);
     if (attributes.Length == 0)
     {
         return((IAttributedImport) new ImportAttribute());
     }
     if (attributes.Length > 1)
     {
         throw new Exception(); //MULTIPLE [Import] and [ImportMany]
     }
     return(attributes[0]);
 }
        public static Attribute?GetAttribute(this ICustomAttributeProvider provider, Type attributeType, bool inherit)
        {
            if (provider is null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            if (attributeType is null)
            {
                throw new ArgumentNullException(nameof(attributeType));
            }

            return(provider.GetAttributes(attributeType, inherit).FirstOrDefault());
        }
Example #22
0
        public static bool TryGetAttribute <T>(this ICustomAttributeProvider provider, bool inherit, out T attribute)
            where T : Attribute
        {
            if (!provider.HasAttribute <T>())
            {
                attribute = default;
                return(false);
            }

            foreach (var attr in provider.GetAttributes <T>(inherit))
            {
                attribute = attr;
                return(true);
            }

            attribute = default;
            return(false);
        }
Example #23
0
        private static IAttributedImport GetAttributedImport(ReflectionItem item, ICustomAttributeProvider attributeProvider)
        {
            IAttributedImport[] imports = attributeProvider.GetAttributes <IAttributedImport>(false);

            // For constructor parameters they may not have an ImportAttribute
            if (imports.Length == 0)
            {
                return(new ImportAttribute());
            }

            if (imports.Length > 1)
            {
                CompositionTrace.MemberMarkedWithMultipleImportAndImportMany(item);
            }

            // Regardless of how many imports, always return the first one
            return(imports[0]);
        }
        private static IAttributedImport GetAttributedImport(ReflectionItem item, ICustomAttributeProvider attributeProvider)
        {
            IAttributedImport[] imports = attributeProvider.GetAttributes <IAttributedImport>(false);

            // For constructor parameters they may not have an ImportAttribute
            if (imports.Length == 0)
            {
                return(new ImportAttribute());
            }

            if (imports.Length == 1)
            {
                return(imports[0]);
            }

            // DiscoveryError (Dev10:602872): This should go through the discovery error reporting when
            // we add a way to report discovery errors properly.
            throw ExceptionBuilder.CreateDiscoveryException(Strings.Discovery_MultipleImportAttributes, item.GetDisplayName());
        }
Example #25
0
File: Test.cs Project: wbratz/nunit
 public void ApplyAttributesToTest(ICustomAttributeProvider provider)
 {
     ApplyAttributesToTest(provider.GetAttributes <IApplyToTest>(inherit: true));
 }
Example #26
0
 public static T GetAttribute <T>(this ICustomAttributeProvider attributeProvider) where T : Attribute
 {
     return(attributeProvider.GetAttributes <T>().FirstOrDefault());
 }
Example #27
0
 /// <summary>
 /// Gets a single attribute defined on the member of the specified type.
 /// </summary>
 /// <typeparam name="T">The type of the attribute to find.</typeparam>
 /// <param name="customAttributeProvider">The member to look on for the attribute.</param>
 /// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param>
 /// <param name="index">If multiple attributes are permitted, then an optional index can be supplied if the first attribute isn't the required one.</param>
 /// <returns>The attribute.</returns>
 /// <exception cref="ArgumentNullException">Thrown if <paramref name="customAttributeProvider"/> is <c>null</c>.</exception>
 public static T GetAttribute <T>(this ICustomAttributeProvider customAttributeProvider, bool inherit = true, int index = 0)
 {
     return(customAttributeProvider.GetAttributes <T>(inherit).ToList()[index]);
 }
 public IEnumerable<ValidationAttribute> GetAttributes(ICustomAttributeProvider attributeProvider)
 {
     return attributeProvider.GetAttributes<ValidationAttribute>();
 }
Example #29
0
        public static TAttr GetAttribute <TAttr>(this ICustomAttributeProvider provider) where TAttr : Attribute
        {
            var attr = provider.GetAttributes <TAttr>().FirstOrDefault();

            return(attr);
        }
Example #30
0
        private static IAttributedImport GetAttributedImport(ReflectionItem item, ICustomAttributeProvider attributeProvider)
        {
            IAttributedImport[] imports = attributeProvider.GetAttributes<IAttributedImport>(false);

            // For constructor parameters they may not have an ImportAttribute
            if (imports.Length == 0)
            {
                return new ImportAttribute();
            }

            if (imports.Length == 1)
            {
                return imports[0];
            }

            // DiscoveryError (Dev10:602872): This should go through the discovery error reporting when
            // we add a way to report discovery errors properly.
            throw ExceptionBuilder.CreateDiscoveryException(Strings.Discovery_MultipleImportAttributes, item.GetDisplayName());
        }
Example #31
0
        private static IAttributedImport GetAttributedImport(ReflectionItem item, ICustomAttributeProvider attributeProvider)
        {
            IAttributedImport[] imports = attributeProvider.GetAttributes<IAttributedImport>(false);

            // For constructor parameters they may not have an ImportAttribute
            if (imports.Length == 0)
            {
                return new ImportAttribute();
            }

            if (imports.Length > 1)
            {
                CompositionTrace.MemberMarkedWithMultipleImportAndImportMany(item);
            }

            // Regardless of how many imports, always return the first one
            return imports[0];
        }
Example #32
0
        public static T GetAttribute <T>(this ICustomAttributeProvider cap) where T : Attribute
        {
            var atts = cap.GetAttributes <T>();

            return((atts.Count > 0) ? atts[0] : null);
        }
Example #33
0
 /// <summary>
 /// Determines whether or not this object has an attribute
 /// </summary>
 /// <typeparam name="TAttribute">The type of the attribute to look for</typeparam>
 public static bool HasAttribute <TAttribute>(this ICustomAttributeProvider attributeProvider) where TAttribute : Attribute
 {
     return(attributeProvider.GetAttributes <TAttribute>().Any());
 }
Example #34
0
 /// <summary>
 /// Gets filters attached to the specified custom attribute provider
 /// </summary>
 /// <typeparam name="TFilter">The type of filter to retrieve</typeparam>
 /// <param name="attributeProvider">The provider to search on</param>
 public static IEnumerable <TestFilter> GetFilters <TFilter>(this ICustomAttributeProvider attributeProvider) where TFilter : Attribute
 {
     return(attributeProvider
            .GetAttributes <TestFilter>()
            .Where(filter => filter.GetType().HasAttribute <TFilter>()));
 }
Example #35
0
 /// <summary>
 /// Determines whether or not a method or class is testable by virtue of being annotated
 /// with an attribute that is marked with a Testable attribute. That was quite a mouthful.
 /// </summary>
 public static bool IsTestable(this ICustomAttributeProvider attributeProvider)
 {
     return(attributeProvider
            .GetAttributes <Attribute>()
            .Any(attribute => attribute.GetType().HasAttribute <TestableAttribute>()));
 }