Exemple #1
0
 public ForeignKey(CustomAttributeData data)
 {
     TableName = (string)data.ConstructorArguments[0].Value;
     ColumnName = (string)data.ConstructorArguments[1].Value;
     FullName = TableName + "." + ColumnName;
     Index = (int)data.ConstructorArguments[2].Value;
 }
 private static string GetCustomAttributeData(CustomAttributeData cad, Type attrType, out Type typeValue, bool allowTypeAlso, bool noArgs, bool zeroArgsAllowed)
 {
     string assemblyQualifiedName = null;
     typeValue = null;
     if (!(cad.Constructor.ReflectedType == attrType))
     {
         return assemblyQualifiedName;
     }
     IList<CustomAttributeTypedArgument> constructorArguments = cad.ConstructorArguments;
     if ((constructorArguments.Count == 1) && !noArgs)
     {
         CustomAttributeTypedArgument argument = constructorArguments[0];
         assemblyQualifiedName = argument.Value as string;
         if (((assemblyQualifiedName == null) && allowTypeAlso) && (argument.ArgumentType == typeof(Type)))
         {
             typeValue = argument.Value as Type;
             assemblyQualifiedName = typeValue.AssemblyQualifiedName;
         }
         if (assemblyQualifiedName == null)
         {
             throw new ArgumentException(System.Xaml.SR.Get("ParserAttributeArgsLow", new object[] { attrType.Name }));
         }
         return assemblyQualifiedName;
     }
     if (constructorArguments.Count != 0)
     {
         throw new ArgumentException(System.Xaml.SR.Get("ParserAttributeArgsHigh", new object[] { attrType.Name }));
     }
     if (!noArgs && !zeroArgsAllowed)
     {
         throw new ArgumentException(System.Xaml.SR.Get("ParserAttributeArgsLow", new object[] { attrType.Name }));
     }
     return string.Empty;
 }
        public Dictionary<string, object> Convert(string propertyName, CustomAttributeData attr)
        {
            var validations = new Dictionary<string, object>();

            var minimum = GetConstructorArgumentValue(attr, 0);
            var maximum = GetConstructorArgumentValue(attr, 1);

            if (!string.IsNullOrWhiteSpace(minimum) && !string.IsNullOrWhiteSpace(maximum))
            {
                validations.Add("min", minimum);

                var displayName = base.GetNamedArgumentValue(propertyName, attr, DataAnnotationConstants.Display);
                if (!string.IsNullOrWhiteSpace(displayName))
                {
                    var msg = GetErrorMessage(propertyName, attr);
                    if (msg != null)
                    {
                        validations.Add("min-msg", msg);
                        validations.Add("max-msg", msg);

                    }
                    validations.Add("max", maximum);
                }
            }
            return validations;
        }
        public CommonAttribute GetCommonAttribute(CustomAttributeData customAttributeData)
        {
            var positionalArguments = customAttributeData.ConstructorArguments.Select(GetCommonPositionalArgument);
              var namedArguments = customAttributeData.NamedArguments.AssertNotNull().Select(GetCommonNamedArgument);

              return new CommonAttribute(GetCommonType(customAttributeData.Constructor.DeclaringType), positionalArguments, namedArguments);
        }
        public static IList<CustomAttributeData> GetCustomAttributes(MemberInfo target)
        {
            if (target == null)
                throw new ArgumentNullException("target");

            IList<CustomAttributeData> cad = GetCustomAttributes(target.Module, target.MetadataToken);

            int pcaCount = 0;
            Attribute[] a = null;
            if (target is RuntimeType)
                a = PseudoCustomAttribute.GetCustomAttributes((RuntimeType)target, typeof(object), false, out pcaCount);
            else if (target is RuntimeMethodInfo)
                a = PseudoCustomAttribute.GetCustomAttributes((RuntimeMethodInfo)target, typeof(object), false, out pcaCount);
            else if (target is RuntimeFieldInfo)
                a = PseudoCustomAttribute.GetCustomAttributes((RuntimeFieldInfo)target, typeof(object), out pcaCount);

            if (pcaCount == 0)
                return cad;

            CustomAttributeData[] pca = new CustomAttributeData[cad.Count + pcaCount];
            cad.CopyTo(pca, pcaCount);
            for (int i = 0; i < pcaCount; i++)
            {
                if (PseudoCustomAttribute.IsSecurityAttribute(a[i].GetType()))
                    continue;

                pca[i] = new CustomAttributeData(a[i]);
            }

            return Array.AsReadOnly(pca);
        }
 public static string Translate(Attribute a, CustomAttributeData d, Type context)
 {
     if (a is EcoElementAttribute)
         return TranslateEcoElementAttribute((EcoElementAttribute)a);
     else
         return d.ToString();
 }
        public string FormatErrorMessage(string propertyName, CustomAttributeData attr)
        {
            try
            {
                var message = ErrorMessages[attr.AttributeType.Name];

                var arguments = new List<object>();
                arguments.Add(propertyName);
                if(attr.AttributeType.Name == "StringLengthAttribute")
                {
                    arguments.Add(attr.NamedArguments.Where(x => x.MemberName == "MinimumLength").Select(x => x.TypedValue.Value).First());
                }
                arguments.AddRange(attr.ConstructorArguments.Select(x => x.Value).Cast<object>());

                return String.Format(message, arguments.ToArray());
            }
            catch (KeyNotFoundException)
            {
                try
                {
                    return String.Format(ErrorMessages["Default"], propertyName);
                }
                catch (KeyNotFoundException)
                {
                    return String.Format("{0} incorrect", propertyName);
                }
            }
        }
        /// <summary>
        /// This methods creates an attribute instance from the attribute data 
        /// information
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static Attribute CreateAttribute(CustomAttributeData data)
        {
            var arguments = from arg in data.ConstructorArguments
                            select arg.Value;

            var attribute = data.Constructor.Invoke(arguments.ToArray()) as Attribute;

            if (data.NamedArguments != null)
            {
                foreach (var namedArgument in data.NamedArguments)
                {
                    var propertyInfo = namedArgument.MemberInfo as PropertyInfo;
                    if (propertyInfo != null)
                    {
                        propertyInfo.SetValue(attribute, namedArgument.TypedValue.Value, null);
                    }
                    else
                    {
                        var fieldInfo = namedArgument.MemberInfo as FieldInfo;
                        if (fieldInfo != null)
                        {
                            fieldInfo.SetValue(attribute, namedArgument.TypedValue.Value);
                        }
                    }
                }
            }
            return attribute;
        }
 public static void CustomAttributeData_NamedArguments(CustomAttributeData customAttributeData)
 {
     String attributeTypeName = customAttributeData.AttributeTypeNameString();
     if (attributeTypeName == null)
         return;
     ReflectionEventSource.Log.CustomAttributeData_NamedArguments(attributeTypeName);
 }
        public Dictionary<string, object> Convert(string propertyName, CustomAttributeData attr)
        {
            var validations = new Dictionary<string, object>();
            var length = GetConstructorArgumentValue(attr, 0);

            return SetMinLengthAAValidation(propertyName, attr, length);
        }
