Example #1
0
		internal TemplateBuilder (ICustomAttributeProvider prov)
		{
			object[] ats = prov.GetCustomAttributes (typeof (TemplateContainerAttribute), true);
			if (ats.Length > 0)
				containerAttribute = (TemplateContainerAttribute) ats [0];

			ats = prov.GetCustomAttributes (typeof (TemplateInstanceAttribute), true);
			if (ats.Length > 0)
				instanceAttribute = (TemplateInstanceAttribute) ats [0];
		}
 private static DashbardIconWithDisplay MakeNode(DashboardIconAttribute sitemapNodeAttr, ICustomAttributeProvider info)
 {
     var sitemapNode = new DashbardIconWithDisplay
     {
         DashboardIcon = sitemapNodeAttr,
         Display = info.GetCustomAttributes(false).OfType<DisplayAttribute>().FirstOrDefault(),
         Url = info.GetCustomAttributes(false).OfType<IUrl>().FirstOrDefault() ?? new ConstUrl("#")
     };
     return sitemapNode;
 }
        private static void BuildInitializedMember(List<InitializedMember> members, ICustomAttributeProvider attributeProvider, InitializedMemberFactory factory)
        {
            var finders = (ComponentFinderAttribute[]) attributeProvider.GetCustomAttributes(typeof(ComponentFinderAttribute), true);
            if (finders.Length == 0)
                return;
            if (finders.Length > 1)
                throw new InvalidOperationException(string.Format("Member '{0}' has more than one ComponentFinderAttribute.", attributeProvider));

            var finder = finders[0];
            var decorators = (ComponentDecoratorAttribute[])attributeProvider.GetCustomAttributes(typeof(ComponentDecoratorAttribute), true);

            InitializedMember member = factory(finder, decorators);
            members.Add(member);
        }
Example #4
0
        public static IEnumerable <TAttribute> GetAttributes <TAttribute>(this ICustomAttributeProvider obj)
            where TAttribute : IAttribute
        {
            var memberInfo = obj as MemberInfo;

            if (memberInfo != null)
            {
                var inheritedAttributes = Attribute.GetCustomAttributes(memberInfo, true).OfType <TAttribute>();
                if (inheritedAttributes != null)
                {
                    foreach (var attribute in inheritedAttributes)
                    {
                        yield return(attribute);
                    }
                }
            }
            else
            {
                var attributes = obj?.GetCustomAttributes(typeof(TAttribute), true).OfType <TAttribute>();
                if (attributes != null)
                {
                    foreach (var attribute in attributes)
                    {
                        yield return(attribute);
                    }
                }
            }
        }
 private void IncludeTypes(ICustomAttributeProvider provider, RecursionLimiter limiter)
 {
     object[] attrs = provider.GetCustomAttributes(typeof(SoapIncludeAttribute), false);
     for (int i = 0; i < attrs.Length; i++) {
         IncludeType(((SoapIncludeAttribute)attrs[i]).Type, limiter);
     }
 }
        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;
            }
        }
Example #7
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;
 }
        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;
            }
        }
 /// <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;
     }
 }
Example #10
0
 public AttributeSet(ICustomAttributeProvider attributeProvider)
 {
     this.attributes = attributeProvider
         .GetCustomAttributes(true)
         .Cast<Attribute>()
         .ToArray();
 }
Example #11
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;
			}
		}
Example #12
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);
            }
        }
Example #13
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;
 }
        private static bool TryGetUpdateSnapshotsAttribute(ICustomAttributeProvider member, out UpdateSnapshotsAttribute attribute)
        {
            var attributes = member?.GetCustomAttributes(typeof(UpdateSnapshotsAttribute), true);

            attribute = attributes?.FirstOrDefault() as UpdateSnapshotsAttribute;
            return(attributes?.Any() ?? false);
        }
 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);
         }
     }
 }
 public static ITypeConverter[] GetTypeConverters(ICustomAttributeProvider attributeProvider)
 {
     var attributes = attributeProvider.GetCustomAttributes(typeof(TypeConverterAttribute), true).Cast<TypeConverterAttribute>();
     return attributes
         .Select(x => new { x.Context, Converter = (ITypeConverter)Activator.CreateInstance(x.ConverterType) })
         .Select(x => x.Context == TypeConversionContext.None ? x.Converter : new ContextBasedTypeConverter(x.Context, x.Converter))
         .ToArray();
 }
 public static IEnumerable<InstrumentationAttribute> FromCustomAttributeProvider(ICustomAttributeProvider provider)
 {
     foreach (CustomAttribute attr in provider.GetCustomAttributes ("Android.App.InstrumentationAttribute")) {
         InstrumentationAttribute self = new InstrumentationAttribute ();
         self.specified = mapping.Load (self, attr);
         yield return self;
     }
 }
