// This constructor is the one used by .Net Native as the current metadata format only contains the name and the "isField" value, // not the actual member. To keep .Net Native running as before, we'll use the name and isField as the principal data and // construct the MemberInfo on demand. internal CustomAttributeNamedArgument(Type attributeType, string memberName, bool isField, CustomAttributeTypedArgument typedValue) { IsField = isField; MemberName = memberName; TypedValue = typedValue; _attributeType = attributeType; _lazyMemberInfo = null; }
// Helper that inspects a specific CustomAttributeData obtained via ReflectionOnlyLoad, and // returns its value if the Type of the attribiutes matches the passed in attrType. It only // looks for attributes with no values or a single value of Type string that is passed in via // a ctor. If allowTypeAlso is true, then it looks for values of typeof(Type) as well in the // single value case. If noArgs == false and zeroArgsAllowed = true, that means 0 or 1 args // are permissible. private static string GetCustomAttributeData(CustomAttributeData cad, Type attrType, out Type typeValue, bool allowTypeAlso, bool noArgs, bool zeroArgsAllowed) { string attrValue = null; typeValue = null; // get the Constructor info ConstructorInfo cinfo = cad.Constructor; if (cinfo.ReflectedType == attrType) { // typedConstructorArguments (the Attribute constructor arguments) // [MyAttribute("test", Name=Hello)] // "test" is the Constructor Argument IList <CustomAttributeTypedArgument> constructorArguments = cad.ConstructorArguments; if (constructorArguments.Count == 1 && !noArgs) { CustomAttributeTypedArgument tca = constructorArguments[0]; attrValue = tca.Value as String; if (attrValue == null && allowTypeAlso && tca.ArgumentType == typeof(Type)) { typeValue = tca.Value as Type; attrValue = typeValue.AssemblyQualifiedName; } if (attrValue == null) { throw new ArgumentException(SR.Get(SRID.ParserAttributeArgsLow, attrType.Name)); } } else if (constructorArguments.Count == 0) { // zeroArgsAllowed = true for CPA for example. // CPA with no args is valid and would mean that this type is overriding a base CPA if (noArgs || zeroArgsAllowed) { attrValue = string.Empty; } else { throw new ArgumentException(SR.Get(SRID.ParserAttributeArgsLow, attrType.Name)); } } else { throw new ArgumentException(SR.Get(SRID.ParserAttributeArgsHigh, attrType.Name)); } } return(attrValue); }
// // Computes the ToString() value for a CustomAttributeTypedArgument struct. // private static String ComputeTypedArgumentString(CustomAttributeTypedArgument cat, bool typed) { Type argumentType = cat.ArgumentType; if (argumentType == null) { return(cat.ToString()); } FoundationTypes foundationTypes = argumentType.AsConfirmedRuntimeType().GetReflectionDomain().FoundationTypes; Object value = cat.Value; TypeInfo argumentTypeInfo = argumentType.GetTypeInfo(); if (argumentTypeInfo.IsEnum) { return(String.Format(typed ? "{0}" : "({1}){0}", value, argumentType.FullName)); } if (value == null) { return(String.Format(typed ? "null" : "({0})null", argumentType.Name)); } if (argumentType.Equals(foundationTypes.SystemString)) { return(String.Format("\"{0}\"", value)); } if (argumentType.Equals(foundationTypes.SystemChar)) { return(String.Format("'{0}'", value)); } if (argumentType.Equals(foundationTypes.SystemType)) { return(String.Format("typeof({0})", ((Type)value).FullName)); } else if (argumentType.IsArray) { String result = null; IList <CustomAttributeTypedArgument> array = value as IList <CustomAttributeTypedArgument>; Type elementType = argumentType.GetElementType(); result = String.Format(@"new {0}[{1}] {{ ", elementType.GetTypeInfo().IsEnum ? elementType.FullName : elementType.Name, array.Count); for (int i = 0; i < array.Count; i++) { result += String.Format(i == 0 ? "{0}" : ", {0}", ComputeTypedArgumentString(array[i], elementType != foundationTypes.SystemObject)); } return(result += " }"); } return(String.Format(typed ? "{0}" : "({1}){0}", value, argumentType.Name)); }
public CustomAttributeNamedArgument(MemberInfo memberInfo, CustomAttributeTypedArgument typedArgument) { if (memberInfo == null) { throw new ArgumentNullException(nameof(memberInfo)); } m_memberInfo = memberInfo; m_value = typedArgument; }
static MetaBuilder() { //get file version Assembly asm = Assembly.Load(new AssemblyName("Parquet")); var fva = asm.CustomAttributes.First(a => a.AttributeType == typeof(AssemblyFileVersionAttribute)); CustomAttributeTypedArgument varg = fva.ConstructorArguments[0]; string fileVersion = varg.Value.ToString(); CreatedBy = $"parquet-dotnet v{fileVersion} (build {fileVersion.GetHash(HashType.Sha1)})"; }
private static object GetCustomAttributeValue(CustomAttributeTypedArgument arg) { Type argumentType = arg.ArgumentType; if (argumentType.IsEnum) { return(Enum.ToObject(Type.GetType(argumentType.FullName), arg.Value)); } return(arg.Value); }
public sealed override IEnumerable <CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, FieldHandle fieldHandle, TypeDefinitionHandle declaringTypeHandle) { TypeAttributes layoutKind = declaringTypeHandle.GetTypeDefinition(reader).Flags & TypeAttributes.LayoutMask; if (layoutKind == TypeAttributes.ExplicitLayout) { int offset = (int)(fieldHandle.GetField(reader).Offset); CustomAttributeTypedArgument offsetArgument = ExtensibleCustomAttributeData.CreateCustomAttributeTypedArgument(typeof(Int32), offset); yield return(ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(FieldOffsetAttribute), new CustomAttributeTypedArgument[] { offsetArgument }, null)); } }
// // Computes the ToString() value for a CustomAttributeTypedArgument struct. // private static String ComputeTypedArgumentString(CustomAttributeTypedArgument cat, bool typed) { Type argumentType = cat.ArgumentType; if (argumentType == null) { return(cat.ToString()); } Object value = cat.Value; if (argumentType.IsEnum) { return(String.Format(typed ? "{0}" : "({1}){0}", value, argumentType.FullName)); } if (value == null) { return(String.Format(typed ? "null" : "({0})null", argumentType.Name)); } if (argumentType.Equals(CommonRuntimeTypes.String)) { return(String.Format("\"{0}\"", value)); } if (argumentType.Equals(CommonRuntimeTypes.Char)) { return(String.Format("'{0}'", value)); } if (argumentType.Equals(CommonRuntimeTypes.Type)) { return(String.Format("typeof({0})", ((Type)value).FullName)); } else if (argumentType.IsArray) { String result = null; IList <CustomAttributeTypedArgument> array = value as IList <CustomAttributeTypedArgument>; Type elementType = argumentType.GetElementType(); result = String.Format(@"new {0}[{1}] {{ ", elementType.IsEnum ? elementType.FullName : elementType.Name, array.Count); for (int i = 0; i < array.Count; i++) { result += String.Format(i == 0 ? "{0}" : ", {0}", ComputeTypedArgumentString(array[i], elementType != CommonRuntimeTypes.Object)); } return(result += " }"); } return(String.Format(typed ? "{0}" : "({1}){0}", value, argumentType.Name)); }
public CustomAttributeNamedArgument(MemberInfo memberInfo, CustomAttributeTypedArgument typedArgument) { if (memberInfo == null) throw new ArgumentNullException(nameof(memberInfo)); _lazyMemberInfo = memberInfo; _attributeType = memberInfo.DeclaringType; TypedValue = typedArgument; IsField = memberInfo is FieldInfo; // For compat with the desktop, there is no validation that a non-field member is a PropertyInfo. MemberName = memberInfo.Name; }
/// <summary> /// Clones a cached CustomAttributeTypedArgument list into a freshly allocated one suitable for direct return through an api. /// </summary> public static ReadOnlyCollection <CustomAttributeTypedArgument> CloneForApiReturn(this IList <CustomAttributeTypedArgument> cats) { int count = cats.Count; CustomAttributeTypedArgument[] clones = new CustomAttributeTypedArgument[count]; for (int i = 0; i < count; i++) { clones[i] = cats[i].CloneForApiReturn(); } return(clones.ToReadOnlyCollection()); }
private static CustomAttributeTypedArgument RewrapArray(Type arrayType, Array array) { Type elementType = arrayType.GetElementType(); CustomAttributeTypedArgument[] newArray = new CustomAttributeTypedArgument[array.Length]; for (int i = 0; i < newArray.Length; i++) { newArray[i] = RewrapValue(elementType, array.GetValue(i)); } return(new CustomAttributeTypedArgument(arrayType, newArray)); }
static Version FileVersion(Type t) { CustomAttributeData fva = t.GetTypeInfo() .Assembly .CustomAttributes .First(a => a.AttributeType == typeof(AssemblyFileVersionAttribute)); CustomAttributeTypedArgument varg = fva.ConstructorArguments[0]; string fileVersion = (string)varg.Value; return(new Version(fileVersion)); }
// These APIs are to detect and support ReflectionOnlyLoadFrom which is used at compile time. // If it isn't the reflection only case, then the normal API to get attributes is used. // // At compile time, the only custom attributes which we extract using GetCustomAttributes are: // Microsoft.JScript.JSFunctionAttribute // Microsoft.JScript.NotRecommended // Microsoft.JScript.ReferenceAttribute // System.AttributeUsageAttribute // System.CLSCompliantAttribute // System.ObsoleteAttribute // System.Runtime.InteropServices.CoClassAttribute // System.Security.AllowPartiallyTrustedCallersAttribute // // The only ones we check for using IsDefined are: // Microsoft.JScript.Expando // Microsoft.JScript.JSFunctionAttribute // System.ParamArrayAttribute // System.Runtime.CompilerServices.RequiredAttributeAttribute // // None of these are Inherited attibutes and so the ReflectionOnly code path can ignore the // inherit flag. The System.* attributes are sealed. The Microsoft.JScript ones are not, // though they should be and the compiler will not respect subtypes of these attributes. // private static Object GetCustomAttributeValue(CustomAttributeTypedArgument arg) { Type reflectionOnlyArgType = arg.ArgumentType; // If it's an enumerated type, the value is the boxed underlying value and must be converted. if (reflectionOnlyArgType.IsEnum) { return(Enum.ToObject(Type.GetType(reflectionOnlyArgType.FullName), arg.Value)); } return(arg.Value); }
private string RouteAttributeValue(IList <CustomAttributeTypedArgument> namedArguments) { string result = string.Empty; if (namedArguments.Count > 0) { CustomAttributeTypedArgument item = namedArguments.First(); result = item.Value.ToString(); } return(result); }
public CustomAttributeTypedArgument CreateTypedArgumentStruct(Type type, object value) { // Because C# doesn't like structs which contain object references to be referenced by pointers // we need to use a special MOSA compiler trick to get its address to create a pointer CustomAttributeTypedArgument typedArgument = new CustomAttributeTypedArgument(); var ptr = (uint **)Intrinsic.GetValueTypeAddress(typedArgument); ptr[0] = (uint *)Intrinsic.GetObjectAddress(type); ptr[1] = (uint *)Intrinsic.GetObjectAddress(value); return(typedArgument); }
private object MapCustomAttributeValue(CustomAttributeTypedArgument argument) { var value = argument.Value; var type = value as Type; if (type != null) { return(CreateReference(type)); } return(value); }
private static object GetValueOrArray(CustomAttributeTypedArgument argument) { if (argument.Value.GetType() == typeof(ReadOnlyCollection <CustomAttributeTypedArgument>)) { return(( from cataElement in (ReadOnlyCollection <CustomAttributeTypedArgument>)argument.Value select cataElement.Value.ToString() ).ToArray()); } return(argument.Value); }
public void Arrays () { IList<CustomAttributeData> cdata = CustomAttributeData.GetCustomAttributes (typeof (CustomAttributeDataTest).GetMethod ("MethodWithAttr")); Assert.AreEqual (1, cdata.Count); CustomAttributeTypedArgument arg = cdata [0].ConstructorArguments [0]; Assert.IsTrue (typeof (IList<CustomAttributeTypedArgument>).IsAssignableFrom (arg.Value.GetType ())); IList<CustomAttributeTypedArgument> arr = (IList<CustomAttributeTypedArgument>)arg.Value; Assert.AreEqual (2, arr.Count); Assert.AreEqual (typeof (byte), arr [0].ArgumentType); Assert.AreEqual (1, arr [0].Value); Assert.AreEqual (typeof (byte), arr [1].ArgumentType); Assert.AreEqual (2, arr [1].Value); }
internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation) { IList <CustomAttributeData> customAttributes = CustomAttributeData.GetCustomAttributes(a); CustomAttributeData data = null; for (int i = 0; i < customAttributes.Count; i++) { if (customAttributes[i].Constructor.DeclaringType == typeof(NeutralResourcesLanguageAttribute)) { data = customAttributes[i]; break; } } if (data == null) { if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNeutralResourceAttributeMissing(a); } fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return(CultureInfo.InvariantCulture); } string name = null; if (data.Constructor.GetParameters().Length == 2) { CustomAttributeTypedArgument argument = data.ConstructorArguments[1]; fallbackLocation = (UltimateResourceFallbackLocation)argument.Value; if ((fallbackLocation < UltimateResourceFallbackLocation.MainAssembly) || (fallbackLocation > UltimateResourceFallbackLocation.Satellite)) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", new object[] { (UltimateResourceFallbackLocation)fallbackLocation })); } } else { fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; } CustomAttributeTypedArgument argument2 = data.ConstructorArguments[0]; name = argument2.Value as string; try { return(CultureInfo.GetCultureInfo(name)); } catch (ArgumentException exception) { if (a != typeof(object).Assembly) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", new object[] { a.ToString(), name }), exception); } return(CultureInfo.InvariantCulture); } }
// // Computes the ToString() value for a CustomAttributeTypedArgument struct. // private static string ComputeTypedArgumentString(CustomAttributeTypedArgument cat, bool typed) { Type argumentType = cat.ArgumentType; if (argumentType == null) { return(cat.ToString()); } object?value = cat.Value; if (argumentType.IsEnum) { return(string.Format(typed ? "{0}" : "({1}){0}", value, argumentType.FullName)); } if (value == null) { return(string.Format(typed ? "null" : "({0})null", argumentType.Name)); } if (argumentType == typeof(string)) { return(string.Format("\"{0}\"", value)); } if (argumentType == typeof(char)) { return(string.Format("'{0}'", value)); } if (argumentType == typeof(Type)) { return(string.Format("typeof({0})", ((Type)value).FullName)); } else if (argumentType.IsArray) { IList <CustomAttributeTypedArgument> array = (IList <CustomAttributeTypedArgument>)value; Type elementType = argumentType.GetElementType() !; string result = string.Format(@"new {0}[{1}] {{ ", elementType.IsEnum ? elementType.FullName : elementType.Name, array.Count); for (int i = 0; i < array.Count; i++) { result += string.Format(i == 0 ? "{0}" : ", {0}", ComputeTypedArgumentString(array[i], elementType != typeof(object))); } return(result += " }"); } return(string.Format(typed ? "{0}" : "({1}){0}", value, argumentType.Name)); }
private static CustomAttributeTypedArgument ExpressionToTypedArgument( [NotNull] Expression expression) { CustomAttributeTypedArgument value; if (expression is ConstantExpression constant) { value = new CustomAttributeTypedArgument(constant.Type, constant.Value); } else if (expression is NewArrayExpression newArray) { int count = newArray.Expressions.Count; var arrayValue = Array.CreateInstance(newArray.Type.GetElementType(), count); for (int i = 0; i < count; ++i) { var element = newArray.Expressions[i]; if (!(element is ConstantExpression constantElement)) { throw new Exception(); } arrayValue.SetValue(constantElement.Value, i); } value = new CustomAttributeTypedArgument(newArray.Type, arrayValue); } else if (expression is DefaultExpression d) { var type = d.Type; object defaultValue = null; if (type.IsValueType) { if (!_valueTypeDefaults.TryGetValue(type, out defaultValue)) { _valueTypeDefaults[type] = defaultValue = Activator.CreateInstance(type); } } value = new CustomAttributeTypedArgument(type, defaultValue); } else { throw new NotSupportedException(); } return(value); }
private Type ExtractType(CustomAttributeTypedArgument arg) { if (arg.ArgumentType == typeof(Type)) { return((Type)arg.Value); } else if (arg.ArgumentType == typeof(string)) { string typeName = (string)arg.Value; return(XamlNamespace.GetTypeFromFullTypeName(typeName)); } return(null); }
/// <summary> /// Ctor /// Attribute使用 /// 根据Attribute TypedArgument 构造方法参数 /// 构造constructorArguments参数ParamModel /// </summary> /// <param name="typedArgument"></param> /// <param name="index">序号</param> private static ParamModel GetParam(CustomAttributeTypedArgument typedArgument, int index = 0) { PTypeModel ptype = GetPType(typedArgument.ArgumentType); ParamModel param = new ParamModel() { Name = $"p{index + 1}", PType = ptype, ParamValue = typedArgument.Value, Position = index }; return(param); }
private static object GetValue(CustomAttributeTypedArgument typedValue) { if (typedValue.Value is IList <CustomAttributeTypedArgument> list) { var array = Array.CreateInstance(typedValue.ArgumentType.GetElementType() !, list.Count); for (var i = 0; i < list.Count; i++) { array.SetValue(list[i].Value, i); } return(array); } return(typedValue.Value); }
private static IEnumerable <XObject> GenerateAttributeArgument(IProcessingContext context, CustomAttributeTypedArgument cata) { // TODO this needs to be cleaned up, and fixed context.AddReference(AssetIdentifier.FromMemberInfo(cata.ArgumentType)); yield return(new XAttribute("type", AssetIdentifier.FromMemberInfo(cata.ArgumentType))); if (cata.ArgumentType.IsEnum) { if ( cata.ArgumentType.GetCustomAttributesData().Any( ca => ca.Constructor.DeclaringType == typeof(FlagsAttribute))) { string flags = Enum.ToObject(cata.ArgumentType, cata.Value).ToString(); string[] parts = flags.Split(','); yield return (new XElement("literal", new XAttribute("value", cata.Value), Array.ConvertAll(parts, s => new XElement("flag", new XAttribute("value", s.Trim()))))); } else { string value = Enum.GetName(cata.ArgumentType, cata.Value); if (value != null) { yield return(new XElement("literal", new XAttribute("value", value))); } yield return(new XElement("literal", new XAttribute("value", cata.Value))); } } else if (cata.ArgumentType == typeof(Type)) { XElement tmp = new XElement("tmp"); DocGenerator.GenerateTypeRef(context.Clone(tmp), (Type)cata.Value, "value"); yield return(tmp.Attribute("value")); foreach (XElement xElement in tmp.Elements()) { yield return(xElement); } } else // TODO fix how this encodes unprintable characters { yield return(new XAttribute("value", cata.Value.ToString().Replace("\0", "\\0"))); } }
protected sealed override Guid?ComputeGuidFromCustomAttributes() { // // Look for a [Guid] attribute. If found, return that. // foreach (CustomAttributeHandle cah in _typeDefinition.GetCustomAttributes()) { // We can't reference the GuidAttribute class directly as we don't have an official dependency on System.Runtime.InteropServices. // Following age-old CLR tradition, we search for the custom attribute using a name-based search. Since this makes it harder // to be sure we won't run into custom attribute constructors that comply with the GuidAttribute(String) signature, // we'll check that it does and silently skip the CA if it doesn't match the expected pattern. CustomAttribute attribute = Reader.GetCustomAttribute(cah); EntityHandle ctorType; EcmaMetadataHelpers.GetAttributeTypeDefRefOrSpecHandle(_reader, attribute.Constructor, out ctorType); StringHandle typeNameHandle; StringHandle typeNamespaceHandle; if (EcmaMetadataHelpers.GetAttributeNamespaceAndName(Reader, ctorType, out typeNamespaceHandle, out typeNameHandle)) { MetadataStringComparer stringComparer = Reader.StringComparer; if (stringComparer.Equals(typeNamespaceHandle, "System.Runtime.InteropServices")) { if (stringComparer.Equals(typeNameHandle, "GuidAttribute")) { ReflectionTypeProvider typeProvider = new ReflectionTypeProvider(throwOnError: false); CustomAttributeValue <RuntimeTypeInfo> customAttributeValue = attribute.DecodeValue(typeProvider); if (customAttributeValue.FixedArguments.Length != 1) { continue; } CustomAttributeTypedArgument <RuntimeTypeInfo> firstArg = customAttributeValue.FixedArguments[0]; if (firstArg.Value == null) { continue; } string guidString = firstArg.Value as string; if (guidString == null) { continue; } return(new Guid(guidString)); } } } } return(null); }
public async Task Scan_Succeeds() { var startingPath = "/home/maarten"; var metadataLoadContext = this.mockRepository.Create <IMetadataLoadContext>(); var assemblyShim = this.mockRepository.Create <IAssemblyShim>(); var directoryTraverser = this.mockRepository.Create <IDirectoryTraverser>(); directoryTraverser.Setup(d => d.TraverseDirectories(startingPath)).Returns(new[] { "pathy/mcpathface" }); directoryTraverser.Setup(d => d.TraverseFiles(It.IsAny <string>(), It.IsAny <IEnumerable <string> >())).Returns(new[] { "filey.mcfile.face" }); var contract = TestableTypeBuilder.New() .WithName("IMyTestType") .WithNamespace("Test.Type") .Build(); var pluginAttributeTypedValue = new CustomAttributeTypedArgument(contract); var pluginAttribute = new TestableAttribute { _AttributeType = typeof(Prise.Plugin.PluginAttribute), _NamedArguments = new[] { new CustomAttributeNamedArgument(new TestableMemberInfo { _Name = "PluginType" }, pluginAttributeTypedValue) } }; var testableType = TestableTypeBuilder.New() .WithCustomAttributes(pluginAttribute) .WithName("MyTestType") .WithNamespace("Test.Type") .Build(); assemblyShim.Setup(a => a.Types).Returns(new[] { testableType }); metadataLoadContext.Setup(c => c.LoadFromAssemblyName(It.IsAny <string>())).Returns(assemblyShim.Object); var scanner = new DefaultAssemblyScanner( (s) => metadataLoadContext.Object, () => directoryTraverser.Object ); var types = await scanner.Scan(new AssemblyScannerOptions { StartingPath = startingPath, PluginType = contract }); var result = types.FirstOrDefault(); Assert.IsNotNull(result); Assert.AreEqual("MyTestType", result.PluginType.Name); Assert.AreEqual("Test.Type", result.PluginType.Namespace); }
private static object ReadAttributeValue(CustomAttributeTypedArgument argument) { var value = argument.Value; if (!argument.ArgumentType.GetTypeInfo().IsArray) { return(value); } var arguments = ((IEnumerable <CustomAttributeTypedArgument>)value) .Select(m => m.Value) .ToArray(); return(arguments); }
private static IEnumerable <TCategory> GetMetricAttributeArgument( CustomAttributeTypedArgument constructorArgument) { var typedArgs = constructorArgument.Value as IEnumerable <CustomAttributeTypedArgument>; var categories = new List <TCategory>(); foreach (var arg in typedArgs) { categories.Add((TCategory)arg.Value); } // Metric attribute doesnt allow multiples so we return first one return(categories); }
/// <summary> /// Получение значения пользовательского атрибута по типу перечисления и строковому имени нужного поля. /// </summary> /// <param name="parEnumType">Тип перечисления.</param> /// <param name="parEnumValue">Имя поля.</param> /// <returns>Значение пользовательского атрибута.</returns> public static object GetValue(Type parEnumType, string parEnumValue) { IEnumerable <CustomAttributeData> attributes = parEnumType.GetField(parEnumValue).CustomAttributes; IEnumerator <CustomAttributeData> attributesEnumerator = attributes.GetEnumerator(); attributesEnumerator.MoveNext(); IList <CustomAttributeTypedArgument> arguments = attributesEnumerator.Current.ConstructorArguments; IEnumerator <CustomAttributeTypedArgument> argumentsEnumerator = arguments.GetEnumerator(); argumentsEnumerator.MoveNext(); CustomAttributeTypedArgument argument = argumentsEnumerator.Current; return(argument.Value); }
protected static Version GetSatelliteContractVersion(Assembly a) { Version version; if (a == null) { throw new ArgumentNullException("a", Environment.GetResourceString("ArgumentNull_Assembly")); } string str = null; if (!a.ReflectionOnly) { object[] customAttributes = a.GetCustomAttributes(typeof(SatelliteContractVersionAttribute), false); if (customAttributes.Length == 0) { return(null); } str = ((SatelliteContractVersionAttribute)customAttributes[0]).Version; } else { foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(a)) { if (data.Constructor.DeclaringType == typeof(SatelliteContractVersionAttribute)) { CustomAttributeTypedArgument argument = data.ConstructorArguments[0]; str = (string)argument.Value; break; } } if (str == null) { return(null); } } try { version = new Version(str); } catch (ArgumentOutOfRangeException exception) { if (a != typeof(object).Assembly) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidSatelliteContract_Asm_Ver", new object[] { a.ToString(), str }), exception); } return(null); } return(version); }
/// <summary> /// /// </summary> /// <param name="argument"></param> /// <returns></returns> public IMetadataExpression GetExpression(CustomAttributeTypedArgument argument) { var type = this.GetType(argument.ArgumentType); var arrayType = type as IArrayTypeReference; if (arrayType != null) { return(new MetadataCreateArrayWrapper(this, arrayType, (ICollection <CustomAttributeTypedArgument>)argument.Value)); } if (argument.Value is Type) { return(new MetadataTypeOfWrapper(this, type, (Type)argument.Value)); } return(new MetadataConstantWrapper(type, argument.Value)); }
public CustomAttributeNamedArgument(MemberInfo memberInfo, object value) { if (memberInfo == null) throw new ArgumentNullException(nameof(memberInfo)); Type type = null; FieldInfo field = memberInfo as FieldInfo; PropertyInfo property = memberInfo as PropertyInfo; if (field != null) type = field.FieldType; else if (property != null) type = property.PropertyType; else throw new ArgumentException(SR.Argument_InvalidMemberForNamedArgument); _lazyMemberInfo = memberInfo; _attributeType = memberInfo.DeclaringType; TypedValue = new CustomAttributeTypedArgument(type, value); IsField = field != null; MemberName = memberInfo.Name; }
internal CustomAttributeNamedArgument(Type attributeType, string memberName, bool isField, CustomAttributeTypedArgument typedValue) { }
public static bool op_Inequality(CustomAttributeTypedArgument left, CustomAttributeTypedArgument right) {}
private static object EncodeAnnotationValue(CustomAttributeTypedArgument arg) { if (arg.ArgumentType.IsEnum) { // if GetWrapperFromType returns null, we've got an ikvmc synthesized .NET enum nested inside a Java enum TypeWrapper tw = ClassLoaderWrapper.GetWrapperFromType(arg.ArgumentType) ?? ClassLoaderWrapper.GetWrapperFromType(arg.ArgumentType.DeclaringType); return new object[] { AnnotationDefaultAttribute.TAG_ENUM, EncodeTypeName(tw), Enum.GetName(arg.ArgumentType, arg.Value) }; } else if (arg.Value is Type) { return new object[] { AnnotationDefaultAttribute.TAG_CLASS, EncodeTypeName(ClassLoaderWrapper.GetWrapperFromType((Type)arg.Value)) }; } else if (arg.ArgumentType.IsArray) { IList<CustomAttributeTypedArgument> array = (IList<CustomAttributeTypedArgument>)arg.Value; object[] arr = new object[array.Count + 1]; arr[0] = AnnotationDefaultAttribute.TAG_ARRAY; for (int i = 0; i < array.Count; i++) { arr[i + 1] = EncodeAnnotationValue(array[i]); } return arr; } else { return arg.Value; } }
private static void WriteAnnotationElementValue(ClassFileWriter classFile, BigEndianStream bes, CustomAttributeTypedArgument value) { if (value.ArgumentType == Types.Boolean) { bes.WriteByte((byte)'Z'); bes.WriteUInt16(classFile.AddInt((bool)value.Value ? 1 : 0)); } else if (value.ArgumentType == Types.Byte) { bes.WriteByte((byte)'B'); bes.WriteUInt16(classFile.AddInt((byte)value.Value)); } else if (value.ArgumentType == Types.Char) { bes.WriteByte((byte)'C'); bes.WriteUInt16(classFile.AddInt((char)value.Value)); } else if (value.ArgumentType == Types.Int16) { bes.WriteByte((byte)'S'); bes.WriteUInt16(classFile.AddInt((short)value.Value)); } else if (value.ArgumentType == Types.Int32) { bes.WriteByte((byte)'I'); bes.WriteUInt16(classFile.AddInt((int)value.Value)); } else if (value.ArgumentType == Types.Single) { bes.WriteByte((byte)'F'); bes.WriteUInt16(classFile.AddFloat((float)value.Value)); } else if (value.ArgumentType == Types.Int64) { bes.WriteByte((byte)'J'); bes.WriteUInt16(classFile.AddLong((long)value.Value)); } else if (value.ArgumentType == Types.Double) { bes.WriteByte((byte)'D'); bes.WriteUInt16(classFile.AddDouble((double)value.Value)); } else if (value.ArgumentType == Types.String) { bes.WriteByte((byte)'s'); bes.WriteUInt16(classFile.AddUtf8((string)value.Value)); } else if (value.ArgumentType == Types.Object.MakeArrayType()) { CustomAttributeTypedArgument[] array = (CustomAttributeTypedArgument[])value.Value; byte type = (byte)array[0].Value; if (type == AnnotationDefaultAttribute.TAG_ARRAY) { bes.WriteByte((byte)'['); bes.WriteUInt16((ushort)(array.Length - 1)); for (int i = 1; i < array.Length; i++) { WriteAnnotationElementValue(classFile, bes, array[i]); } } else if (type == AnnotationDefaultAttribute.TAG_CLASS) { bes.WriteByte((byte)'c'); bes.WriteUInt16(classFile.AddUtf8((string)array[1].Value)); } else if (type == AnnotationDefaultAttribute.TAG_ENUM) { bes.WriteByte((byte)'e'); bes.WriteUInt16(classFile.AddUtf8((string)array[1].Value)); bes.WriteUInt16(classFile.AddUtf8((string)array[2].Value)); } else if (type == AnnotationDefaultAttribute.TAG_ANNOTATION) { bes.WriteByte((byte)'@'); bes.WriteUInt16(classFile.AddUtf8((string)array[1].Value)); bes.WriteUInt16((ushort)((array.Length - 2) / 2)); for (int i = 2; i < array.Length; i += 2) { bes.WriteUInt16(classFile.AddUtf8((string)array[i].Value)); WriteAnnotationElementValue(classFile, bes, array[i + 1]); } } else { Warning("Warning: incorrect annotation default element tag: " + type); } } else { Warning("Warning: incorrect annotation default element type: " + value.ArgumentType); } }
public sealed override IEnumerable<CustomAttributeData> GetPseudoCustomAttributes(MetadataReader reader, FieldHandle fieldHandle, TypeDefinitionHandle declaringTypeHandle) { TypeAttributes layoutKind = declaringTypeHandle.GetTypeDefinition(reader).Flags & TypeAttributes.LayoutMask; if (layoutKind == TypeAttributes.ExplicitLayout) { int offset = (int)(fieldHandle.GetField(reader).Offset); CustomAttributeTypedArgument offsetArgument = new CustomAttributeTypedArgument(typeof(Int32), offset); yield return ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(FieldOffsetAttribute), new CustomAttributeTypedArgument[] { offsetArgument }, null); } }
// // Computes the ToString() value for a CustomAttributeTypedArgument struct. // private static String ComputeTypedArgumentString(CustomAttributeTypedArgument cat, bool typed) { Type argumentType = cat.ArgumentType; if (argumentType == null) return cat.ToString(); FoundationTypes foundationTypes = argumentType.AsConfirmedRuntimeType().GetReflectionDomain().FoundationTypes; Object value = cat.Value; TypeInfo argumentTypeInfo = argumentType.GetTypeInfo(); if (argumentTypeInfo.IsEnum) return String.Format(typed ? "{0}" : "({1}){0}", value, argumentType.FullName); if (value == null) return String.Format(typed ? "null" : "({0})null", argumentType.Name); if (argumentType.Equals(foundationTypes.SystemString)) return String.Format("\"{0}\"", value); if (argumentType.Equals(foundationTypes.SystemChar)) return String.Format("'{0}'", value); if (argumentType.Equals(foundationTypes.SystemType)) return String.Format("typeof({0})", ((Type)value).FullName); else if (argumentType.IsArray) { String result = null; IList<CustomAttributeTypedArgument> array = value as IList<CustomAttributeTypedArgument>; Type elementType = argumentType.GetElementType(); result = String.Format(@"new {0}[{1}] {{ ", elementType.GetTypeInfo().IsEnum ? elementType.FullName : elementType.Name, array.Count); for (int i = 0; i < array.Count; i++) result += String.Format(i == 0 ? "{0}" : ", {0}", ComputeTypedArgumentString(array[i], elementType != foundationTypes.SystemObject)); return result += " }"; } return String.Format(typed ? "{0}" : "({1}){0}", value, argumentType.Name); }
private static byte[] GetAnnotationDefault(ClassFileWriter classFile, CustomAttributeTypedArgument value) { MemoryStream mem = new MemoryStream(); BigEndianStream bes = new BigEndianStream(mem); try { WriteAnnotationElementValue(classFile, bes, value); } catch (InvalidCastException) { Warning("Warning: incorrect annotation default value"); } catch (IndexOutOfRangeException) { Warning("Warning: incorrect annotation default value"); } return mem.ToArray(); }
private static ReadOnlyCollection<CustomAttributeTypedArgument> GetAttributeArrayArgumentValue(CustomAttributeTypedArgument argument) { // Per https://msdn.microsoft.com/en-us/library/system.reflection.customattributetypedargument.argumenttype(v=vs.110).aspx, // if ArgumentType indicates an array, then Value will actually be a ReadOnlyCollection. return (ReadOnlyCollection<CustomAttributeTypedArgument>)argument.Value; }