private static object CreateSubstituteRequest(ICustomAttributeProvider request, SubstituteAttribute attribute)
        {
            var parameter = request as ParameterInfo;
            if (parameter != null)
            {
                return new SubstituteRequest(parameter.ParameterType);
            }

            var property = request as PropertyInfo;
            if (property != null)
            {
                return new SubstituteRequest(property.PropertyType);
            }

            var field = request as FieldInfo;
            if (field != null)
            {
                return new SubstituteRequest(field.FieldType);
            }

            throw new NotSupportedException(
                string.Format(
                    CultureInfo.CurrentCulture,
                    "{0} is applied to an unsupported code element {1}",
                    attribute, request));
        }
Exemplo n.º 2
0
        internal static IModelBinder GetBinderFromAttributes(ICustomAttributeProvider element, Func<string> errorMessageAccessor)
        {
            // this method is used to get a custom binder based on the attributes of the element passed to it.
            // it will return null if a binder cannot be detected based on the attributes alone.

            var attrs = (CustomModelBinderAttribute[]) element.GetCustomAttributes(typeof (CustomModelBinderAttribute), true /* inherit */);
            if (attrs == null)
            {
                return null;
            }

            switch (attrs.Length)
            {
                case 0:
                    return null;

                case 1:
                    var binder = attrs[0].GetBinder();
                    return binder;

                default:
                    var errorMessage = errorMessageAccessor();
                    throw new InvalidOperationException(errorMessage);
            }
        }
        void ProcessExports(ICustomAttributeProvider provider)
        {
            if (provider == null)
                return;
            if (!provider.HasCustomAttributes)
                return;

            var attributes = provider.CustomAttributes;

            for (int i = 0; i < attributes.Count; i++) {
                var attribute = attributes [i];
                switch (attribute.Constructor.DeclaringType.FullName) {
                case "Java.Interop.ExportAttribute":
                    Annotations.Mark (provider);
                    if (!attribute.HasProperties)
                        break;
                    var throwsAtt = attribute.Properties.FirstOrDefault (p => p.Name == "Throws");
                    var thrownTypesArgs = throwsAtt.Argument.Value != null ? (CustomAttributeArgument []) throwsAtt.Argument.Value : null;
                    if (thrownTypesArgs != null)
                        foreach (var attArg in thrownTypesArgs)
                            Annotations.Mark (((TypeReference) attArg.Value).Resolve ());
                    break;
                case "Java.Interop.ExportFieldAttribute":
                    Annotations.Mark (provider);
                    break;
                default:
                    continue;
                }
                if (provider is MemberReference)
                    Annotations.Mark (((MemberReference) provider).DeclaringType.Resolve ());
                if (provider is MethodDefinition)
                    Annotations.SetAction (((MethodDefinition) provider), MethodAction.ForceParse);
            }
        }
        public IEnumerable<TypeReference> OfProvider(ICustomAttributeProvider provider)
        {
            if (provider == null)
                throw new ArgumentNullException("provider");

            return provider.CustomAttributes.Select(x => x.AttributeType);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Create annotations for all included attributes
 /// </summary>
 public static void Create(AssemblyCompiler compiler, ICustomAttributeProvider attributeProvider,
                           IAnnotationProvider annotationProvider, DexTargetPackage targetPackage, bool customAttributesOnly = false)
 {
     if (!attributeProvider.HasCustomAttributes)
         return;
     var annotations = new List<Annotation>();
     foreach (var attr in attributeProvider.CustomAttributes)
     {
         var attributeType = attr.AttributeType.Resolve();
         if (!attributeType.HasIgnoreAttribute())
         {
             Create(compiler, attr, attributeType, annotations, targetPackage);
         }
     }
     if (annotations.Count > 0)
     {
         // Create 1 IAttributes annotation
         var attrsAnnotation = new Annotation { Visibility = AnnotationVisibility.Runtime };
         attrsAnnotation.Type = compiler.GetDot42InternalType("IAttributes").GetClassReference(targetPackage);
         attrsAnnotation.Arguments.Add(new AnnotationArgument("Attributes", annotations.ToArray()));
         annotationProvider.Annotations.Add(attrsAnnotation);
     }
     if (!customAttributesOnly)
     {
         // Add annotations specified using AnnotationAttribute
         foreach (var attr in attributeProvider.CustomAttributes.Where(IsAnnotationAttribute))
         {
             var annotationType = (TypeReference) attr.ConstructorArguments[0].Value;
             var annotationClass = annotationType.GetClassReference(targetPackage, compiler.Module);
             annotationProvider.Annotations.Add(new Annotation(annotationClass, AnnotationVisibility.Runtime));
         }
     }
 }
        public static JsonRpcHelpAttribute Get(ICustomAttributeProvider attributeProvider)
        {
            if (attributeProvider == null)
                return null;

            return (JsonRpcHelpAttribute) CustomAttribute.Get(attributeProvider, typeof(JsonRpcHelpAttribute));
        }
		internal static object[] GetPseudoCustomAttributes (ICustomAttributeProvider obj, Type attributeType) {
			object[] pseudoAttrs = null;

			/* FIXME: Add other types */
			if (obj is MonoMethod)
				pseudoAttrs = ((MonoMethod)obj).GetPseudoCustomAttributes ();
			else if (obj is FieldInfo)
				pseudoAttrs = ((FieldInfo)obj).GetPseudoCustomAttributes ();
			else if (obj is ParameterInfo)
				pseudoAttrs = ((ParameterInfo)obj).GetPseudoCustomAttributes ();
			else if (obj is Type)
				pseudoAttrs = ((Type)obj).GetPseudoCustomAttributes ();

			if ((attributeType != null) && (pseudoAttrs != null)) {
				for (int i = 0; i < pseudoAttrs.Length; ++i)
					if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
						if (pseudoAttrs.Length == 1)
							return pseudoAttrs;
						else
							return new object [] { pseudoAttrs [i] };
				return new object [0];
			}
			else
				return pseudoAttrs;
		}
        public static bool IsValidParameter(Type type, ICustomAttributeProvider attributeProvider, bool allowReferences)        
        {

            object[] attributes = System.ServiceModel.Description.ServiceReflector.GetCustomAttributes(attributeProvider, typeof(MarshalAsAttribute), true);

            foreach (MarshalAsAttribute attr in attributes)
            {
                UnmanagedType marshalAs = attr.Value;

                if (marshalAs == UnmanagedType.IDispatch ||
                    marshalAs == UnmanagedType.Interface ||
                    marshalAs == UnmanagedType.IUnknown)
                {
                    return allowReferences;
                }
            }

            XsdDataContractExporter exporter = new XsdDataContractExporter();
            if (!exporter.CanExport(type))
            {
                return false;
            }

            return true;
        }
Exemplo n.º 9
0
 /// <summary>
 /// Check customer attributes
 /// </summary>
 private void Check(ICustomAttributeProvider provider, string context)
 {
     foreach (var ca in provider.CustomAttributes)
     {
         Check(ca.AttributeType, context);
     }
 }
Exemplo n.º 10
0
 public static ReferenceType<Boolean3> Draw3(Rect position, object eventsObj, GUIContent content, ICustomAttributeProvider info = null)
 {
     Boolean3 boolPair = (Boolean3)eventsObj;
     var boolArray = new bool[] { boolPair.x, boolPair.y, boolPair.z };
     Builder = new StringBuilder();
     char flags = (char)EditorNameFlags.Default;
     if (info != null && info.HasAttribute(typeof(CustomNamesAttribute)))
     {
         CustomNamesAttribute attribute = info.GetCustomAttributes<CustomNamesAttribute>()[0];
         flags = (char)attribute.CustomFlags;
         Builder.Append(flags);
         if (attribute.UseVariableNameAsTitle)
         {
             Builder.Append(Seperator);
             Builder.Append(content.text);
         }
         Builder.Append(attribute.CombinedName);
     }
     else
     {
         Builder.Append(flags);
         Builder.Append(Seperator);
         Builder.Append(content.text);
     }
     content.text = Builder.ToString();
     DrawMultiBoolean(ref boolArray, position, content);
     boolPair.x = boolArray[0];
     boolPair.y = boolArray[1];
     boolPair.z = boolArray[2];
     return boolPair;
 }
        /// <summary>
        /// Attempts to create a property editor for the given edited data type
        /// from the given editor type.
        /// </summary>
        /// <param name="editedType">The type that is being edited.</param>
        /// <param name="editorType">The editor type.</param>
        /// <param name="attributes">
        /// The attributes that were specified for the type.
        /// </param>
        /// <param name="forceInherit">
        /// Should inheritance behavior be forced? The expected value is false.
        /// </param>
        /// <returns>
        /// A property editor that can edit the given edited type.
        /// </returns>
        public static IPropertyEditor TryCreateEditor(Type editedType, Type editorType, ICustomAttributeProvider attributes, bool forceInherit)
        {
            // If our editor isn't inherited, then we only want to create a
            // specific editor
            var customPropertyEditorAttribute = fsPortableReflection.GetAttribute<CustomPropertyEditorAttribute>(editorType);
            if (!forceInherit && (customPropertyEditorAttribute == null || customPropertyEditorAttribute.Inherit == false)) {
                return TryCreateSpecificEditor(editedType, editedType, editorType, attributes);
            }

            // Otherwise we want to try to create a property editor from any of
            // the edited type's associated types.
            Type baseType = editedType;

            while (baseType != null) {
                IPropertyEditor editor = TryCreateSpecificEditor(baseType, editedType, editorType, attributes);
                if (editor != null) {
                    return editor;
                }

                foreach (Type iface in baseType.GetInterfaces()) {
                    editor = TryCreateSpecificEditor(iface, editedType, editorType, attributes);
                    if (editor != null) {
                        return editor;
                    }
                }

                baseType = baseType.BaseType;
            }

            return null;
        }
Exemplo n.º 12
0
 /// <summary>
 /// Get attribute of a given type on a member. If multiple attributes
 /// of a type are present, the first one found is returned.
 /// </summary>
 /// <param name="member">The member to examine</param>
 /// <param name="attrName">The FullName of the attribute type to look for</param>
 /// <param name="inherit">True to include inherited attributes</param>
 /// <returns>The attribute or null</returns>
 public static System.Attribute GetAttribute(ICustomAttributeProvider member, string attrName, bool inherit)
 {
     foreach (Attribute attribute in GetAttributes( member, inherit ) )
         if ( IsInstanceOfType( attrName, attribute ) )
             return attribute;
     return null;
 }
Exemplo n.º 13
0
		public XmlAttributes (ICustomAttributeProvider provider)
		{
			object[] attributes = provider.GetCustomAttributes(false);
			foreach(object obj in attributes)
			{
				if(obj is XmlAnyAttributeAttribute)
					xmlAnyAttribute = (XmlAnyAttributeAttribute) obj;
				else if(obj is XmlAnyElementAttribute)
					xmlAnyElements.Add((XmlAnyElementAttribute) obj);
				else if(obj is XmlArrayAttribute)
					xmlArray = (XmlArrayAttribute) obj;
				else if(obj is XmlArrayItemAttribute)
					xmlArrayItems.Add((XmlArrayItemAttribute) obj);
				else if(obj is XmlAttributeAttribute)
					xmlAttribute = (XmlAttributeAttribute) obj;
				else if(obj is XmlChoiceIdentifierAttribute)
					xmlChoiceIdentifier = (XmlChoiceIdentifierAttribute) obj;
				else if(obj is DefaultValueAttribute)
					xmlDefaultValue = ((DefaultValueAttribute)obj).Value;
				else if(obj is XmlElementAttribute )
					xmlElements.Add((XmlElementAttribute ) obj);
				else if(obj is XmlEnumAttribute)
					xmlEnum = (XmlEnumAttribute) obj;
				else if(obj is XmlIgnoreAttribute)
					xmlIgnore = true;
				else if(obj is XmlNamespaceDeclarationsAttribute)
					xmlns = true;
				else if(obj is XmlRootAttribute)
					xmlRoot = (XmlRootAttribute) obj;
				else if(obj is XmlTextAttribute)
					xmlText = (XmlTextAttribute) obj;
				else if(obj is XmlTypeAttribute)
					xmlType = (XmlTypeAttribute) obj;
			}
		}
Exemplo n.º 14
0
 internal static string GetDescrition(MemberInfo member, ICustomAttributeProvider provider, string defaultValue, string memberSuffix)
 {
     Type t = member as Type;
      if (t == null)
      {
     t = member.DeclaringType;
      }
      object[] attributes = t.GetCustomAttributes(typeof(MBeanResourceAttribute), true);
      if (attributes.Length > 0)
      {
     ResourceManager manager = new ResourceManager(((MBeanResourceAttribute)attributes[0]).ResourceName, t.Assembly);
     string name = memberSuffix == null ? member.Name : member.Name + "__" + memberSuffix;
     string descr = manager.GetString(member.Name);
     if (descr != null)
     {
        return descr;
     }
      }
      attributes = provider.GetCustomAttributes(typeof(DescriptionAttribute), true);
      if (attributes.Length > 0)
      {
     return ((DescriptionAttribute)attributes[0]).Description;
      }
      return defaultValue;
 }
Exemplo n.º 15
0
		/// <summary>
		/// Check presence of attribute of a given type on a member.
		/// </summary>
		/// <param name="member">The member to examine</param>
		/// <param name="attrName">The FullName of the attribute type to look for</param>
		/// <param name="inherit">True to include inherited attributes</param>
		/// <returns>True if the attribute is present</returns>
		public static bool HasAttribute( ICustomAttributeProvider member, string attrName, bool inherit )
		{
			foreach( Attribute attribute in GetAttributes( member, inherit ) )
				if ( IsInstanceOfType( attrName, attribute ) )
					return true;
			return false;
		}
        public static bool IsDefined(ICustomAttributeProvider attributeProvider)
        {
            if (attributeProvider == null)
                return false;

            return CustomAttribute.IsDefined(attributeProvider, typeof(JsonRpcParamsAttribute));
        }
Exemplo n.º 17
0
        public static string GetDescription(ICustomAttributeProvider thing)
        {
            string description = string.Empty;
            thing.ForAttribute<DescriptionAttribute>(att => description = att.Text);

            return description;
        }
        public static TypeDefinition ResolveType(string type, ICustomAttributeProvider provider, IAssemblyResolver resolver)
        {
            if (provider == null)
                throw new ArgumentException ("Type resolution support requires an AssemblyDefinition or TypeDefinition.", "provider");
            if (resolver == null)
                throw new ArgumentException ("Type resolution support requires a IAssemblyResolver.", "resolver");

            // `type` is either a "bare" type "Foo.Bar", or an
            // assembly-qualified type "Foo.Bar, AssemblyName [Version=...]?".
            //
            // Bare types are looked up via `provider`; assembly-qualified types are
            // looked up via `resolver`

            int c = type.IndexOf (',');
            string typeName = c < 0 ? type  : type.Substring (0, c);
            string assmName = c < 0 ? null  : type.Substring (c+1);

            AssemblyDefinition assembly = assmName == null ? null : resolver.Resolve (assmName);
            if (assembly == null) {
                assembly = provider as AssemblyDefinition;
                if (assembly == null) {
                    TypeDefinition decl = (TypeDefinition) provider;
                    assembly = decl.Module.Assembly;
                }
            }
            var ret = assembly.Modules.Cast<ModuleDefinition> ()
                .Select (md => md.Types.FirstOrDefault (t => t.FullName == typeName))
                .FirstOrDefault (td => td != null);
            if (ret == null)
                throw new ArgumentException ("Type not found: " + type, "type");

            return ret;
        }
 private static IEnumerable<string> GetInvalidSuppressMessageAttributeErrorsCore(ICustomAttributeProvider target, string name, string targetType, IEnumerable<Exemption> exemptions) {
     foreach (SuppressMessageAttribute attr in target.GetCustomAttributes(typeof(SuppressMessageAttribute), false).OfType<SuppressMessageAttribute>()) {
         if (String.IsNullOrWhiteSpace(attr.Justification) && !IsExempt(exemptions, attr.CheckId, name, targetType)) {
             yield return FormatErrorMessage(attr, name, targetType);
         }
     }
 }
Exemplo n.º 20
0
 public virtual void ProcessAttributes(IMetaData metaData, ICustomAttributeProvider attributeProvider)
 {
     foreach(AttributeProcessor processor in AttributeProcessors)
     {
         processor.Process(metaData, attributeProvider, this.Config);
     }
 }
Exemplo n.º 21
0
Arquivo: Common.cs Projeto: JuRogn/OA
        public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
        {
            System.Collections.Generic.List<System.Type> knownTypes =
                new System.Collections.Generic.List<System.Type>();
            //// Add any types to include here.

            //return knownTypes;
            Type[] types = Assembly.Load("SMT_FB_EFModel").GetTypes();

            for (int i = 0; i < types.Length; i++)
            {
                if ((types[i].BaseType == typeof(EntityObject)) || typeof(VisitUserBase).IsAssignableFrom(types[i]))
                {
                    knownTypes.Add(types[i]);
                }
            }
            //List<Type> typesO = knownTypes.ToList();
            //typesO.ForEach(item =>
            //{
            //    knownTypes.Add(typeof(List<>).MakeGenericType(new Type[] { item }));
            //});

            knownTypes.Add(typeof(AuditResult));
            knownTypes.Add(typeof(SaveResult));
            knownTypes.Add(typeof(VirtualAudit));
            knownTypes.Add(typeof(SMT.SaaS.BLLCommonServices.FlowWFService.SubmitData));

            return knownTypes;
        }
        public static IEnumerable<UsesFeatureAttribute> FromCustomAttributeProvider(ICustomAttributeProvider provider)
        {
            var attrs = provider.GetCustomAttributes ("Android.App.UsesFeatureAttribute");
            foreach (var attr in attrs) {

                UsesFeatureAttribute self = new UsesFeatureAttribute ();

                if (attr.HasProperties) {
                    // handle the case where the user sets additional properties
                    self.specified = mapping.Load (self, attr);
                    if (self.specified.Contains("GLESVersion") && self.GLESVersion==0) {
                        throw new InvalidOperationException("Invalid value '0' for UsesFeatureAttribute.GLESVersion.");
                    }
                }
                if (attr.HasConstructorArguments) {
                    // in this case the user used one of the Consructors to pass arguments and possibly properties
                    // so we only create the specified list if its not been created already
                    if (self.specified == null)
                        self.specified = new List<string>();
                    foreach(var arg in attr.ConstructorArguments) {
                        if (arg.Value.GetType() == typeof(string)) {
                            self.specified.Add("Name");
                            self.Name = (string)arg.Value;
                        }
                    }
                }
                yield return self;
            }
        }
        public void SetUp()
        {
            _attributeProvider = NewTypeDefinition();
            CustomAttributes.ForEach(x => _attributeProvider.CustomAttributes.Add(x));

            _findInCustomAttributes = new FindTypeReferencesInCustomAttributes();
        }
 void AssertDescriptorMatches(ILookup<string, SecurityAttributeDescriptor> descriptors, string signature, ICustomAttributeProvider element)
 {
     if (descriptors.Contains(signature))
         AssertContainsAttribute(element, descriptors[signature].Single().AttributeTypeName);
     else
         AssertContainsNoAttribute(element);
 }
 /// <include file='doc\SoapAttributes.uex' path='docs/doc[@for="SoapAttributes.SoapAttributes1"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public SoapAttributes(ICustomAttributeProvider provider) {
     object[] attrs = provider.GetCustomAttributes(false);
     for (int i = 0; i < attrs.Length; i++) {
         if (attrs[i] is SoapIgnoreAttribute || attrs[i] is ObsoleteAttribute) {
             this.soapIgnore = true;
             break;
         }
         else if (attrs[i] is SoapElementAttribute) {
             this.soapElement = (SoapElementAttribute)attrs[i];
         }
         else if (attrs[i] is SoapAttributeAttribute) {
             this.soapAttribute = (SoapAttributeAttribute)attrs[i];
         }
         else if (attrs[i] is SoapTypeAttribute) {
             this.soapType = (SoapTypeAttribute)attrs[i];
         }
         else if (attrs[i] is SoapEnumAttribute) {
             this.soapEnum = (SoapEnumAttribute)attrs[i];
         }
         else if (attrs[i] is DefaultValueAttribute) {
             this.soapDefaultValue = ((DefaultValueAttribute)attrs[i]).Value;
         }
     }
     if (soapIgnore) {
         this.soapElement = null;
         this.soapAttribute = null;
         this.soapType = null;
         this.soapEnum = null;
         this.soapDefaultValue = null;
     }
 }