Example #18
0
 public static HttpHeader[] GetHeaders(ICustomAttributeProvider provider)
 {
     return provider
         .GetCustomAttributes(typeof(HeaderAttribute), true)
         .Cast<HeaderAttribute>()
         .Select(x => new HttpHeader(x.Name, x.Values))
         .ToArray();
 }
 private static BackgroundInvokeAttribute GetAttribute(ICustomAttributeProvider method)
 {
     BackgroundInvokeAttribute[] attributes = (BackgroundInvokeAttribute[])method.GetCustomAttributes(typeof(BackgroundInvokeAttribute), true);
       if (attributes.Length != 1)
       {
     return null;
       }
       return attributes[0];
 }
 protected virtual BackgroundJobAttribute FindAttribute(ICustomAttributeProvider type)
 {
     BackgroundJobAttribute[] attributes = (BackgroundJobAttribute[]) type.GetCustomAttributes(typeof (BackgroundJobAttribute), true);
       if (attributes.Length != 1)
       {
     return null;
       }
       return attributes[0];
 }
 protected IJsonTypeConverter CreateTypeConverter(ICustomAttributeProvider provider)
 {
     if (provider.IsDefined(typeof(JsonConvertAttribute), false))
     {
         JsonConvertAttribute convAttr = (JsonConvertAttribute)provider.GetCustomAttributes(typeof(JsonConvertAttribute), false)[0];
         return CreateTypeConverter(convAttr);
     }
     return null;
 }
Example #22
0
 internal static List<string> GetSectionNames(ICustomAttributeProvider type)
 {
     var nameList = new List<string>();
     var attriubtes = type.GetCustomAttributes(typeof(ConfigSectionNamesAttribute), true);
     if (attriubtes != null && attriubtes.Length > 0) {
         var names = ((ConfigSectionNamesAttribute)attriubtes[0]).Names;
         nameList.AddRange(names);
     }
     return nameList;
 }
        public string Transform(string value, string valueName, ICustomAttributeProvider property)
        {
            var propertyTransformers = property?.GetCustomAttributes(true)
                                       .OfType <IValueTransformer>() ?? Enumerable.Empty <IValueTransformer>();

            return(propertyTransformers
                   .Union(_transformers)
                   .OrderBy(x => x.Order)
                   .Aggregate(value, (x, y) => y.Transform(x, valueName, property)));
        }
Example #24
0
		public static string GetArgumentName (ICustomAttributeProvider attrProvider, string defaultName)
		{
			string argName = defaultName;

			//TODO: no need for foreach
			foreach (ArgumentAttribute aa in attrProvider.GetCustomAttributes (typeof (ArgumentAttribute), true))
				argName = aa.Name;

			return argName;
		}
 public static void IsTaggedWithAttribute(
     ICustomAttributeProvider type,
     Type attributeType,
     bool inherit)
 {
     Object[] attributes = type.GetCustomAttributes(attributeType, inherit);
     if (attributes == null || attributes.Length == 0)
         Assert.Fail(
             "{0} is not tagged with {1}", type, attributeType);
 }
Example #26
0
        public static ITestAction[] GetActionsFromAttributeProvider(ICustomAttributeProvider attributeProvider)
#endif
        {
            if (attributeProvider == null)
                return new ITestAction[0];

            var actions = new List<ITestAction>((ITestAction[])attributeProvider.GetCustomAttributes(typeof(ITestAction), false));
            actions.Sort(SortByTargetDescending);

            return actions.ToArray();
        }
        private void Apply(ICustomAttributeProvider provider)
        {
            foreach (var o in provider.GetCustomAttributes(false))
            {
                var attr = o as IDb4oAttribute;
                if (null == attr)
                    continue;

                attr.Apply(provider, this);
            }
        }
