예제 #1
0
        private static string GenerateAttributeAssembly(Assembly assembly, string outputDirectory)
        {
            AssemblyName srcName = new AssemblyName(assembly.FullName);

            if (srcName == null || string.IsNullOrEmpty(srcName.Name))
            {
                return(null);
            }

            try
            {
                // Prepare dynamic assembly for resources
                AssemblyName asmName = new AssemblyName(srcName.FullName);
                asmName.Name = "Tmp." + srcName.Name;

                // Only create an on-disk assembly. We never have to execute anything
                AssemblyBuilder newAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.ReflectionOnly, outputDirectory);

                string tmpFile = srcName.Name + ".dll";
                newAssembly.DefineDynamicModule(asmName.Name, tmpFile);

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(OnReflectionOnlyAssemblyResolve);

                try
                {
                    Assembly mscorlib = Assembly.ReflectionOnlyLoad(typeof(int).Assembly.FullName);
                    Assembly system   = Assembly.ReflectionOnlyLoad(typeof(Uri).Assembly.FullName);
                    bool     hasInformationalVersion = false;
                    bool     hasVersion = false;

                    foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(assembly))
                    {
                        if ((attr.NamedArguments.Count > 0) || (attr.Constructor == null))
                        {
                            // We don't use named arguments at this time; not needed for the version resources
                            continue;
                        }

                        Type type = attr.Constructor.ReflectedType;

                        if (type.Assembly != mscorlib && type.Assembly != system)
                        {
                            continue;
                        }

                        if (type.Assembly == mscorlib)
                        {
                            switch (type.Name)
                            {
                            case "System.Reflection.AssemblyInformationalVersionAttribute":
                                hasInformationalVersion = true;
                                break;

                            case "System.Reflection.AssemblyVersionAttribute":
                                hasVersion = true;
                                break;
                            }
                        }

                        List <object> values = new List <object>();
                        foreach (CustomAttributeTypedArgument arg in attr.ConstructorArguments)
                        {
                            values.Add(arg.Value);
                        }

                        CustomAttributeBuilder cb = new CustomAttributeBuilder(attr.Constructor, values.ToArray());

                        newAssembly.SetCustomAttribute(cb);
                    }

                    if (!hasVersion)
                    {
                        newAssembly.SetCustomAttribute(
                            new CustomAttributeBuilder(typeof(AssemblyVersionAttribute).GetConstructor(new Type[] { typeof(String) }),
                                                       new object[] { srcName.Version.ToString() }));
                    }
                    if (!hasInformationalVersion)
                    {
                        newAssembly.SetCustomAttribute(
                            new CustomAttributeBuilder(typeof(AssemblyInformationalVersionAttribute).GetConstructor(new Type[] { typeof(String) }),
                                                       new object[] { srcName.Version.ToString() }));
                    }

                    newAssembly.SetCustomAttribute(
                        new CustomAttributeBuilder(typeof(AssemblyCultureAttribute).GetConstructor(new Type[] { typeof(String) }),
                                                   new object[] { "" }));
                }
                finally
                {
                    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= new ResolveEventHandler(OnReflectionOnlyAssemblyResolve);
                }

                newAssembly.DefineVersionInfoResource();
                newAssembly.Save(tmpFile);

                return(QQnPath.Combine(outputDirectory, tmpFile));
            }
            catch (FileLoadException)
            {
                return(null);
            }
            catch (IOException)
            {
                return(null);
            }
        }
예제 #2
0
        private static MergeArgType GetMergeArgType(MethodInfo m)
        {
            string   streamName  = null;
            TypeName action      = null;
            TypeName cancelToken = null;

            // ReSharper disable once PossibleNullReferenceException
            var typeName = $"{m.DeclaringType.Namespace}_{m.DeclaringType.Name}_{m.Name}Param2";
            var typeNameWithoutStreamName = $"{m.DeclaringType.Namespace}_{m.DeclaringType.Name}_{m.Name}Param";
            var cis = new List <CustomsPropertyInfo>();

            var attributeData = CustomAttributeData.GetCustomAttributes(m).Where(i => i.AttributeType == typeof(ExampleAttribute)).ToList();
            var addedCallId   = false;
            var addedStream   = false;

            foreach (var p in m.GetParameters())
            {
                //Stream
                if (p.ParameterType == typeof(Stream))
                {
                    streamName  = p.Name;
                    addedStream = true;
                    continue;
                }

                //callback
                if (p.ParameterType.IsFuncT())
                {
                    action = new TypeName
                    {
                        Type = p.ParameterType,
                        Name = p.Name
                    };

                    addedCallId = true;
                    continue;
                }

                //cancel
                if (p.ParameterType == typeof(CancellationToken?) || p.ParameterType == typeof(CancellationToken))
                {
                    cancelToken = new TypeName
                    {
                        Type = p.ParameterType,
                        Name = p.Name
                    };

                    addedCallId = true;
                    continue;
                }

                //ExampleAttribute
                var found = attributeData.Find(i => (string)i.ConstructorArguments[0].Value == p.Name);
                if (found != null)
                {
                    cis.Add(new CustomsPropertyInfo(p.ParameterType, p.Name, found));
                }
                else
                {
                    cis.Add(new CustomsPropertyInfo(p.ParameterType, p.Name));
                }
            }

            //connectionId callId
            if (addedCallId)
            {
                cis.Add(new CustomsPropertyInfo(typeof(string), CallConst.ConnectionIdName));
                cis.Add(new CustomsPropertyInfo(typeof(string), CallConst.CallIdName));
            }

            //StreamLength
            if (addedStream)
            {
                cis.Add(new CustomsPropertyInfo(typeof(long), CallConst.StreamLength));
            }

            var t  = TypeFactory.BuildType(typeName, cis);
            var t2 = BuildTypeWithoutStreamName(typeNameWithoutStreamName, cis);

            if (cis.Count == 0)
            {
                return(new MergeArgType(null, null, null, null, null));
            }

            return(new MergeArgType(t, t2, streamName, action, cancelToken));
        }
예제 #3
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));
 }
예제 #4
0
        public static bool ReadTest(MethodInfo test, IFixtureData data, string workingDirectory)
        {
            //set the default modelPath to the empty.rfa file that will live in the build directory
            string modelPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "empty.rfa");

            var testAttribs = CustomAttributeData.GetCustomAttributes(test);

            var testModelAttrib =
                testAttribs.FirstOrDefault(x => x.Constructor.DeclaringType.Name == "TestModelAttribute");

            if (testModelAttrib != null)
            {
                //overwrite the model path with the one
                //specified in the test model attribute
                var relModelPath = testModelAttrib.ConstructorArguments.FirstOrDefault().Value.ToString();
                if (workingDirectory == null)
                {
                    // If the working directory is not specified.
                    // Add the relative path to the assembly's path.
                    modelPath =
                        Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                      relModelPath));
                }
                else
                {
                    modelPath = Path.GetFullPath(Path.Combine(workingDirectory, relModelPath));
                }
            }

            var runDynamoAttrib =
                testAttribs.FirstOrDefault(x => x.Constructor.DeclaringType.Name == "RunDynamoAttribute");

            var runDynamo = false;

            if (runDynamoAttrib != null)
            {
                runDynamo = Boolean.Parse(runDynamoAttrib.ConstructorArguments.FirstOrDefault().Value.ToString());
            }

            var testData = new TestData(data, test.Name, modelPath, runDynamo);

            data.Tests.Add(testData);

            var category        = string.Empty;
            var categoryAttribs =
                testAttribs.Where(x => x.Constructor.DeclaringType.Name == "CategoryAttribute");

            foreach (var categoryAttrib in categoryAttribs)
            {
                category = categoryAttrib.ConstructorArguments.FirstOrDefault().Value.ToString();
                if (!String.IsNullOrEmpty(category))
                {
                    var cat = data.Assembly.Categories.FirstOrDefault(x => x.Name == category);
                    if (cat != null)
                    {
                        cat.Tests.Add(testData);
                    }
                    else
                    {
                        var catData = new CategoryData(data.Assembly, category);
                        catData.Tests.Add(testData);
                        data.Assembly.Categories.Add(catData);
                    }
                }
            }

            Console.WriteLine("Loaded test: {0}", testData);

            return(true);
        }