Exemple #11
0
 public static bool IsSamplePageByCategory(this Page self, CustomAttributeData attr, string category)
 {
     if(attr == null)
     {
         throw new ArgumentNullException("attr");
     }
     return attr.NamedArguments.Any(arg => attr.AttributeType == typeof(SamplePageAttribute) && arg.MemberName == "Category" && arg.TypedValue.Value.ToString() == category);
 }       
 public Dictionary<string, object> Convert(string propertyName, CustomAttributeData attr)
 {
     var pattern = GetConstructorArgumentValue(attr, 0);
     if (!string.IsNullOrWhiteSpace(pattern))
     {
         return SetRegularExpressionAAValidation(propertyName, attr, pattern);
     }
     return new Dictionary<string, object>();
 }
		public CustomAttributeInfo(CustomAttributeData data) {
			attributeType = new QualifiedTypeNameInfo(data.Constructor.DeclaringType);
			constructorArguments = data.Constructor.GetParameters().OrderBy(p => p.Position).Select(p => new KeyValuePair<QualifiedTypeNameInfo, object>(new QualifiedTypeNameInfo(p.ParameterType), GetSimpleValue(data.ConstructorArguments[p.Position].Value))).ToArray();
			if (data.NamedArguments == null) {
				namedArguments = new KeyValuePair<TypeMemberInfo, object>[0];
			} else {
				namedArguments = data.NamedArguments.Select(argument => new KeyValuePair<TypeMemberInfo, object>(new TypeMemberInfo(argument.MemberInfo), GetSimpleValue(argument.TypedValue.Value))).ToArray();
			}
		}
Exemple #14
0
		public FileInstallStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
			//[assembly: InstallFile(RepositoryPath = "/Root/Test/asdf.css", ResourcePath = "/res.asdf.css")]
			var repositoryPath = GetParameterValue<string>("RepositoryPath");
			var contentName = ContentManager.Path.GetFileName(repositoryPath);
			var containerPath = ContentManager.Path.GetParentPath(repositoryPath);

			ContainerPath = containerPath;
			ContentName = contentName;
			RawAttachments = "Binary:" + ResourceName;
		}
        public static string Translate(Attribute a, CustomAttributeData d, FieldInfo context)
        {
            var ecoAttr = a as EcoFieldAttribute;
            if (ecoAttr != null && !ecoAttr.ApplyToGeneratedClass) return null;

            if (a is KnownTypesAttribute)
                return TranslateKnownTypesAttribute((KnownTypesAttribute)a);
            else if (a is DefaultAttribute)
                return TranslateDefaultAttribute((DefaultAttribute)a);
            else
                return d.ToString();
        }
        internal static object GetRawConstant(CustomAttributeData attr)
        {
            foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
            {
                if (namedArgument.MemberInfo.Name.Equals("Value"))
                    return namedArgument.TypedValue.Value;
            }

            // Return DBNull to indicate that no default value is available.
            // Not to be confused with a null return which indicates a null default value.
            return DBNull.Value;
        }