Exemplo n.º 26
0
 public AttributeSet(ICustomAttributeProvider attributeProvider)
 {
     this.attributes = attributeProvider
         .GetCustomAttributes(true)
         .Cast<Attribute>()
         .ToArray();
 }
		internal TemplateBuilder (ICustomAttributeProvider prov)
		{
			object[] ats = prov.GetCustomAttributes (typeof(TemplateContainerAttribute), true);
			if (ats.Length > 0) {
				containerAttribute = (TemplateContainerAttribute) ats [0];
			}
		}
        public static IEnumerable<UsesLibraryAttribute> FromCustomAttributeProvider(ICustomAttributeProvider provider)
        {
            var attrs = provider.GetCustomAttributes ("Android.App.UsesLibraryAttribute");
            foreach (var attr in attrs) {
                UsesLibraryAttribute self;

                string[] extra = null;
                if (attr.ConstructorArguments.Count == 1) {
                    self = new UsesLibraryAttribute (
                            (string)  attr.ConstructorArguments [0].Value);
                    extra = new[]{"Name"};
                } else if (attr.ConstructorArguments.Count == 2) {
                    self = new UsesLibraryAttribute (
                            (string)  attr.ConstructorArguments [0].Value,
                            (bool)    attr.ConstructorArguments [1].Value);
                    extra = new[]{"Name", "Required"};
                } else {
                    self = new UsesLibraryAttribute ();
                    extra = new string[0];
                }

                self.specified = mapping.Load (self, attr);

                foreach (var e in extra)
                    self.specified.Add (e);

                yield return self;
            }
        }