예제 #5
0
        /// <summary>
        /// 生成单个线程(或 Task任务)的 API 方法(Method),最小粒度
        /// </summary>
        private async Task BuildApiMethodForOneThread(IGrouping <string, KeyValuePair <string, ApiBindInfo> > apiBindGroup,
                                                      KeyValuePair <string, ApiBindInfo>[] apiBindInfoBlock, ConcurrentDictionary <string, string> apiMethodName, string keyName,
                                                      TypeBuilder tb, FieldBuilder fbServiceProvider, int apiIndex)
        {
            foreach (var apiBindInfo in apiBindInfoBlock)
            {
                #region ApiBuild

                try
                {
                    //if (apiIndex > 9999)//200-250
                    //{
                    //    return;//用于小范围分析
                    //}

                    var category = apiBindGroup.Key;

                    //定义版本号
                    if (!ApiAssemblyVersions.ContainsKey(category))
                    {
                        ApiAssemblyVersions[category] = apiBindInfo.Value.MethodInfo.DeclaringType.Assembly.GetName().Version.ToString(3);
                    }

                    //当前方法名称
                    var methodName         = regexForMethodName.Replace(apiBindInfo.Value.GlobalName, "_");
                    var apiBindGlobalName  = apiBindInfo.Value.GlobalName.Split('.')[0];
                    var apiBindName        = apiBindInfo.Value.Name.Split('.')[0];
                    var indexOfApiGroupDot = apiBindInfo.Value.GlobalName.IndexOf(".");
                    var apiName            = apiBindInfo.Value.GlobalName.Substring(indexOfApiGroupDot + 1, apiBindInfo.Value.GlobalName.Length - indexOfApiGroupDot - 1);

                    //确保名称不会有重复
                    while (apiMethodName.ContainsKey(methodName))
                    {
                        methodName += "0";
                        apiName    += "0";
                    }
                    apiMethodName[methodName] = apiName;

                    //当前 API 的 MethodInfo
                    MethodInfo apiMethodInfo = apiBindInfo.Value.MethodInfo;
                    //当前 API 的所有参数信息
                    var parameters = apiMethodInfo.GetParameters();

                    WriteLog($"\t search API[{apiIndex}]: {keyName} > {apiBindInfo.Key} -> {methodName} \t\t Parameters Count: {parameters.Count()}\t\t", true);

                    //添加静态方法的标记
                    string showStaticApiState = null;//$"{(apiMethodInfo.IsStatic ? "_StaticApi" : "_NonStaticApi")}";

                    MethodBuilder setPropMthdBldr =
                        tb.DefineMethod(methodName /* + showStaticApiState*/, MethodAttributes.Public | MethodAttributes.Virtual,
                                        apiMethodInfo.ReturnType,                         //返回类型
                                        parameters.Select(z => z.ParameterType).ToArray() //输入参数
                                        );

                    //Controller已经使用过一次SwaggerOperationAttribute
                    var t2_3           = typeof(SwaggerOperationAttribute);
                    var tagName        = new[] { $"{keyName}:{apiBindName}" };
                    var tagAttrBuilder = new CustomAttributeBuilder(t2_3.GetConstructor(new Type[] { typeof(string), typeof(string) }),
                                                                    new object[] { (string)null, (string)null },
                                                                    new[] { t2_3.GetProperty("Tags") }, new[] { tagName });
                    setPropMthdBldr.SetCustomAttribute(tagAttrBuilder);
                    //其他Method排序方法参考:https://stackoverflow.com/questions/34175018/grouping-of-api-methods-in-documentation-is-there-some-custom-attribute

                    //TODO:

                    //[Route("/api/...", Name="xxx")]
                    var t2_4 = typeof(RouteAttribute);
                    //var routeName = apiBindInfo.Value.ApiBindAttribute.Name.Split('.')[0];
                    var apiBindGroupNamePath = apiBindName.Replace(":", "_");
                    var apiNamePath          = apiName.Replace(":", "_");
                    var apiPath          = $"/api/{keyName}/{apiBindGroupNamePath}/{apiNamePath}{showStaticApiState}";
                    var routeAttrBuilder = new CustomAttributeBuilder(t2_4.GetConstructor(new Type[] { typeof(string) }),
                                                                      new object[] { apiPath } /*, new[] { t2_2.GetProperty("Name") }, new[] { routeName }*/);
                    setPropMthdBldr.SetCustomAttribute(routeAttrBuilder);

                    //TODO:从ApiBind中自定义

                    WriteLog($"added Api path: {apiPath}", true);

                    //[HttpPost]
                    var specialMethod = apiBindInfo.Value.ApiBindAttribute.ApiRequestMethod;
                    if (specialMethod == ApiRequestMethod.GlobalDefault)
                    {
                        specialMethod = _defaultRequestMethod;//使用全局默认
                    }
                    Type tActionMethod = GetRequestMethodAttribute(specialMethod);

                    setPropMthdBldr.SetCustomAttribute(new CustomAttributeBuilder(tActionMethod.GetConstructor(new Type[0]), new object[0]));

                    //添加默认已有特性
                    if (_copyCustomAttributes)
                    {
                        //类上的自定义特性     TODO:缓存以增加效率
                        var classAttrs = CustomAttributeData.GetCustomAttributes(apiMethodInfo.DeclaringType).ToList();
                        //反转数组
                        classAttrs.Reverse();

                        //当前方法的自定义特性
                        var customAttrs = CustomAttributeData.GetCustomAttributes(apiMethodInfo).ToList();
                        foreach (var classAttr in classAttrs)
                        {
                            if (customAttrs.FirstOrDefault(z => z.AttributeType == classAttr.AttributeType) == null)
                            {
                                customAttrs.Insert(0, classAttr);
                            }
                        }

                        //叠加类和特性的方法
                        foreach (var item in customAttrs)
                        {
                            if (item.AttributeType == _typeOfApiBind)
                            {
                                continue;
                            }

                            var attrBuilder = new CustomAttributeBuilder(item.Constructor, item.ConstructorArguments.Select(z => z.Value).ToArray());
                            setPropMthdBldr.SetCustomAttribute(attrBuilder);
                        }
                    }

                    //添加用户自定义特性
                    if (AdditionalAttributeFunc != null)
                    {
                        var additionalAttrs = AdditionalAttributeFunc(apiMethodInfo);
                        if (additionalAttrs != null)
                        {
                            foreach (var item in additionalAttrs)
                            {
                                setPropMthdBldr.SetCustomAttribute(item);
                            }
                        }
                    }


                    //用户限制  ——  Jeffrey Su 2021.06.18
                    //var t4 = typeof(UserAuthorizeAttribute);//[UserAuthorize("UserOnly")]
                    //setPropMthdBldr.SetCustomAttribute(new CustomAttributeBuilder(t4.GetConstructor(new Type[] { typeof(string) }), new[] { "UserOnly" }));


                    //设置返回类型
                    //setPropMthdBldr.SetReturnType(apiMethodInfo.ReturnType);

                    //设置参数
                    var boundSourceMetadata = false; //参数使用了[FromBody]等特性标记
                    var boundClassType      = false; //参数中已经绑定了 class 复杂类型
                    //定义其他参数
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        var p = parameters[i];
                        ParameterBuilder pb = setPropMthdBldr.DefineParameter(i + 1 /*从1开始,0为返回值*/, p.Attributes, p.Name);
                        //处理参数,反之出现复杂类型的参数,抛出异常:InvalidOperationException: Action 'WeChat_OfficialAccountController.CardApi_GetOrderList (WeixinApiAssembly)' has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be bound from body. Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to specify bound from route, and 'FromBodyAttribute' for parameters to be bound from body:


                        boundSourceMetadata = boundSourceMetadata || typeof(IBindingSourceMetadata).IsAssignableFrom(p.ParameterType);

                        //复制添加单个参数上的所有特性
                        try
                        {
                            var paramAttrs = p.CustomAttributes;// CustomAttributeData.GetCustomAttributes(p.ParameterType).ToList();
                            foreach (var item in paramAttrs)
                            {
                                var attrBuilder = new CustomAttributeBuilder(item.Constructor, item.ConstructorArguments.Select(z => z.Value).ToArray());
                                pb.SetCustomAttribute(attrBuilder);
                            }
                        }
                        catch (Exception)
                        {
                            //TODO:收集错误信息
                            //throw;
                        }

                        try
                        {
                            if (p.ParameterType.IsClass && !boundClassType)
                            {
                                boundClassType = true;//第一个绑定,可以不处理
                            }
                            else if (boundClassType && !boundSourceMetadata)
                            {
                                //第二个开始使用标签     TODO:可以自定义更多的类型
                                var tFromQuery = typeof(FromQueryAttribute);
                                pb.SetCustomAttribute(new CustomAttributeBuilder(tFromQuery.GetConstructor(new Type[0]), new object[0]));
                            }

                            //if (!boundSourceMetadata && p.ParameterType.IsClass)
                            //{
                            //    if (boundClassType == false)
                            //    {

                            //    }
                            //    else
                            //    {

                            //    }
                            //}
                        }
                        catch (Exception)
                        {
                            //throw;
                        }

                        try
                        {
                            //设置默认值
                            if (p.HasDefaultValue)
                            {
                                pb.SetConstant(p.DefaultValue);
                            }
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }

                    //执行具体方法(body)
                    BuildMethodBody(apiMethodInfo, setPropMthdBldr, parameters, fbServiceProvider);

                    //var dt1 = SystemTime.Now;
                    //修改XML文档
                    await BuildXmlDoc(category, methodName, apiMethodInfo, tb);

                    //WriteLog($"methodName 文档修改耗时:{SystemTime.DiffTotalMS(dt1)}ms");
                }
                catch (Exception ex)
                {
                    //遇到错误
                    WriteLog($"==== Error ====\r\n \t{ex}");
                }
                #endregion
            }
        }
 public static IList <CustomAttributeData> GetCustomAttributesPortable(MemberInfo target) =>
 CustomAttributeData.GetCustomAttributes(target);
        public void ReadFrom(string versionInfo)
        {
            StringWriter asmInfo = new StringWriter();

            asmInfo.WriteLine("using System;");
            asmInfo.WriteLine();

            using (DisposingList disposable = new DisposingList())
            {
                if (versionInfo.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase))
                {
                    string           dir  = Path.GetDirectoryName(versionInfo);
                    XmlLightDocument proj = new XmlLightDocument(File.ReadAllText(versionInfo));
                    foreach (XmlLightElement xref in proj.Select("/Project/ItemGroup/Compile"))
                    {
                        if (!xref.Attributes.ContainsKey("Include") ||
                            !xref.Attributes["Include"].EndsWith("AssemblyInfo.cs", StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }
                        string include = xref.Attributes["Include"];
                        versionInfo = Path.Combine(dir, include);
                        break;
                    }
                    if (versionInfo.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new ApplicationException("Unable to locate AssemblyInfo.cs");
                    }
                }
                if (versionInfo.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
                {
                    _assemblyInfo = File.ReadAllText(versionInfo);

                    TempFile dll = TempFile.FromExtension(".dll");
                    disposable.Add(dll);
                    dll.Delete();

                    CSharpCodeProvider csc  = new CSharpCodeProvider();
                    CompilerParameters args = new CompilerParameters();
                    args.GenerateExecutable      = false;
                    args.IncludeDebugInformation = false;
                    args.OutputAssembly          = dll.TempPath;
                    args.ReferencedAssemblies.Add("System.dll");
                    CompilerResults results = csc.CompileAssemblyFromFile(args, versionInfo);

                    StringWriter sw = new StringWriter();
                    foreach (CompilerError ce in results.Errors)
                    {
                        if (ce.IsWarning)
                        {
                            continue;
                        }
                        String line = String.Format("{0}({1},{2}): error {3}: {4}", ce.FileName, ce.Line, ce.Column,
                                                    ce.ErrorNumber, ce.ErrorText);
                        Trace.WriteLine(line);
                        sw.WriteLine(line);
                    }
                    string errorText = sw.ToString();
                    if (errorText.Length > 0)
                    {
                        throw new ApplicationException(errorText);
                    }
                    versionInfo = dll.TempPath;
                }
                if (!File.Exists(versionInfo) || (!versionInfo.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !versionInfo.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)))
                {
                    throw new ApplicationException("Expected an existing dll: " + versionInfo);
                }

                try
                {
                    Regex truefalse = new Regex(@"(?<=[^\w_\.])(?:True)|(?:False)(?=[^\w_\.])");
                    _fileVersion = FileVersionInfo.GetVersionInfo(versionInfo);

                    if (_assemblyInfo == null)
                    {
                        Assembly asm = Assembly.ReflectionOnlyLoad(File.ReadAllBytes(versionInfo));
                        IList <CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes(asm);
                        foreach (CustomAttributeData data in attrs)
                        {
                            if (!data.ToString().StartsWith("[System.Runtime.CompilerServices."))
                            {
                                string attribute = data.ToString().Trim();
                                if (attribute[0] != '[')
                                {
                                    continue; //unexpected...
                                }
                                attribute = attribute.Insert(1, "assembly: ");
                                attribute = truefalse.Replace(attribute, delegate(Match x) { return(x.Value.ToLower()); });
                                asmInfo.WriteLine(attribute);
                            }
                        }
                    }
                }
                catch
                {
                }
            }

            _assemblyInfo = _assemblyInfo ?? asmInfo.ToString();
        }