Example #28
0
 internal static IModelBinder GetBinderFromAttributes(ICustomAttributeProvider element, Action<ICustomAttributeProvider> errorAction)
 {
     CustomModelBinderAttribute[] attrs = (CustomModelBinderAttribute[])element.GetCustomAttributes(typeof(CustomModelBinderAttribute), true /* inherit */);
     // For compatibility, return null if no attributes.
     if (attrs == null)
     {                
         return null;
     }
     CustomModelBinderAttribute binder = attrs.SingleDefaultOrError(errorAction, element);
     return binder == null ? null : binder.GetBinder();
 }
 public static IEnumerable<SupportsGLTextureAttribute> FromCustomAttributeProvider(ICustomAttributeProvider provider)
 {
     var attrs = provider.GetCustomAttributes ("Android.App.SupportsGLTextureAttribute");
     foreach (var attr in attrs) {
         if (attr.HasConstructorArguments && attr.ConstructorArguments.Count == 1) {
             SupportsGLTextureAttribute self = new SupportsGLTextureAttribute((string)attr.ConstructorArguments[0].Value);
             self.specified = mapping.Load (self, attr);
             self.specified.Add("Name");
             yield return self;
         }
     }
 }
Example #30
0
 /// <summary>
 /// Прочитать атрибуты
 /// </summary>
 /// <param name="attr">Тип атрибута</param>
 /// <param name="provider">Параметр</param>
 /// <returns>Атрибуты или пустая коллекция, если отсутствуют</returns>
 public IReadOnlyCollection<object> ReadMany(Type attr, ICustomAttributeProvider provider)
 {
     if (attr == null) throw new ArgumentNullException(nameof(attr));
     if (provider == null) throw new ArgumentNullException(nameof(provider));
     var key = _attributesReaderKeyFactory.Create(attr, provider);
     var res = _cacherFactory.Create<IReadOnlyCollection<object>>().GetOrAdd(key, s => provider.GetCustomAttributes(attr, false));
     if (res == null)
     {
         throw new InvalidOperationException($"Get custom attributes returned null or null in cache for key {key}");
     }
     return res;
 }
 public static IEnumerable<MetaDataAttribute> FromCustomAttributeProvider(ICustomAttributeProvider type)
 {
     IEnumerable<CustomAttribute> attrs = type.GetCustomAttributes ("Android.App.MetaDataAttribute");
     if (!attrs.Any ())
         yield break;
     foreach (CustomAttribute attr in attrs) {
         var self = new MetaDataAttribute ((string) attr.ConstructorArguments [0].Value);
         self.specified = mapping.Load (self, attr);
         self.specified.Add ("Name");
         yield return self;
     }
 }
        private static Type getInterface(ICustomAttributeProvider member)
        {
            object[] attributes = member.GetCustomAttributes(typeof(Implements),
                false);

            if (attributes.Length < 1)
            {
                error("Could not find the 'Implements' attribute on member");
            }

            Implements attribute = (Implements)attributes[0];
            return attribute.ImplementedInterface;
        }
        public static ScriptMethodThrows[] ArrayOfProvider(ICustomAttributeProvider m)
        {
            try
            {
                ScriptMethodThrows[] s = m.GetCustomAttributes(typeof(ScriptMethodThrows), false) as ScriptMethodThrows[];

                return s;
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }
 private static IEnumerable <WrappedAttribute> GetAttributes(ICustomAttributeProvider obj)
 {
     if (obj is MemberInfo memberInfo)
     {
         var attributes = memberInfo.GetCustomAttributes(true).OfType <TAttribute>();
         return(FlattenAttributeCollection(attributes));
     }
     else
     {
         var attributes = obj?.GetCustomAttributes(typeof(TAttribute), true).OfType <TAttribute>();
         return(FlattenAttributeCollection(attributes));
     }
 }
Example #35
0
        /// <summary>
        /// Coerce the raw string value into the expected result type.
        /// </summary>
        /// <typeparam name="T">The expected result type after coercion.</typeparam>
        /// <param name="value">The raw string value to be coerced.</param>
        /// <param name="valueName">The name of the value to be coerced.</param>
        /// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
        /// <param name="result">The coerced value.</param>
        /// <returns>True if the value could be coerced, false otherwise.</returns>
        public bool Coerce <T>(string value, string valueName, ICustomAttributeProvider property, out T result)
        {
            var propertyCoercers = property?.GetCustomAttributes(true)
                                   .OfType <IValueCoercer>() ?? Enumerable.Empty <IValueCoercer>();

            foreach (var coercer in propertyCoercers.Union(_coercers))
            {
                if (coercer.Coerce(value, valueName, property, out result))
                {
                    return(true);
                }
            }

            result = default(T);
            return(false);
        }
Example #36
0
 public static bool HasAttribute(this ICustomAttributeProvider self, Type attributeType)
 {
     return(self.GetCustomAttributes(attributeType, true).Any());
 }
Example #37
0
        //public static Type[] GetAppliesToTypes(this Type mixinType)
        //{
        //    IEnumerable<Type> appliesTo = from attribs in mixinType.GetCustomAttributes(typeof(AppliesToAttribute), true).Cast<AppliesToAttribute>()
        //                                  from type in attribs.AppliesToTypes
        //                                  select type;

        //    return appliesTo.ToArray();
        //}

        public static T GetAttribute <T>(this ICustomAttributeProvider self) where T : Attribute
        {
            var attrib = self.GetCustomAttributes(typeof(T), true).FirstOrDefault() as T;

            return(attrib);
        }
Example #38
0
        public static IEnumerable <T> GetAttributes <T>(this ICustomAttributeProvider self) where T : Attribute
        {
            IEnumerable <T> attribs = self.GetCustomAttributes(typeof(T), true).Cast <T>();

            return(attribs);
        }
Example #39
0
        public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit)
        {
            ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider");

            object provider = attributeProvider;

            // http://hyperthink.net/blog/getcustomattributes-gotcha/
            // ICustomAttributeProvider doesn't do inheritance

            if (provider is Type)
            {
                Type        t          = (Type)provider;
                object[]    a          = (attributeType != null) ? t.GetCustomAttributes(attributeType, inherit) : t.GetCustomAttributes(inherit);
                Attribute[] attributes = a.Cast <Attribute>().ToArray();

#if (NET20 || NET35)
                // ye olde .NET GetCustomAttributes doesn't respect the inherit argument
                if (inherit && t.BaseType != null)
                {
                    attributes = attributes.Union(GetAttributes(t.BaseType, attributeType, inherit)).ToArray();
                }
#endif

                return(attributes);
            }

            if (provider is Assembly)
            {
                Assembly a = (Assembly)provider;
                return((attributeType != null) ? Attribute.GetCustomAttributes(a, attributeType) : Attribute.GetCustomAttributes(a));
            }

            if (provider is MemberInfo)
            {
                MemberInfo m = (MemberInfo)provider;
                return((attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit));
            }

#if !PORTABLE40
            if (provider is Module)
            {
                Module m = (Module)provider;
                return((attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit));
            }
#endif

            if (provider is ParameterInfo)
            {
                ParameterInfo p = (ParameterInfo)provider;
                return((attributeType != null) ? Attribute.GetCustomAttributes(p, attributeType, inherit) : Attribute.GetCustomAttributes(p, inherit));
            }

#if !PORTABLE40
            ICustomAttributeProvider customAttributeProvider = (ICustomAttributeProvider)attributeProvider;
            object[] result = (attributeType != null) ? customAttributeProvider.GetCustomAttributes(attributeType, inherit) : customAttributeProvider.GetCustomAttributes(inherit);

            return((Attribute[])result);
#else
            throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
#endif
        }
        } // RemotingCachedData

        // Retrieve SOAP attribute info for _mi (or create for caching if not specified)
        internal SoapAttribute GetSoapAttribute()
        {
            if (_soapAttr == null)
            {
                lock (this)
                {
                    if (_soapAttr == null)
                    {
                        SoapAttribute tempSoapAttr = null;

                        ICustomAttributeProvider cap = (ICustomAttributeProvider)RI;

                        if (RI is Type)
                        {
                            Object[] attrs = cap.GetCustomAttributes(typeof(SoapTypeAttribute), true);
                            if ((attrs != null) && (attrs.Length != 0))
                            {
                                tempSoapAttr = (SoapAttribute)attrs[0];
                            }
                            else
                            {
                                tempSoapAttr = new SoapTypeAttribute();
                            }
                        }
                        else
                        if (RI is MethodBase)
                        {
                            Object[] attrs = cap.GetCustomAttributes(typeof(SoapMethodAttribute), true);
                            if ((attrs != null) && (attrs.Length != 0))
                            {
                                tempSoapAttr = (SoapAttribute)attrs[0];
                            }
                            else
                            {
                                tempSoapAttr = new SoapMethodAttribute();
                            }
                        }
                        else
                        if (RI is FieldInfo)
                        {
                            Object[] attrs = cap.GetCustomAttributes(typeof(SoapFieldAttribute), false);
                            if ((attrs != null) && (attrs.Length != 0))
                            {
                                tempSoapAttr = (SoapAttribute)attrs[0];
                            }
                            else
                            {
                                tempSoapAttr = new SoapFieldAttribute();
                            }
                        }
                        else
                        if (RI is ParameterInfo)
                        {
                            Object[] attrs = cap.GetCustomAttributes(typeof(SoapParameterAttribute), true);
                            if ((attrs != null) && (attrs.Length != 0))
                            {
                                tempSoapAttr = (SoapParameterAttribute)attrs[0];
                            }
                            else
                            {
                                tempSoapAttr = new SoapParameterAttribute();
                            }
                        }

                        // IMPORTANT: This has to be done for certain values to be automatically
                        //   generated in the attribute.
                        tempSoapAttr.SetReflectInfo(RI);

                        _soapAttr = tempSoapAttr;
                    } // if (_soapAttr == null)
                }     // lock (this)
            }

            return(_soapAttr);
        } // GetSoapAttribute