Exemplo n.º 29
0
 public IEnumerable<ValidationAttribute> GetAttributes(ICustomAttributeProvider attributeProvider)
 {
     return attributeProvider
         .GetAttributes<ValidationAttribute>()
         .Select(attr => container.BuildUp(attr.GetType(), attr))
         .Cast<ValidationAttribute>();
 }
Exemplo n.º 30
0
 private static Type GetJsonConverterType(ICustomAttributeProvider attributeProvider)
 {
     return(JsonTypeReflector.JsonConverterTypeCache.Get(attributeProvider));
 }
Exemplo n.º 31
0
 /// <summary>
 /// Gets all attributes of the specified generic type.
 /// </summary>
 /// <param name="member">The member.</param>
 public static IEnumerable <T> GetAttributes <T>(this ICustomAttributeProvider member) where T : Attribute
 {
     return(GetAttributes <T>(member, false));
 }
Exemplo n.º 32
0
 public FallbackAttributeProvider(ICustomAttributeProvider customAttributeProvider) => this.customAttributeProvider = customAttributeProvider;
Exemplo n.º 33
0
 /// <summary>
 /// Returns true if the given type can be used as a kRPC class type.
 /// </summary>
 public static bool IsAClassType(ICustomAttributeProvider type)
 {
     return(Reflection.HasAttribute <KRPCClassAttribute> (type));
 }