예제 #8
0
 public Attributes(MemberInfo member, params Type[] excludedTypes)
 {
     Initialize(CustomAttributeData.GetCustomAttributes(member), excludedTypes);
 }
예제 #9
0
        /// <summary>
        /// Generate the assembly metedata attributes for the specified assembly.
        /// Will not replicate strong named attributes, as this information is not available
        /// and would be a violation of security restrictions.  Therefore, it is not entirely
        /// possible to compile against a doppleganger version of a strong-named assembly and then
        /// run the code unmodified with the actual assembly.  In order to run with a strong
        /// named assembly, the application must be compiled with that strong named assembly
        /// as a reference.  However, the doppleganger version of the assembly can still be used as
        /// a stand-in during the development cycle.  Just remember to do a final compile against
        /// the real strong named assembly before final deployment.
        /// </summary>
        /// <param name="importlib"></param>
        protected void generateAssemblyInfo(Assembly importlib)
        {
            IList <CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(importlib);
            bool hasDescriptionAttribute           = false;

            output(getApacheCopyrightAttribute());

            AssemblyName assemblyName = importlib.GetName();

            output("[assembly: System.Reflection.AssemblyVersionAttribute(\"" + assemblyName.Version + "\")]");

            foreach (CustomAttributeData attribute in attributes)
            {
                if (!shouldGenerateAttribute(attribute.Constructor.DeclaringType))
                {
                    continue;
                }

                string attributeSig = ("[assembly: " + attribute.Constructor.DeclaringType.FullName);

                if (attribute.ConstructorArguments.Count > 0)
                {
                    int argumentIndex = 0;

                    attributeSig += "(";
                    foreach (CustomAttributeTypedArgument argument in attribute.ConstructorArguments)
                    {
                        string fieldDelim = getFieldDelim(argument.ArgumentType);

                        if (argumentIndex > 0)
                        {
                            attributeSig += ", ";
                        }

                        attributeSig += fieldDelim;
                        if (argument.ArgumentType.IsEnum)
                        {
                            if (argument.Value != null)
                            {
                                foreach (object val in Enum.GetValues(argument.ArgumentType))
                                {
                                    if (val == argument.Value)
                                    {
                                        string name = Enum.GetName(argument.ArgumentType, val);

                                        attributeSig += argument.ArgumentType + name;
                                    }
                                }
                            }
                        }
                        else if (argument.ArgumentType == typeof(bool))
                        {
                            attributeSig += argument.Value.ToString().ToLower();
                        }
                        else
                        {
                            if (attribute.Constructor.DeclaringType == typeof(AssemblyDescriptionAttribute))
                            {
                                attributeSig           += assemblyDescriptionAttributeMarkup;
                                hasDescriptionAttribute = true;
                            }

                            attributeSig += argument.Value;
                        }

                        attributeSig += fieldDelim;
                        argumentIndex++;
                    }

                    attributeSig += ")";
                }

                attributeSig += "]";
                output(attributeSig);
            }

            if (!hasDescriptionAttribute)
            {
                output("[assembly: System.Reflection.AssemblyDescriptionAttribute(\""
                       + assemblyDescriptionAttributeMarkup + "\")]");
            }
        }