Example #41
0
 public static TAttribute GetAttributeOrDefault <TAttribute>(this ICustomAttributeProvider attributeProvider)
 => attributeProvider.GetCustomAttributes(false).OfType <TAttribute>().SingleOrDefault();
Example #42
0
 internal static T GetAttribute <T>(this ICustomAttributeProvider provider) where T : Attribute =>
 (provider.GetCustomAttributes(typeof(T), true)?[0] as T) ?? null;
Example #43
0
 /// <summary>
 /// Gets the typed attributes.
 /// </summary>
 /// <typeparam name="TAttribute">The type of the attribute.</typeparam>
 /// <param name="attributeProvider">The attribute provider.</param>
 /// <returns></returns>
 public static IEnumerable <TAttribute> GetAttributes <TAttribute>(this ICustomAttributeProvider attributeProvider)
 {
     return(attributeProvider.GetCustomAttributes(false).OfType <TAttribute>());
 }
Example #44
0
 public static T GetCustomAttribute <T>(this ICustomAttributeProvider type)
     where T : Attribute
 {
     return(type.GetCustomAttributes <T>().FirstOrDefault());
 }
 /// <summary>
 /// Gets a single custom attribute, usable without this ugly cast.
 /// </summary>
 /// <typeparam name="TAttribute">The type of the attribute.</typeparam>
 /// <param name="customAttributeProvider">The custom attribute provider.</param>
 /// <param name="inherit">if set to <c>true</c> [inherit].</param>
 /// <returns></returns>
 public static TAttribute GetCustomAttribute <TAttribute>(this ICustomAttributeProvider customAttributeProvider, bool inherit = true)
     where TAttribute : Attribute
 {
     return(customAttributeProvider.GetCustomAttributes(typeof(TAttribute), inherit).Cast <TAttribute>().SingleOrDefault());
 }