Exemplo n.º 34
0
        public static T GetAttribute <T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute
        {
            T[] attributes = GetAttributes <T>(attributeProvider, inherit);

            return(attributes.SingleOrDefault());
        }
Exemplo n.º 35
0
 public static T GetAttribute <T>(ICustomAttributeProvider attributeProvider) where T : Attribute
 {
     return(GetAttribute <T>(attributeProvider, true));
 }
Exemplo n.º 36
0
 /// <summary>
 /// 获取特性列表
 /// </summary>
 /// <typeparam name="T">特性类型</typeparam>
 /// <param name="customAttributeProvider">自定义特性提供程序</param>
 /// <param name="inherit">是否继承</param>
 public static IEnumerable <T> GetAttributes <T>(this ICustomAttributeProvider customAttributeProvider,
                                                 bool inherit = false) where T : Attribute =>
 customAttributeProvider
 .GetCustomAttributes(typeof(T), inherit)
 .OfType <T>();
Exemplo n.º 37
0
 /// <summary>
 /// 获取特性
 /// </summary>
 /// <typeparam name="T">特性类型</typeparam>
 /// <param name="customAttributeProvider">自定义特性提供程序</param>
 /// <param name="inherit">是否继承</param>
 public static T GetAttribute <T>(this ICustomAttributeProvider customAttributeProvider, bool inherit = false)
     where T : Attribute =>
 customAttributeProvider
 .GetCustomAttributes(typeof(T), inherit)
 .OfType <T>()
 .FirstOrDefault();