Exemple #17
0
        public static TagBuilder GetRequiredSpan(CustomAttributeData cs, MemberInfo member)
        {
            CustomAttributeNamedArgument namedArg = cs.NamedArguments.Where(p => p.MemberName == "ErrorMessage").First();
            string errorMsg = string.Empty;

            if (namedArg != null)
                errorMsg = namedArg.TypedValue.Value.ToString();
            else
                errorMsg = "Please enter " + member.Name.ToLower();

            return GetSpan(errorMsg, member.Name.ToLower(), "required");
        }
        public string FormatErrorMessage(string propertyName, CustomAttributeData attr)
        {
            string value = null;

            if (attr.NamedArguments != null && attr.NamedArguments.Count > 0)
            {
                var namedArg = attr.NamedArguments.FirstOrDefault(na => na.MemberName == NameOfArgument);
                if (namedArg != null && namedArg.TypedValue != null && namedArg.TypedValue.Value != null)
                {
                    value = namedArg.TypedValue.Value.ToString();
                }
            }

            return value;
        }
        internal static DateTime GetRawDateTimeConstant(CustomAttributeData attr)
        {
            Contract.Requires(attr.Constructor.DeclaringType == typeof(DateTimeConstantAttribute));
            Contract.Requires(attr.ConstructorArguments.Count == 1);

            foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
            {
                if (namedArgument.MemberInfo.Name.Equals("Value"))
                {
                    return new DateTime((long)namedArgument.TypedValue.Value);
                }
            }

            // Look at the ctor argument if the "Value" property was not explicitly defined.
            return new DateTime((long)attr.ConstructorArguments[0].Value);
        }
Exemple #20
0
        private XElement fillPropElementJSON(System.Reflection.PropertyInfo prop, System.Reflection.CustomAttributeData attrib, Type classType)
        {
            string name, alias;

            GetNameAndAlias(attrib, prop.Name, out name, out alias);
            var propElement = new XElement(name);

            propElement.Add(new XElement("name", name));
            propElement.Add(new XElement("name_en", alias));

            var access = findAccess(attrib, prop);

            AppendXmlDocsJSON(propElement, "P:" + classType.FullName + "." + prop.Name);
            buildAccessProperty(access["canRead"], access["canWrite"], propElement);
            return(propElement);
        }
        public static TypeInfo GetType(Assembly asm, Func<CustomAttributeData, bool> match, out CustomAttributeData matchingAttributeData)
        {
            matchingAttributeData = null;
            foreach (var type in asm.DefinedTypes)
            {
                foreach (var attribute in type.CustomAttributes)
                {
                    if (match(attribute))
                    {
                        matchingAttributeData = attribute;
                        return type;
                    }
                }
            }

            return null;
        }
        public Dictionary<string, object> Convert(string propertyName, CustomAttributeData attr)
        {
            var validations = new Dictionary<string, object>();

            validations.Add("required", true);

            var displayName = GetNamedArgumentValue(propertyName, attr, DataAnnotationConstants.Display);
            if (!string.IsNullOrWhiteSpace(displayName))
            {
                var msg = GetErrorMessage(propertyName, attr);
                if (msg != null)
                {
                    validations.Add("required-msg", msg);
                }
            }
            return validations;
        }
        public TestFixture(TypeInfo testType, CustomAttributeData testFixtureAttribute)
        {
            Type = testType;
            Tests = new List<Test>();

            // Tesztesetek meghatározása
            foreach (var method in TestHelper.GetMethods(Type, attribute => attribute.AttributeType.FullName == TestAttributes.Test))
            {
                Tests.Add(new Test(this, method));
            }

            TestFixtureAttribute = testFixtureAttribute;
            Instance = TestHelper.CreateTestFixture(Type.AsType(), testFixtureAttribute);

            FindSetUpFixture(out _setUpFixture, out _setUpMethod);
            FindTearDownFixture(out _tearDownFixture, out _tearDownMethod);
        }
        public CustomAttributeData(System.Reflection.CustomAttributeData data)
        {
            var dataDynamic = data as dynamic;

            this.AttributeType        = dataDynamic.AttributeType.FullName;
            this.ConstructorArguments = new List <CustomAttributeTypedArgument>();
            this.NamedArguments       = new List <CustomAttributeNamedArgument>();

            foreach (var arg in ((IList <System.Reflection.CustomAttributeTypedArgument>)dataDynamic.ConstructorArguments))
            {
                this.ConstructorArguments.Add(new CustomAttributeTypedArgument(arg));
            }

            foreach (var arg in ((IList <System.Reflection.CustomAttributeNamedArgument>)dataDynamic.NamedArguments))
            {
                this.NamedArguments.Add(new CustomAttributeNamedArgument(arg));
            }
        }