예제 #10
0
        /// <summary>
        /// Returns the Type of the generated Interface Proxy
        /// </summary>
        public static Type GetInterfaceProxyType(Type typeOfT)
        {
            if (TypeCache.TryGetValue(typeOfT, out Type k))
            {
                return(k);
            }
            var assemblyBuilder = GetAsmBuilder(typeOfT.Name);

            var moduleBuilder = assemblyBuilder.DefineDynamicModule("SqlMapperExtensions." + typeOfT.Name); //NOTE: to save, add "asdasd.dll" parameter
            var interfaceType = typeof(IProxy);
            var typeBuilder   = moduleBuilder.DefineType(typeOfT.Name + "_" + Guid.NewGuid(),
                                                         TypeAttributes.Public | TypeAttributes.Class);

            typeBuilder.AddInterfaceImplementation(typeOfT);
            typeBuilder.AddInterfaceImplementation(interfaceType);
            foreach (var a in CustomAttributeData.GetCustomAttributes(typeOfT))
            {
                var attrBuilder = GenerateAttributeBuilder(a);
                if (attrBuilder != null)
                {
                    typeBuilder.SetCustomAttribute(attrBuilder);
                }
            }


            //create our _isDirty field, which implements IProxy
            var setIsDirtyMethod = CreateIsDirtyProperty(typeBuilder);

            // Generate a field for each property, which implements the T
            foreach (var property in typeOfT.GetPublicProperties())
            {
                CreateProperty(typeBuilder, property.Name, property.PropertyType, setIsDirtyMethod, CustomAttributeData.GetCustomAttributes(property), typeOfT);
            }

#if NETSTANDARD2_0
            var generatedType = typeBuilder.CreateTypeInfo().AsType();
#else
            var generatedType = typeBuilder.CreateType();
#endif

            if (!TypeCache.TryAdd(typeOfT, generatedType))
            {
                if (TypeCache.TryGetValue(typeOfT, out Type k2))
                {
                    return(k2);
                }
            }
            return(generatedType);
        }
예제 #11
0
 public Attributes(ParameterInfo parameter, params Type[] excludedTypes)
 {
     Initialize(CustomAttributeData.GetCustomAttributes(parameter), excludedTypes);
 }
예제 #12
0
        public ReflectionClass(ICompilationUnit compilationUnit, Type type, string fullName, IClass declaringType) : base(compilationUnit, declaringType)
        {
            if (fullName.Length > 2 && fullName[fullName.Length - 2] == '`')
            {
                FullyQualifiedName = fullName.Substring(0, fullName.Length - 2);
            }
            else
            {
                FullyQualifiedName = fullName;
            }

            this.UseInheritanceCache = true;

            try {
                AddAttributes(compilationUnit.ProjectContent, this.Attributes, CustomAttributeData.GetCustomAttributes(type));
            } catch (Exception ex) {
                HostCallback.ShowError("Error reading custom attributes", ex);
            }

            // set classtype
            if (type.IsInterface)
            {
                this.ClassType = ClassType.Interface;
            }
            else if (type.IsEnum)
            {
                this.ClassType = ClassType.Enum;
            }
            else if (type.IsValueType)
            {
                this.ClassType = ClassType.Struct;
            }
            else if (IsDelegate(type))
            {
                this.ClassType = ClassType.Delegate;
            }
            else
            {
                this.ClassType = ClassType.Class;
                ApplySpecialsFromAttributes(this);
            }
            if (type.IsGenericTypeDefinition)
            {
                foreach (Type g in type.GetGenericArguments())
                {
                    this.TypeParameters.Add(new DefaultTypeParameter(this, g));
                }
                int i = 0;
                foreach (Type g in type.GetGenericArguments())
                {
                    AddConstraintsFromType(this.TypeParameters[i++], g);
                }
            }

            ModifierEnum modifiers = ModifierEnum.None;

            if (type.IsNestedAssembly)
            {
                modifiers |= ModifierEnum.Internal;
            }
            if (type.IsSealed)
            {
                modifiers |= ModifierEnum.Sealed;
            }
            if (type.IsAbstract)
            {
                modifiers |= ModifierEnum.Abstract;
            }

            if (type.IsNestedPrivate)                // I assume that private is used most and public last (at least should be)
            {
                modifiers |= ModifierEnum.Private;
            }
            else if (type.IsNestedFamily)
            {
                modifiers |= ModifierEnum.Protected;
            }
            else if (type.IsNestedPublic || type.IsPublic)
            {
                modifiers |= ModifierEnum.Public;
            }
            else if (type.IsNotPublic)
            {
                modifiers |= ModifierEnum.Internal;
            }
            else if (type.IsNestedFamORAssem || type.IsNestedFamANDAssem)
            {
                modifiers |= ModifierEnum.Protected;
                modifiers |= ModifierEnum.Internal;
            }
            this.Modifiers = modifiers;

            // set base classes
            if (type.BaseType != null)               // it's null for System.Object ONLY !!!
            {
                BaseTypes.Add(ReflectionReturnType.Create(this, type.BaseType, false));
            }

            foreach (Type iface in type.GetInterfaces())
            {
                BaseTypes.Add(ReflectionReturnType.Create(this, iface, false));
            }

            InitMembers(type);
        }
