Esempio n. 1
0
 private static ReadOnlyCollection<byte> GetDynamicFlags(CustomAttributeData attribute)
 {
     var arguments = attribute.ConstructorArguments;
     if (arguments.Count == 0)
     {
         return DynamicFlagsTrue;
     }
     else if (arguments.Count == 1)
     {
         var argument = arguments[0];
         var argumentType = argument.ArgumentType;
         if (argumentType.IsArray && argumentType.GetElementType().IsBoolean())
         {
             var collection = GetAttributeArrayArgumentValue(argument);
             var numFlags = collection.Count;
             var builder = ArrayBuilder<bool>.GetInstance(numFlags);
             foreach (var typedArg in collection)
             {
                 builder.Add((bool)typedArg.Value);
             }
             var result = DynamicFlagsCustomTypeInfo.ToBytes(builder);
             builder.Free();
             return result;
         }
     }
     return null;
 }
Esempio n. 2
0
 private static ReadOnlyCollection<string> GetTupleElementNames(CustomAttributeData attribute)
 {
     var arguments = attribute.ConstructorArguments;
     if (arguments.Count == 1)
     {
         var argument = arguments[0];
         var argumentType = argument.ArgumentType;
         if (argumentType.IsArray && argumentType.GetElementType().IsString())
         {
             var collection = GetAttributeArrayArgumentValue(argument);
             var numFlags = collection.Count;
             var builder = ArrayBuilder<string>.GetInstance(numFlags);
             foreach (var typedArg in collection)
             {
                 builder.Add((string)typedArg.Value);
             }
             return builder.ToImmutableAndFree();
         }
     }
     return null;
 }
Esempio n. 3
0
 protected void ThrowInvalidMetadata(CustomAttributeData cad, int expectedCount, Type expectedType)
 {
     throw new XamlSchemaException(SR.Get(SRID.UnexpectedConstructorArg,
         cad.Constructor.DeclaringType, Member, expectedCount, expectedType));
 }
Esempio n. 4
0
 public override IList <CustomAttributeData> GetCustomAttributesData()
 {
     return(CustomAttributeData.GetCustomAttributesInternal(this));
 }
Esempio n. 5
0
 public void Read(ClrModuleReader reader)
 {
     this.Parent = reader.ReadCodedIndex<HasCustomAttribute>();
     this.Type = reader.ReadCodedIndex<CustomAttributeType>();
     this.Value = new CustomAttributeData(reader.ReadBlob());
 }
Esempio n. 6
0
 public static Type GetAttributeType(this CustomAttributeData source)
 {
     return(source.AttributeType);
 }
Esempio n. 7
0
 public static IEnumerable <CustomAttributeData> GetCustomAttributesData(this MemberInfo source)
 {
     return(CustomAttributeData.GetCustomAttributes(source));
 }
        private void GetPropertyDrawerType(SerializedProperty property)
        {
            if (_genericAttributeDrawerInstance != null)
            {
                return;
            }

            //Get the second attribute flag
            try {
                _genericAttribute = (PropertyAttribute)fieldInfo.GetCustomAttributes(typeof(PropertyAttribute), false)
                                    .FirstOrDefault(a => !(a is ConditionalFieldAttribute));

                if (_genericAttribute is ContextMenuItemAttribute ||
                    _genericAttribute is SeparatorAttribute | _genericAttribute is AutoPropertyAttribute)
                {
                    LogWarning("[ConditionalField] does not work with " + _genericAttribute.GetType(), property);
                    return;
                }

                if (_genericAttribute is TooltipAttribute)
                {
                    return;
                }
            } catch (Exception e) {
                LogWarning("Can't find stacked propertyAttribute after ConditionalProperty: " + e, property);
                return;
            }

            //Get the associated attribute drawer
            try {
                _genericAttributeDrawerType = _allPropertyDrawerAttributeTypes.First(x =>
                                                                                     (Type)CustomAttributeData.GetCustomAttributes(x).First().ConstructorArguments.First().Value == _genericAttribute.GetType());
            } catch (Exception e) {
                LogWarning("Can't find property drawer from CustomPropertyAttribute of " + _genericAttribute.GetType() + " : " + e, property);
                return;
            }

            //Create instances of each (including the arguments)
            try {
                _genericAttributeDrawerInstance = (PropertyDrawer)Activator.CreateInstance(_genericAttributeDrawerType);
                //Get arguments
                IList <CustomAttributeTypedArgument> attributeParams = fieldInfo.GetCustomAttributesData()
                                                                       .First(a => a.AttributeType == _genericAttribute.GetType()).ConstructorArguments;
                IList <CustomAttributeTypedArgument> unpackedParams = new List <CustomAttributeTypedArgument>();
                //Unpack any params object[] args
                foreach (CustomAttributeTypedArgument singleParam in attributeParams)
                {
                    if (singleParam.Value.GetType() == typeof(ReadOnlyCollection <CustomAttributeTypedArgument>))
                    {
                        foreach (CustomAttributeTypedArgument unpackedSingleParam in (ReadOnlyCollection <CustomAttributeTypedArgument>)singleParam
                                 .Value)
                        {
                            unpackedParams.Add(unpackedSingleParam);
                        }
                    }
                    else
                    {
                        unpackedParams.Add(singleParam);
                    }
                }

                object[] attributeParamsObj = unpackedParams.Select(x => x.Value).ToArray();

                if (attributeParamsObj.Any())
                {
                    _genericAttribute = (PropertyAttribute)Activator.CreateInstance(_genericAttribute.GetType(), attributeParamsObj);
                }
                else
                {
                    _genericAttribute = (PropertyAttribute)Activator.CreateInstance(_genericAttribute.GetType());
                }
            } catch (Exception e) {
                LogWarning("No constructor available in " + _genericAttribute.GetType() + " : " + e, property);
                return;
            }

            //Reassign the attribute field in the drawer so it can access the argument values
            try {
                var genericDrawerAttributeField = _genericAttributeDrawerType.GetField("m_Attribute", BindingFlags.Instance | BindingFlags.NonPublic);
                genericDrawerAttributeField.SetValue(_genericAttributeDrawerInstance, _genericAttribute);
            } catch (Exception e) {
                LogWarning("Unable to assign attribute to " + _genericAttributeDrawerInstance.GetType() + " : " + e, property);
            }
        }
Esempio n. 9
0
        public static bool IsComVisible(Type t)
        {
            var attrs = CustomAttributeData.GetCustomAttributes(t);

            return(IsComVisible(attrs));
        }
Esempio n. 10
0
		public abstract void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName);
 public static void CustomAttributeData_NamedArguments(CustomAttributeData customAttributeData)
 {
     String attributeTypeName = customAttributeData.AttributeTypeNameString();
     if (attributeTypeName == null)
         return;
     ReflectionEventSource.Log.CustomAttributeData_NamedArguments(attributeTypeName);
 }