Exemple #25
0
        private XElement fillPropElement(System.Reflection.PropertyInfo prop, System.Reflection.CustomAttributeData attrib, Type classType)
        {
            var    propElement = new XElement("property");
            string name, alias;

            GetNameAndAlias(attrib, prop.Name, out name, out alias);
            propElement.Add(new XAttribute("clr-name", classType.FullName + "." + prop.Name));
            propElement.Add(new XElement("name", name));
            propElement.Add(new XElement("alias", alias));

            var access = findAccess(attrib, prop);

            propElement.Add(new XElement("readable", access["canRead"]));
            propElement.Add(new XElement("writeable", access["canWrite"]));

            AppendXmlDocs(propElement, "P:" + classType.FullName + "." + prop.Name);
            return(propElement);
        }
        internal static Decimal GetRawDecimalConstant(CustomAttributeData attr)
        {
            Contract.Requires(attr.Constructor.DeclaringType == typeof(DecimalConstantAttribute));

            foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
            {
                if (namedArgument.MemberInfo.Name.Equals("Value"))
                {
                    // This is not possible because Decimal cannot be represented directly in the metadata.
                    Contract.Assert(false, "Decimal cannot be represented directly in the metadata.");
                    return (Decimal)namedArgument.TypedValue.Value;
                }
            }

            ParameterInfo[] parameters = attr.Constructor.GetParameters();
            Contract.Assert(parameters.Length == 5);

            System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attr.ConstructorArguments;
            Contract.Assert(args.Count == 5);

            if (parameters[2].ParameterType == typeof(uint))
            {
                // DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low)
                int low = (int)(UInt32)args[4].Value;
                int mid = (int)(UInt32)args[3].Value;
                int hi = (int)(UInt32)args[2].Value;
                byte sign = (byte)args[1].Value;
                byte scale = (byte)args[0].Value;

                return new System.Decimal(low, mid, hi, (sign != 0), scale);
            }
            else
            {
                // DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low)
                int low = (int)args[4].Value;
                int mid = (int)args[3].Value;
                int hi = (int)args[2].Value;
                byte sign = (byte)args[1].Value;
                byte scale = (byte)args[0].Value;

                return new System.Decimal(low, mid, hi, (sign != 0), scale);
            }
        }
 static private void AppendCustomAttributeData(CustomAttributeData attribute, StringBuilder sb)
 {
     sb.Append("[");
     AppendType(attribute.Constructor.DeclaringType, sb);
     sb.Append("(");
     foreach (var positionalArgument in attribute.ConstructorArguments)
     {
         AppendValue(positionalArgument.Value, sb, false);
         AppendComma(sb);
     }
     foreach (var namedArgument in attribute.NamedArguments)
     {
         sb.Append(namedArgument.MemberInfo.Name);
         AppendValue(namedArgument.TypedValue.Value, sb);
         AppendComma(sb);
     }
     RemoveTrailingComma(sb);
     sb.Append(")]");
 }
        public Dictionary<string, object> Convert(string propertyName, CustomAttributeData attr)
        {
            var validations = new Dictionary<string, object>();

            var maxLength = GetConstructorArgumentValue(attr, 0);
            if (!string.IsNullOrWhiteSpace(maxLength))
            {
                var maxValidations = SetMaxLengthAAValidation(propertyName, attr, maxLength);
                validations = validations.Concat(maxValidations).ToDictionary(x => x.Key, x => x.Value);
            }

            var minLength = base.GetNamedArgumentValue(propertyName, attr, DataAnnotationConstants.MinimumLength, false);
            if (!string.IsNullOrWhiteSpace(minLength))
            {
                var minValidations = SetMinLengthAAValidation(propertyName, attr, minLength);
                validations = validations.Concat(minValidations).ToDictionary(x => x.Key, x => x.Value);
            }

            return validations;
        }
        private XElement GenerateAttributeReference(CustomAttributeData attribute)
        {
            var attributeElement = new XElement (
              "HasAttribute", new XAttribute ("ref", _attributeIdentifierGenerator.GetIdentifier (attribute.Constructor.DeclaringType)));

              for (int i = 0; i < attribute.ConstructorArguments.Count; i++)
              {
            var constructorArgument = attribute.ConstructorArguments[i];
            var parameterName = attribute.Constructor.GetParameters()[i].Name;
            attributeElement.Add (GenerateParameterElement ("constructor", constructorArgument.ArgumentType, parameterName, constructorArgument.Value));
              }

              foreach (var namedArgument in attribute.NamedArguments)
              {
            attributeElement.Add (
            GenerateParameterElement ("named", namedArgument.TypedValue.ArgumentType, namedArgument.MemberInfo.Name, namedArgument.TypedValue.Value));
              }

              return attributeElement;
        }
Exemple #30
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeType target)
        {
            Contract.Assert(target != null);

            IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);

            int pcaCount = 0;
            Attribute[] a = PseudoCustomAttribute.GetCustomAttributes((RuntimeType)target, typeof(object) as RuntimeType, true, out pcaCount);

            if (pcaCount == 0)
                return cad;

            CustomAttributeData[] pca = new CustomAttributeData[cad.Count + pcaCount];
            cad.CopyTo(pca, pcaCount);
            for (int i = 0; i < pcaCount; i++)
            {
                pca[i] = new CustomAttributeData(a[i]);
            }

            return Array.AsReadOnly(pca);
        }
Exemple #31
0
        public AttributeDetail(RootDetail parent, CustomAttributeData cad)
            : base(parent, cad.Constructor.DeclaringType.FullName)
        {
            _declaration = cad.ToString();

            CodeStringBuilder csb = new CodeStringBuilder();

            AppendAttributesDeclaration(csb);

            csb.AppendType(cad.Constructor.DeclaringType);

            if (cad.ConstructorArguments.Count > 0)
            {
                csb.AppendText("(");
                csb.AppendQuotedValue(cad.ConstructorArguments[0].Value);
                csb.AppendText(")");
            }

            _declaration = csb.ToString();
            _declarationHtml = csb.ToHtmlString();
        }