예제 #13
0
        /// <summary>
        /// Analyzes an assembly to read its attributes.
        /// </summary>
        /// <param name="assemblyFile">Path to the assembly.</param>
        /// <returns>Attributes from the assembly.</returns>
        public static AssemblyAttributes ReadAssembly(string assemblyFile)
        {
            AssemblyAttributes attribs = new AssemblyAttributes();

            attribs.FileName = new FileInfo(assemblyFile).Name;

            Assembly reflectedAssembly;

            try
            {
                reflectedAssembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile);
            }
            catch (BadImageFormatException)
            {
                // Not a valid asssembly
                attribs.IsManagedAssembly = false;
                return(attribs);
            }
            catch (FileLoadException)
            {
                // Not a .Net managed assembly
                attribs.IsManagedAssembly = false;
                return(attribs);
            }

            attribs.IsManagedAssembly = true;

            // If the 'DebuggableAttribute' is not found then it is definitely an OPTIMIZED build
            attribs.BuildType   = "Release";
            attribs.DebugOutput = "Full";

            attribs.Version = reflectedAssembly.GetName().Version;

            IList <CustomAttributeData> list = CustomAttributeData.GetCustomAttributes(reflectedAssembly);

            foreach (CustomAttributeData data in list)
            {
                if (data.AttributeType == typeof(DebuggableAttribute))
                {
                    attribs.HasDebuggableAttribute = true;

                    // Just because the 'DebuggableAttribute' is found doesn't necessarily mean
                    // it's a DEBUG build; we have to check the JIT Optimization flag
                    // i.e. it could have the "generate PDB" checked but have JIT Optimization enabled
                    DebuggingModes modes = (DebuggingModes)data.ConstructorArguments[0].Value;
                    attribs.IsJitOptimized = (modes & DebuggingModes.DisableOptimizations) != DebuggingModes.DisableOptimizations;
                    attribs.BuildType      = attribs.IsJitOptimized ? "Release" : "Debug";

                    // check for Debug Output "full" or "pdb-only"
                    attribs.DebugOutput = (modes & DebuggingModes.Default) != DebuggingModes.None ? "Full" : "pdb-only";

                    continue;
                }
                else if (data.AttributeType == typeof(AssemblyFileVersionAttribute))
                {
                    Version ver;
                    if (Version.TryParse((string)data.ConstructorArguments[0].Value, out ver))
                    {
                        attribs.FileVersion = ver;
                    }
                }
                else if (data.AttributeType == typeof(AssemblyCompanyAttribute))
                {
                    attribs.Company = (string)data.ConstructorArguments[0].Value;
                }
                else if (data.AttributeType == typeof(AssemblyCopyrightAttribute))
                {
                    attribs.Copyright = (string)data.ConstructorArguments[0].Value;
                }
            }

            ////object[] customAttribs = reflectedAssembly.GetCustomAttributes(typeof(DebuggableAttribute), false);

            ////// If the 'DebuggableAttribute' is not found then it is definitely an OPTIMIZED build
            ////if (customAttribs.Length > 0)
            ////{
            ////    // Just because the 'DebuggableAttribute' is found doesn't necessarily mean
            ////    // it's a DEBUG build; we have to check the JIT Optimization flag
            ////    // i.e. it could have the "generate PDB" checked but have JIT Optimization enabled
            ////    DebuggableAttribute debuggableAttribute = customAttribs[0] as DebuggableAttribute;
            ////    if (debuggableAttribute != null)
            ////    {
            ////        attribs.HasDebuggableAttribute = true;
            ////        attribs.IsJitOptimized = !debuggableAttribute.IsJITOptimizerDisabled;
            ////        attribs.BuildType = attribs.IsJitOptimized ? "Release" : "Debug";

            ////        // check for Debug Output "full" or "pdb-only"
            ////        attribs.DebugOutput = (debuggableAttribute.DebuggingFlags & DebuggableAttribute.DebuggingModes.Default) != DebuggableAttribute.DebuggingModes.None ? "Full" : "pdb-only";
            ////    }
            ////}
            ////else
            ////{
            ////    attribs.BuildType = "Release";
            ////    attribs.DebugOutput = "Full";
            ////}

            ////customAttribs = reflectedAssembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
            ////if (customAttribs.Length > 0)
            ////{
            ////    attribs.FileVersion = Version.Parse((customAttribs[0] as AssemblyFileVersionAttribute).Version);
            ////}

            ////attribs.Version = reflectedAssembly.GetName().Version;

            ////customAttribs = reflectedAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
            ////if (customAttribs.Length > 0)
            ////{
            ////    attribs.Company = (customAttribs[0] as AssemblyCompanyAttribute).Company;
            ////}

            ////customAttribs = reflectedAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
            ////if (customAttribs.Length > 0)
            ////{
            ////    attribs.Copyright = (customAttribs[0] as AssemblyCopyrightAttribute).Copyright;
            ////}

            return(attribs);
        }
        /// <summary>
        ///     Discovers types (and their declaring assemblies) that are decorated with the
        ///     <see cref="ServedClassNameAttribute" />, which identifies an ASCOM driver that should be served
        ///     by the LocalServer.
        /// </summary>
        /// <remarks>
        ///     Assemblies are loaded using <see cref="Assembly.ReflectionOnlyLoad(string)" /> to prevent any code execution.
        ///     This would otherwise be a potential malware attack vector, since untrusted assemblies would be loaded and
        ///     potentially into
        ///     a privileged user context. If any of the loaded assemblies must later execute, then this operation should be
        ///     performed
        ///     in an isolated application domain so that the domain and all the loaded assemblies can later be unloaded. Unloaing
        ///     an entire
        ///     AppDomain is the only way to remove assemblies from memory.
        ///     The class inherits from <see cref="MarshalByRefObject" /> specifically so that it can be proxied across an
        ///     App Domain boundary.
        /// </remarks>
        /// <seealso cref="AppDomainIsolated{TWorker}" />
        public void DiscoverServedClasses()
        {
            Log.Info("Loading served COM classes");

            // put everything into one folder, the same as the server.
            string assyPath = Assembly.GetExecutingAssembly().Location;

            assyPath = Path.GetDirectoryName(assyPath);
            Log.Debug($"Assembly load path is {assyPath}");

            var d         = new DirectoryInfo(assyPath);
            var fileInfos = d.GetFiles("*.dll");

            Log.Debug($"Discovered {fileInfos.Length} candidate assemblies");
            try
            {
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += HandleReflectionOnlyAssemblyResolve;
                foreach (var fi in fileInfos)
                {
                    Log.Trace($"Examining types in {fi.Name}");
                    string aPath = fi.FullName;
                    try
                    {
                        Log.Trace($"Attempting reflection only load for {aPath}");
                        var    so          = Assembly.ReflectionOnlyLoad(Path.GetFileNameWithoutExtension(fi.Name));
                        string soShortName = so.GetName().Name;
                        var    types       = so.GetTypes();
                        Log.Trace($"Reflection found {types.Length} types in assembly {so.FullName}");
                        var servedClasses = from type in types.AsParallel()
                                            let memberInfo = (MemberInfo)type
                                                             let safeAttributes = CustomAttributeData.GetCustomAttributes(memberInfo)
                                                                                  where safeAttributes.Any(
                            p => p.AttributeType.Name == nameof(ServedClassNameAttribute))
                                                                                  select type;
                        var discoveredTypes = servedClasses.ToList();
                        if (discoveredTypes.Any())
                        {
                            DiscoveredTypes.AddRange(discoveredTypes);
                            DiscoveredAssemblyNames.Add(so.FullName);
                            Log.Warn($"Discovered {discoveredTypes.Count} served clases in assembly {soShortName}");
                        }
                    }
                    catch (BadImageFormatException ex)
                    {
                        Log.Warn(ex, $"BadImageFormat: {fi.Name}.{fi.Extension} continuing");

                        // Probably an attempt to load a Win32 DLL (i.e. not a .net assembly)
                        // Just swallow the exception and continue to the next item.
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, $"Unexpected error processing {fi.Name}: {ex.Message}");

                        // return false;
                    }
                }
            }
            finally
            {
                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= HandleReflectionOnlyAssemblyResolve;
            }
        }