Example #46
0
        bool GetFacet(ref string sParam, ICustomAttributeProvider ap, ref string prmName, ref object defVal)
        {
            //Debugger.Launch();
            bool isFacet         = false;
            bool SetFacet        = false;
            Type attr            = typeof(SqlFacetAttribute);
            Type attr2           = typeof(SqlParamFacetAttribute);
            SqlFacetAttribute fc = null;

            if (ap.IsDefined(attr2, false))
            {
                SqlParamFacetAttribute prmfcarr = ((SqlParamFacetAttribute[])ap.GetCustomAttributes(attr2, false))[0];
                if (prmfcarr.Name != null)
                {
                    prmName = prmfcarr.Name;
                }
                if (prmfcarr.DefaultValue != null)
                {
                    defVal = prmfcarr.DefaultValue;
                }
                isFacet = true;
                fc      = (SqlFacetAttribute)prmfcarr;
            }

            if (ap.IsDefined(attr, false) && !isFacet)
            {
                SqlFacetAttribute[] fcarr = (SqlFacetAttribute[])ap.GetCustomAttributes(attr, false);

                //I assume I can only have one sqlfacet per param
                fc      = (SqlFacetAttribute)fcarr[0];
                isFacet = true;
            }

            if (isFacet)
            {
                switch (sParam)
                {
                case "nvarchar":
                    if (fc.IsFixedLength)
                    {
                        sParam   = "nchar";
                        SetFacet = true;
                    }

                    if (fc.MaxSize > 0 && fc.MaxSize < 4001)
                    {
                        sParam   = sParam + "(" + fc.MaxSize.ToString() + ")";
                        SetFacet = true;
                    }
                    else if (fc.MaxSize == -1)
                    {
                        sParam   = sParam + "(max)";
                        SetFacet = true;
                    }
                    else
                    {
                        sParam   = sParam + "(50)";
                        SetFacet = true;
                    }

                    break;

                case "varbinary":
                    if (fc.MaxSize == -1)
                    {
                        sParam   = sParam + "(max)";
                        SetFacet = true;
                    }
                    else if (fc.MaxSize > 0)
                    {
                        sParam   = sParam + "(" + fc.MaxSize.ToString() + ")";
                        SetFacet = true;
                    }
                    else
                    {
                        sParam   = sParam + "(50)";
                        SetFacet = true;
                    }

                    break;

                case "decimal":
                    if (fc.Precision > 0 && fc.Scale > 0)
                    {
                        sParam   = sParam + "(" + fc.Precision.ToString() + ", " + fc.Scale.ToString() + ")";
                        SetFacet = true;
                    }

                    break;
                }
            }

            return(SetFacet);
        }
 /// <summary>
 /// Will return true if the attributeTarget is decorated with an attribute of type TAttribute.
 /// Will return false if not.
 /// </summary>
 /// <typeparam name="TAttribute"></typeparam>
 /// <param name="attributeTarget"></param>
 /// <returns></returns>
 public static bool IsDecoratedWith <TAttribute>(this ICustomAttributeProvider attributeTarget) where TAttribute : Attribute
 {
     return(attributeTarget.GetCustomAttributes(typeof(TAttribute), false).Length > 0);
 }
 /// <summary>
 /// Will return true the first attribute of type TAttribute on the attributeTarget.
 /// </summary>
 /// <typeparam name="TAttribute"></typeparam>
 /// <param name="attributeTarget"></param>
 /// <returns></returns>
 public static TAttribute GetAttribute <TAttribute>(this ICustomAttributeProvider attributeTarget) where TAttribute : Attribute
 {
     return((TAttribute)attributeTarget.GetCustomAttributes(typeof(TAttribute), false)[0]);
 }