Exemple #32
0
        private Dictionary <string, bool?> findAccess(System.Reflection.CustomAttributeData attrib, System.Reflection.PropertyInfo prop)
        {
            bool?canRead  = null;
            bool?canWrite = null;

            if (attrib.NamedArguments != null)
            {
                foreach (var attributeNamedArgument in attrib.NamedArguments)
                {
                    if (attributeNamedArgument.MemberName == "CanRead")
                    {
                        canRead = (bool)attributeNamedArgument.TypedValue.Value;
                    }

                    if (attributeNamedArgument.MemberName == "CanWrite")
                    {
                        canWrite = (bool)attributeNamedArgument.TypedValue.Value;
                    }
                }
            }
            if (canRead == null)
            {
                canRead = prop.GetMethod != null;
            }

            if (canWrite == null)
            {
                canWrite = prop.SetMethod != null;
            }

            var result = new Dictionary <string, bool?>();

            result.Add("canRead", canRead);
            result.Add("canWrite", canWrite);

            return(result);
        }
 private static IList<CustomAttributeData> GetCustomAttributes(Module module, int tkTarget)
 {
     CustomAttributeRecord[] customAttributeRecords = GetCustomAttributeRecords(module, tkTarget);
     CustomAttributeData[] array = new CustomAttributeData[customAttributeRecords.Length];
     for (int i = 0; i < customAttributeRecords.Length; i++)
     {
         array[i] = new CustomAttributeData(module, customAttributeRecords[i]);
     }
     return Array.AsReadOnly<CustomAttributeData>(array);
 }
 public static IList<CustomAttributeData> GetCustomAttributes(ParameterInfo target)
 {
     if (target == null)
     {
         throw new ArgumentNullException("target");
     }
     IList<CustomAttributeData> customAttributes = GetCustomAttributes(target.Member.Module, target.MetadataToken);
     int count = 0;
     Attribute[] attributeArray = PseudoCustomAttribute.GetCustomAttributes(target, typeof(object), out count);
     if (count == 0)
     {
         return customAttributes;
     }
     CustomAttributeData[] array = new CustomAttributeData[customAttributes.Count + count];
     customAttributes.CopyTo(array, count);
     for (int i = 0; i < count; i++)
     {
         array[i] = new CustomAttributeData(attributeArray[i]);
     }
     return Array.AsReadOnly<CustomAttributeData>(array);
 }
Exemple #35
0
 public override IList <CustomAttributeData> GetCustomAttributesData()
 {
     return(CustomAttributeData.GetCustomAttributes(this));
 }
Exemple #36
0
 public virtual IList <CustomAttributeData> GetCustomAttributesData()
 {
     return(CustomAttributeData.GetCustomAttributes(this));
 }
Exemple #37
0
 internal CustomAttributeData(ConstructorInfo ctorInfo, object[] ctorArgs, object[] namedArgs)
 {
     this.ctorInfo  = ctorInfo;
     this.ctorArgs  = Array.AsReadOnly <CustomAttributeTypedArgument>((ctorArgs == null) ? new CustomAttributeTypedArgument[0] : CustomAttributeData.UnboxValues <CustomAttributeTypedArgument>(ctorArgs));
     this.namedArgs = Array.AsReadOnly <CustomAttributeNamedArgument>((namedArgs == null) ? new CustomAttributeNamedArgument[0] : CustomAttributeData.UnboxValues <CustomAttributeNamedArgument>(namedArgs));
 }