Esempio n. 12
0
    static int Main(string[] args)
    {
        Assembly assembly = typeof(Class).GetTypeInfo().Assembly;

        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <int> >(assembly) != null);
        Assert(((ICustomAttributeProvider)assembly).GetCustomAttributes(typeof(SingleAttribute <int>), true) != null);
        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <bool> >(assembly) != null);
        Assert(((ICustomAttributeProvider)assembly).GetCustomAttributes(typeof(SingleAttribute <bool>), true) != null);
        Assert(CustomAttributeExtensions.IsDefined(assembly, typeof(SingleAttribute <int>)));
        Assert(((ICustomAttributeProvider)assembly).IsDefined(typeof(SingleAttribute <int>), true));
        Assert(CustomAttributeExtensions.IsDefined(assembly, typeof(SingleAttribute <bool>)));
        Assert(((ICustomAttributeProvider)assembly).IsDefined(typeof(SingleAttribute <bool>), true));
        Assert(CustomAttributeExtensions.GetCustomAttributes(assembly, typeof(SingleAttribute <>)).GetEnumerator().MoveNext());
        Assert(CustomAttributeExtensions.GetCustomAttributes(assembly, typeof(SingleAttribute <>)).GetEnumerator().MoveNext());

        // Uncomment when https://github.com/dotnet/runtime/issues/66168 is resolved
        // Module module = programTypeInfo.Module;
        // AssertAny(CustomAttributeExtensions.GetCustomAttributes(module), a => a is SingleAttribute<long>);
        // Assert(CustomAttributeExtensions.GetCustomAttributes(module, typeof(SingleAttribute<long>)).GetEnumerator().MoveNext());
        // Assert(CustomAttributeExtensions.GetCustomAttributes(module, typeof(SingleAttribute<long>)).GetEnumerator().MoveNext());
        // Assert(CustomAttributeExtensions.GetCustomAttributes(module, typeof(SingleAttribute<>)).GetEnumerator().MoveNext());
        // Assert(CustomAttributeExtensions.GetCustomAttributes(module, typeof(SingleAttribute<>)).GetEnumerator().MoveNext());

        TypeInfo programTypeInfo = typeof(Class).GetTypeInfo();

        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <int> >(programTypeInfo) != null);
        Assert(((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(SingleAttribute <int>), true) != null);
        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <bool> >(programTypeInfo) != null);
        Assert(((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(SingleAttribute <bool>), true) != null);
        Assert(CustomAttributeExtensions.IsDefined(programTypeInfo, typeof(SingleAttribute <int>)));
        Assert(((ICustomAttributeProvider)programTypeInfo).IsDefined(typeof(SingleAttribute <int>), true));
        Assert(CustomAttributeExtensions.IsDefined(programTypeInfo, typeof(SingleAttribute <bool>)));
        Assert(((ICustomAttributeProvider)programTypeInfo).IsDefined(typeof(SingleAttribute <bool>), true));

        var propertyPropertyInfo = typeof(Class).GetTypeInfo().GetProperty(nameof(Class.Property));

        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <int> >(propertyPropertyInfo) != null);
        Assert(((ICustomAttributeProvider)propertyPropertyInfo).GetCustomAttributes(typeof(SingleAttribute <int>), true) != null);
        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <bool> >(propertyPropertyInfo) != null);
        Assert(((ICustomAttributeProvider)propertyPropertyInfo).GetCustomAttributes(typeof(SingleAttribute <bool>), true) != null);
        Assert(CustomAttributeExtensions.IsDefined(propertyPropertyInfo, typeof(SingleAttribute <int>)));
        Assert(((ICustomAttributeProvider)propertyPropertyInfo).IsDefined(typeof(SingleAttribute <int>), true));
        Assert(CustomAttributeExtensions.IsDefined(propertyPropertyInfo, typeof(SingleAttribute <bool>)));
        Assert(((ICustomAttributeProvider)propertyPropertyInfo).IsDefined(typeof(SingleAttribute <bool>), true));

        var deriveTypeInfo = typeof(Class.Derive).GetTypeInfo();

        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <int> >(deriveTypeInfo, false) == null);
        Assert(((ICustomAttributeProvider)deriveTypeInfo).GetCustomAttributes(typeof(SingleAttribute <int>), true) != null);
        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <bool> >(deriveTypeInfo, false) == null);
        Assert(((ICustomAttributeProvider)deriveTypeInfo).GetCustomAttributes(typeof(SingleAttribute <bool>), true) != null);
        Assert(!CustomAttributeExtensions.IsDefined(deriveTypeInfo, typeof(SingleAttribute <int>), false));
        Assert(!CustomAttributeExtensions.IsDefined(deriveTypeInfo, typeof(SingleAttribute <bool>), false));

        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <int> >(deriveTypeInfo, true) != null);
        Assert(CustomAttributeExtensions.GetCustomAttribute <SingleAttribute <bool> >(deriveTypeInfo, true) != null);
        Assert(CustomAttributeExtensions.IsDefined(deriveTypeInfo, typeof(SingleAttribute <int>), true));
        Assert(((ICustomAttributeProvider)deriveTypeInfo).IsDefined(typeof(SingleAttribute <int>), true));
        Assert(CustomAttributeExtensions.IsDefined(deriveTypeInfo, typeof(SingleAttribute <bool>), true));
        Assert(((ICustomAttributeProvider)deriveTypeInfo).IsDefined(typeof(SingleAttribute <bool>), true));

        var a1 = CustomAttributeExtensions.GetCustomAttributes(programTypeInfo, true);

        AssertAny(a1, a => a is SingleAttribute <int>);
        AssertAny(a1, a => a is SingleAttribute <bool>);
        AssertAny(a1, a => (a as MultiAttribute <int>)?.Value == 0);
        AssertAny(a1, a => (a as MultiAttribute <int>)?.Value == 1);
        AssertAny(a1, a => (a as MultiAttribute <int>)?.Value == 2);
        AssertAny(a1, a => (a as MultiAttribute <bool>)?.Value == false);
        AssertAny(a1, a => (a as MultiAttribute <bool>)?.Value == true, 2);
        AssertAny(a1, a => (a as MultiAttribute <bool?>)?.Value == null);

        var b1 = ((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(true);

        AssertAny(b1, a => a is SingleAttribute <int>);
        AssertAny(b1, a => a is SingleAttribute <bool>);
        AssertAny(b1, a => (a as MultiAttribute <int>)?.Value == 0);
        AssertAny(b1, a => (a as MultiAttribute <int>)?.Value == 1);
        AssertAny(b1, a => (a as MultiAttribute <int>)?.Value == 2);
        AssertAny(b1, a => (a as MultiAttribute <bool>)?.Value == false);
        AssertAny(b1, a => (a as MultiAttribute <bool>)?.Value == true, 2);
        AssertAny(b1, a => (a as MultiAttribute <bool?>)?.Value == null);

        var a2 = CustomAttributeExtensions.GetCustomAttributes(deriveTypeInfo, false);

        Assert(!a2.GetEnumerator().MoveNext());

        var b2 = ((ICustomAttributeProvider)deriveTypeInfo).GetCustomAttributes(false);

        Assert(!b2.GetEnumerator().MoveNext());

        var a3 = CustomAttributeExtensions.GetCustomAttributes(deriveTypeInfo, true);

        AssertAny(a3, a => a is SingleAttribute <int>);
        AssertAny(a3, a => a is SingleAttribute <bool>);
        AssertAny(a3, a => (a as MultiAttribute <int>)?.Value == 0);
        AssertAny(a3, a => (a as MultiAttribute <int>)?.Value == 1);
        AssertAny(a3, a => (a as MultiAttribute <int>)?.Value == 2);
        AssertAny(a3, a => (a as MultiAttribute <bool>)?.Value == false);
        AssertAny(a3, a => (a as MultiAttribute <bool>)?.Value == true);

        var b3 = ((ICustomAttributeProvider)deriveTypeInfo).GetCustomAttributes(true);

        AssertAny(b3, a => a is SingleAttribute <int>);
        AssertAny(b3, a => a is SingleAttribute <bool>);
        AssertAny(b3, a => (a as MultiAttribute <int>)?.Value == 0);
        AssertAny(b3, a => (a as MultiAttribute <int>)?.Value == 1);
        AssertAny(b3, a => (a as MultiAttribute <int>)?.Value == 2);
        AssertAny(b3, a => (a as MultiAttribute <bool>)?.Value == false);
        AssertAny(b3, a => (a as MultiAttribute <bool>)?.Value == true);

        var a4 = CustomAttributeExtensions.GetCustomAttributes <SingleAttribute <int> >(programTypeInfo, true);

        AssertAny(a4, a => a is SingleAttribute <int>);

        var b4 = ((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(SingleAttribute <int>), true);

        AssertAny(b4, a => a is SingleAttribute <int>);

        var a5 = CustomAttributeExtensions.GetCustomAttributes <SingleAttribute <bool> >(programTypeInfo);

        AssertAny(a5, a => a is SingleAttribute <bool>);

        var b5 = ((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(SingleAttribute <bool>), true);

        AssertAny(b5, a => a is SingleAttribute <bool>);

        var a6 = CustomAttributeExtensions.GetCustomAttributes <MultiAttribute <int> >(programTypeInfo, true);

        AssertAny(a6, a => (a as MultiAttribute <int>)?.Value == 0);
        AssertAny(a6, a => (a as MultiAttribute <int>)?.Value == 1);
        AssertAny(a6, a => (a as MultiAttribute <int>)?.Value == 2);

        var b6 = ((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(MultiAttribute <int>), true);

        AssertAny(b6, a => (a as MultiAttribute <int>)?.Value == 0);
        AssertAny(b6, a => (a as MultiAttribute <int>)?.Value == 1);
        AssertAny(b6, a => (a as MultiAttribute <int>)?.Value == 2);

        var a7 = CustomAttributeExtensions.GetCustomAttributes <MultiAttribute <bool> >(programTypeInfo, true);

        AssertAny(a7, a => (a as MultiAttribute <bool>)?.Value == false);
        AssertAny(a7, a => (a as MultiAttribute <bool>)?.Value == true);

        var b7 = ((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(MultiAttribute <bool>), true);

        AssertAny(b7, a => (a as MultiAttribute <bool>)?.Value == false);
        AssertAny(b7, a => (a as MultiAttribute <bool>)?.Value == true);

        var a8 = CustomAttributeExtensions.GetCustomAttributes <MultiAttribute <bool?> >(programTypeInfo, true);

        AssertAny(a8, a => (a as MultiAttribute <bool?>)?.Value == null);

        var b8 = ((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(MultiAttribute <bool?>), true);

        AssertAny(b8, a => (a as MultiAttribute <bool?>)?.Value == null);

        var a9 = CustomAttributeExtensions.GetCustomAttributes <MultiAttribute <string> >(programTypeInfo, true);

        AssertAny(a9, a => (a as MultiAttribute <string>)?.Value == "Ctor");
        AssertAny(a9, a => (a as MultiAttribute <string>)?.Value == "Property");

        var b9 = ((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(MultiAttribute <string>), true);

        AssertAny(b9, a => (a as MultiAttribute <string>)?.Value == "Ctor");
        AssertAny(b9, a => (a as MultiAttribute <string>)?.Value == "Property");

        var a10 = CustomAttributeExtensions.GetCustomAttributes <MultiAttribute <Type> >(programTypeInfo, true);

        AssertAny(a10, a => (a as MultiAttribute <Type>)?.Value == typeof(Class));
        AssertAny(a10, a => (a as MultiAttribute <Type>)?.Value == typeof(Class.Derive));

        var b10 = ((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(MultiAttribute <Type>), true);

        AssertAny(b10, a => (a as MultiAttribute <Type>)?.Value == typeof(Class));
        AssertAny(b10, a => (a as MultiAttribute <Type>)?.Value == typeof(Class.Derive));

        Assert(CustomAttributeExtensions.GetCustomAttributes(programTypeInfo, typeof(MultiAttribute <>), false).GetEnumerator().MoveNext());
        Assert(CustomAttributeExtensions.GetCustomAttributes(programTypeInfo, typeof(MultiAttribute <>), true).GetEnumerator().MoveNext());
        Assert(((ICustomAttributeProvider)programTypeInfo).GetCustomAttributes(typeof(MultiAttribute <>), true).GetEnumerator().MoveNext());

        // Test coverage for CustomAttributeData api surface
        var a1_data = CustomAttributeData.GetCustomAttributes(programTypeInfo);

        AssertAny(a1_data, a => a.AttributeType == typeof(SingleAttribute <int>));
        AssertAny(a1_data, a => a.AttributeType == typeof(SingleAttribute <bool>));

        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <int>) && a.ConstructorArguments.Count == 0 && a.NamedArguments.Count == 0);
        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <int>) && a.ConstructorArguments.Count == 1 && a.NamedArguments.Count == 0 && a.ConstructorArguments[0].ArgumentType == typeof(int) && ((int)a.ConstructorArguments[0].Value) == 1);
        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <int>) && a.ConstructorArguments.Count == 0 && a.NamedArguments.Count == 1 && a.NamedArguments[0].TypedValue.ArgumentType == typeof(int) && ((int)a.NamedArguments[0].TypedValue.Value) == 2);

        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <bool>) && a.ConstructorArguments.Count == 0 && a.NamedArguments.Count == 0);
        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <bool>) && a.ConstructorArguments.Count == 1 && a.NamedArguments.Count == 0 && a.ConstructorArguments[0].ArgumentType == typeof(bool) && ((bool)a.ConstructorArguments[0].Value) == true);
        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <bool>) && a.ConstructorArguments.Count == 0 && a.NamedArguments.Count == 1 && a.NamedArguments[0].TypedValue.ArgumentType == typeof(bool) && ((bool)a.NamedArguments[0].TypedValue.Value) == true);

        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <bool?>) && a.ConstructorArguments.Count == 0 && a.NamedArguments.Count == 0);

        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <Type>) && a.ConstructorArguments.Count == 1 && a.NamedArguments.Count == 0 && a.ConstructorArguments[0].ArgumentType == typeof(Type) && ((Type)a.ConstructorArguments[0].Value) == typeof(Class));
        AssertAny(a1_data, a => a.AttributeType == typeof(MultiAttribute <Type>) && a.ConstructorArguments.Count == 0 && a.NamedArguments.Count == 1 && a.NamedArguments[0].TypedValue.ArgumentType == typeof(Type) && ((Type)a.NamedArguments[0].TypedValue.Value) == typeof(Class.Derive));

        return(100);
    }
        /// <summary>
        /// Parses an object by name and sets the oObject
        /// member with the result.
        /// </summary>
        /// <param name="className">Class name to search</param>
        /// <returns></returns>
        public bool GetObject(string className)
        {
            lError = false;

            bool   GenericType = (className.IndexOf("<") > -1);
            string BaseType    = className;

            if (GenericType)
            {
                BaseType = className.Substring(0, className.IndexOf("<"));
            }

            if (aObjects == null)
            {
                if (GetAllObjects(true) == 0 && lError)
                {
                    return(false);
                }
            }

            for (int x = 0; x < aXObjects.Length; x++)
            {
                Type loType = aXObjects[x];

                // Check for Obsolete members
                IList <CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes(loType);
                bool isObsolete = false;
                foreach (CustomAttributeData attr in attrs)
                {
                    string name = attr.ToString();
                    if (name.Contains("ObsoleteAttribute("))
                    {
                        isObsolete = true;
                        break;
                    }
                }

                // skip over this type
                if (isObsolete)
                {
                    continue;
                }

                // *** Check for matching type or generic type
                if (!(loType.Name.ToLower() == className.ToLower() ||
                      (GenericType && loType.Name.ToLower().StartsWith(BaseType.ToLower() + "`")))
                    )
                {
                    continue;
                }

                oObject             = new DotnetObject();
                oObject.Name        = loType.Name;
                oObject.RawTypeName = loType.Name;

                oObject.Syntax = cSyntax;
                oObject.RetrieveDeclaredMembersOnly = RetrieveDeclaredMembersOnly;

                ParseObject(oObject, loType, false);
            }

            if (cXmlFilename.Length > 0)
            {
                ParseXmlProperties(oObject);
            }

            return(true);
        }
