System.Reflection.MemberInfo.GetCustomAttributesData()

Here are the examples of the csharp api System.Reflection.MemberInfo.GetCustomAttributesData() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

71 Examples 7

19 Source : WrappedMethodInfo.cs
with MIT License
from Aragas

public override IList<CustomAttributeData> GetCustomAttributesData() => _methodInfoImplementation.GetCustomAttributesData();

19 Source : WrappedPropertyInfo.cs
with MIT License
from Aragas

public override IList<CustomAttributeData> GetCustomAttributesData() => _propertyInfoImplementation.GetCustomAttributesData();

19 Source : ReflectionFacade.cs
with Apache License 2.0
from AutomateThePlanet

public IEnumerable<CustomAttributeData> GetCustomAttributesData(Type type) => type.GetCustomAttributesData();

19 Source : NativeTestsRunnerTestCasesPluginService.cs
with Apache License 2.0
from AutomateThePlanet

public void ExtractAllTestCasesFromTestLibrary(string testLibraryPath)
        {
            try
            {
                var replacedembly = GetreplacedemblyFromFile(testLibraryPath);

                foreach (var currentType in replacedembly.GetTypes())
                {
                    if (currentType.GetCustomAttributesData().Any(x => x.ToString().Contains(MsTestClreplacedAttributeName)))
                    {
                        foreach (var currentMethod in currentType.GetMethods())
                        {
                            if (currentMethod.GetCustomAttributes().Any(x => x.GetType().FullName.Equals(MsTestTestAttributeName)))
                            {
                                var currentTestCase = string.Concat(currentMethod?.ReflectedType?.FullName, ".", currentMethod.Name);
                                Console.WriteLine(currentTestCase);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

19 Source : TypeBuilderHelper.cs
with MIT License
from awesomedotnetcore

public static TypeConfig GetConfig(Type type)
        {
            TypeConfig typeConfig = new TypeConfig
            {
                FullName = type.FullName,
                replacedemblyName = type.replacedembly.FullName,
                Attributes = GetAttributeConfigs(type),
                Properties = type.GetProperties().Select(x => new PropertyConfig
                {
                    PropertyName = x.Name,
                    Attributes = GetAttributeConfigs(x),
                    PropertyType = x.PropertyType
                }).ToList()
            };

            return typeConfig;

            List<AttributeConfig> GetAttributeConfigs(MemberInfo theType)
            {
                return theType.GetCustomAttributesData().Select(y => new AttributeConfig
                {
                    Attribute = y.AttributeType,
                    ConstructorArgs = y.ConstructorArguments.Select(x => x.Value).ToList(),
                    Properties = y.NamedArguments.Select(x => (x.MemberName, x.TypedValue.Value)).ToList()
                }).ToList();
            }
        }

19 Source : EnhancedStackTrace.Frames.cs
with Apache License 2.0
from benaadams

private static bool IsStackTraceHidden(MemberInfo memberInfo)
        {
            if (StackTraceHiddenAttributeType is not null && !memberInfo.Module.replacedembly.ReflectionOnly)
            {
                return memberInfo.GetCustomAttributes(StackTraceHiddenAttributeType, false).Length != 0;
            }

            EnumerableIList<CustomAttributeData> attributes;
            try
            {
                attributes = EnumerableIList.Create(memberInfo.GetCustomAttributesData());
            }
            catch (NotImplementedException)
            {
                return false;
            }

            foreach (var attribute in attributes)
            {
                // reflection-only attribute, match on name
                if (attribute.AttributeType.FullName == StackTraceHiddenAttributeType?.FullName)
                {
                    return true;
                }
            }

            return false;
        }

19 Source : TypeDefinitionProvider.cs
with MIT License
from bonsai-rx

static CodeTypeMember GetPropertyDeclaration(PropertyInfo property, HashSet<string> importNamespaces, HashSet<MethodInfo> getterSetters)
        {
            var declaration = new CodeMemberProperty();
            declaration.Name = property.Name;
            declaration.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            var attributes = property.GetCustomAttributesData()
                .Select(a => GetAttributeDeclaration(a, importNamespaces))
                .ToArray();
            declaration.CustomAttributes.AddRange(attributes);

            var getter = property.GetGetMethod();
            if (getter != null)
            {
                declaration.HasGet = true;
                getterSetters.Add(getter);
            }
            else declaration.HasGet = false;

            var setter = property.GetSetMethod();
            if (setter != null)
            {
                declaration.Hreplacedet = true;
                getterSetters.Add(setter);
            }
            else declaration.Hreplacedet = false;

            declaration.Type = GetTypeReference(property.PropertyType, importNamespaces);
            return declaration;
        }

19 Source : TypeDefinitionProvider.cs
with MIT License
from bonsai-rx

static CodeTypeDeclaration GetTypeDeclaration(Type type, HashSet<string> importNamespaces)
        {
            var getterSetters = new HashSet<MethodInfo>();
            var declaration = new CodeTypeDeclaration(type.Name);
            if (type.IsGenericType)
            {
                var genericSeparatorIndex = type.Name.LastIndexOf('`');
                declaration.Name = type.Name.Substring(0, genericSeparatorIndex);
                var typeParameters = type.GetGenericArguments();
                AddGenericTypeParameters(declaration.TypeParameters, typeParameters, importNamespaces);
            }

            var attributes = type.GetCustomAttributesData()
                .Select(a => GetAttributeDeclaration(a, importNamespaces))
                .ToArray();

            if (type.BaseType != null && type.BaseType != typeof(object))
            {
                declaration.BaseTypes.Add(GetTypeReference(type.BaseType, importNamespaces));
            }

            var interfaces = type.GetInterfaces();
            if (interfaces.Length > 0)
            {
                declaration.BaseTypes.AddRange(Array.ConvertAll(interfaces, i => GetTypeReference(i, importNamespaces)));
            }

            var properties = type.GetProperties().Select(p => GetPropertyDeclaration(p, importNamespaces, getterSetters));
            var methods = type.GetMethods().Except(getterSetters).Select(m => GetMethodDeclaration(m, importNamespaces));
            var members = properties.Concat(methods).Where(declaration => declaration != null).ToArray();
            declaration.CustomAttributes.AddRange(attributes);
            declaration.Members.AddRange(members);
            return declaration;
        }

19 Source : Util.cs
with GNU General Public License v3.0
from CheezLang

[SkipInStackFrameAttribute]
        [DebuggerStepThrough]
        [System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Exception not required. This is for error reporting only.")]
        public static (string function, string file, int line)? GetCallingFunction()
        {
            try
            {
                var trace = new StackTrace(true);
                var frames = trace.GetFrames();

                foreach (var frame in frames)
                {
                    var method = frame.GetMethod();
                    var attribute = method.GetCustomAttributesData().FirstOrDefault(d => d.AttributeType == typeof(SkipInStackFrameAttribute));
                    if (attribute != null)
                        continue;

                    return (method.Name, frame.GetFileName(), frame.GetFileLineNumber());
                }
            }
            catch (Exception)
            { }

            return null;
        }

19 Source : NullableHelper.cs
with MIT License
from ChilliCream

private static NullableContextAttribute? GetNullableContextAttribute(
        MemberInfo member) =>
        GetNullableContextAttribute(member.GetCustomAttributesData());

19 Source : NullableHelper.cs
with MIT License
from ChilliCream

private static NullableAttribute? GetNullableAttribute(
        MemberInfo member) =>
        GetNullableAttribute(member.GetCustomAttributesData());

19 Source : ServiceReflector.cs
with MIT License
from CoreWCF

internal static bool IsServiceContractAttributeDefined(Type type)
        {
            // Fast path for CoreWCF.ServiceContractAttribute
            if (type.IsDefined(typeof(ServiceContractAttribute), false))
            {
                return true;
            }

            // GetCustomAttributesData doesn't traverse the inheritence chain so this is the equivalent of IsDefined(..., false)
            IList<CustomAttributeData> cadList = type.GetCustomAttributesData();
            foreach (CustomAttributeData cad in cadList)
            {
                if (cad.AttributeType.FullName.Equals(SMServiceContractAttributeFullName))
                {
                    return true;
                }
            }

            return false;
        }

19 Source : AvatarGeneration.cs
with MIT License
from devlooped

static IEnumerable<object[]> GetTargetTypes() => Directory.EnumerateFiles(".", "*.dll")
            //.Select(file => replacedembly.LoadFrom(file))
            .Select(file => replacedemblyName.GetreplacedemblyName(file))
            //.GetExecutingreplacedembly().GetReferencedreplacedemblies()
            .Where(name =>
                !name.Name.StartsWith("Microsoft.Codereplacedysis") &&
                !name.Name.StartsWith("xunit") &&
                !name.Name.StartsWith("Avatar"))
            .Select(name => replacedembly.Load(name))
            .SelectMany(TryGetExportedTypes)
            .Where(type => type.IsInterface && !type.IsGenericTypeDefinition && !typeof(Delegate).IsreplacedignableFrom(type)
                    // Hard-coded exclusions we know don't work
                    && !type.GetCustomAttributesData().Any(d =>
                        d.AttributeType == typeof(ObsoleteAttribute) || // Obsolete types could generate build errors
                        d.AttributeType == typeof(CompilerGeneratedAttribute))
                    && type.Name[0] != '_')  // These are sort of internal too...
#if QUICK
            .Take(2)
#endif
            .Where(x =>
                x.FullName == typeof(Microsoft.DiaSymReader.ISymUnmanagedReader5).FullName
            )
            .Select(type => new object[] { type });

19 Source : MethodExtensions.cs
with GNU General Public License v3.0
from Devscord-Team

public static IEnumerable<T> GetAttributeInstances<T>(this MethodInfo method) where T : Attribute
        {
            var commandArguments = method.GetCustomAttributesData()
                .Where(x => x.AttributeType.FullName == typeof(T).FullName)
                .SelectMany(x => x.ConstructorArguments, (x, arg) => arg.Value).ToArray();
            return commandArguments.Select(x => (T) Activator.CreateInstance(typeof(T), x));
        }

19 Source : XrmExtensions.cs
with MIT License
from drivardxrm

public static string GetColumnName<T>(Expression<Func<T, object>> lambda) where T : Enreplacedy
        {
            MemberExpression body = lambda.Body as MemberExpression;

            if (body == null)
            {
                UnaryExpression ubody = (UnaryExpression)lambda.Body;
                body = ubody.Operand as MemberExpression;
            }

            if (body.Member.CustomAttributes != null)
            {
                var customAttributes = body.Member.GetCustomAttributesData();
                var neededAttribute = customAttributes.FirstOrDefault(x => x.AttributeType == typeof(AttributeLogicalNameAttribute));
                if (neededAttribute != null)
                {
                    return neededAttribute.ConstructorArguments.FirstOrDefault().Value.ToString();
                }
            }

            return body.Member.Name;
        }

19 Source : FrameControlTypeProvider.cs
with MIT License
from Egor92

public Type GetFrameControlType(Type navigationManagerType)
        {
            var attributeData = navigationManagerType.GetCustomAttributesData()
                                                     .FirstOrDefault(a => a.AttributeType == typeof(NavigationManagerAttribute));

            if (attributeData?.ConstructorArguments.Count != 1)
            {
                return null;
            }

            var argument = attributeData.ConstructorArguments[0];
            return (Type) argument.Value;
        }

19 Source : EnhancedStackTrace.Frames.cs
with Apache License 2.0
from elastic

private static bool IsStackTraceHidden(MemberInfo memberInfo)
		{
			if (StackTraceHiddenAttributeType is not null && !memberInfo.Module.replacedembly.ReflectionOnly)
				return memberInfo.GetCustomAttributes(StackTraceHiddenAttributeType, false).Length != 0;

			EnumerableIList<CustomAttributeData> attributes;
			try
			{
				attributes = EnumerableIList.Create(memberInfo.GetCustomAttributesData());
			}
			catch (NotImplementedException)
			{
				return false;
			}

			foreach (var attribute in attributes)
			{
				// reflection-only attribute, match on name
				if (attribute.AttributeType.FullName == StackTraceHiddenAttributeType?.FullName) return true;
			}

			return false;
		}

19 Source : AttributeAspectFactory.cs
with MIT License
from erhan0

public object CreateInstance(Type type, IJointPoint joinpoint)
        {
            MemberInfo member=null;
            if (joinpoint is ICallJointPoint callJp)
            {
                member = callJp.TargetMember;
            }

            if (joinpoint is IMemberJointPoint memberJp)
            {
                member = memberJp.Member;
            }

            return member == null ? null : member.GetCustomAttributesData()
                .Where(a=> type.IsreplacedignableFrom(a.Constructor.ReflectedType))
                .Select(ReflectionHelper.CreateAttribute)
                .FirstOrDefault();
        }

19 Source : Program.cs
with MIT License
from erhan0

static void Main(string[] args)
        {
            Console.WriteLine("OrderService.SubmitOrder attributes:");
            foreach(var attr in typeof(OrderService).GetMethod("SubmitOrder").GetCustomAttributesData())
                Console.WriteLine(attr);

            Console.ReadLine();
        }

19 Source : MethodAttributesTest.cs
with MIT License
from erhan0

[replacedert]
        public void AttributeShouldBeCopiedToTargetMethod()
        {
            Type type = target.GetType();
            var attrs = type.GetMethod("TestMethod").GetCustomAttributesData();
            attrs.Should().HaveCount(1);
            attrs.First().Constructor.DeclaringType.Should().Be(typeof(MyTestAttribute));
            attrs.First().ConstructorArguments.Should().OnlyContain(x => x.Value.Equals("Constructor Arg"));
        }

19 Source : PropertyAttributesTest.cs
with MIT License
from erhan0

[replacedert]
        public void AttributeShouldBeCopiedToTargetMethod()
        {
            Type type = target.GetType();
            var attrs = type.GetProperty("TestProperty").GetCustomAttributesData();
            attrs.Should().HaveCount(1);
            attrs.First().Constructor.DeclaringType.Should().Be(typeof(MyTestAttribute));
            attrs.First().ConstructorArguments.Should().OnlyContain(x => x.Value.Equals("Constructor Arg"));
        }

19 Source : ApplicationModulesManagerService.cs
with Apache License 2.0
from eXpandFramework

public static IObservable<T> WhenGeneratingModelNodes<T>(this ApplicationModulesManager manager,Expression<Func<IModelApplication,T>> selector=null,bool emitCached=false) where T : IEnumerable<IModelNode> 
		    => manager.Modules.FindModule<ReactiveModule>().GeneratingModelNodes
			    .SelectMany(updaters => {
				    var updaterType = (Type)typeof(T).GetCustomAttributesData().First(data => data.AttributeType==typeof(ModelNodesGeneratorAttribute)).ConstructorArguments.First().Value;
				    var updater = typeof(NodesUpdater<>).MakeGenericType(updaterType).CreateInstance();
				    updaters.Add((IModelNodesGeneratorUpdater) updater);
				    var name =emitCached? nameof(NodesUpdater<ModelNodesGeneratorBase>.UpdateCached):nameof(NodesUpdater<ModelNodesGeneratorBase>.Update);
				    return ((IObservable<ModelNode>) updater.GetPropertyValue(name)).Cast<T>();
			    });

19 Source : Metadata.cs
with Apache License 2.0
from eXpandFramework

private static string[] References(this Type type, PropertyInfo[] propertyInfos,Type[] additionalTypes){
            var referencedTypes = propertyInfos.SelectMany(_ => new[]{_.PropertyType,_.DeclaringType}).ToArray();
            return referencedTypes
                .Concat(additionalTypes.SelectMany(_ => _.PublicProperties().SelectMany(info => info.GetCustomAttributesData().ReferencedTypes())))
                .Concat(additionalTypes.SelectMany(_ => _.GetCustomAttributesData().ReferencedTypes()))
                .Concat(referencedTypes.SelectMany(_ => _.GetCustomAttributesData().ReferencedTypes()))
                .Concat(propertyInfos.SelectMany(_ => _.GetCustomAttributesData().ReferencedTypes()))
                .Concat(new []{type})
                .Select(_ => _.replacedembly.Location)
                .Concat(AdditionalReferences)
                .Distinct()
                .ToArray();
        }

19 Source : ModelMapperPropertyInfo.cs
with Apache License 2.0
from eXpandFramework

private static IEnumerable<ModelMapperCustomAttributeData> CustomAttributeDatas(PropertyInfo propertyInfo){
            return propertyInfo is ModelMapperPropertyInfo mapperPropertyInfo
                ? mapperPropertyInfo._customAttributeData
                : propertyInfo.GetCustomAttributesData().ToModelMapperConfigurationData();
        }

19 Source : DynamicClassGenerator.cs
with MIT License
from firebend

private static void CreatePreplacedThroughConstructors(TypeBuilder builder, Type baseType, List<Type> implementedTypes)
        {
            var constructors = baseType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (var constructor in constructors)
            {
                var parameters = constructor.GetParameters();

                if (parameters.Length > 0 && parameters.Last().IsDefined(typeof(ParamArrayAttribute), false))
                {
                    continue;
                }

                var parameterTypes = parameters
                    .Select(pi => implementedTypes.FirstOrDefault(t => pi.ParameterType.IsreplacedignableFrom(t)) ?? pi.ParameterType)
                    .ToArray();

                var requiredCustomModifiers = parameters.Select(p => p.GetRequiredCustomModifiers()).ToArray();
                var optionalCustomModifiers = parameters.Select(p => p.GetOptionalCustomModifiers()).ToArray();

                var ctor = builder.DefineConstructor(MethodAttributes.Public,
                    constructor.CallingConvention,
                    parameterTypes,
                    requiredCustomModifiers,
                    optionalCustomModifiers);

                for (var i = 0; i < parameters.Length; ++i)
                {
                    var parameter = parameters[i];

                    var parameterBuilder = ctor.DefineParameter(i + 1, parameter.Attributes, parameter.Name);

                    if (((int)parameter.Attributes & (int)ParameterAttributes.HasDefault) != 0)
                    {
                        parameterBuilder.SetConstant(parameter.RawDefaultValue);
                    }

                    foreach (var attribute in BuildCustomAttributes(parameter.GetCustomAttributesData()))
                    {
                        parameterBuilder.SetCustomAttribute(attribute);
                    }
                }

                foreach (var attribute in BuildCustomAttributes(constructor.GetCustomAttributesData()))
                {
                    ctor.SetCustomAttribute(attribute);
                }

                var emitter = ctor.GetILGenerator();

                emitter.Emit(OpCodes.Nop);

                emitter.Emit(OpCodes.Ldarg_0);

                for (var i = 1; i <= parameters.Length; ++i)
                {
                    emitter.Emit(OpCodes.Ldarg, i);
                }

                emitter.Emit(OpCodes.Call, constructor);

                emitter.Emit(OpCodes.Ret);
            }
        }

19 Source : TypeSymbolInfo.cs
with MIT License
from fs7744

private void SetInfo(Type type, string name, Func<string> fullName, string @namespace)
        {
            RealType = type;
            Accessibility = type.ConvertAccessibilityInfo();
            IsStatic = type.IsAbstract && type.IsSealed;
            Name = name;
            Namespace = @namespace;
            baseType = new Lazy<ITypeSymbolInfo>(() => RealType.BaseType?.GetSymbolInfo());
            if (type.IsGenericType)
            {
                TypeArguments = EnumerableExtensions.CreateLazyImmutableArray(() => type.GenericTypeArguments.Select(i => i.GetSymbolInfo()));
                TypeParameters = EnumerableExtensions.CreateLazyImmutableArray<ITypeParameterSymbolInfo>(() => (type.IsGenericTypeDefinition ? type : type.GetGenericTypeDefinition()).GetGenericArguments().Select(i => new TypeParameterSymbolInfo(i)));
                Func<IEnumerable<ITypeSymbolInfo>> genericParams = () => type.IsGenericTypeDefinition ? TypeParameters.Cast<ITypeSymbolInfo>() : TypeArguments;
                Name = genericParamsNumber.Replace(name, string.Empty);
                Func<string> newFullName = () => genericParamsNumber.Replace($"{(type.IsNested ? type.DeclaringType.GetSymbolInfo().FullName : Namespace)}.{Name}", string.Empty);
                genericDefinitionName = new Lazy<string>(() => $"{newFullName()}<{genericParams().Select(i => string.Empty).InsertSeparator(",").Aggregate((i, j) => i + j)}>");
                fullName = () => $"{newFullName()}<{genericParams().Select(i => i.FullName).InsertSeparator(",").Aggregate((i, j) => i + j)}>";
            }
            else
            {
                genericDefinitionName = new Lazy<string>(() => string.Empty);
                TypeArguments = EnumerableExtensions.EmptyImmutableArray<ITypeSymbolInfo>();
                TypeParameters = EnumerableExtensions.EmptyImmutableArray<ITypeParameterSymbolInfo>();
            }
            this.fullName = new Lazy<string>(fullName);
            Attributes = EnumerableExtensions.CreateLazyImmutableArray<IAttributeSymbolInfo>(() => RealType.GetCustomAttributesData().Select(i => new AttributeSymbolInfo(i)));
            Interfaces = EnumerableExtensions.CreateLazyImmutableArray(() => RealType.GetInterfaces().Distinct().Select(i => i.GetSymbolInfo()));
            Members = EnumerableExtensions.CreateLazyImmutableArray(() => RealType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
            .Select(RuntimeSymbolExtensions.ConvertToStructure)
            .Where(i => i != null));
            isAnonymousType = new Lazy<bool>(() => Attribute.IsDefined(RealType, typeof(CompilerGeneratedAttribute), false)
            && RealType.Name.Contains("AnonymousType")
            && RealType.Name.StartsWith("<>"));
        }

19 Source : MatchDefaultCaseMethodCanHandleAllCasesAssertion.cs
with MIT License
from Galad

private IEnumerable<UnionCase> GetCases(Type type)
        {

            var caseClreplaced = type.GetNestedType("Cases", BindingFlags.NonPublic | BindingFlags.Static);
            if (caseClreplaced == null)
            {
                ThrowreplacedertionException(type, $"The Cases clreplaced is missing for type {type.Name}");
            }
            // clreplaced
            if (type.IsClreplaced)
            {
                var cases = caseClreplaced.GetNestedTypes()
                                     .Select(c =>
                                     {
                                         if (c.IsGenericTypeDefinition)
                                         {
                                             c = c.MakeGenericType(type.GenericTypeArguments);
                                         }
                                         return new UnionCase(c.Name, c.GetFields(BindingFlags.NonPublic | BindingFlags.Instance));
                                     });
                return cases;
            }
            // struct
            var valuelessCases = caseClreplaced.GetCustomAttributesData()
                                          .Where(d => d.AttributeType == (typeof(StructCaseAttribute)))
                                          .Select(a =>
                                                new UnionCase(
                                                    a.ConstructorArguments[0].Value.ToString(),
                                                    new FieldInfo[] { }
                                                    )
                                                );
            var fieldInfoCases = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                                     .Where(f => f.Name != "_tag")
                                     .Select(f => (f.GetCustomAttributesData()
                                                   .Single(d => d.AttributeType == (typeof(StructCaseAttribute)))
                                                   .ConstructorArguments[0].Value.ToString(),
                                                   f)
                                            )
                                     .GroupBy(f => f.Item1)
                                     .Select(g => new UnionCase(g.Key, g.Select(gg => gg.f).ToArray()));
            return valuelessCases.Concat(fieldInfoCases);
        }

19 Source : SerializationTarget.cs
with Apache License 2.0
from HanJunJun

private static IEnumerable<SerializingMember> GetTargetMembers( Type type )
		{
			Contract.replacedert( type != null, "type != null" );

			var members = GetDistinctMembers( type );
			var filtered = members.Where( item =>
#if !UNITY
				item.GetCustomAttributesData().Any( a => a.GetAttributeType().FullName == MessagePackMemberAttributeTypeName )
#else
				item.GetCustomAttributes( typeof( MessagePackMemberAttribute ), true ).Any()
#endif // !UNITY
			).ToArray();

			if ( filtered.Length > 0 )
			{
				return GetAnnotatedMembersWithDuplicationDetection( type, filtered );
			}

			if (
#if !UNITY
				type.GetCustomAttributesData().Any( attr =>
					attr.GetAttributeType().FullName == "System.Runtime.Serialization.DataContractAttribute" )
#else
				type.GetCustomAttributes( true ).Any( attr =>
					attr.GetType().FullName == "System.Runtime.Serialization.DataContractAttribute" ) 
#endif // !UNITY
			)
			{
				return GetSystemRuntimeSerializationCompatibleMembers( members );
			}

			return GetPublicUnpreventedMembers( members );
		}

19 Source : SerializationTarget.cs
with Apache License 2.0
from HanJunJun

private static IEnumerable<SerializingMember> GetAnnotatedMembersWithDuplicationDetection( Type type, MemberInfo[] filtered )
		{
			var duplicated =
				filtered.FirstOrDefault(
#if !UNITY
					member => member.GetCustomAttributesData().Any( a => a.GetAttributeType().FullName == MessagePackIgnoreAttributeTypeName )
#else
					member => member.GetCustomAttributes( typeof( MessagePackIgnoreAttribute ), true ).Any()
#endif // !UNITY
				);

			if ( duplicated != null )
			{
				throw new SerializationException(
					String.Format(
						CultureInfo.CurrentCulture,
						"A member '{0}' of type '{1}' is marked with both MessagePackMemberAttribute and MessagePackIgnoreAttribute.",
						duplicated.Name,
						type
					)
				);
			}

			return
				filtered.Select(
					member =>
					{
#if !UNITY
						var attribute = member.GetCustomAttributesData().Single( a => a.GetAttributeType().FullName == MessagePackMemberAttributeTypeName );
						return
							new SerializingMember(
								member,
								new DataMemberContract(
									member,
									( string )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "Name" ),
#if !SILVERLIGHT
									( NilImplication )( ( int? )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "NilImplication" ) ).GetValueOrDefault(),
									( int? )GetAttributeArgument( MessagePackMemberAttributeTypeName, attribute, 0 )
#else
									( NilImplication )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "NilImplication" ),
									( int? )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "Id" )
#endif // !SILVERLIGHT
								)
							);
#else
						var attribute = member.GetCustomAttributes( typeof( MessagePackMemberAttribute ), true ).Single() as MessagePackMemberAttribute;
						return 
							new SerializingMember(
								member,
								new DataMemberContract(
									member,
									attribute.Name,
									attribute.NilImplication,
									attribute.Id
								)
							);
#endif // !UNITY
					}
				);
		}

19 Source : SerializationTarget.cs
with Apache License 2.0
from HanJunJun

private static IEnumerable<SerializingMember> GetSystemRuntimeSerializationCompatibleMembers( MemberInfo[] members )
		{
			return
				members.Select(
					item =>
						new
						{
							member = item,
							data =
#if !UNITY
								item.GetCustomAttributesData()
								.FirstOrDefault(
									data => data.GetAttributeType().FullName == "System.Runtime.Serialization.DataMemberAttribute"
								)
#else
								item.GetCustomAttributes( true )
								.FirstOrDefault(
									data => data.GetType().FullName == "System.Runtime.Serialization.DataMemberAttribute"
								)
#endif // !UNITY
						}
					).Where( item => item.data != null )
					.Select(
						item =>
						{
#if !UNITY
							var name =
								item.data.GetNamedArguments()
								.Where( arg => arg.GetMemberName() == "Name" )
								.Select( arg => ( string )arg.GetTypedValue().Value )
								.FirstOrDefault();
							var id =
								item.data.GetNamedArguments()
								.Where( arg => arg.GetMemberName() == "Order" )
								.Select( arg => ( int? )arg.GetTypedValue().Value )
								.FirstOrDefault();
							if ( id == -1 )
							{
								id = null;
							}

							return
								new SerializingMember(
									item.member,
									new DataMemberContract( item.member, name, NilImplication.MemberDefault, id )
								);
#else
							var nameProperty = item.data.GetType().GetProperty( "Name" );
							var orderProperty = item.data.GetType().GetProperty( "Order" );
							
							if ( nameProperty == null || !nameProperty.CanRead || nameProperty.GetGetMethod().GetParameters().Length > 0 )
							{
								throw new SerializationException(
									String.Format(
										CultureInfo.CurrentCulture,
										"Failed to get Name property from {0} type.",
										item.data.GetType().replacedemblyQualifiedName
									)
								);
							} 

							if( orderProperty == null || !orderProperty.CanRead || orderProperty.GetGetMethod().GetParameters().Length > 0 )
							{
								throw new SerializationException(
									String.Format(
										CultureInfo.CurrentCulture,
										"Failed to get Order property from {0} type.",
										item.data.GetType().replacedemblyQualifiedName
									)
								);
							}

							var name = ( string )nameProperty.GetValue( item.data, null );
							var id = ( int? )orderProperty.GetValue( item.data, null );
							if ( id == -1 )
							{
								id = null;
							}

							return
								new SerializingMember(
									item.member,
									new DataMemberContract( item.member, name, NilImplication.MemberDefault, id )
								);							
#endif // !UNITY
						}
					);
		}

19 Source : SerializationTarget.cs
with Apache License 2.0
from HanJunJun

private static IEnumerable<SerializingMember> GetPublicUnpreventedMembers( MemberInfo[] members )
		{
			return members.Where(
				member =>
					member.GetIsPublic()
					&& !member
#if !UNITY
						.GetCustomAttributesData()
						.Select( data => data.GetAttributeType().FullName )
#else
						.GetCustomAttributes( true )
						.Select( data => data.GetType().FullName )
#endif // !UNITY
						.Any( attr =>
							attr == "MsgPack.Serialization.MessagePackIgnoreAttribute"
							|| attr == "System.Runtime.Serialization.IgnoreDataMemberAttribute"
						)
					&& !IsNonSerializedField( member )
				).Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
		}

19 Source : SerializationTarget.cs
with Apache License 2.0
from HanJunJun

private static IList<ConstructorInfo> FindExplicitDeserializationConstructors( IEnumerable<ConstructorInfo> construtors )
		{
			return
				construtors
				.Where( ctor =>
#if !UNITY
					ctor.GetCustomAttributesData().Any( a =>
						a.GetAttributeType().FullName
#else
					ctor.GetCustomAttributes( true ).Any( a =>
						a.GetType().FullName
#endif // !UNITY
						== MessagePackDeserializationConstructorAttributeTypeName
					)
				).ToArray();
		}

19 Source : TypeConvertersCache.cs
with GNU General Public License v3.0
from ipphone

private static TypeConverter GetTypeConverter(Type type)
        {
            return type.GetCustomAttributes(typeof(TypeConverterAttribute), true)
                .Select(x => x as TypeConverterAttribute)
                .Where(x => x != null && !Equals(x, TypeConverterAttribute.Default) && !string.IsNullOrEmpty(x.ConverterTypeName))
                .Join(type.GetCustomAttributesData(), x => x.GetType(), x => x.AttributeType, (x, y) => new {Attribute = x, Data = y})
                .Select(x => (TypeConverterAttribute) x.Data.Constructor.Invoke(x.Data.ConstructorArguments.Select(p => p.Value).ToArray()))
                .Where(x => x != null)
                .Select(x => TypeHelpers.GetTypeByName(x.ConverterTypeName))
                .Where(x => x != null)
                .Select(CreateTypeConverter)
                .FirstOrDefault();
        }

19 Source : ComponentManifestGenerator.cs
with MIT License
from isc30

public Dictionary<string, object>? GenerateManifest(replacedembly replacedembly, MetadataLoadContext metadataLoadContext)
        {
            var componentTypes = replacedembly.GetTypes()
                .Where(t => !t.IsAbstract && t.GetInterfaces().Any(i => i.FullName == "Microsoft.AspNetCore.Components.IComponent"));

            var components = new List<ComponentManifest>();

            foreach (var component in componentTypes)
            {
                var lazyNameAttribute = component.GetCustomAttributesData()
                    .SingleOrDefault(a => a.AttributeType.FullName == "BlazorLazyLoading.LazyNameAttribute");

                if (lazyNameAttribute == null)
                {
                    components.Add(new ComponentManifest(component.FullName, null));
                    continue;
                }

                var lazyName = (string)lazyNameAttribute.ConstructorArguments[0].Value;
                components.Add(new ComponentManifest(component.FullName, lazyName));
            }

            if (!components.Any())
            {
                return null;
            }

            return new Dictionary<string, object>
            {
                { "Components", components }
            };
        }

19 Source : RouteManifestGenerator.cs
with MIT License
from isc30

public Dictionary<string, object>? GenerateManifest(replacedembly replacedembly, MetadataLoadContext metadataLoadContext)
        {
            var componentTypes = replacedembly.GetTypes()
                .Where(t => !t.IsAbstract && t.GetInterfaces().Any(i => i.FullName == "Microsoft.AspNetCore.Components.IComponent"));

            var routes = componentTypes.SelectMany(t => t.GetCustomAttributesData()
                .Where(a => a.AttributeType.FullName == "Microsoft.AspNetCore.Components.RouteAttribute")
                .Select(a => new RouteManifest((string)a.ConstructorArguments[0].Value, t.FullName)))
                .ToList();

            if (!routes.Any())
            {
                return null;
            }

            return new Dictionary<string, object>
            {
                { "Routes", routes }
            };
        }

19 Source : StringResources.cs
with GNU Lesser General Public License v2.1
from jet-global

public bool ValidateLoadedResourceManager(out string error)
		{
			error = null;
			if (this.ResourceManager == null)
			{
				error = "No resource manager loaded.";
				return false;
			}
			var resourceKeys = this.GetType()
				.GetProperties()
				.Where(p => p.GetCustomAttributesData().Any(a => a.AttributeType == typeof(StringResource)))
				.Select(p => p.Name);
			var missingStringResources = resourceKeys.Where(k => this.ResourceManager.GetString(k) == null);
			if (missingStringResources.Any())
			{
				error = $"The following string resources were missing:{Environment.NewLine}{string.Join(", ", missingStringResources)}";
				return false;
			}
			return true;
		}

19 Source : AssemblyGenerator.Methods.cs
with MIT License
from Lokad

private void CreateMethod(MethodInfo method, List<DelayedWrite> genericParams)
        {
            if (!_metadata.TryGetMethodDefinition(method, out var metadata))
            {
                ThrowMetadataIsNotReserved("Method", method);
            }

            EnsureMetadataWasNotEmitted(metadata, method);

            var body = method.GetMethodBody();

            var localVariablesSignature = default(StandaloneSignatureHandle);

            if (body != null && body.LocalVariables.Count > 0)
            {
                localVariablesSignature = _metadata.Builder.AddStandaloneSignature(_metadata.GetOrAddBlob(
                    MetadataHelper.BuildSignature(x =>
                    {
                        x.LocalVariableSignature(body.LocalVariables.Count).AddRange(body.LocalVariables, _metadata);
                    })));
            }

            var offset = -1;

            // If body exists, we write it in IL body stream
            if (body != null && !method.IsAbstract)
            {
                var methodBodyWriter = new MethodBodyStreamWriter(_metadata);

                // offset can be aligned during serialization. So, override the correct offset.
                offset = methodBodyWriter.AddMethodBody(method, localVariablesSignature);
            }

            var parameters = CreateParameters(method.GetParameters());

            var handle = _metadata.Builder.AddMethodDefinition(
                method.Attributes,
                method.MethodImplementationFlags,
                _metadata.GetOrAddString(method.Name),
                _metadata.GetMethodOrConstructorSignature(method),
                offset,
                parameters);

            // The generation of interface method overrides has been moved to 
            // replacedemblyGenerator.DeclareInterfacesAndCreateInterfaceMap in
            // replacedemblyGenerator.Types.cs.

            // Add generic parameters
            if (method.IsGenericMethodDefinition)
            {
                int index = 0;
                foreach (var arg in method.GetGenericArguments())
                {
                    genericParams.Add(new DelayedWrite(CodedIndex.TypeOrMethodDef(handle), () =>
                    {
                        // Add the argument
                        var gaHandle = _metadata.Builder.AddGenericParameter(handle, arg.GenericParameterAttributes, _metadata.GetOrAddString(arg.Name), index++);

                        // Add it's constraints
                        foreach (var constraint in arg.GetGenericParameterConstraints())
                        {
                            _metadata.Builder.AddGenericParameterConstraint(gaHandle, _metadata.GetTypeHandle(constraint));
                        }
                    }));
                }
            }
            else if (method.Attributes.HasFlag(MethodAttributes.PinvokeImpl))
            {
                ProcessPInvokeMapData(
                    method,
                    out string libraryName,
                    out string entryName,
                    out MethodImportAttributes attrs);

                var libraryNameHandle = _metadata.GetOrAddString(libraryName);
                var moduleRefHandle = _metadata.Builder.AddModuleReference(libraryNameHandle);
                var entryNameHandle = _metadata.GetOrAddString(entryName);

                // Add the ImplMap entry for the P/Invoke
                _metadata.Builder.AddMethodImport(
                    handle,
                    attrs,
                    entryNameHandle,
                    moduleRefHandle);
            }

            VerifyEmittedHandle(metadata, handle);
            metadata.MarkAsEmitted();

            CreateCustomAttributes(handle, method.GetCustomAttributesData());
        }

19 Source : AssemblyGenerator.Properties.cs
with MIT License
from Lokad

private void CreateProperty(PropertyInfo property, bool addToPropertyMap)
        {
            if (!_metadata.TryGetPropertyMetadata(property, out var metadata))
            {
                ThrowMetadataIsNotReserved("Property", property);
            }

            EnsureMetadataWasNotEmitted(metadata, property);

            var propertyHandle = _metadata.Builder.AddProperty(
                property.Attributes,
                _metadata.GetOrAddString(property.Name),
                GetPropertySignature(property));

            // If this is the first property for this type then add to the property map
            // (Without this ildasm doesn't show the .property block and intellisense doesn't show any properties)
            if (addToPropertyMap)
            {
                if (!_metadata.TryGetTypeDefinition(property.DeclaringType, out var typeHandle))
                {
                    ThrowMetadataIsNotReserved("Type", property.DeclaringType);
                }
                _metadata.Builder.AddPropertyMap((TypeDefinitionHandle)typeHandle.Handle, propertyHandle);
            }

            VerifyEmittedHandle(metadata, propertyHandle);
            metadata.MarkAsEmitted();
            this.CreateCustomAttributes(propertyHandle, property.GetCustomAttributesData());
            if (property.GetMethod != null)
            {
                if (!_metadata.TryGetMethodDefinition(property.GetMethod, out var getMethodMetadata))
                {
                    ThrowMetadataIsNotReserved("Property getter method", property);
                }

                _metadata.Builder.AddMethodSemantics(
                    propertyHandle,
                    MethodSemanticsAttributes.Getter,
                    getMethodMetadata.Handle);
            }

            if (property.SetMethod != null)
            {
                if (!_metadata.TryGetMethodDefinition(property.SetMethod, out var setMethodMetadata))
                {
                    ThrowMetadataIsNotReserved("Property setter method", property);
                }

                _metadata.Builder.AddMethodSemantics(
                    propertyHandle,
                    MethodSemanticsAttributes.Setter,
                    setMethodMetadata.Handle);
            }
        }

19 Source : AssemblyGenerator.Types.cs
with MIT License
from Lokad

private void CreateType(Type type, List<DelayedWrite> genericParams)
        {
            // Check reserved and not already emitted
            if (!_metadata.TryGetTypeDefinition(type, out var metadata))
            {
                ThrowMetadataIsNotReserved("Type", type);
            }
            EnsureMetadataWasNotEmitted(metadata, type);

            // Add the type definition
            var baseTypeHandle = type.BaseType != null ? _metadata.GetTypeHandle(type.BaseType) : default;
            var handle = _metadata.Builder.AddTypeDefinition(
                type.Attributes,
                type.DeclaringType == null ? _metadata.GetOrAddString(ApplyNameChange(type.Namespace)) : default(StringHandle),
                _metadata.GetOrAddString(type.Name),
                baseTypeHandle,
                MetadataTokens.FieldDefinitionHandle(_metadata.Builder.GetRowCount(TableIndex.Field) + 1),
                MetadataTokens.MethodDefinitionHandle(_metadata.Builder.GetRowCount(TableIndex.MethodDef) + 1));

            // Verify and mark emitted
            VerifyEmittedHandle(metadata, handle);
            metadata.MarkAsEmitted();

            // Setup pack and size attributes (if explicit layout)
            if (type.IsExplicitLayout)
            {
                _metadata.Builder.AddTypeLayout(
                    handle,
                    (ushort)type.StructLayoutAttribute.Pack,
                    (uint)type.StructLayoutAttribute.Size
                    );
            }

            // Add implemented interfaces (not for enums though - eg: IComparable etc...)
            if (!type.IsEnum)
            {
                DeclareInterfacesAndCreateInterfaceMap(type, handle);
            }

            // Setup enclosing type
            if (type.DeclaringType != null)
            {
                _metadata.Builder.AddNestedType(handle, (TypeDefinitionHandle)_metadata.GetTypeHandle(type.DeclaringType));
            }

            // Create attributes
            CreateCustomAttributes(handle, type.GetCustomAttributesData());

            // Handle generics type
            if (type.IsGenericType)
            {
                if (type.IsGenericTypeDefinition)
                {
                    var genericType = type.GetGenericTypeDefinition();
                    var typeInfo = genericType.GetTypeInfo();

                    int index = 0;
                    foreach(var arg in typeInfo.GenericTypeParameters)
                    {
                        var attr = arg.GenericParameterAttributes;

                        genericParams.Add(new DelayedWrite(CodedIndex.TypeOrMethodDef(handle), () =>
                        {
                            var gpHandle = _metadata.Builder.AddGenericParameter(handle, attr, _metadata.GetOrAddString(arg.Name), index++);

                            foreach (var constraint in arg.GetGenericParameterConstraints())
                            {
                                _metadata.Builder.AddGenericParameterConstraint(gpHandle,
                                          _metadata.GetTypeHandle(constraint));
                            }
                        }));
                    }
                }
            }

            // Create members...
            CreateFields(type.GetFields(AllFields));
            CreatePropertiesForType(type.GetProperties(AllProperties));
            CreateEventsForType(type.GetEvents(AllEvents));
            CreateConstructors(type.GetConstructors(AllMethods));
            CreateMethods(type.GetMethods(AllMethods), genericParams);
        }

19 Source : AssemblyGenerator.Methods.cs
with MIT License
from Lokad

private void ProcessPInvokeMapData(
            MethodInfo method,
            out string libraryName,
            out string entryName,
            out MethodImportAttributes implAttr)
        {
            CustomAttributeData dllImportData = null;
            foreach (var custAttr in method.GetCustomAttributesData())
            {
                if (custAttr.AttributeType == typeof(DllImportAttribute))
                {
                    dllImportData = custAttr;
                    break;
                }
            }

            if (dllImportData == null)
            {
                throw new InvalidProgramException($"Missing P/Invoke map data for: {method.Name}");
            }

            // Initialize the outputs
            libraryName = (string)dllImportData.ConstructorArguments[0].Value;
            entryName = method.Name;
            implAttr = MethodImportAttributes.CallingConventionWinApi;

            foreach (var nargs in dllImportData.NamedArguments)
            {
                object argValue = nargs.TypedValue.Value;
                switch (nargs.MemberName)
                {
                    case nameof(DllImportAttribute.BestFitMapping):
                        implAttr |= ((bool)argValue)
                                ? MethodImportAttributes.BestFitMappingEnable
                                : MethodImportAttributes.BestFitMappingDisable;
                        break;
                    case nameof(DllImportAttribute.CallingConvention):
                        // Clear previous value.
                        implAttr &= ~MethodImportAttributes.CallingConventionMask;

                        implAttr |= (CallingConvention)argValue switch
                        {
                            CallingConvention.Winapi => MethodImportAttributes.CallingConventionWinApi,
                            CallingConvention.Cdecl => MethodImportAttributes.CallingConventionCDecl,
                            CallingConvention.StdCall => MethodImportAttributes.CallingConventionStdCall,
                            CallingConvention.ThisCall => MethodImportAttributes.CallingConventionThisCall,
                            CallingConvention.FastCall => MethodImportAttributes.CallingConventionFastCall,
                            _ => MethodImportAttributes.CallingConventionWinApi,
                        };
                        break;
                    case nameof(DllImportAttribute.CharSet):
                        // Clear previous value.
                        implAttr &= ~MethodImportAttributes.CharSetMask;

                        implAttr |= (CharSet)argValue switch
                        {
                            CharSet.Ansi => MethodImportAttributes.CharSetAnsi,
                            CharSet.Unicode => MethodImportAttributes.CharSetUnicode,
                            CharSet.Auto => MethodImportAttributes.CharSetAuto,
                            _ => MethodImportAttributes.None,
                        };
                        break;
                    case nameof(DllImportAttribute.EntryPoint):
                        entryName = (string)argValue;
                        break;
                    case nameof(DllImportAttribute.ExactSpelling):
                        implAttr |= ((bool)argValue)
                                ? MethodImportAttributes.ExactSpelling
                                : MethodImportAttributes.None;
                        break;
                    case nameof(DllImportAttribute.SetLastError):
                        implAttr |= ((bool)argValue)
                                ? MethodImportAttributes.SetLastError
                                : MethodImportAttributes.None;
                        break;
                    case nameof(DllImportAttribute.ThrowOnUnmappableChar):
                        implAttr |= ((bool)argValue)
                                ? MethodImportAttributes.ThrowOnUnmappableCharEnable
                                : MethodImportAttributes.ThrowOnUnmappableCharDisable;
                        break;
                }

19 Source : AssemblyGenerator.Fields.cs
with MIT License
from Lokad

private void CreateField(FieldInfo field)
        {
            if (!_metadata.TryGetFieldDefinition(field, out var metadata))
            {
                ThrowMetadataIsNotReserved("Field", field);
            }

            EnsureMetadataWasNotEmitted(metadata, field);

            var handle = _metadata.Builder.AddFieldDefinition(
                field.Attributes,
                _metadata.GetOrAddString(field.Name),
                _metadata.GetFieldSignature(field));

            if (field.Attributes.HasFlag(FieldAttributes.Literal))
                _metadata.Builder.AddConstant(handle, field.GetRawConstantValue());

            if (field.DeclaringType.IsExplicitLayout)
                _metadata.Builder.AddFieldLayout(handle, (int)Marshal.OffsetOf(field.DeclaringType, field.Name));

            VerifyEmittedHandle(metadata, handle);
            metadata.MarkAsEmitted();

            CreateCustomAttributes(handle, field.GetCustomAttributesData());

            if (field.IsStatic && (field.Attributes & FieldAttributes.HasFieldRVA) != 0)
            {
                // HasFieldRVA fields are used by C# for static array initializers 
                // (eg: x = new int { 1,2,3}).  The easiest way to understand these is to
                // look at an ildasm dump, but basically it creates a static field initialized
                // to point to a blob of data (via the RVA)
                // 
                // There's no reflection API to get the raw bytes from the RVA so we
                // author a little dynamic method to grab it.  This code basically mirrors
                // what C# generates for array initializers.

                // Allocate memory for the initialization data
                var bytes = new byte[Marshal.SizeOf(field.FieldType)];

                // Create a dynamic method
                var method = new DynamicMethod("getInitData", typeof(void), new System.Type[] {typeof(byte[]) }, true);
                var il = method.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);               // Load "bytes"
                il.Emit(OpCodes.Ldtoken, field);        // Token for the field
                il.Emit(OpCodes.Call, typeof(System.Runtime.CompilerServices.RuntimeHelpers).GetMethod("InitializeArray"));
                il.Emit(OpCodes.Ret);
                var getInitData = (Action<byte[]>)method.CreateDelegate(typeof(Action<byte[]>));

                // Call it
                getInitData(bytes);

                // Write the data to the mapped field data builder
                _metadata.Builder.AddFieldRelativeVirtualAddress(handle, _metadata.MappedFieldDataBuilder.Count);
                _metadata.MappedFieldDataBuilder.WriteBytes(bytes);
            }
        }

19 Source : Generator.cs
with MIT License
from lzybkr

public static void Generate(Type type, Type proxyOf, ICondition when, List<Descriptor> descriptors)
        {
            List<DisplayPropertyData> defaultProperties = new List<DisplayPropertyData>();
            List<TableColumnData> tableColumns = new List<TableColumnData>();

            foreach (var member in type.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public))
            {
                MethodInfo methodInfo = null;
                switch (member)
                {
                    case PropertyInfo pi:
                        if (pi.GetMethod == null
                            || pi.GetMethod.IsStatic
                            || !pi.GetMethod.IsPublic) continue;
                        break;

                    case FieldInfo fi:
                        if (!fi.IsPublic || fi.IsStatic) continue;
                        break;

                    case MethodInfo mi:
                        if (!mi.IsPublic
                            || !mi.IsStatic
                            || mi.ReturnParameter == null
                            || mi.ReturnParameter.ParameterType == typeof(void)
                            || mi.GetParameters().Length != 1)
                            continue;
                        methodInfo = mi;
                        break;

                    default:
                        continue;
                }

                bool sawDefaultDisplay = false;
                bool sawTableColumn = false;
                foreach (var cad in member.GetCustomAttributesData())
                {
                    if (cad.AttributeType == typeof(DisplayPropertyAttribute))
                    {
                        // Compilers should make these checks unnecessary, but compilers could have bugs.
                        if (cad.ConstructorArguments.Count != 0) continue; // We only have a default ctor.
                        if (sawDefaultDisplay) continue; // Ignore multiple attributes.

                        object position = null;
                        object isDefault = null;
                        if (cad.NamedArguments != null)
                        {
                            foreach (var na in cad.NamedArguments)
                            {
                                if (na.MemberName.Equals(nameof(DisplayPropertyAttribute.Position), StringComparison.Ordinal))
                                {
                                    position = na.TypedValue.Value;
                                    continue;
                                }

                                if (na.MemberName.Equals(nameof(DisplayPropertyAttribute.Default), StringComparison.Ordinal))
                                {
                                    isDefault = na.TypedValue.Value;
                                    continue;
                                }
                            }
                        }

                        sawDefaultDisplay = true;
                        defaultProperties.Add(new DisplayPropertyData
                        {
                            Name = member.Name,
                            Method = methodInfo,
                            Position = position is int p ? p : -1,
                            Default = isDefault is bool b && b,
                        });
                    }
                    else if (cad.AttributeType == typeof(TableColumnAttribute))
                    {
                        // Compilers should make these checks unnecessary, but compilers could have bugs.
                        if (cad.ConstructorArguments.Count != 0) continue; // We only have a default ctor.
                        if (sawTableColumn) continue; // Ignore multiple attributes.

                        object position = null;
                        object alignment = null;
                        object width = null;
                        object label = null;
                        if (cad.NamedArguments != null)
                        {
                            foreach (var na in cad.NamedArguments)
                            {
                                if (na.MemberName.Equals(nameof(TableColumnAttribute.Position), StringComparison.Ordinal))
                                {
                                    position = na.TypedValue.Value;
                                    continue;
                                }
                                if (na.MemberName.Equals(nameof(TableColumnAttribute.Alignment), StringComparison.Ordinal))
                                {
                                    alignment = na.TypedValue.Value;
                                    continue;
                                }
                                if (na.MemberName.Equals(nameof(TableColumnAttribute.Width), StringComparison.Ordinal))
                                {
                                    width = na.TypedValue.Value;
                                    continue;
                                }
                                if (na.MemberName.Equals(nameof(TableColumnAttribute.Label), StringComparison.Ordinal))
                                {
                                    label = na.TypedValue.Value;
                                    continue;
                                }
                            }
                        }

                        sawTableColumn = true;
                        tableColumns.Add(new TableColumnData
                        {
                            Property = member.Name,
                            Method = methodInfo,
                            Position = position is int p ? p : -1,
                            Alignment = alignment is int ca ? (ColumnAlignment)ca : ColumnAlignment.Right,
                            Width = width is int w ? w : 0,
                            Label = label is string s ? s : null,
                        });
                    }
                }
            }

            if (defaultProperties.Count > 0)
            {
                var sortedEntries = defaultProperties
                    .OrderBy(op => op.Position)
                    .Select(op => new ListDescriptorPropertyEntry(op.Name, op.Method));
                descriptors.Add(new ListDescriptor(sortedEntries, proxyOf, when));
            }

            if (tableColumns.Count > 0)
            {
                var sortedColumns = tableColumns
                    .OrderBy(op => op.Position)
                    .Select(op => new TableColumn(op.Property, op.Method, op.Alignment, op.Width, op.Label));
                descriptors.Add(new TableDescriptor(sortedColumns));
            }
        }

19 Source : DelegatingFieldInfo.cs
with MIT License
from microsoftarchive

public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return _field.GetCustomAttributesData();
        }

19 Source : DelegatingConstructorInfo.cs
with MIT License
from microsoftarchive

public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return _constructor.GetCustomAttributesData();
        }

19 Source : DelegatingEventInfo.cs
with MIT License
from microsoftarchive

public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return _event.GetCustomAttributesData();
        }

19 Source : DelegatingType.cs
with MIT License
from microsoftarchive

public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return _type.GetCustomAttributesData();
        }