Exemple #38
0
        // returns DBNull.Value if the parameter doesn't have a default value
        private Object GetDefaultValueInternal(bool raw)
        {
            Debug.Assert(!m_noMetadata);

            if (m_noDefaultValue)
            {
                return(DBNull.Value);
            }

            object defaultValue = null;

            // Why check the parameter type only for DateTime and only for the ctor arguments?
            // No check on the parameter type is done for named args and for Decimal.

            // We should move this after MdToken.IsNullToken(m_tkParamDef) and combine it
            // with the other custom attribute logic. But will that be a breaking change?
            // For a DateTime parameter on which both an md constant and a ca constant are set,
            // which one should win?
            if (ParameterType == typeof(DateTime))
            {
                if (raw)
                {
                    CustomAttributeTypedArgument value =
                        CustomAttributeData.Filter(
                            CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0);

                    if (value.ArgumentType != null)
                    {
                        return(new DateTime((long)value.Value));
                    }
                }
                else
                {
                    object[] dt = GetCustomAttributes(typeof(DateTimeConstantAttribute), false);
                    if (dt != null && dt.Length != 0)
                    {
                        return(((DateTimeConstantAttribute)dt[0]).Value);
                    }
                }
            }

            #region Look for a default value in metadata
            if (!MdToken.IsNullToken(m_tkParamDef))
            {
                // This will return DBNull.Value if no constant value is defined on m_tkParamDef in the metadata.
                defaultValue = MdConstant.GetValue(m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw);
            }
            #endregion

            if (defaultValue == DBNull.Value)
            {
                #region Look for a default value in the custom attributes
                if (raw)
                {
                    foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(this))
                    {
                        Type attrType = attr.Constructor.DeclaringType;

                        if (attrType == typeof(DateTimeConstantAttribute))
                        {
                            defaultValue = DateTimeConstantAttribute.GetRawDateTimeConstant(attr);
                        }
                        else if (attrType == typeof(DecimalConstantAttribute))
                        {
                            defaultValue = DecimalConstantAttribute.GetRawDecimalConstant(attr);
                        }
                        else if (attrType.IsSubclassOf(s_CustomConstantAttributeType))
                        {
                            defaultValue = CustomConstantAttribute.GetRawConstant(attr);
                        }
                    }
                }
                else
                {
                    Object[] CustomAttrs = GetCustomAttributes(s_CustomConstantAttributeType, false);
                    if (CustomAttrs.Length != 0)
                    {
                        defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value;
                    }
                    else
                    {
                        CustomAttrs = GetCustomAttributes(s_DecimalConstantAttributeType, false);
                        if (CustomAttrs.Length != 0)
                        {
                            defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value;
                        }
                    }
                }
                #endregion
            }

            if (defaultValue == DBNull.Value)
            {
                m_noDefaultValue = true;
            }

            return(defaultValue);
        }
        internal static unsafe object[] GetCustomAttributes(Module decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType, bool mustBeInheritable, IList derivedAttributes)
        {
            if (decoratedModule.Assembly.ReflectionOnly)
            {
                throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyCA"));
            }
            MetadataImport metadataImport = decoratedModule.MetadataImport;

            CustomAttributeRecord[] customAttributeRecords = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
            Type elementType = (((attributeFilterType == null) || attributeFilterType.IsValueType) || attributeFilterType.ContainsGenericParameters) ? typeof(object) : attributeFilterType;

            if ((attributeFilterType == null) && (customAttributeRecords.Length == 0))
            {
                return(Array.CreateInstance(elementType, 0) as object[]);
            }
            object[]             attributes = Array.CreateInstance(elementType, customAttributeRecords.Length) as object[];
            int                  length     = 0;
            SecurityContextFrame frame      = new SecurityContextFrame();

            frame.Push(decoratedModule.Assembly.InternalAssembly);
            Assembly lastAptcaOkAssembly = null;

            for (int i = 0; i < customAttributeRecords.Length; i++)
            {
                bool   flag2;
                bool   flag3;
                object obj2 = null;
                CustomAttributeRecord caRecord      = customAttributeRecords[i];
                RuntimeMethodHandle   ctor          = new RuntimeMethodHandle();
                RuntimeType           attributeType = null;
                int    namedArgs = 0;
                IntPtr signature = caRecord.blob.Signature;
                IntPtr blobEnd   = (IntPtr)(((void *)signature) + caRecord.blob.Length);
                if (FilterCustomAttributeRecord(caRecord, metadataImport, ref lastAptcaOkAssembly, decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable, attributes, derivedAttributes, out attributeType, out ctor, out flag2, out flag3))
                {
                    if (!ctor.IsNullHandle())
                    {
                        ctor.CheckLinktimeDemands(decoratedModule, decoratedMetadataToken);
                    }
                    RuntimeConstructorInfo.CheckCanCreateInstance(attributeType, flag3);
                    if (flag2)
                    {
                        obj2 = CreateCaObject(decoratedModule, ctor, ref signature, blobEnd, out namedArgs);
                    }
                    else
                    {
                        obj2 = attributeType.TypeHandle.CreateCaInstance(ctor);
                        if (Marshal.ReadInt16(signature) != 1)
                        {
                            throw new CustomAttributeFormatException();
                        }
                        signature = (IntPtr)(((void *)signature) + 2);
                        namedArgs = Marshal.ReadInt16(signature);
                        signature = (IntPtr)(((void *)signature) + 2);
                    }
                    for (int j = 0; j < namedArgs; j++)
                    {
                        string str;
                        bool   flag4;
                        Type   type3;
                        object obj3;
                        IntPtr ptr1 = caRecord.blob.Signature;
                        GetPropertyOrFieldData(decoratedModule, ref signature, blobEnd, out str, out flag4, out type3, out obj3);
                        try
                        {
                            if (flag4)
                            {
                                if ((type3 == null) && (obj3 != null))
                                {
                                    type3 = (obj3.GetType() == typeof(RuntimeType)) ? typeof(Type) : obj3.GetType();
                                }
                                RuntimePropertyInfo property = null;
                                if (type3 == null)
                                {
                                    property = attributeType.GetProperty(str) as RuntimePropertyInfo;
                                }
                                else
                                {
                                    property = attributeType.GetProperty(str, type3, Type.EmptyTypes) as RuntimePropertyInfo;
                                }
                                RuntimeMethodInfo setMethod = property.GetSetMethod(true) as RuntimeMethodInfo;
                                if (setMethod.IsPublic)
                                {
                                    setMethod.MethodHandle.CheckLinktimeDemands(decoratedModule, decoratedMetadataToken);
                                    setMethod.Invoke(obj2, BindingFlags.Default, null, new object[] { obj3 }, null, true);
                                }
                            }
                            else
                            {
                                (attributeType.GetField(str) as RtFieldInfo).InternalSetValue(obj2, obj3, BindingFlags.Default, Type.DefaultBinder, null, false);
                            }
                        }
                        catch (Exception exception)
                        {
                            throw new CustomAttributeFormatException(string.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString(flag4 ? "RFLCT.InvalidPropFail" : "RFLCT.InvalidFieldFail"), new object[] { str }), exception);
                        }
                    }
                    if (!signature.Equals(blobEnd))
                    {
                        throw new CustomAttributeFormatException();
                    }
                    attributes[length++] = obj2;
                }
            }
            frame.Pop();
            if ((length == customAttributeRecords.Length) && (pcaCount == 0))
            {
                return(attributes);
            }
            if (length == 0)
            {
                Array.CreateInstance(elementType, 0);
            }
            object[] destinationArray = Array.CreateInstance(elementType, (int)(length + pcaCount)) as object[];
            Array.Copy(attributes, 0, destinationArray, 0, length);
            return(destinationArray);
        }
        public void Intercept(IInvocation invocation)
        {
            ServiceRquestInfo rquestInfo = new ServiceRquestInfo();
            IList <System.Reflection.CustomAttributeData> customAttributeDatas = invocation.Method.GetCustomAttributesData();

            for (int j = 0; j < customAttributeDatas.Count; j++)
            {
                System.Reflection.CustomAttributeData customAttribute = customAttributeDatas[j];
                if (customAttribute.AttributeType == typeof(POSTAttribute))
                {
                    rquestInfo.HttpMethod = HttpMethod.Post;
                    if (customAttribute.ConstructorArguments[0].Value is string)
                    {
                        rquestInfo.Url = customAttribute.ConstructorArguments[0].Value as string;
                    }
                }
                else if (customAttribute.AttributeType == typeof(GETAttribute))
                {
                    rquestInfo.HttpMethod = HttpMethod.Get;
                    if (customAttribute.ConstructorArguments[0].Value is string)
                    {
                        rquestInfo.Url = customAttribute.ConstructorArguments[0].Value as string;
                    }
                }
                else if (customAttribute.AttributeType == typeof(HeaderAttribute))
                {
                    if (customAttribute.ConstructorArguments[0].Value is string)
                    {
                        rquestInfo.Header.Add(customAttribute.ConstructorArguments[0].Value as string);
                    }
                }
                else if (customAttribute.AttributeType == typeof(UploadFileAttribute))
                {
                    rquestInfo.IsUploadFile = true;
                }
            }

            if (invocation.Arguments.Count() > 0)//这个请求方法有传参
            {
                //获取参数
                ParameterInfo[] parameterInfos = invocation.Method.GetParameters();
                for (int j = 0; j < parameterInfos.Length; j++)
                {
                    ParameterInfo           parameter  = parameterInfos[j];
                    IEnumerable <Attribute> attributes = parameter.GetCustomAttributes();
                    if (attributes.Count() == 0)//这个参数没有使用我们的特性,过滤掉这个参数值
                    {
                        continue;
                    }
                    string paramName  = parameter.Name;          //参数原始名字
                    object paramValue = invocation.Arguments[j]; //参数值
                    for (int z = 0; z < attributes.Count(); z++)
                    {
                        Attribute a = attributes.ElementAt(z);
                        //Query属性
                        if (a is QueryAttribute)
                        {
                            if (!(paramValue is string))
                            {
                                throw new Exception("Query的请求非String");
                            }

                            QueryAttribute query        = a as QueryAttribute;
                            string         cfgParamName = query.ParamName; //在自定义特性中定义的属性名
                            if (string.IsNullOrEmpty(cfgParamName))        //如果没有配置Query的参数名,默认使用参数的㡳名称
                            {
                                rquestInfo.Param.Add(paramName, paramValue as string);
                            }
                            else
                            {
                                rquestInfo.Param.Add(cfgParamName, paramValue as string);
                            }
                        }
                        else if (a is BodyAttribute)
                        {
                            BodyAttribute body = a as BodyAttribute;
                            //将这个参数序列化成json
                            string json = Newtonsoft.Json.JsonConvert.SerializeObject(paramValue);
                            rquestInfo.Body = json;
                        }
                        else if (a is DynamicHeaderAttribute)
                        {
                            DynamicHeaderAttribute dynamicHeader = a as DynamicHeaderAttribute;
                            string headername = dynamicHeader.Header;
                            if (string.IsNullOrEmpty(headername))//如果没有配置Header的参数名,默认使用参数的㡳名称
                            {
                                rquestInfo.Header.Add(paramName + ":" + paramValue);
                            }
                            else
                            {
                                rquestInfo.Header.Add(headername + ":" + paramValue);
                            }
                        }
                        else if (a is FilePathAttribute)
                        {
                            rquestInfo.FilePath = paramValue as string;
                        }
                    }
                }
            }


            Console.WriteLine("拦截了");
            Call call = new Call();

            call.RquestInfo        = rquestInfo;
            call.Msg               = "测试";
            call.Client            = RetrofitClientCache.Instance.GetClient(invocation.Proxy.GetHashCode());
            invocation.ReturnValue = call;
            //不用实现方法
            //invocation.Proceed();
        }