Esempio n. 14
0
 /// <summary>
 /// Adds assembly attributes from the specified assembly.
 ///
 /// The constructor already does this, this method is meant for unit tests only!
 /// </summary>
 public void AddAssemblyAttributes(Assembly assembly)
 {
     ReflectionClass.AddAttributes(this, assemblyCompilationUnit.Attributes, CustomAttributeData.GetCustomAttributes(assembly));
 }
Esempio n. 15
0
 public AttributeDataMap(CustomAttributeData attribute)
 {
     this.attribute = attribute;
 }
Esempio n. 16
0
 public ContentInstallStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
 {
     //[assembly: InstallContent(RepositoryContainerPath = "/Root/Test", ResourcePath = "/res.asdf.css.Content", Attachments = "Binary:/res.asdf.css")]
     ContainerPath  = GetParameterValue <string>("RepositoryContainerPath");
     RawAttachments = GetParameterValue <string>("Attachments");
 }
Esempio n. 17
0
        public List <Model.Employee> GetExcelDate_Read1(string fileName)
        {
            ExcelHelper excelHelper = null;

            Model.Employee        entity = new Model.Employee();
            List <Model.Employee> list   = new List <Model.Employee>();

            try
            {
                excelHelper = new ExcelHelper(fileName);

                object[,] data = (object[, ])excelHelper.GetData(Common.SheetName_Read1, Common.EndColumn_Read1);
                List <Header> headerList = new List <Header>();

                PropertyInfo[] properties = entity.GetType().GetProperties();

                //填充Header
                for (int i = 0; i < properties.Length; i++)
                {
                    PropertyInfo item = properties[i];
                    if (properties[i].CustomAttributes != null && properties[i].CustomAttributes.Count <CustomAttributeData>() != 0)
                    {
                        CustomAttributeData ca = item.CustomAttributes.First <CustomAttributeData>();
                        Header header          = new Header();
                        //header.PropertyInfo = item;
                        foreach (CustomAttributeNamedArgument na in ca.NamedArguments)
                        {
                            if (na.MemberName == "ColumnIndex")
                            {
                                header.ColumnIndex = int.Parse(na.TypedValue.Value.ToString());
                            }
                            if (na.MemberName == "RowName")
                            {
                                header.RowName = na.TypedValue.Value.ToString();
                            }
                        }
                        if (!headerList.Any(h => h.ColumnIndex == header.ColumnIndex && h.RowName == header.RowName))
                        {
                            headerList.Add(header);
                        }
                    }
                }
                bool needAddHeader = true;
                for (int i = int.Parse(Common.StartRow_Read1.ToString()); i <= data.GetLength(0); i++)
                {
                    for (int j = 1; j <= data.GetLength(1); j++)
                    {
                        if (data[i, j] != null)
                        {
                            //var header = headerList.Where(h => data[i, j].ToString().Contains(h.ColumnName)).ToList();
                            //if (header != null && header.Count > 0)
                            //{
                            //    header.ForEach(h => h.ColumnIndex = j);
                            //}
                            if (data[i, j].ToString() == "员 工")
                            {
                                entity = new Model.Employee();
                                list.Add(entity);

                                var headerUpdate = headerList.Where(h => data[i, j].ToString().Contains(h.RowName) && h.ColumnIndex != 0).ToList();
                                if (headerUpdate != null && headerUpdate.Count > 0)
                                {
                                    headerUpdate.ForEach(h =>
                                    {
                                        entity.Info = data[i, h.ColumnIndex]?.ToString().Trim();
                                        //h.PropertyInfo.SetValue(entity, data[i, h.ColumnIndex]?.ToString().Trim());
                                    });
                                }

                                break;
                            }
                            //填充Header
                            else if (data[i, j].ToString() == "日 期" && needAddHeader)
                            {
                                for (int tem = 2; tem < data.GetLength(1); tem++)
                                {
                                    if (data[i, tem] != null && int.Parse(data[i, tem].ToString()) <= Common.TotalDays)
                                    {
                                        headerList.Add(new Header()
                                        {
                                            RowName = "日 期", ColumnName = data[i, tem].ToString().Trim(), ColumnIndex = tem
                                        });
                                    }
                                }
                                if (headerList.Count(h => h.RowName == "日 期") >= 28)
                                {
                                    needAddHeader = false;
                                }

                                break;
                            }
                            else if (data[i, j].ToString() == "考 勤")
                            {
                                var headerDate = headerList.Where(h => h.RowName == "日 期").ToList();
                                if (headerDate != null && headerDate.Count > 0)
                                {
                                    foreach (var item in headerDate)
                                    {
                                        if (data[i - 1, item.ColumnIndex] != null && data[i - 1, item.ColumnIndex].ToString() == item.ColumnName)
                                        {
                                            entity.Date   = item.ColumnName;
                                            entity.Record = data[i, item.ColumnIndex]?.ToString().Trim();

                                            entity.AttendanceList.Add(new Model.Attendance(entity.Date, entity.Record, 1));
                                        }
                                    }
                                }

                                break;
                            }
                        }
                        //else if (j == 1 && data[i, j] == null)
                        //{
                        //    if (!string.IsNullOrEmpty(entity.Id))
                        //    {
                        //        list.Add(entity);
                        //        entity = new Model.Employee();
                        //    }

                        //    break;
                        //}
                    }
                }
                return(list);
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (excelHelper != null)
                {
                    excelHelper.Close();
                }
            }
        }