예제 #15
0
        public ReflectionMethod(MethodBase methodBase, ReflectionClass declaringType)
            : base(declaringType, methodBase is ConstructorInfo ? "#ctor" : methodBase.Name)
        {
            if (methodBase is MethodInfo)
            {
                this.ReturnType = ReflectionReturnType.Create(this, ((MethodInfo)methodBase).ReturnType, false);
            }
            else if (methodBase is ConstructorInfo)
            {
                this.ReturnType = DeclaringType.DefaultReturnType;
            }

            foreach (ParameterInfo paramInfo in methodBase.GetParameters())
            {
                this.Parameters.Add(new ReflectionParameter(paramInfo, this));
            }

            if (methodBase.IsGenericMethodDefinition)
            {
                foreach (Type g in methodBase.GetGenericArguments())
                {
                    this.TypeParameters.Add(new DefaultTypeParameter(this, g));
                }
                int i = 0;
                foreach (Type g in methodBase.GetGenericArguments())
                {
                    declaringType.AddConstraintsFromType(this.TypeParameters[i++], g);
                }
            }

            ModifierEnum modifiers = ModifierEnum.None;

            if (methodBase.IsStatic)
            {
                modifiers |= ModifierEnum.Static;
            }
            if (methodBase.IsPrivate)               // I assume that private is used most and public last (at least should be)
            {
                modifiers |= ModifierEnum.Private;
            }
            else if (methodBase.IsFamily || methodBase.IsFamilyOrAssembly)
            {
                modifiers |= ModifierEnum.Protected;
            }
            else if (methodBase.IsPublic)
            {
                modifiers |= ModifierEnum.Public;
            }
            else
            {
                modifiers |= ModifierEnum.Internal;
            }

            if (methodBase.IsVirtual)
            {
                modifiers |= ModifierEnum.Virtual;
            }
            if (methodBase.IsAbstract)
            {
                modifiers |= ModifierEnum.Abstract;
            }
            if (methodBase.IsFinal)
            {
                modifiers |= ModifierEnum.Sealed;
            }
            this.Modifiers = modifiers;

            ReflectionClass.AddAttributes(declaringType.ProjectContent, this.Attributes, CustomAttributeData.GetCustomAttributes(methodBase));
            ApplySpecialsFromAttributes(this);
        }
예제 #16
0
        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);
            }
        }
예제 #17
0
        public static MergeArgType Create(MethodInfo method, List <string> pathQueryParams)
        {
            //GetFirstLevelParams
            var(firstLevelParams, isSingleValue, singleValue) = InnerType.GetFirstLevelParams(method);

            string?  streamName  = null;
            TypeName?action      = null;
            TypeName?cancelToken = null;

            //paramName
            string typeNameWithoutStreamName;
            string typeName;

            if (isSingleValue)
            {
                typeNameWithoutStreamName = GetName(singleValue !.ParameterType.Name);
                typeName = GetName(singleValue !.ParameterType.Name);
            }
            else
            {
                typeNameWithoutStreamName = GetName($"{method.Name}Param");
                typeName = GetName($"{method.Name}Param");
            }

            //cis
            var cis           = new List <CustomsPropertyInfo>();
            var attributeData = CustomAttributeData.GetCustomAttributes(method).Where(i => i.AttributeType == typeof(ExampleAttribute)).ToList();
            var addedCallId   = false;
            var addedStream   = false;
            var hasCustomType = false;

            foreach (var p in firstLevelParams)
            {
                //callback
                if (p.Type.IsFuncT())
                {
                    action      = new TypeName(p.Name !, p.Type);
                    addedCallId = true;
                    continue;
                }

                //cancel
                if (p.Type.IsCancellationToken())
                {
                    cancelToken = new TypeName(p.Name !, p.Type);
                    addedCallId = true;
                    continue;
                }

                //hasCustomType
                hasCustomType = true;

                //Stream
                if (p.Type.IsStream())
                {
                    streamName  = p.Name;
                    addedStream = true;
                    continue;
                }

                //Custom Type
                //ExampleAttribute
                var found = FindCustomAttributeData(attributeData, p);
                if (found != null)
                {
                    cis.Add(new CustomsPropertyInfo(p.Type, p.Name !, found));
                }
                else
                {
                    cis.Add(new CustomsPropertyInfo(p.Type, p.Name !));
                }
            }

            //connectionId callId
            if (addedCallId)
            {
                cis.Add(new CustomsPropertyInfo(typeof(string), CallConst.ConnIdName));
                cis.Add(new CustomsPropertyInfo(typeof(string), CallConst.CallIdName));
            }

            //StreamLength
            if (addedStream)
            {
                cis.Add(new CustomsPropertyInfo(typeof(long), CallConst.StreamLength));
            }

            var t  = TypeFactory.BuildType(typeName, cis);
            var t2 = BuildTypeWithoutPathQueryStream(typeNameWithoutStreamName, cis, pathQueryParams);

            if (cis.Count == 0)
            {
                return(new MergeArgType(null, null, null, null, null,
                                        false, false, null, method));
            }

            //SetInnerTypeMap
            SetInnerTypeMap(t2, isSingleValue, singleValue !);

            return(new MergeArgType(t, t2, streamName, action, cancelToken, hasCustomType, isSingleValue, singleValue, method));
        }
        /// <summary>
        /// 返回如果在成员中涉及这种类型是否要跳过
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsSkipType(Type type, bool includeref = false)
        {
            if (type == null)
            {
                return(true);
            }
            var c = CustomAttributeData.GetCustomAttributes(type);

            foreach (CustomAttributeData item in c)
            {
                if (item.Constructor.DeclaringType == typeof(System.ObsoleteAttribute))
                {
                    return(true);
                }
            }

            //object[] objs = type.GetCustomAttributes(typeof(System.ObsoleteAttribute), false);

            //if (objs.Length > 0)
            //{
            //	return true;
            //}



            if (Equals(type, typeof(Type)))             //Type会转换为Class
            {
                return(false);
            }

            if (type.IsCOMObject)
            {
                return(true);
            }

            if (Equals(type, typeof(Enum)))
            {
                return(true);
            }

            if (type.IsNested && !type.IsNestedPublic)
            {
                return(true);
            }

            if (type.IsEnum)
            {
                foreach (var item in NotCreateNameSpace)
                {
                    if (type.Namespace == item)
                    {
                        return(true);
                    }
                    if (type.Namespace.StartsWith(item + "."))
                    {
                        return(true);
                    }
                }

                if (NotCreateTypes.Contains(type.FullName))
                {
                    return(true);
                }
                return(false);
            }


            if (type.IsByRef)
            {
                if (!includeref)
                {
                    return(true);
                }
                else if (type.HasElementType)
                {
                    return(IsSkipType(type.GetElementType()));
                }
            }



            if (type.IsNotPublic)
            {
                return(true);
            }

            if (type.IsNested)
            {
                if (IsSkipType(type.DeclaringType))
                {
                    return(true);
                }
            }

            if (type.IsGenericTypeDefinition)
            {
                return(true);
            }
            if (type.IsGenericType && type.IsInterface)
            {
                return(true);
            }


            if (type.IsArray)
            {
                return(IsSkipType(type.GetElementType()));
            }

            if (type.Namespace == null)
            {
                return(true);
            }

            foreach (var item in NotCreateNameSpace)
            {
                if (type.Namespace == item)
                {
                    return(true);
                }
                if (type.Namespace.StartsWith(item + "."))
                {
                    return(true);
                }
            }

            if (NotCreateTypes.Contains(type.FullName))
            {
                return(true);
            }

            if (IsDelegate(type))
            {
                var m = GetDelegateMethodInfo(type);
                //***如果该委托包含要跳过的类型,则跳过****
                if (m.IsGenericMethod)
                {
                    return(true);
                }

                if (m.ReturnType.IsGenericTypeDefinition)
                {
                    return(true);
                }

                var rt = MethodNativeCodeCreator.GetAS3Runtimetype(m.ReturnType);
                if (rt > ASBinCode.RunTimeDataType.unknown)
                {
                    if (IsSkipType(m.ReturnType))
                    {
                        return(true);
                    }
                }

                var paras = m.GetParameters();
                foreach (var p in paras)
                {
                    if (p.IsOut)
                    {
                        return(true);
                    }
                    if (p.ParameterType.IsByRef)
                    {
                        return(true);
                    }
                    //if (p.ParameterType.IsGenericType)
                    if (p.ParameterType.IsGenericTypeDefinition)
                    {
                        return(true);
                    }

                    if (p.IsOptional)
                    {
                        if (p.RawDefaultValue != null)
                        {
                            var rrt = MethodNativeCodeCreator.GetAS3Runtimetype(p.ParameterType);
                            if (rrt > ASBinCode.RunTimeDataType.unknown)
                            {
                                return(true);
                            }
                        }
                    }

                    if (IsSkipType(p.ParameterType))
                    {
                        return(true);
                    }
                }

                return(false);
            }



            if (Equals(type, typeof(TypedReference)))
            {
                return(true);
            }

            if (type.BaseType != null)
            {
                return(IsSkipType(type.BaseType));
            }

            return(false);
        }