Exemple #41
0
        internal static IList <CustomAttributeData> GetCustomAttributesData(ICustomAttributeProvider obj, Type attributeType, bool inherit)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }
            if (attributeType == null)
            {
                throw new ArgumentNullException(nameof(attributeType));
            }

            if (attributeType == typeof(CustomAttribute))
            {
                attributeType = null;
            }

            const string Message = "Invalid custom attribute data format";
            IList <CustomAttributeData> r;
            IList <CustomAttributeData> res = GetCustomAttributesDataBase(obj, attributeType, false);

            // shortcut
            if (!inherit && res.Count == 1)
            {
                if (res[0] == null)
                {
                    throw new CustomAttributeFormatException(Message);
                }
                if (attributeType != null)
                {
                    if (attributeType.IsAssignableFrom(res[0].AttributeType))
                    {
                        r = new CustomAttributeData[] { res[0] }
                    }
                    ;
                    else
                    {
                        r = Array.Empty <CustomAttributeData>();
                    }
                }
                else
                {
                    r = new CustomAttributeData[] { res[0] };
                }

                return(r);
            }

            if (inherit && GetBase(obj) == null)
            {
                inherit = false;
            }

            // if AttributeType is sealed, and Inherited is set to false, then
            // there's no use in scanning base types
            if ((attributeType != null && attributeType.IsSealed) && inherit)
            {
                AttributeUsageAttribute?usageAttribute = RetrieveAttributeUsage(attributeType);
                if (!usageAttribute.Inherited)
                {
                    inherit = false;
                }
            }

            int initialSize = Math.Max(res.Count, 16);
            List <CustomAttributeData> a     = null;
            ICustomAttributeProvider   btype = obj;

            /* Non-inherit case */
            if (!inherit)
            {
                if (attributeType == null)
                {
                    foreach (CustomAttributeData attrData in res)
                    {
                        if (attrData == null)
                        {
                            throw new CustomAttributeFormatException(Message);
                        }
                    }

                    var result = new CustomAttributeData[res.Count];
                    res.CopyTo(result, 0);
                    return(result);
                }
                else
                {
                    a = new List <CustomAttributeData>(initialSize);
                    foreach (CustomAttributeData attrData in res)
                    {
                        if (attrData == null)
                        {
                            throw new CustomAttributeFormatException(Message);
                        }
                        if (!attributeType.IsAssignableFrom(attrData.AttributeType))
                        {
                            continue;
                        }
                        a.Add(attrData);
                    }

                    return(a.ToArray());
                }
            }

            /* Inherit case */
            var attributeInfos   = new Dictionary <Type, AttributeInfo>(initialSize);
            int inheritanceLevel = 0;

            a = new List <CustomAttributeData>(initialSize);

            do
            {
                foreach (CustomAttributeData attrData in res)
                {
                    AttributeUsageAttribute usage;
                    if (attrData == null)
                    {
                        throw new CustomAttributeFormatException(Message);
                    }

                    Type attrType = attrData.AttributeType;
                    if (attributeType != null)
                    {
                        if (!attributeType.IsAssignableFrom(attrType))
                        {
                            continue;
                        }
                    }

                    AttributeInfo firstAttribute;
                    if (attributeInfos.TryGetValue(attrType, out firstAttribute))
                    {
                        usage = firstAttribute.Usage;
                    }
                    else
                    {
                        usage = RetrieveAttributeUsage(attrType);
                    }

                    // The same as for CustomAttributes.
                    //
                    // Only add attribute to the list of attributes if
                    // - we are on the first inheritance level, or the attribute can be inherited anyway
                    // and (
                    // - multiple attributes of the type are allowed
                    // or (
                    // - this is the first attribute we've discovered
                    // or
                    // - the attribute is on same inheritance level than the first
                    //   attribute that was discovered for this attribute type ))
                    if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple ||
                                                                       (firstAttribute == null || (firstAttribute != null &&
                                                                                                   firstAttribute.InheritanceLevel == inheritanceLevel))))
                    {
                        a.Add(attrData);
                    }

                    if (firstAttribute == null)
                    {
                        attributeInfos.Add(attrType, new AttributeInfo(usage, inheritanceLevel));
                    }
                }

                if ((btype = GetBase(btype)) != null)
                {
                    inheritanceLevel++;
                    res = GetCustomAttributesDataBase(btype, attributeType, true);
                }
            } while (inherit && btype != null);

            return(a.ToArray());
        }