Esempio n. 18
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (readFailed)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This component has changed or cannot be found, please create a new one");
                return;
            }

            if (SelectedConstructor is null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No schema has been selected.");
                return;
            }

            var units = Units.GetUnitsFromString(Rhino.RhinoDoc.ActiveDoc.GetUnitSystemName(true, false, false, false));

            List <object> cParamsValues = new List <object>();
            var           cParams       = SelectedConstructor.GetParameters();
            object        mainSchemaObj = null;

            for (var i = 0; i < cParams.Length; i++)
            {
                var    cParam     = cParams[i];
                var    param      = Params.Input[i];
                object objectProp = null;
                if (param.Access == GH_ParamAccess.list)
                {
                    var inputValues = new List <object>();
                    DA.GetDataList(i, inputValues);
                    if (!inputValues.Any() && !param.Optional)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input list `" + param.Name + "` is empty.");
                        return;
                    }

                    try
                    {
                        inputValues = inputValues.Select(x => ExtractRealInputValue(x)).ToList();
                        objectProp  = GetObjectListProp(param, inputValues, cParam.ParameterType);
                    }
                    catch (Exception e)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
                        return;
                    }
                }
                else if (param.Access == GH_ParamAccess.item)
                {
                    object inputValue = null;
                    DA.GetData(i, ref inputValue);
                    var extractRealInputValue = ExtractRealInputValue(inputValue);
                    objectProp = GetObjectProp(param, extractRealInputValue, cParam.ParameterType);
                }
                cParamsValues.Add(objectProp);
                if (CustomAttributeData.GetCustomAttributes(cParam)?.Where(o => o.AttributeType.IsEquivalentTo(typeof(SchemaMainParam)))?.Count() > 0)
                {
                    mainSchemaObj = objectProp;
                }
            }


            object schemaObject = null;

            try
            {
                schemaObject = SelectedConstructor.Invoke(cParamsValues.ToArray());
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
                return;
            }

            var @base = ((Base)schemaObject);

            @base.applicationId = $"{Seed}-{SelectedConstructor.DeclaringType.FullName}-{DA.Iteration}";
            @base.units         = units;

            // create commit obj from main geometry param and try to attach schema obj. use schema obj if no main geom param was found.
            Base commitObj = (Base)schemaObject;

            try
            {
                if (mainSchemaObj != null)
                {
                    commitObj = (Base)mainSchemaObj;
                    commitObj["@SpeckleSchema"] = schemaObject;
                    commitObj.units             = units;
                }
            }
            catch { }

            // Finally, add any custom props created by the user.
            for (var j = cParams.Length; j < Params.Input.Count; j++)
            {
                // Additional props added to the object
                var ghParam = Params.Input[j];
                if (ghParam.Access == GH_ParamAccess.item)
                {
                    object input = null;
                    DA.GetData(j, ref input);

                    commitObj[ghParam.Name] = Utilities.TryConvertItemToSpeckle(input, Converter);
                }
                else if (ghParam.Access == GH_ParamAccess.list)
                {
                    List <object> input = new List <object>();
                    DA.GetDataList(j, input);
                    commitObj[ghParam.Name] = input.Select(i => Utilities.TryConvertItemToSpeckle(i, Converter)).ToList();
                }
            }
            DA.SetData(0, new GH_SpeckleBase()
            {
                Value = commitObj
            });
        }