Exemplo n.º 38
0
 /// <summary>
 /// 检查指定类型成员中是否存在指定的特性
 /// </summary>
 /// <typeparam name="T">特性类型</typeparam>
 /// <param name="customAttributeProvider">自定义特性提供程序</param>
 /// <param name="inherit">是否继承</param>
 public static bool ExistsAttribute <T>(this ICustomAttributeProvider customAttributeProvider,
                                        bool inherit = false) where T : Attribute => customAttributeProvider
 .GetCustomAttributes(typeof(T), inherit)
 .Any(m => m is T);
Exemplo n.º 39
0
 public TAttribute GetAttributeOrDefault <TAttribute>(ICustomAttributeProvider attributeProvider)
 => attributeProvider.GetCustomAttributes(false).OfType <TAttribute>().SingleOrDefault();
Exemplo n.º 40
0
 private static bool IsImport(ICustomAttributeProvider attributeProvider)
 {
     return(attributeProvider.IsAttributeDefined <IAttributedImport>(false));
 }
Exemplo n.º 41
0
        private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider)
        {
            JsonConverterAttribute attribute = JsonTypeReflector.GetAttribute <JsonConverterAttribute>(attributeProvider);

            return((attribute == null) ? null : attribute.ConverterType);
        }
Exemplo n.º 42
0
 public IListPropertyEditor(Type editedType, ICustomAttributeProvider attributes)
     : base(editedType, attributes)
 {
 }