Example #49
0
 /// <summary>
 ///     检查指定指定类型成员中是否存在指定的Attribute特性
 /// </summary>
 /// <typeparam name="T">要检查的Attribute特性类型</typeparam>
 /// <param name="assembly">The assembly<see cref="ICustomAttributeProvider" /></param>
 /// <param name="inherit">是否从继承中查找</param>
 /// <returns>是否存在</returns>
 public static bool AttributeExists <T>(this ICustomAttributeProvider assembly, bool inherit = false)
     where T : Attribute
 {
     return(assembly.GetCustomAttributes(typeof(T), inherit).Any(m => m as T != null));
 }
Example #50
0
 public static bool HasAttribute <T>(this ICustomAttributeProvider self) where T : Attribute
 {
     return(self.GetCustomAttributes(typeof(T), true).Any());
 }
 private static T?GetAttribute <T>(this ICustomAttributeProvider type)
     where T : Attribute
 => (T?)type
 ?.GetCustomAttributes(typeof(T), false)
 .SingleOrDefault();
Example #52
0
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlAttributes(ICustomAttributeProvider provider)
        {
            object[] attrs = provider.GetCustomAttributes(false);

            // most generic <any/> matches everything
            XmlAnyElementAttribute wildcard = null;

            for (int i = 0; i < attrs.Length; i++)
            {
                if (attrs[i] is XmlIgnoreAttribute || attrs[i] is ObsoleteAttribute || attrs[i].GetType() == IgnoreAttribute)
                {
                    _xmlIgnore = true;
                    break;
                }
                else if (attrs[i] is XmlElementAttribute)
                {
                    _xmlElements.Add((XmlElementAttribute)attrs[i]);
                }
                else if (attrs[i] is XmlArrayItemAttribute)
                {
                    _xmlArrayItems.Add((XmlArrayItemAttribute)attrs[i]);
                }
                else if (attrs[i] is XmlAnyElementAttribute)
                {
                    XmlAnyElementAttribute any = (XmlAnyElementAttribute)attrs[i];
                    if ((any.Name == null || any.Name.Length == 0) && any.GetNamespaceSpecified() && any.Namespace == null)
                    {
                        // ignore duplicate wildcards
                        wildcard = any;
                    }
                    else
                    {
                        _xmlAnyElements.Add((XmlAnyElementAttribute)attrs[i]);
                    }
                }
                else if (attrs[i] is DefaultValueAttribute)
                {
                    _xmlDefaultValue = ((DefaultValueAttribute)attrs[i]).Value;
                }
                else if (attrs[i] is XmlAttributeAttribute)
                {
                    _xmlAttribute = (XmlAttributeAttribute)attrs[i];
                }
                else if (attrs[i] is XmlArrayAttribute)
                {
                    _xmlArray = (XmlArrayAttribute)attrs[i];
                }
                else if (attrs[i] is XmlTextAttribute)
                {
                    _xmlText = (XmlTextAttribute)attrs[i];
                }
                else if (attrs[i] is XmlEnumAttribute)
                {
                    _xmlEnum = (XmlEnumAttribute)attrs[i];
                }
                else if (attrs[i] is XmlRootAttribute)
                {
                    _xmlRoot = (XmlRootAttribute)attrs[i];
                }
                else if (attrs[i] is XmlTypeAttribute)
                {
                    _xmlType = (XmlTypeAttribute)attrs[i];
                }
                else if (attrs[i] is XmlAnyAttributeAttribute)
                {
                    _xmlAnyAttribute = (XmlAnyAttributeAttribute)attrs[i];
                }
                else if (attrs[i] is XmlChoiceIdentifierAttribute)
                {
                    _xmlChoiceIdentifier = (XmlChoiceIdentifierAttribute)attrs[i];
                }
                else if (attrs[i] is XmlNamespaceDeclarationsAttribute)
                {
                    _xmlns = true;
                }
            }
            if (_xmlIgnore)
            {
                _xmlElements.Clear();
                _xmlArrayItems.Clear();
                _xmlAnyElements.Clear();
                _xmlDefaultValue     = null;
                _xmlAttribute        = null;
                _xmlArray            = null;
                _xmlText             = null;
                _xmlEnum             = null;
                _xmlType             = null;
                _xmlAnyAttribute     = null;
                _xmlChoiceIdentifier = null;
                _xmlns = false;
            }
            else
            {
                if (wildcard != null)
                {
                    _xmlAnyElements.Add(wildcard);
                }
            }
        }
 public static IEnumerable <TAttribute> GetCustomAttributes <TAttribute>(this ICustomAttributeProvider instance, bool inherit)
 {
     Ensure.IsNotNull(instance);
     return(instance.GetCustomAttributes(typeof(TAttribute), inherit).OfType <TAttribute>());
 }
 public Array <T> Get(ICustomAttributeProvider parameter)
 => parameter.GetCustomAttributes(_type, _inherit)
 .Cast <T>()
 .ToArray();