Esempio n. 19
0
 private static string GetAnnotationInterface(CustomAttributeData cad)
 {
     object[] attr = cad.Constructor.DeclaringType.GetCustomAttributes(typeof(IKVM.Attributes.ImplementsAttribute), false);
     if (attr.Length == 1)
     {
         string[] interfaces = ((IKVM.Attributes.ImplementsAttribute)attr[0]).Interfaces;
         if (interfaces.Length == 1)
         {
             return interfaces[0];
         }
     }
     return null;
 }
Esempio n. 20
0
        // Returns null if attribute wasn't found, string.Empty if attribute string was null or empty
        public string GetAttributeString(Type attributeType, out bool checkedInherited)
        {
            if (CustomAttributeProvider != null)
            {
                // Passes inherit=true for reasons explained in comment on XamlType.TryGetAttributeString
                checkedInherited = true;

                object[] attributes = CustomAttributeProvider.GetCustomAttributes(attributeType, true /*inherit*/);
                if (attributes.Length == 0)
                {
                    return null;
                }
                if (attributeType == typeof(ContentPropertyAttribute))
                {
                    return ((ContentPropertyAttribute)attributes[0]).Name;
                }
                if (attributeType == typeof(RuntimeNamePropertyAttribute))
                {
                    return ((RuntimeNamePropertyAttribute)attributes[0]).Name;
                }
                if (attributeType == typeof(DictionaryKeyPropertyAttribute))
                {
                    return ((DictionaryKeyPropertyAttribute)attributes[0]).Name;
                }
                if (attributeType == typeof(XamlSetMarkupExtensionAttribute))
                {
                    return ((XamlSetMarkupExtensionAttribute)attributes[0]).XamlSetMarkupExtensionHandler;
                }
                if (attributeType == typeof(XamlSetTypeConverterAttribute))
                {
                    return ((XamlSetTypeConverterAttribute)attributes[0]).XamlSetTypeConverterHandler;
                }
                if (attributeType == typeof(UidPropertyAttribute))
                {
                    return ((UidPropertyAttribute)attributes[0]).Name;
                }
                if (attributeType == typeof(XmlLangPropertyAttribute))
                {
                    return ((XmlLangPropertyAttribute)attributes[0]).Name;
                }
                if (attributeType == typeof(ConstructorArgumentAttribute))
                {
                    return ((ConstructorArgumentAttribute)attributes[0]).ArgumentName;
                }
                Debug.Fail("Unexpected attribute type requested: " + attributeType.Name);
                return null;
            }
            try
            {
                // CustomAttributeData doesn't have an inherit=true option
                checkedInherited = false;

                CustomAttributeData cad = GetAttribute(attributeType);
                if (cad == null)
                {
                    return null;
                }
                return Extract<string>(cad) ?? string.Empty;
            }
            catch (CustomAttributeFormatException)
            {
                CustomAttributeProvider = Member;
                return GetAttributeString(attributeType, out checkedInherited);
            }
        }
Esempio n. 21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ReflectionAttributeInfo"/> class.
 /// </summary>
 /// <param name="attribute">The attribute to be wrapped.</param>
 public ReflectionAttributeInfo(CustomAttributeData attribute)
 {
     AttributeData = attribute;
     Attribute     = Instantiate(AttributeData);
 }