Exemplo n.º 43
0
 public static bool HasCustomAttribute(this ICustomAttributeProvider attributeProvider, TypeReference attribute)
 {
     // Linq allocations don't matter in weaver
     return(attributeProvider.CustomAttributes.Any(attr => attr.AttributeType.FullName == attribute.FullName));
 }
Exemplo n.º 44
0
 public virtual DialogResult ShowDialog(ICustomAttributeProvider provider, CustomAttribute attribute)
 {
     SelectedProvider  = provider;
     SelectedAttribute = attribute;
     return(ShowDialog());
 }
Exemplo n.º 45
0
 private static bool IsInheritedExport(ICustomAttributeProvider attributedProvider)
 {
     return(attributedProvider.IsAttributeDefined <InheritedExportAttribute>(false));
 }
Exemplo n.º 46
0
 static T GetAttribute <T>(ICustomAttributeProvider provider) where T : Attribute
 {
     return(provider.GetCustomAttributes(typeof(T), false).OfType <T>().FirstOrDefault());
 }
Exemplo n.º 47
0
 public DocumentationDefinition(ICustomAttributeProvider provider)
 {
     Titles.AddRange(provider.GetXRoadTitles());
     Notes.AddRange(provider.GetXRoadNotes());
     TechNotes.AddRange(provider.GetXRoadTechNotes());
 }
Exemplo n.º 48
0
 public T [] GetCustomAttributes <T> (ICustomAttributeProvider provider) where T : System.Attribute
 {
     return(FilterAttributes <T> (GetIKVMAttributes(provider), provider));
 }
 public static T[] GetCustomAttributes <T>(this ICustomAttributeProvider type, bool inherit)
     where T : Attribute
 {
     return((T[])type.GetCustomAttributes(typeof(T), inherit));
 }
Exemplo n.º 50
0
 public void IncludeTypes(ICustomAttributeProvider provider)
 {
     IncludeTypes(provider, new RecursionLimiter());
 }