19 Source : DelegatingMethodInfo.cs
with MIT License
from microsoftarchive

public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return _method.GetCustomAttributesData();
        }

19 Source : DelegatingPropertyInfo.cs
with MIT License
from microsoftarchive

public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return _property.GetCustomAttributesData();
        }

19 Source : AppCfgTypeMixer.cs
with MIT License
from minhhungit

internal K ExtendWith<K>()
        {
            replacedemblyBuilder replacedembly = replacedemblyBuilder.DefineDynamicreplacedembly(new replacedemblyName(Guid.NewGuid().ToString()), replacedemblyBuilderAccess.Run);
            ModuleBuilder module = replacedembly.DefineDynamicModule("AppCfgModule");

            var typeBuilder = module.DefineType(typeof(T).Name + "_" + typeof(K).Name, TypeAttributes.Public, typeof(T));
            typeBuilder.AddInterfaceImplementation(typeof(K));

            foreach (var v in typeof(K).GetProperties())
            {
                var field = typeBuilder.DefineField("_f_" + v.Name.ToLower(), v.PropertyType, FieldAttributes.Private);
                var propertyBuilder = typeBuilder.DefineProperty(v.Name, PropertyAttributes.None, v.PropertyType, new Type[0]);
                var getter = typeBuilder.DefineMethod("_get_" + v.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.Virtual, v.PropertyType, new Type[0]);
                var setter = typeBuilder.DefineMethod("_set_" + v.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.Virtual, null, new Type[] { v.PropertyType });

                var getGenerator = getter.GetILGenerator();
                var setGenerator = setter.GetILGenerator();

                getGenerator.Emit(OpCodes.Ldarg_0);
                getGenerator.Emit(OpCodes.Ldfld, field);
                getGenerator.Emit(OpCodes.Ret);

                setGenerator.Emit(OpCodes.Ldarg_0);
                setGenerator.Emit(OpCodes.Ldarg_1);
                setGenerator.Emit(OpCodes.Stfld, field);
                setGenerator.Emit(OpCodes.Ret);

                propertyBuilder.SetGetMethod(getter);
                propertyBuilder.SetSetMethod(setter);

                var cusAttData =  v.GetCustomAttributesData();
                foreach (var attr in v.GetCustomAttributes())
                {
                    var attributeBuilder = CreateAttributeBuilderFor(v.GetCustomAttribute(attr.GetType()), cusAttData.FirstOrDefault(x=>x.AttributeType == attr.GetType()));
                    if (attributeBuilder != null)
                    {
                        propertyBuilder.SetCustomAttribute(attributeBuilder);
                    }
                }                

                if (v.GetGetMethod() != null) typeBuilder.DefineMethodOverride(getter, v.GetGetMethod());
                if (v.GetSetMethod() != null) typeBuilder.DefineMethodOverride(setter, v.GetSetMethod());
            }

            return (K)Activator.CreateInstance(typeBuilder.CreateTypeInfo());
        }