Esempio n. 22
0
 private static string?GetVersionFromAttribute(CustomAttributeData attribute)
 {
     return(attribute.AttributeType.FullName == typeof(SemanticVersionAttribute).FullName ?
            attribute.ConstructorArguments[0].Value?.ToString() : null);
 }
        private void GetTypeDrawerType(SerializedProperty property)
        {
            if (_genericTypeDrawerInstance != null)
            {
                return;
            }

            //Get the associated attribute drawer
            try {
                // Of all property drawers in the assembly we need to find one that affects target type
                // or one of the base types of target type
                foreach (Type propertyDrawerType in _allPropertyDrawerAttributeTypes)
                {
                    _genericType = fieldInfo.FieldType;
                    var affectedType = (Type)CustomAttributeData.GetCustomAttributes(propertyDrawerType).First().ConstructorArguments.First().Value;
                    while (_genericType != null)
                    {
                        if (_genericTypeDrawerType != null)
                        {
                            break;
                        }
                        if (affectedType == _genericType)
                        {
                            _genericTypeDrawerType = propertyDrawerType;
                        }
                        else
                        {
                            _genericType = _genericType.BaseType;
                        }
                    }
                    if (_genericTypeDrawerType != null)
                    {
                        break;
                    }
                }
            } catch (Exception) {
                // Commented out because of multiple false warnings on Behaviour types
                //LogWarning("[ConditionalField] does not work with "+_genericType+". Unable to find property drawer from the Type", property);
                return;
            }
            if (_genericTypeDrawerType == null)
            {
                return;
            }

            //Create instances of each (including the arguments)
            try {
                _genericTypeDrawerInstance = (PropertyDrawer)Activator.CreateInstance(_genericTypeDrawerType);
            } catch (Exception e) {
                LogWarning("no constructor available in " + _genericType + " : " + e, property);
                return;
            }

            //Reassign the attribute field in the drawer so it can access the argument values
            try {
                _genericTypeDrawerType.GetField("m_Attribute", BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(_genericTypeDrawerInstance, fieldInfo);
            } catch (Exception) {
                //LogWarning("Unable to assign attribute to " + _genericTypeDrawerInstance.GetType() + " : " + e, property);
            }
        }
Esempio n. 24
0
        internal static void WriteClass(Stream stream, TypeWrapper tw, bool includeNonPublicInterfaces, bool includeNonPublicMembers, bool includeSerialVersionUID, bool includeParameterNames)
        {
            string name  = tw.Name.Replace('.', '/');
            string super = null;

            if (tw.IsInterface)
            {
                super = "java/lang/Object";
            }
            else if (tw.BaseTypeWrapper != null)
            {
                super = tw.BaseTypeWrapper.Name.Replace('.', '/');
            }
            ClassFileWriter writer = new ClassFileWriter(tw.Modifiers, name, super, 0, includeParameterNames ? (ushort)52 : (ushort)49);

            foreach (TypeWrapper iface in tw.Interfaces)
            {
                if (iface.IsPublic || includeNonPublicInterfaces)
                {
                    writer.AddInterface(iface.Name.Replace('.', '/'));
                }
            }
            InnerClassesAttribute innerClassesAttribute = null;

            if (tw.DeclaringTypeWrapper != null)
            {
                TypeWrapper outer     = tw.DeclaringTypeWrapper;
                string      innername = name;
                int         idx       = name.LastIndexOf('$');
                if (idx >= 0)
                {
                    innername = innername.Substring(idx + 1);
                }
                innerClassesAttribute = new InnerClassesAttribute(writer);
                innerClassesAttribute.Add(name, outer.Name.Replace('.', '/'), innername, (ushort)tw.ReflectiveModifiers);
            }
            foreach (TypeWrapper inner in tw.InnerClasses)
            {
                if (inner.IsPublic)
                {
                    if (innerClassesAttribute == null)
                    {
                        innerClassesAttribute = new InnerClassesAttribute(writer);
                    }
                    string namePart = inner.Name;
                    namePart = namePart.Substring(namePart.LastIndexOf('$') + 1);
                    innerClassesAttribute.Add(inner.Name.Replace('.', '/'), name, namePart, (ushort)inner.ReflectiveModifiers);
                }
            }
            if (innerClassesAttribute != null)
            {
                writer.AddAttribute(innerClassesAttribute);
            }
            string genericTypeSignature = tw.GetGenericSignature();

            if (genericTypeSignature != null)
            {
                writer.AddStringAttribute("Signature", genericTypeSignature);
            }
            AddAnnotations(writer, writer, tw.TypeAsBaseType);
            AddTypeAnnotations(writer, writer, tw, tw.GetRawTypeAnnotations());
            writer.AddStringAttribute("IKVM.NET.Assembly", GetAssemblyName(tw));
            if (tw.TypeAsBaseType.IsDefined(JVM.Import(typeof(ObsoleteAttribute)), false))
            {
                writer.AddAttribute(new DeprecatedAttribute(writer));
            }
            foreach (MethodWrapper mw in tw.GetMethods())
            {
                if (!mw.IsHideFromReflection && (mw.IsPublic || mw.IsProtected || includeNonPublicMembers))
                {
                    FieldOrMethod m;
                    // HACK javac has a bug in com.sun.tools.javac.code.Types.isSignaturePolymorphic() where it assumes that
                    // MethodHandle doesn't have any native methods with an empty argument list
                    // (or at least it throws a NPE when it examines the signature of a method without any parameters when it
                    // accesses argtypes.tail.tail)
                    if (mw.Name == "<init>" || (tw == CoreClasses.java.lang.invoke.MethodHandle.Wrapper && (mw.Modifiers & Modifiers.Native) == 0))
                    {
                        m = writer.AddMethod(mw.Modifiers, mw.Name, mw.Signature.Replace('.', '/'));
                        CodeAttribute code = new CodeAttribute(writer);
                        code.MaxLocals = (ushort)(mw.GetParameters().Length * 2 + 1);
                        code.MaxStack  = 3;
                        ushort index1 = writer.AddClass("java/lang/UnsatisfiedLinkError");
                        ushort index2 = writer.AddString("ikvmstub generated stubs can only be used on IKVM.NET");
                        ushort index3 = writer.AddMethodRef("java/lang/UnsatisfiedLinkError", "<init>", "(Ljava/lang/String;)V");
                        code.ByteCode = new byte[] {
                            187, (byte)(index1 >> 8), (byte)index1,                     // new java/lang/UnsatisfiedLinkError
                            89,                                                         // dup
                            19, (byte)(index2 >> 8), (byte)index2,                      // ldc_w "..."
                            183, (byte)(index3 >> 8), (byte)index3,                     // invokespecial java/lang/UnsatisfiedLinkError/init()V
                            191                                                         // athrow
                        };
                        m.AddAttribute(code);
                    }
                    else
                    {
                        Modifiers mods = mw.Modifiers;
                        if ((mods & Modifiers.Abstract) == 0)
                        {
                            mods |= Modifiers.Native;
                        }
                        m = writer.AddMethod(mods, mw.Name, mw.Signature.Replace('.', '/'));
                        if (mw.IsOptionalAttributeAnnotationValue)
                        {
                            m.AddAttribute(new AnnotationDefaultClassFileAttribute(writer, GetAnnotationDefault(writer, mw.ReturnType)));
                        }
                    }
                    MethodBase mb = mw.GetMethod();
                    if (mb != null)
                    {
                        ThrowsAttribute throws = AttributeHelper.GetThrows(mb);
                        if (throws == null)
                        {
                            string[] throwsArray = mw.GetDeclaredExceptions();
                            if (throwsArray != null && throwsArray.Length > 0)
                            {
                                ExceptionsAttribute attrib = new ExceptionsAttribute(writer);
                                foreach (string ex in throwsArray)
                                {
                                    attrib.Add(ex.Replace('.', '/'));
                                }
                                m.AddAttribute(attrib);
                            }
                        }
                        else
                        {
                            ExceptionsAttribute attrib = new ExceptionsAttribute(writer);
                            if (throws.classes != null)
                            {
                                foreach (string ex in throws.classes)
                                {
                                    attrib.Add(ex.Replace('.', '/'));
                                }
                            }
                            if (throws.types != null)
                            {
                                foreach (Type ex in throws.types)
                                {
                                    attrib.Add(ClassLoaderWrapper.GetWrapperFromType(ex).Name.Replace('.', '/'));
                                }
                            }
                            m.AddAttribute(attrib);
                        }
                        if (mb.IsDefined(JVM.Import(typeof(ObsoleteAttribute)), false)
                            // HACK the instancehelper methods are marked as Obsolete (to direct people toward the ikvm.extensions methods instead)
                            // but in the Java world most of them are not deprecated (and to keep the Japi results clean we need to reflect this)
                            && (!mb.Name.StartsWith("instancehelper_") ||
                                mb.DeclaringType.FullName != "java.lang.String"
                                // the Java deprecated methods actually have two Obsolete attributes
                                || GetObsoleteCount(mb) == 2))
                        {
                            m.AddAttribute(new DeprecatedAttribute(writer));
                        }
                        CustomAttributeData attr = GetAnnotationDefault(mb);
                        if (attr != null)
                        {
                            m.AddAttribute(new AnnotationDefaultClassFileAttribute(writer, GetAnnotationDefault(writer, attr.ConstructorArguments[0])));
                        }
                        if (includeParameterNames)
                        {
                            MethodParametersEntry[] mp = tw.GetMethodParameters(mw);
                            if (mp == MethodParametersEntry.Malformed)
                            {
                                m.AddAttribute(new MethodParametersAttribute(writer, null, null));
                            }
                            else if (mp != null)
                            {
                                ushort[] names = new ushort[mp.Length];
                                ushort[] flags = new ushort[mp.Length];
                                for (int i = 0; i < names.Length; i++)
                                {
                                    if (mp[i].name != null)
                                    {
                                        names[i] = writer.AddUtf8(mp[i].name);
                                    }
                                    flags[i] = mp[i].flags;
                                }
                                m.AddAttribute(new MethodParametersAttribute(writer, names, flags));
                            }
                        }
                    }
                    string sig = tw.GetGenericMethodSignature(mw);
                    if (sig != null)
                    {
                        m.AddAttribute(writer.MakeStringAttribute("Signature", sig));
                    }
                    AddAnnotations(writer, m, mw.GetMethod());
                    AddParameterAnnotations(writer, m, mw.GetMethod());
                    AddTypeAnnotations(writer, m, tw, tw.GetMethodRawTypeAnnotations(mw));
                }
            }
            bool hasSerialVersionUID = false;

            foreach (FieldWrapper fw in tw.GetFields())
            {
                if (!fw.IsHideFromReflection)
                {
                    bool isSerialVersionUID = includeSerialVersionUID && fw.Name == "serialVersionUID" && fw.FieldTypeWrapper == PrimitiveTypeWrapper.LONG;
                    hasSerialVersionUID |= isSerialVersionUID;
                    if (fw.IsPublic || fw.IsProtected || isSerialVersionUID || includeNonPublicMembers)
                    {
                        object constant = null;
                        if (fw.GetField() != null && fw.GetField().IsLiteral&& (fw.FieldTypeWrapper.IsPrimitive || fw.FieldTypeWrapper == CoreClasses.java.lang.String.Wrapper))
                        {
                            constant = fw.GetField().GetRawConstantValue();
                            if (fw.GetField().FieldType.IsEnum)
                            {
                                constant = EnumHelper.GetPrimitiveValue(EnumHelper.GetUnderlyingType(fw.GetField().FieldType), constant);
                            }
                        }
                        FieldOrMethod f   = writer.AddField(fw.Modifiers, fw.Name, fw.Signature.Replace('.', '/'), constant);
                        string        sig = tw.GetGenericFieldSignature(fw);
                        if (sig != null)
                        {
                            f.AddAttribute(writer.MakeStringAttribute("Signature", sig));
                        }
                        if (fw.GetField() != null && fw.GetField().IsDefined(JVM.Import(typeof(ObsoleteAttribute)), false))
                        {
                            f.AddAttribute(new DeprecatedAttribute(writer));
                        }
                        AddAnnotations(writer, f, fw.GetField());
                        AddTypeAnnotations(writer, f, tw, tw.GetFieldRawTypeAnnotations(fw));
                    }
                }
            }
            if (includeSerialVersionUID && !hasSerialVersionUID && IsSerializable(tw))
            {
                // class is serializable but doesn't have an explicit serialVersionUID, so we add the field to record
                // the serialVersionUID as we see it (mainly to make the Japi reports more realistic)
                writer.AddField(Modifiers.Private | Modifiers.Static | Modifiers.Final, "serialVersionUID", "J", SerialVersionUID.Compute(tw));
            }
            AddMetaAnnotations(writer, tw);
            writer.Write(stream);
        }
 private static bool IsAttributeDataForType(CustomAttributeData attributeData, Type attributeType)
 {
     return(attributeData.Constructor.DeclaringType.AssemblyQualifiedName == attributeType.AssemblyQualifiedName);
 }
Esempio n. 26
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(MonoCustomAttrs))
            {
                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)
            {
                var usageAttribute = RetrieveAttributeUsage(attributeType);
                if (!usageAttribute.Inherited)
                {
                    inherit = false;
                }
            }

            var 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());
        }