Exemplo n.º 51
0
        bool ShouldSetHasSecurityToFalse(ISecurityDeclarationProvider providerAsSecurity, ICustomAttributeProvider provider, bool existingHasSecurity, IList <CustomAttribute> removedAttributes)
        {
            if (existingHasSecurity && removedAttributes.Count > 0 && !providerAsSecurity.HasSecurityDeclarations)
            {
                // If the method or type had security before and all attributes were removed, or no remaining attributes are security attributes,
                // then we need to set HasSecurity to false
                if (provider.CustomAttributes.Count == 0 || provider.CustomAttributes.All(attr => !IsSecurityAttributeType(attr.AttributeType.Resolve())))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 52
0
 /// <summary>
 /// Retrieves custom attribute for the specified attribute type.
 /// </summary>
 /// <param name="attributeProvider">
 /// Method/Parameter to get attribute from.
 /// </param>
 /// <param name="attributeType">
 /// Attribute type.
 /// </param>
 /// <returns>
 /// Attribute instance if one is found, <c>null</c> otherwise.
 /// </returns>
 protected object[] GetCustomAttributes(ICustomAttributeProvider attributeProvider, Type attributeType)
 {
     object[] attributes = attributeProvider.GetCustomAttributes(attributeType, false);
     return(attributes);
 }
Exemplo n.º 53
0
    IEnumerable <T> CreateAttributeInstance <T> (CustomAttributeData attribute, ICustomAttributeProvider provider) where T : System.Attribute
    {
        var convertedAttributes = ConvertOldAttributes(attribute);

        if (convertedAttributes.Any())
        {
            return(convertedAttributes.OfType <T> ());
        }

        var expectedType = ConvertType(typeof(T), provider);

        if (attribute.AttributeType != expectedType && !IsSubclassOf(expectedType, attribute.AttributeType))
        {
            return(Enumerable.Empty <T> ());
        }

        System.Type attribType = ConvertType(attribute.AttributeType, provider);

        var constructorArguments = new object [attribute.ConstructorArguments.Count];

        for (int i = 0; i < constructorArguments.Length; i++)
        {
            var value = attribute.ConstructorArguments [i].Value;
            switch (attribute.ConstructorArguments [i].ArgumentType.FullName)
            {
            case "System.Type":
                if (value != null)
                {
                    if (attribType.Assembly == typeof(TypeManager).Assembly)
                    {
                        constructorArguments [i] = value;
                    }
                    else
                    {
                        constructorArguments [i] = System.Type.GetType(((Type)value).FullName);
                    }
                    if (constructorArguments [i] == null)
                    {
                        throw ErrorHelper.CreateError(1056, "Internal error: failed to instantiate mock attribute '{0}' (could not convert type constructor argument #{1}). Please file a bug report (https://github.com/xamarin/xamarin-macios/issues/new) with a test case.", attribType.FullName, i + 1);
                    }
                }
                break;

            default:
                constructorArguments [i] = value;
                break;
            }
        }

        var parameters = attribute.Constructor.GetParameters();
        var ctorTypes  = new System.Type [parameters.Length];

        for (int i = 0; i < ctorTypes.Length; i++)
        {
            var paramType = parameters [i].ParameterType;
            switch (paramType.FullName)
            {
            case "System.Type":
                if (attribType.Assembly == typeof(TypeManager).Assembly)
                {
                    ctorTypes [i] = typeof(Type);
                }
                else
                {
                    ctorTypes [i] = typeof(System.Type);
                }
                break;

            default:
                ctorTypes [i] = ConvertType(paramType, provider);
                break;
            }
            if (ctorTypes [i] == null)
            {
                throw ErrorHelper.CreateError(1057, "Internal error: failed to instantiate mock attribute '{0}' (could not convert constructor type #{1} ({2})). Please file a bug report (https://github.com/xamarin/xamarin-macios/issues/new) with a test case.", attribType.FullName, i, paramType.FullName);
            }
        }
        var ctor = attribType.GetConstructor(ctorTypes);

        if (ctor == null)
        {
            throw ErrorHelper.CreateError(1058, "Internal error: could not find a constructor for the mock attribute '{0}'. Please file a bug report (https://github.com/xamarin/xamarin-macios/issues/new) with a test case.", attribType.FullName);
        }
        var instance = ctor.Invoke(constructorArguments);

        for (int i = 0; i < attribute.NamedArguments.Count; i++)
        {
            var arg   = attribute.NamedArguments [i];
            var value = arg.TypedValue.Value;
            if (arg.TypedValue.ArgumentType == TypeManager.System_String_Array)
            {
                var typed_values = (CustomAttributeTypedArgument [])arg.TypedValue.Value;
                var arr          = new string [typed_values.Length];
                for (int a = 0; a < arr.Length; a++)
                {
                    arr [a] = (string)typed_values [a].Value;
                }
                value = arr;
            }
            else if (arg.TypedValue.ArgumentType.FullName == "System.Type[]")
            {
                var typed_values = (CustomAttributeTypedArgument [])arg.TypedValue.Value;
                var arr          = new Type [typed_values.Length];
                for (int a = 0; a < arr.Length; a++)
                {
                    arr [a] = (Type)typed_values [a].Value;
                }
                value = arr;
            }
            else if (arg.TypedValue.ArgumentType.IsArray)
            {
                throw ErrorHelper.CreateError(1059, "Internal error: failed to instantiate mock attribute '{0}' (unknown type for the named argument #{1} ({2}). Please file a bug report (https://github.com/xamarin/xamarin-macios/issues/new) with a test case.", attribType.FullName, i + 1, arg.MemberName);
            }
            if (arg.IsField)
            {
                attribType.GetField(arg.MemberName).SetValue(instance, value);
            }
            else
            {
                attribType.GetProperty(arg.MemberName).SetValue(instance, value, new object [0]);
            }
        }

        return(((T)instance).Yield());
    }
Exemplo n.º 54
0
        /// <summary>
        /// Returns the first found custom attribute of type T on this member
        /// Returns null if none was found
        /// </summary>
        public static T GetAttribute <T>(this ICustomAttributeProvider member, bool inherit) where T : Attribute
        {
            var all = GetAttributes <T>(member, inherit).ToArray();

            return((all == null || all.Length == 0) ? null : all[0]);
        }
Exemplo n.º 55
0
 /// <summary>
 /// Creates competition features. <see cref="BenchmarkDotNet.Characteristics.CharacteristicObject.Frozen"/> is false.
 /// </summary>
 /// <param name="jobId">The job identifier.</param>
 /// <param name="metadataSource">The metadata source.</param>
 /// <returns>
 /// New competition features. <see cref="BenchmarkDotNet.Characteristics.CharacteristicObject.Frozen"/> is false.
 /// </returns>
 protected virtual CompetitionFeatures CreateCompetitionFeaturesUnfrozen(
     [CanBeNull] string jobId,
     [CanBeNull] ICustomAttributeProvider metadataSource) =>
 new CompetitionFeatures(jobId, GetCompetitionFeatures(metadataSource));
Exemplo n.º 56
0
 /// <summary>
 /// Returns the first found non-inherited custom attribute of type T on this member
 /// Returns null if none was found
 /// </summary>
 public static T GetAttribute <T>(this ICustomAttributeProvider member) where T : Attribute
 {
     return(GetAttribute <T>(member, false));
 }
Exemplo n.º 57
0
 DynamicallyAccessedMemberTypes GetMemberTypesForDynamicallyAccessedMemberAttribute(ICustomAttributeProvider provider, IMemberDefinition locationMember = null)
 {
     if (!_source.HasCustomAttributes(provider))
     {
         return(DynamicallyAccessedMemberTypes.None);
     }
     foreach (var attribute in _source.GetCustomAttributes(provider))
     {
         if (!IsDynamicallyAccessedMembersAttribute(attribute))
         {
             continue;
         }
         if (attribute.ConstructorArguments.Count == 1)
         {
             return((DynamicallyAccessedMemberTypes)(int)attribute.ConstructorArguments[0].Value);
         }
         else if (attribute.ConstructorArguments.Count == 0)
         {
             _context.LogWarning($"DynamicallyAccessedMembersAttribute was specified but no argument was proportioned", 2020, locationMember ?? (provider as IMemberDefinition));
         }
         else
         {
             _context.LogWarning($"DynamicallyAccessedMembersAttribute was specified but there is more than one argument", 2022, locationMember ?? (provider as IMemberDefinition));
         }
     }
     return(DynamicallyAccessedMemberTypes.None);
 }
Exemplo n.º 58
0
 /// <summary>
 /// Returns true if the attribute whose type is specified by the generic argument is defined on this member
 /// </summary>
 public static bool IsDefined <T>(this ICustomAttributeProvider member) where T : Attribute
 {
     return(IsDefined <T>(member, false));
 }
Exemplo n.º 59
0
        /// <summary>
        /// 获取程序集CustomAttribute属性
        /// </summary>
        /// <typeparam name="T">CustomAttribute</typeparam>
        /// <param name="provider">Type、Assembly、Module、MethodInfo</param>
        /// <returns>CustomAttribute</returns>
        public static T GetCustomAttribute <T>(this ICustomAttributeProvider provider) where T : Attribute
        {
            var attributes = provider.GetCustomAttributes(typeof(T), false);

            return(attributes.Length > 0 ? attributes[0] as T : default(T));
        }
        public static List<Type> GetListOfKnownTypes(ICustomAttributeProvider provider)
        {
            List<Type> knownTypes = new List<Type>();

            Type interLinqQuery = typeof(InterLinqQuery<>);
            Type genericList = typeof(List<>);

            List<Type> coreTypes = new List<Type>
            {
                typeof(Customer),
                typeof(Order),
                typeof(Product),
                typeof(Supplier),
            };

            coreTypes.ForEach(type =>
                {
                    knownTypes.Add(type);

                    knownTypes.Add(interLinqQuery.MakeGenericType(type));

                    knownTypes.Add(type.MakeArrayType());
                }
            );

            return knownTypes;
        }