Exemple #42
0
        private object GetDefaultValueInternal(bool raw)
        {
            if (this.m_noDefaultValue)
            {
                return((object)DBNull.Value);
            }
            object obj = (object)null;

            if (this.ParameterType == typeof(DateTime))
            {
                if (raw)
                {
                    CustomAttributeTypedArgument attributeTypedArgument = CustomAttributeData.Filter(CustomAttributeData.GetCustomAttributes((ParameterInfo)this), typeof(DateTimeConstantAttribute), 0);
                    if (attributeTypedArgument.ArgumentType != (Type)null)
                    {
                        return((object)new DateTime((long)attributeTypedArgument.Value));
                    }
                }
                else
                {
                    object[] customAttributes = this.GetCustomAttributes(typeof(DateTimeConstantAttribute), false);
                    if (customAttributes != null && customAttributes.Length != 0)
                    {
                        return(((CustomConstantAttribute)customAttributes[0]).Value);
                    }
                }
            }
            if (!System.Reflection.MetadataToken.IsNullToken(this.m_tkParamDef))
            {
                obj = MdConstant.GetValue(this.m_scope, this.m_tkParamDef, this.ParameterType.GetTypeHandleInternal(), raw);
            }
            if (obj == DBNull.Value)
            {
                if (raw)
                {
                    foreach (CustomAttributeData customAttribute in (IEnumerable <CustomAttributeData>)CustomAttributeData.GetCustomAttributes((ParameterInfo)this))
                    {
                        Type declaringType = customAttribute.Constructor.DeclaringType;
                        if (declaringType == typeof(DateTimeConstantAttribute))
                        {
                            obj = (object)DateTimeConstantAttribute.GetRawDateTimeConstant(customAttribute);
                        }
                        else if (declaringType == typeof(DecimalConstantAttribute))
                        {
                            obj = (object)DecimalConstantAttribute.GetRawDecimalConstant(customAttribute);
                        }
                        else if (declaringType.IsSubclassOf(RuntimeParameterInfo.s_CustomConstantAttributeType))
                        {
                            obj = CustomConstantAttribute.GetRawConstant(customAttribute);
                        }
                    }
                }
                else
                {
                    object[] customAttributes1 = this.GetCustomAttributes(RuntimeParameterInfo.s_CustomConstantAttributeType, false);
                    if (customAttributes1.Length != 0)
                    {
                        obj = ((CustomConstantAttribute)customAttributes1[0]).Value;
                    }
                    else
                    {
                        object[] customAttributes2 = this.GetCustomAttributes(RuntimeParameterInfo.s_DecimalConstantAttributeType, false);
                        if (customAttributes2.Length != 0)
                        {
                            obj = (object)((DecimalConstantAttribute)customAttributes2[0]).Value;
                        }
                    }
                }
            }
            if (obj == DBNull.Value)
            {
                this.m_noDefaultValue = true;
            }
            return(obj);
        }