예제 #19
0
        //straight copy from vvvv-sdk
        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);
        }
예제 #20
0
 public override IList <CustomAttributeData> GetCustomAttributesData() => CustomAttributeData.GetCustomAttributes(this);
예제 #21
0
        private void GetPropertyDrawerType(SerializedProperty property)
        {
            if (_genericDrawerInstance != null)
            {
                return;
            }

            //Get the second attribute flag
            try
            {
                _genericAttribute = (PropertyAttribute)fieldInfo.GetCustomAttributes(typeof(PropertyAttribute), false)[1];

                if (_genericAttribute is ContextMenuItemAttribute)
                {
                    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
            {
                _genericDrawerType = _typesCache.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
            {
                _genericDrawerInstance = (PropertyDrawer)Activator.CreateInstance(_genericDrawerType);
                //Get arguments
                IList <CustomAttributeTypedArgument> attributeParams = fieldInfo.GetCustomAttributesData()[1].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
            {
                _genericDrawerType.GetField("m_Attribute", BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(_genericDrawerInstance, _genericAttribute);
            }
            catch (Exception e)
            {
                LogWarning("Unable to assign attribute to " + _genericDrawerInstance.GetType() + " : " + e, property);
            }
        }
예제 #22
0
        /// <summary>
        /// Get custom attributes on a member for both normal and reflection only load.
        /// </summary>
        /// <param name="memberInfo">Member for which attributes needs to be retrieved.</param>
        /// <param name="type">Type of attribute to retrieve.</param>
        /// <param name="inherit">If inherited type of attribute.</param>
        /// <returns>All attributes of give type on member.</returns>
        internal object[] GetCustomAttributes(MemberInfo memberInfo, Type type, bool inherit)
        {
            if (memberInfo == null)
            {
                return(null);
            }

            bool shouldGetAllAttributes = type == null;

            if (!this.IsReflectionOnlyLoad(memberInfo))
            {
                if (shouldGetAllAttributes)
                {
                    return(memberInfo.GetCustomAttributes(inherit));
                }
                else
                {
                    return(memberInfo.GetCustomAttributes(type, inherit));
                }
            }
            else
            {
                List <object> nonUniqueAttributes            = new List <object>();
                Dictionary <string, object> uniqueAttributes = new Dictionary <string, object>();

                var inheritanceThreshold = 10;
                var inheritanceLevel     = 0;

                if (inherit && memberInfo.MemberType == MemberTypes.TypeInfo)
                {
                    // This code is based on the code for fetching CustomAttributes in System.Reflection.CustomAttribute(RuntimeType type, RuntimeType caType, bool inherit)
                    var tempTypeInfo = memberInfo as TypeInfo;

                    do
                    {
                        var attributes = CustomAttributeData.GetCustomAttributes(tempTypeInfo);
                        this.AddNewAttributes(
                            attributes,
                            shouldGetAllAttributes,
                            type,
                            uniqueAttributes,
                            nonUniqueAttributes);
                        tempTypeInfo = tempTypeInfo.BaseType?.GetTypeInfo();
                        inheritanceLevel++;
                    }while (tempTypeInfo != null && tempTypeInfo != typeof(object).GetTypeInfo() &&
                            inheritanceLevel < inheritanceThreshold);
                }
                else if (inherit && memberInfo.MemberType == MemberTypes.Method)
                {
                    // This code is based on the code for fetching CustomAttributes in System.Reflection.CustomAttribute(RuntimeMethodInfo method, RuntimeType caType, bool inherit).
                    var tempMethodInfo = memberInfo as MethodInfo;

                    do
                    {
                        var attributes = CustomAttributeData.GetCustomAttributes(tempMethodInfo);
                        this.AddNewAttributes(
                            attributes,
                            shouldGetAllAttributes,
                            type,
                            uniqueAttributes,
                            nonUniqueAttributes);
                        var baseDefinition = tempMethodInfo.GetBaseDefinition();

                        if (baseDefinition != null)
                        {
                            if (string.Equals(
                                    string.Concat(tempMethodInfo.DeclaringType.FullName, tempMethodInfo.Name),
                                    string.Concat(baseDefinition.DeclaringType.FullName, baseDefinition.Name)))
                            {
                                break;
                            }
                        }

                        tempMethodInfo = baseDefinition;
                        inheritanceLevel++;
                    }while (tempMethodInfo != null && inheritanceLevel < inheritanceThreshold);
                }
                else
                {
                    // Ideally we should not be reaaching here. We only query for attributes on types/methods currently.
                    // Return the attributes that CustomAttributeData returns in this cases not considering inheritance.
                    var firstLevelAttributes =
                        CustomAttributeData.GetCustomAttributes(memberInfo);
                    this.AddNewAttributes(firstLevelAttributes, shouldGetAllAttributes, type, uniqueAttributes, nonUniqueAttributes);
                }

                nonUniqueAttributes.AddRange(uniqueAttributes.Values);
                return(nonUniqueAttributes.ToArray());
            }
        }
예제 #23
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);
    }
예제 #24
0
 public static IList <CustomAttributeData> GetCustomAttributeData(this PropertyInfo prop)
 {
     return(CustomAttributeData.GetCustomAttributes(prop));
 }
예제 #25
0
 public bool Exclude(Type type)
 {
     return(CustomAttributeData.GetCustomAttributes(type).Any(a => a.AttributeType == typeof(TAttribute)));
 }
예제 #26
0
 public static IList <CustomAttributeData> GetCustomAttributeData(this MethodInfo method)
 {
     return(CustomAttributeData.GetCustomAttributes(method));
 }
예제 #27
0
파일: MonoType.cs 프로젝트: tpetazzoni/mono
 public override IList <CustomAttributeData> GetCustomAttributesData()
 {
     return(CustomAttributeData.GetCustomAttributes(this));
 }
예제 #28
0
            public void ProcessApplicationAssemblies(ProcessArgument args)
            {
                try
                {
#if !WINDOWS_PHONE && !iOS && !ANDROID
                    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ReflectionOnlyAssemblyResolve;

                    if (args.loadedDomains != null)
                    {
                        foreach (var domain in args.loadedDomains)
                        {
                            try
                            {
                                AppDomain.CurrentDomain.Load(domain);
                            }
                            catch (FileNotFoundException) { }
                        }
                    }
#endif

                    //Store the serializer and processor types as we will need then repeatedly
                    var serializerType = typeof(DPSBase.DataSerializer);
                    var processorType  = typeof(DPSBase.DataProcessor);

                    //We're now going to look through the assemly reference tree to look for more components
                    //This will be done by first checking whether a relefection only load of each assembly and checking
                    //for reference to DPSBase.  We will therefore get a reference to DPSBase
                    var dpsBaseAssembly = typeof(DPSManager).Assembly;

                    //Loop through all loaded assemblies looking for types that are not abstract and implement DataProcessor or DataSerializer.  They also need to have a paramterless contstructor
                    var alreadyLoadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();

                    //We are also going to keep a track of all assemblies with which we have considered types within
                    var dicOfSearchedAssemblies = new Dictionary <string, Assembly>();

                    //And all the assembly names we have tried to load
                    var listofConsideredAssemblies = new List <string>();

                    foreach (var ass in alreadyLoadedAssemblies)
                    {
#if WINDOWS_PHONE || iOS || ANDROID
#else
                        foreach (var refAss in ass.GetReferencedAssemblies())
                        {
                            if (AssemblyComparer.Instance.Equals(dpsBaseAssembly.GetName(), refAss) || ass == dpsBaseAssembly)
                            {
#endif
                        foreach (var type in ass.GetTypes())
                        {
                            byte id;
                            var  attributes = type.GetCustomAttributes(typeof(DataSerializerProcessorAttribute), false);

                            if (attributes.Length == 1)
                            {
                                id = (attributes[0] as DataSerializerProcessorAttribute).Identifier;
                            }
                            else
                            {
                                continue;
                            }

                            if (serializerType.IsAssignableFrom(type) && !type.IsAbstract &&
                                (type.GetConstructors(BindingFlags.Instance).Length != 0 || type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Length != 0))
                            {
                                //SerializersByType.Add(type, null);
                                //DataSerializerIdToType.Add(id, type);
                                serializerTypes.Add(id, type.AssemblyQualifiedName);
                            }

                            if (processorType.IsAssignableFrom(type) && !type.IsAbstract &&
                                (type.GetConstructors(BindingFlags.Instance).Length != 0 || type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Length != 0))
                            {
                                //DataProcessorsByType.Add(type, null);
                                //DataProcessorIdToType.Add(id, type);
                                processorTypes.Add(id, type.AssemblyQualifiedName);
                            }
                        }
#if WINDOWS_PHONE || iOS || ANDROID
#else
                        break;
                    }
                }
#endif
                        dicOfSearchedAssemblies.Add(ass.FullName, ass);
                    }

#if WINDOWS_PHONE || iOS || ANDROID
#else
                    //Set an identifier to come back to as we load assemblies
AssemblySearchStart:

                    //Loop through all assemblies
                    foreach (var pair in dicOfSearchedAssemblies)
                    {
                        var assembly = pair.Value;

                        //Loop through the assemblies this assemlby references
                        foreach (var referencedAssembly in assembly.GetReferencedAssemblies())
                        {
                            //If we've already tried this assembly name then keep going.  Otherwise record that we will have tried this assembly
                            if (listofConsideredAssemblies.Contains(referencedAssembly.FullName))
                            {
                                continue;
                            }
                            else
                            {
                                listofConsideredAssemblies.Add(referencedAssembly.FullName);
                            }

                            Assembly refAssembly = null;

                            //Occationally assemblies will not resolve (f**k knows why).  They will then throw a FileNotFoundException that we can catch and ignore
                            try
                            {
                                //Do a reflection only load of the assembly so that we can see if it references DPSBase and also what it does reference
                                refAssembly = System.Reflection.Assembly.ReflectionOnlyLoad(referencedAssembly.FullName);
                            }
                            catch (FileNotFoundException)
                            { continue; }

                            //Note that multiple assembly names/versions could resolve to this assembly so check if we're already considered the actual
                            //loaded assembly
                            if (!dicOfSearchedAssemblies.ContainsKey(refAssembly.FullName))
                            {
                                //if not add it to the considered list
                                dicOfSearchedAssemblies.Add(refAssembly.FullName, refAssembly);

                                //if it references DPSBase directly it might contain components. Add the assembly to the catalog
                                foreach (var refAss in refAssembly.GetReferencedAssemblies())
                                {
                                    if (AssemblyComparer.Instance.Equals(dpsBaseAssembly.GetName(), refAss))
                                    {
                                        foreach (var type in refAssembly.GetTypes())
                                        {
                                            bool idSet = false;
                                            byte id    = 0;
                                            //var attributes = type.GetCustomAttributes(typeof(DataSerializerProcessorAttribute), false);
                                            var attributes = CustomAttributeData.GetCustomAttributes(type);

                                            foreach (var attr in attributes)
                                            {
                                                if (attr.Constructor.ReflectedType.AssemblyQualifiedName == typeof(DataSerializerProcessorAttribute).AssemblyQualifiedName)
                                                {
                                                    id    = (byte)attr.ConstructorArguments[0].Value;
                                                    idSet = true;
                                                }
                                            }

                                            if (!idSet)
                                            {
                                                continue;
                                            }

                                            Type baseType = type.BaseType;

                                            while (baseType != null)
                                            {
                                                if (baseType.AssemblyQualifiedName == serializerType.AssemblyQualifiedName)
                                                {
                                                    //SerializersByType.Add(type, null);
                                                    //DataSerializerIdToType.Add(id, type);
                                                    serializerTypes.Add(id, type.AssemblyQualifiedName);
                                                    break;
                                                }

                                                if (baseType.AssemblyQualifiedName == processorType.AssemblyQualifiedName)
                                                {
                                                    //DataProcessorsByType.Add(type, null);
                                                    //DataProcessorIdToType.Add(id, type);
                                                    processorTypes.Add(id, type.AssemblyQualifiedName);
                                                    break;
                                                }

                                                baseType = baseType.BaseType;
                                            }
                                        }

                                        break;
                                    }
                                }

                                //We're changed allAssemblies and loadedAssemblies so restart
                                goto AssemblySearchStart;
                            }
                        }
                    }
#endif
                }
                catch (Exception)
                {
                    //int i = 1;

                    //using (StreamWriter sw = new StreamWriter("DPSManagerLoadError.txt", false))
                    //Console.WriteLine(ex.ToString());
                }
                finally
                {
                    args.processorTypes  = processorTypes;
                    args.serializerTypes = serializerTypes;
                }
            }
예제 #29
0
    static int Main(string[] args)
    {
/* Re-enable once the fix to https://github.com/dotnet/msbuild/issues/6734 propagates to this repo.
 *      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);
    }
 public static void AsTextAttributes(CodeWriter writer, ParameterInfo parameterInfo, AttributeTarget attributeTarget)
 {
     // Use the static method to get the attributes so that this works with types from reflection-only assemblies
     AsTextAttributes(writer, CustomAttributeData.GetCustomAttributes(parameterInfo), attributeTarget);
 }