Esempio n. 27
0
 public static Type GetAttributeType(this CustomAttributeData source)
 {
     return(source.Constructor.DeclaringType);
 }
Esempio n. 28
0
 static bool IsViewType(CustomAttributeData attributeData, UIViewType viewType)
 {
     Debug.Assert(attributeData.NamedArguments != null);
     return(attributeData.AttributeType == typeof(ExportViewAttribute) &&
            (UIViewType)attributeData.NamedArguments[0].TypedValue.Value == viewType);
 }
Esempio n. 29
0
 public static IEnumerable <CustomAttributeNamedArgument> GetNamedArguments(this CustomAttributeData source)
 {
     return(source.NamedArguments);
 }
Esempio n. 30
0
 static bool IsMenuType(CustomAttributeData attributeData, MenuType type)
 {
     Debug.Assert(attributeData.NamedArguments != null);
     return(attributeData.AttributeType == typeof(ExportMenuAttribute) &&
            (MenuType)attributeData.NamedArguments[0].TypedValue.Value == type);
 }
Esempio n. 31
0
 /// <summary>
 /// Converts an <see cref="Attribute"/> into an <see cref="IAttributeInfo"/> using reflection.
 /// </summary>
 /// <param name="attribute">The attribute to wrap.</param>
 /// <returns>The wrapper</returns>
 public static IReflectionAttributeInfo Wrap(CustomAttributeData attribute)
 {
     return(new ReflectionAttributeInfo(attribute));
 }
    IEnumerable <T> CreateAttributeInstance <T> (CustomAttributeData attribute, ICustomAttributeProvider provider) where T : System.Attribute
    {
        var convertedAttributes = ConvertOldAttributes(attribute);

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

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

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

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

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

        for (int i = 0; i < constructorArguments.Length; i++)
        {
            var value = attribute.ConstructorArguments [i].Value;
            switch (attribute.ConstructorArguments [i].ArgumentType.FullName)
            {
            case "System.Type":
                if (value != null)
                {
                    if (attribType.Assembly == typeof(TypeManager).Assembly)
                    {
                        constructorArguments [i] = value;
                    }
                    else
                    {
                        constructorArguments [i] = System.Type.GetType(((Type)value).FullName);
                    }
                    if (constructorArguments [i] == null)
                    {
                        throw ErrorHelper.CreateError(1056, attribType.FullName, i + 1);
                    }
                }
                break;

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

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

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

            default:
                ctorTypes [i] = ConvertType(paramType, provider);
                break;
            }
            if (ctorTypes [i] == null)
            {
                throw ErrorHelper.CreateError(1057, attribType.FullName, i, paramType.FullName);
            }
        }
        var ctor = attribType.GetConstructor(ctorTypes);

        if (ctor == null)
        {
            throw ErrorHelper.CreateError(1058, attribType.FullName);
        }
        var instance = ctor.Invoke(constructorArguments);

        for (int i = 0; i < attribute.NamedArguments.Count; i++)
        {
            var arg   = attribute.NamedArguments [i];
            var value = arg.TypedValue.Value;
            if (arg.TypedValue.ArgumentType == TypeManager.System_String_Array)
            {
                var typed_values = (CustomAttributeTypedArgument [])arg.TypedValue.Value;
                var arr          = new string [typed_values.Length];
                for (int a = 0; a < arr.Length; a++)
                {
                    arr [a] = (string)typed_values [a].Value;
                }
                value = arr;
            }
            else if (arg.TypedValue.ArgumentType.FullName == "System.Type[]")
            {
                var typed_values = (CustomAttributeTypedArgument [])arg.TypedValue.Value;
                var arr          = new Type [typed_values.Length];
                for (int a = 0; a < arr.Length; a++)
                {
                    arr [a] = (Type)typed_values [a].Value;
                }
                value = arr;
            }
            else if (arg.TypedValue.ArgumentType.IsArray)
            {
                throw ErrorHelper.CreateError(1073, attribType.FullName, i + 1, arg.MemberName);
            }
            if (arg.IsField)
            {
                attribType.GetField(arg.MemberName).SetValue(instance, value);
            }
            else
            {
                attribType.GetProperty(arg.MemberName).SetValue(instance, value, new object [0]);
            }
        }

        return(((T)instance).Yield());
    }