Example #55
0
 /// <summary>Initializes a new instance of the <see cref="T:System.Xml.Serialization.XmlAttributes" /> class and customizes how the <see cref="T:System.Xml.Serialization.XmlSerializer" /> serializes and deserializes an object. </summary>
 /// <param name="provider">A class that can provide alternative implementations of attributes that control XML serialization.</param>
 public XmlAttributes(ICustomAttributeProvider provider)
 {
     object[] customAttributes = provider.GetCustomAttributes(false);
     foreach (object obj in customAttributes)
     {
         if (obj is XmlAnyAttributeAttribute)
         {
             this.xmlAnyAttribute = (XmlAnyAttributeAttribute)obj;
         }
         else if (obj is XmlAnyElementAttribute)
         {
             this.xmlAnyElements.Add((XmlAnyElementAttribute)obj);
         }
         else if (obj is XmlArrayAttribute)
         {
             this.xmlArray = (XmlArrayAttribute)obj;
         }
         else if (obj is XmlArrayItemAttribute)
         {
             this.xmlArrayItems.Add((XmlArrayItemAttribute)obj);
         }
         else if (obj is XmlAttributeAttribute)
         {
             this.xmlAttribute = (XmlAttributeAttribute)obj;
         }
         else if (obj is XmlChoiceIdentifierAttribute)
         {
             this.xmlChoiceIdentifier = (XmlChoiceIdentifierAttribute)obj;
         }
         else if (obj is DefaultValueAttribute)
         {
             this.xmlDefaultValue = ((DefaultValueAttribute)obj).Value;
         }
         else if (obj is XmlElementAttribute)
         {
             this.xmlElements.Add((XmlElementAttribute)obj);
         }
         else if (obj is XmlEnumAttribute)
         {
             this.xmlEnum = (XmlEnumAttribute)obj;
         }
         else if (obj is XmlIgnoreAttribute)
         {
             this.xmlIgnore = true;
         }
         else if (obj is XmlNamespaceDeclarationsAttribute)
         {
             this.xmlns = true;
         }
         else if (obj is XmlRootAttribute)
         {
             this.xmlRoot = (XmlRootAttribute)obj;
         }
         else if (obj is XmlTextAttribute)
         {
             this.xmlText = (XmlTextAttribute)obj;
         }
         else if (obj is XmlTypeAttribute)
         {
             this.xmlType = (XmlTypeAttribute)obj;
         }
     }
 }