19 Source : DataModelBase.cs
with GNU General Public License v3.0
from nightness

public static List<Type> GetModelClreplacedes()
        {
            var results = new List<Type>();

            // Setup event handler to resolve replacedemblies
            AppDomain.CurrentDomain.ReflectionOnlyreplacedemblyResolve +=
                CurrentDomain_ReflectionOnlyreplacedemblyResolve;

            string path = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            replacedembly a = replacedembly.ReflectionOnlyLoadFrom(path + @"\PosModels.dll");

            // process types here
            foreach (Type t in a.GetTypes())
            {
                MemberInfo info = t;
                IList<CustomAttributeData> list = info.GetCustomAttributesData();

                bool found = list.Any(customAttribute =>
                    (customAttribute.Constructor.DeclaringType != null) &&
                    (customAttribute.Constructor.DeclaringType.Name.Equals("ModeledDataClreplacedAttribute") ||
                    customAttribute.Constructor.DeclaringType.Name.Equals("TableAttribute")));
                if (!found)
                    continue;
                string clreplacedName = t.ToString();
                if (clreplacedName.Contains("+"))
                    clreplacedName = clreplacedName.Substring(0, clreplacedName
                        .IndexOf("+", StringComparison.Ordinal));
                Type t1 = Type.GetType(clreplacedName);
                if (!results.Contains(t1))
                    results.Add(t1);
            }

            results.Sort(new TypeCompare());
            return results;
        }

See More Examples