Esempio n. 33
0
    // the ToString function of CustomAttribute Data
    string AttrToString(CustomAttributeData ca)
    {
        var ctorArgs = new StringBuilder();
        //bool shouldReplace = false;
        for (int i = 0; i < ca.ConstructorArguments.Count; i++)
        {
            // some intro whidbey breaking change, swallow the diff
            // one of MarshalAsAttributes's field value change from IidParamIndex to IidParameterIndex
            /*if (ca.Constructor.DeclaringType == typeof(System.Runtime.InteropServices.MarshalAsAttribute))
            {
                shouldReplace = true;
            }*/
            ctorArgs.Append(string.Format(i == 0 ? "{0}" : ", {0}", ca.ConstructorArguments[i]));
        }

        var namedArgs = new StringBuilder();
        for (int i = 0; i < ca.NamedArguments.Count; i++)
        {
            if (ca.NamedArguments[i].TypedValue.ToString().Contains("System.Runtime.InteropServices.CustomMarshalers"))
            {
                namedArgs.Append(String.Format(i == 0 && ctorArgs.Length == 0 ? "{0}" : ", {0}", Regex.Replace(ca.NamedArguments[i].ToString(), @"\d+\.\d+\.\d+\.\d+", "2.0.0.0")));
            }
            else
                namedArgs.Append(String.Format(i == 0 && ctorArgs.Length == 0 ? "{0}" : ", {0}", ca.NamedArguments[i]));
        }
        if (ca.Constructor.DeclaringType.Assembly != CurrentAssembly)
            return String.Format("[{0}]{1}({2}{3})", ca.Constructor.DeclaringType.Assembly.GetName().Name, ca.Constructor.DeclaringType.FullName, ctorArgs.ToString(), namedArgs.ToString());
        else
            return String.Format("{0}({1}{2})", ca.Constructor.DeclaringType.FullName, ctorArgs.ToString(), namedArgs.ToString());
    }
    public static System.Attribute ConvertPlatformAttribute(CustomAttributeData attribute, PlatformName platform)
    {
        var constructorArguments = new object [attribute.ConstructorArguments.Count];

        for (int i = 0; i < attribute.ConstructorArguments.Count; ++i)
        {
            constructorArguments [i] = attribute.ConstructorArguments [i].Value;
        }

        Func <string> createErrorMessage = () => {
            var b = new System.Text.StringBuilder(" Types { ");
            for (int i = 0; i < constructorArguments.Length; ++i)
            {
                b.Append(constructorArguments[i].GetType().ToString() + " ");
            }
            b.Append("}");
            return(b.ToString());
        };

        Func <string> unknownFormatError = () => $"Unknown format for old style availability attribute {attribute.AttributeType.FullName} {attribute.ConstructorArguments.Count} {createErrorMessage ()}";

        object []      ctorValues;
        System.Type [] ctorTypes;

        switch (attribute.ConstructorArguments.Count)
        {
        case 2:
            if (constructorArguments [0].GetType() == typeof(byte) &&
                constructorArguments [1].GetType() == typeof(byte))
            {
                ctorValues = new object [] { (byte)platform, (int)(byte)constructorArguments [0], (int)(byte)constructorArguments [1], (byte)0xff, null };
                ctorTypes  = new System.Type [] { AttributeFactory.PlatformEnum, typeof(int), typeof(int), AttributeFactory.PlatformArch, typeof(string) };
                break;
            }
            throw new NotImplementedException(unknownFormatError());

        case 3:
            if (constructorArguments [0].GetType() == typeof(byte) &&
                constructorArguments [1].GetType() == typeof(byte) &&
                constructorArguments [2].GetType() == typeof(byte))
            {
                ctorValues = new object [] { (byte)platform, (int)(byte)constructorArguments [0], (int)(byte)constructorArguments [1], (int)(byte)constructorArguments [2], (byte)0xff, null };
                ctorTypes  = new System.Type [] { AttributeFactory.PlatformEnum, typeof(int), typeof(int), typeof(int), AttributeFactory.PlatformArch, typeof(string) };
                break;
            }
            if (constructorArguments [0].GetType() == typeof(byte) &&
                constructorArguments [1].GetType() == typeof(byte) &&
                constructorArguments [2].GetType() == typeof(bool))
            {
                byte arch = (bool)constructorArguments [2] ? (byte)2 : (byte)0xff;
                ctorValues = new object [] { (byte)platform, (int)(byte)constructorArguments [0], (int)(byte)constructorArguments [1], arch, null };
                ctorTypes  = new System.Type [] { AttributeFactory.PlatformEnum, typeof(int), typeof(int), AttributeFactory.PlatformArch, typeof(string) };
                break;
            }
            throw new NotImplementedException(unknownFormatError());

        case 4:
            if (constructorArguments [0].GetType() == typeof(byte) &&
                constructorArguments [1].GetType() == typeof(byte) &&
                constructorArguments [2].GetType() == typeof(byte) &&
                constructorArguments [3].GetType() == typeof(bool))
            {
                byte arch = (bool)constructorArguments [3] ? (byte)2 : (byte)0xff;
                ctorValues = new object [] { (byte)platform, (int)(byte)constructorArguments [0], (int)(byte)constructorArguments [1], (int)(byte)constructorArguments [2], arch, null };
                ctorTypes  = new System.Type [] { AttributeFactory.PlatformEnum, typeof(int), typeof(int), typeof(int), AttributeFactory.PlatformArch, typeof(string) };
                break;
            }
            if (constructorArguments [0].GetType() == typeof(byte) &&
                constructorArguments [1].GetType() == typeof(byte) &&
                constructorArguments [2].GetType() == typeof(byte) &&
                constructorArguments [3].GetType() == typeof(byte) /* ObjCRuntime.PlatformArchitecture */)
            {
                ctorValues = new object [] { (byte)platform, (int)(byte)constructorArguments [0], (int)(byte)constructorArguments [1], (int)(byte)constructorArguments [2], constructorArguments [3], null };
                ctorTypes  = new System.Type [] { AttributeFactory.PlatformEnum, typeof(int), typeof(int), typeof(int), AttributeFactory.PlatformArch, typeof(string) };
                break;
            }

            throw new NotImplementedException(unknownFormatError());

        default:
            throw new NotImplementedException($"Unknown count {attribute.ConstructorArguments.Count} {createErrorMessage ()}");
        }

        return(AttributeFactory.CreateNewAttribute(AttributeFactory.IntroducedAttributeType, ctorTypes, ctorValues));
    }
Esempio n. 35
0
    public static IReflectionAttributeInfo TestFrameworkAttribute(Type type)
    {
        var attribute = Activator.CreateInstance(type);
        var result    = Substitute.For <IReflectionAttributeInfo, InterfaceProxy <IReflectionAttributeInfo> >();

        result.Attribute.Returns(attribute);
        result.GetCustomAttributes(null).ReturnsForAnyArgs(callInfo => LookupAttribute(callInfo.Arg <string>(), CustomAttributeData.GetCustomAttributes(attribute.GetType()).Select(Reflector.Wrap).ToArray()));
        return(result);
    }
Esempio n. 36
0
        private static CustomAttributeData GetPluginInfoAttributeData(Type type)
        {
            var attributes = CustomAttributeData.GetCustomAttributes(type).Where(ca => ca.Constructor.DeclaringType.FullName == typeof(PluginInfoAttribute).FullName).ToArray();

            return(attributes.Length > 0 ? attributes[0] : null);
        }
Esempio n. 37
0
 private static object[] GetAnnotation(CustomAttributeData cad)
 {
     if (cad.ConstructorArguments.Count == 1 && cad.ConstructorArguments[0].ArgumentType == typeof(object[]) &&
         (cad.Constructor.DeclaringType.BaseType == typeof([email protected])
         || cad.Constructor.DeclaringType == typeof(DynamicAnnotationAttribute)))
     {
         return UnpackArray((IList<CustomAttributeTypedArgument>)cad.ConstructorArguments[0].Value);
     }
     else if (cad.Constructor.DeclaringType.BaseType == typeof([email protected]))
     {
         string annotationType = GetAnnotationInterface(cad);
         if (annotationType != null)
         {
             // this is a custom attribute annotation applied in a non-Java module
             List<object> list = new List<object>();
             list.Add(AnnotationDefaultAttribute.TAG_ANNOTATION);
             list.Add("L" + annotationType.Replace('.', '/') + ";");
             ParameterInfo[] parameters = cad.Constructor.GetParameters();
             for (int i = 0; i < parameters.Length; i++)
             {
                 list.Add(parameters[i].Name);
                 list.Add(EncodeAnnotationValue(cad.ConstructorArguments[i]));
             }
             foreach (CustomAttributeNamedArgument arg in cad.NamedArguments)
             {
                 list.Add(arg.MemberInfo.Name);
                 list.Add(EncodeAnnotationValue(arg.TypedValue));
             }
             return list.ToArray();
         }
     }
     return null;
 }
 private static bool ProcessAttribute(CustomAttributeData attribute, in NetworkCompatibility networkCompatibility)
Esempio n. 39
0
 public AttributeDataMap(CustomAttributeData attribute)
 {
     this.attribute = attribute;
 }
Esempio n. 40
0
 private static object[] GetAnnotation(CustomAttributeData cad)
 {
     if (cad.ConstructorArguments.Count == 1 && cad.ConstructorArguments[0].ArgumentType == typeof(object[]) &&
         (cad.Constructor.DeclaringType.IsSubclassOf(JVM.Import(typeof([email protected])))
         || cad.Constructor.DeclaringType == JVM.Import(typeof(DynamicAnnotationAttribute))))
     {
         return UnpackArray((IList<CustomAttributeTypedArgument>)cad.ConstructorArguments[0].Value);
     }
     return null;
 }