Example #56
0
 static T GetAttribute <T>(ICustomAttributeProvider provider) where T : Attribute
 {
     return(provider.GetCustomAttributes(typeof(T), false).OfType <T>().FirstOrDefault());
 }
Example #57
0
 public static bool HasAttribute <T>(ICustomAttributeProvider t)
     where T : Attribute
 {
     object[] attributes = t.GetCustomAttributes(typeof(T), true);
     return(attributes != null && attributes.Length > 0);
 }
    public static void Main()
    {
// <Snippet3>
        Type       myType       = typeof(MyService);
        MethodInfo myMethodInfo = myType.GetMethod("Add");
// <Snippet1>
// <Snippet2>
        // Create a synchronous 'LogicalMethodInfo' instance.
        LogicalMethodInfo myLogicalMethodInfo =
            (LogicalMethodInfo.Create(new MethodInfo[] { myMethodInfo },
                                      LogicalMethodTypes.Sync))[0];

// </Snippet2>
// </Snippet1>
        // Display the method for which the attributes are being displayed.
        Console.WriteLine("\nDisplaying the attributes for the method : {0}\n",
                          myLogicalMethodInfo.MethodInfo);
// </Snippet3>

        // Displaying a custom attribute of type 'MyAttribute'
        Console.WriteLine("\nDisplaying attribute of type 'MyAttribute'\n");
        object attribute = myLogicalMethodInfo.GetCustomAttribute(typeof(MyAttribute));

        Console.WriteLine(((MyAttribute)attribute).Name);

        // Display all custom attribute of type 'MyAttribute'.
        Console.WriteLine("\nDisplaying all attributes of type 'MyAttribute'\n");
        object[] attributes = myLogicalMethodInfo.GetCustomAttributes(typeof(MyAttribute));
        for (int i = 0; i < attributes.Length; i++)
        {
            Console.WriteLine(((MyAttribute)attributes[i]).Name);
        }

        // Display all return attributes of type 'MyAttribute'.
        Console.WriteLine("\nDisplaying all return attributes of type 'MyAttribute'\n");
        ICustomAttributeProvider myCustomAttributeProvider =
            myLogicalMethodInfo.ReturnTypeCustomAttributeProvider;

        if (myCustomAttributeProvider.IsDefined(typeof(MyAttribute), true))
        {
            attributes = myCustomAttributeProvider.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length; i++)
            {
                if (attributes[i].GetType().Equals(typeof(MyAttribute)))
                {
                    Console.WriteLine(((MyAttribute)attributes[i]).Name);
                }
            }
        }

        // Display all the custom attributes of type 'MyAttribute'.
        Console.WriteLine("\nDisplaying all attributes of type 'MyAttribute'\n");
        myCustomAttributeProvider = myLogicalMethodInfo.CustomAttributeProvider;
        if (myCustomAttributeProvider.IsDefined(typeof(MyAttribute), true))
        {
            attributes = myCustomAttributeProvider.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length; i++)
            {
                if (attributes[i].GetType().Equals(typeof(MyAttribute)))
                {
                    Console.WriteLine(((MyAttribute)attributes[i]).Name);
                }
            }
        }
    }
 /// <summary>
 /// 获得自定义属性
 /// </summary>
 /// <typeparam name="T">类型</typeparam>
 /// <param name="type">自定义属性类型</param>
 /// <param name="inherit">是否继承</param>
 /// <returns></returns>
 public static T[] GetCustomerAttributes <T>(this ICustomAttributeProvider type) where T : Attribute
 {
     return(type.GetCustomAttributes(typeof(T), false).Cast <T>().ToArray());
 }
Example #60
0
 static string GetCsvFormat(this ICustomAttributeProvider attributeProvider)
 => attributeProvider?.GetCustomAttributes(false).OfType <CsvFormatAttribute>().FirstOrDefault()?.Format;