Exemplo n.º 1
0
        private static void FindApplicableConstructor(
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType,
            Type[] argumentTypes,
            out ConstructorInfo matchingConstructor,
            out int?[] matchingParameterMap)
        {
            ConstructorInfo?constructorInfo = null;

            int?[]? parameterMap = null;

            if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref constructorInfo, ref parameterMap) &&
                !TryFindMatchingConstructor(instanceType, argumentTypes, ref constructorInfo, ref parameterMap))
            {
                string?message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided.";
                throw new InvalidOperationException(message);
            }

            matchingConstructor  = constructorInfo;
            matchingParameterMap = parameterMap;
        }
Exemplo n.º 2
0
        private static ConstructorInfo CreateHandlerInternal <THandler, TRule>()
            where THandler : class
        {
            ConstructorInfo?constructor = typeof(THandler).GetTypeInfo()
                                          .DeclaredConstructors.SingleOrDefault(c =>
            {
                ParameterInfo[] parameters = c.GetParameters();
                return(parameters.Length == 1 &&
                       parameters[0].ParameterType ==
                       typeof(TRule));
            });

            if (constructor == null)
            {
                throw new ArgumentException(StitchingResources
                                            .SchemaMergerExtensions_NoValidConstructor);
            }

            return(constructor);
        }
Exemplo n.º 3
0
        private JsonConverter GetConverterFromAttribute(JsonConverterAttribute converterAttribute, Type typeToConvert, Type classTypeAttributeIsOn, PropertyInfo?propertyInfo)
        {
            JsonConverter?converter;

            Type?type = converterAttribute.ConverterType;

            if (type == null)
            {
                // Allow the attribute to create the converter.
                converter = converterAttribute.CreateConverter(typeToConvert);
                if (converter == null)
                {
                    ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, propertyInfo, typeToConvert);
                }
            }
            else
            {
                ConstructorInfo?ctor = type.GetConstructor(Type.EmptyTypes);
                if (!typeof(JsonConverter).IsAssignableFrom(type) || ctor == null || !ctor.IsPublic)
                {
                    ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(classTypeAttributeIsOn, propertyInfo);
                }

                converter = (JsonConverter)Activator.CreateInstance(type) !;
            }

            Debug.Assert(converter != null);
            if (!converter.CanConvert(typeToConvert))
            {
                Type?underlyingType = Nullable.GetUnderlyingType(typeToConvert);
                if (underlyingType != null && converter.CanConvert(underlyingType))
                {
                    // Allow nullable handling to forward to the underlying type's converter.
                    return(NullableConverterFactory.CreateValueConverter(underlyingType, converter));
                }

                ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, propertyInfo, typeToConvert);
            }

            return(converter);
        }
Exemplo n.º 4
0
        public DeputyBase GetOrCreateNativeReference(ByRefValue byRefValue)
        {
            if (!_references.ContainsKey(byRefValue.Value))
            {
                ConstructorInfo constructorInfo = GetByRefConstructor();
                _references[byRefValue.Value] = (DeputyBase)constructorInfo.Invoke(new object[] { byRefValue });
            }

            var existing = _references[byRefValue.Value];

            existing.Reference.Merge(byRefValue);
            return(existing);

            ConstructorInfo GetByRefConstructor()
            {
                Type type = _types.GetClassType(byRefValue.FullyQualifiedName);

                // If type is an interface or abstract class
                if (type == null || type.IsAbstract)
                {
                    type = _types.GetProxyType(byRefValue.FullyQualifiedName);
                }

                if (type == null)
                {
                    throw new ArgumentException(
                              $"Could not find type with fully qualified name '{byRefValue.FullyQualifiedName}'",
                              nameof(byRefValue)
                              );
                }

                BindingFlags    constructorFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
                ConstructorInfo?constructorInfo  = type.GetConstructor(constructorFlags, null, new[] { typeof(ByRefValue) }, null);

                if (constructorInfo == null)
                {
                    throw new JsiiException($"Could not find constructor to initialize {type.FullName} with a {typeof(ByRefValue).FullName}");
                }
                return(constructorInfo);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Caches the metadata.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        protected override void CacheMetadata(CodeActivityMetadata metadata)
        {
            var foundError         = false;
            var oldConstructorInfo = this.constructorInfo;

            // Loop through each argument, validate it, and if validation
            // passed expose it to the metadata
            var types = new Type?[this.Arguments.Count];

            for (var i = 0; i < this.Arguments.Count; i++)
            {
                var argument = this.Arguments[i];
                if (argument == null || argument.Expression == null)
                {
                    metadata.AddValidationError(SR.ArgumentRequired("Arguments", typeof(New <TResult>)));
                    foundError = true;
                }
                else
                {
                    var runtimeArgument = new RuntimeArgument("Argument" + i, this.arguments?[i].ArgumentType, this.arguments?[i].Direction, true);
                    metadata.Bind(this.arguments?[i], runtimeArgument);
                    metadata.AddArgument(runtimeArgument);
                    types[i] = this.Arguments[i].Direction == ArgumentDirection.In ? this.Arguments[i].ArgumentType : this.Arguments[i].ArgumentType?.MakeByRefType();
                }
            }

            // If we didn't find any errors in the arguments then
            // we can look for an appropriate constructor.
            if (!foundError)
            {
                this.constructorInfo = typeof(TResult).GetConstructor(types);
                if (this.constructorInfo == null && (!typeof(TResult).IsValueType || types.Length > 0))
                {
                    metadata.AddValidationError(SR.ConstructorInfoNotFound(typeof(TResult).Name));
                }
                else if ((this.constructorInfo != oldConstructorInfo) || (this.function == null))
                {
                    this.function = MethodCallExpressionHelper.GetFunc(metadata, this.constructorInfo, funcCache, locker);
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Converts the given object to another type. The most common types to convert
        /// are to and from a string object. The default implementation will make a call
        /// to ToString on the object if the object is valid and if the destination
        /// type is string. If this cannot convert to the desitnation type, this will
        /// throw a NotSupportedException.
        /// </summary>
        public override object?ConvertTo(ITypeDescriptorContext?context, CultureInfo?culture, object?value, Type destinationType)
        {
            ArgumentNullException.ThrowIfNull(destinationType);

            if (value is Margins margins)
            {
                if (destinationType == typeof(string))
                {
                    if (culture == null)
                    {
                        culture = CultureInfo.CurrentCulture;
                    }
                    string        sep          = culture.TextInfo.ListSeparator + " ";
                    TypeConverter intConverter = GetIntConverter();
                    string?[]     args         = new string[4];
                    int           nArg         = 0;

                    // Note: ConvertToString will raise exception if value cannot be converted.
                    args[nArg++] = intConverter.ConvertToString(context, culture, margins.Left);
                    args[nArg++] = intConverter.ConvertToString(context, culture, margins.Right);
                    args[nArg++] = intConverter.ConvertToString(context, culture, margins.Top);
                    args[nArg++] = intConverter.ConvertToString(context, culture, margins.Bottom);

                    return(string.Join(sep, args));
                }
                if (destinationType == typeof(InstanceDescriptor))
                {
                    ConstructorInfo?ctor = typeof(Margins).GetConstructor(new Type[] {
                        typeof(int), typeof(int), typeof(int), typeof(int)
                    });

                    if (ctor != null)
                    {
                        return(new InstanceDescriptor(ctor, new object[] {
                            margins.Left, margins.Right, margins.Top, margins.Bottom
                        }));
                    }
                }
            }
            return(base.ConvertTo(context, culture, value, destinationType));
        }
Exemplo n.º 7
0
        public static ConstructorInfo?ResolveEnumerableCollectionConstructor(
            Type collectionType,
            Type collectionItemType,
            Type constructorArgumentType
            )
        {
            Type            genericEnumerable = typeof(IEnumerable <>).MakeGenericType(collectionItemType);
            ConstructorInfo?match             = null;

            foreach (
                ConstructorInfo constructor in collectionType.GetConstructors(
                    BindingFlags.Public | BindingFlags.Instance
                    )
                )
            {
                IList <ParameterInfo> parameters = constructor.GetParameters();

                if (parameters.Count == 1)
                {
                    Type parameterType = parameters[0].ParameterType;

                    if (genericEnumerable == parameterType)
                    {
                        // exact match
                        match = constructor;
                        break;
                    }

                    // in case we can't find an exact match, use first inexact
                    if (match == null)
                    {
                        if (parameterType.IsAssignableFrom(constructorArgumentType))
                        {
                            match = constructor;
                        }
                    }
                }
            }

            return(match);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a <see cref="NewExpression"/> that represents calling the parameterless constructor of the specified type.
        /// </summary>
        /// <param name="type">A <see cref="Type"/> that has a constructor that takes no arguments.</param>
        /// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.New"/> and the <see cref="NewExpression.Constructor"/> property set to the <see cref="ConstructorInfo"/> that represents the parameterless constructor of the specified type.</returns>
        public static NewExpression New(
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type)
        {
            ContractUtils.RequiresNotNull(type, nameof(type));
            if (type == typeof(void))
            {
                throw Error.ArgumentCannotBeOfTypeVoid(nameof(type));
            }
            TypeUtils.ValidateType(type, nameof(type));

            if (!type.IsValueType)
            {
                ConstructorInfo?ci = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SingleOrDefault(c => c.GetParametersCached().Length == 0);
                if (ci == null)
                {
                    throw Error.TypeMissingDefaultConstructor(type, nameof(type));
                }
                return(New(ci));
            }
            return(new NewValueTypeExpression(type, EmptyReadOnlyCollection <Expression> .Instance, null));
        }
Exemplo n.º 9
0
        public void CanCreateReturnsFalseWhenNoPublicConstructorFoundAndStaticMethodContainsTypeParameter()
        {
            var             type            = typeof(NotFactoryItem);
            ConstructorInfo?constructorInfo = null;

            var configuration       = Substitute.For <IBuildConfiguration>();
            var typeResolver        = Substitute.For <ITypeResolver>();
            var constructorResolver = Substitute.For <IConstructorResolver>();
            var buildChain          = Substitute.For <IBuildChain>();

            configuration.TypeResolver.Returns(typeResolver);
            configuration.ConstructorResolver.Returns(constructorResolver);
            typeResolver.GetBuildType(configuration, type).Returns(type);
            constructorResolver.Resolve(type, Arg.Any <object?[]?>()).Returns(constructorInfo);

            var sut = new FactoryTypeCreator(CacheLevel.PerInstance);

            var actual = sut.CanCreate(configuration, buildChain, type);

            actual.Should().BeFalse();
        }
Exemplo n.º 10
0
        public void SetConstructor(ConstructorInfo? info, int parmCount)
        {
            BuilderFunc = null;

            if (info == null) return;

            var single = parmCount == 0;

            if (parmCount == -1)
                single = info.GetParameters().Length switch
                {
                    0 => true,
                    1 => false,
                    _ => single
                };

            if (parmCount > 1) return;

            if (single) BuilderFunc = o => info.Invoke(null);
            else BuilderFunc = o => info.Invoke(new[] {o});
        }
Exemplo n.º 11
0
        /// <summary>
        /// Emits an array construction code.
        /// The code assumes that bounds for all dimensions
        /// are already emitted.
        /// </summary>
        internal static void EmitArray(this ILGenerator il, Type arrayType)
        {
            Debug.Assert(arrayType != null);
            Debug.Assert(arrayType.IsArray);

            if (arrayType.IsSZArray)
            {
                il.Emit(OpCodes.Newarr, arrayType.GetElementType() !);
            }
            else
            {
                Type[] types = new Type[arrayType.GetArrayRank()];
                for (int i = 0; i < types.Length; i++)
                {
                    types[i] = typeof(int);
                }
                ConstructorInfo?ci = arrayType.GetConstructor(types);
                Debug.Assert(ci != null);
                il.EmitNew(ci);
            }
        }
        public void CanCreateReturnsFalseWhenNoPublicConstructorFound()
        {
            var             type            = typeof(FactoryItem);
            ConstructorInfo?constructorInfo = null;

            var configuration       = Substitute.For <IBuildConfiguration>();
            var typeResolver        = Substitute.For <ITypeResolver>();
            var constructorResolver = Substitute.For <IConstructorResolver>();
            var buildChain          = Substitute.For <IBuildChain>();

            configuration.TypeResolver.Returns(typeResolver);
            configuration.ConstructorResolver.Returns(constructorResolver);
            typeResolver.GetBuildType(configuration, type).Returns(type);
            constructorResolver.Resolve(type, Arg.Any <object?[]?>()).Returns(constructorInfo);

            var sut = new DefaultTypeCreator();

            var actual = sut.CanCreate(configuration, buildChain, type);

            actual.Should().BeFalse();
        }
Exemplo n.º 13
0
        public void CanCreateReturnsTrueWhenNoPublicConstructorAndStaticFactoryMethodExistsWithParameters()
        {
            var             type            = typeof(FactoryWithValue);
            ConstructorInfo?constructorInfo = null;

            var configuration       = Substitute.For <IBuildConfiguration>();
            var typeResolver        = Substitute.For <ITypeResolver>();
            var constructorResolver = Substitute.For <IConstructorResolver>();
            var buildChain          = Substitute.For <IBuildChain>();

            configuration.TypeResolver.Returns(typeResolver);
            configuration.ConstructorResolver.Returns(constructorResolver);
            typeResolver.GetBuildType(configuration, type).Returns(type);
            constructorResolver.Resolve(type, Arg.Any <object?[]?>()).Returns(constructorInfo);

            var sut = new FactoryTypeCreator(CacheLevel.PerInstance);

            var actual = sut.CanCreate(configuration, buildChain, type);

            actual.Should().BeTrue();
        }
Exemplo n.º 14
0
        internal static T Deserialize <T>(SerializationInfo info, TraceSource?traceSource)
            where T : Exception
        {
            string?runtimeTypeName = info.GetString("ClassName");

            if (runtimeTypeName is null)
            {
                throw new NotSupportedException("ClassName was not found in the serialized data.");
            }

            Type?runtimeType = Type.GetType(runtimeTypeName);

            if (runtimeType is null)
            {
                if (traceSource?.Switch.ShouldTrace(TraceEventType.Warning) ?? false)
                {
                    traceSource.TraceEvent(TraceEventType.Warning, (int)JsonRpc.TraceEvents.ExceptionTypeNotFound, "{0} type could not be loaded. Falling back to System.Exception.", runtimeTypeName);
                }

                // fallback to deserializing the base Exception type.
                runtimeType = typeof(Exception);
            }

            // Sanity/security check: ensure the runtime type derives from the expected type.
            if (!typeof(T).IsAssignableFrom(runtimeType))
            {
                throw new NotSupportedException($"{runtimeTypeName} does not derive from {typeof(T).FullName}.");
            }

            EnsureSerializableAttribute(runtimeType);

            ConstructorInfo?ctor = FindDeserializingConstructor(runtimeType);

            if (ctor is null)
            {
                throw new NotSupportedException($"{runtimeType.FullName} does not declare a deserializing constructor with signature ({string.Join(", ", DeserializingConstructorParameterTypes.Select(t => t.FullName))}).");
            }

            return((T)ctor.Invoke(new object?[] { info, Context }));
        }
Exemplo n.º 15
0
        public override object?ConvertTo(ITypeDescriptorContext?context, CultureInfo?culture, object?value, Type destinationType)
        {
            ArgumentNullException.ThrowIfNull(destinationType);

            if (value is Rectangle rect)
            {
                if (destinationType == typeof(string))
                {
                    culture ??= CultureInfo.CurrentCulture;

                    string        sep          = culture.TextInfo.ListSeparator + " ";
                    TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int));

                    // Note: ConvertToString will raise exception if value cannot be converted.
                    var args = new string?[]
                    {
                        intConverter.ConvertToString(context, culture, rect.X),
                        intConverter.ConvertToString(context, culture, rect.Y),
                        intConverter.ConvertToString(context, culture, rect.Width),
                        intConverter.ConvertToString(context, culture, rect.Height)
                    };
                    return(string.Join(sep, args));
                }
                else if (destinationType == typeof(InstanceDescriptor))
                {
                    ConstructorInfo?ctor = typeof(Rectangle).GetConstructor(new Type[] {
                        typeof(int), typeof(int), typeof(int), typeof(int)
                    });

                    if (ctor != null)
                    {
                        return(new InstanceDescriptor(ctor, new object[] {
                            rect.X, rect.Y, rect.Width, rect.Height
                        }));
                    }
                }
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Exemplo n.º 16
0
        private static ExitCode ExecuteTest(Type testClass, MethodInfo testMethod)
        {
            try
            {
                ConstructorInfo?ctorWithLogger = testClass.GetConstructors().FirstOrDefault(
                    ctor => ctor.GetParameters().Length == 1 && ctor.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(TestOutputHelper)));
                ConstructorInfo?ctorDefault       = testClass.GetConstructor(Type.EmptyTypes);
                object?         testClassInstance =
                    ctorWithLogger?.Invoke(new object[] { new TestOutputHelper() }) ??
                    ctorDefault?.Invoke(Type.EmptyTypes);
                if (testClassInstance is null)
                {
                    return(ExitCode.TestNotSupported);
                }

                object result = testMethod.Invoke(testClassInstance, Type.EmptyTypes);
                if (result is Task resultTask)
                {
                    resultTask.GetAwaiter().GetResult();
                }

                if (testClassInstance is IDisposable disposableTestClass)
                {
                    disposableTestClass.Dispose();
                }

                return(ExitCode.TestPassed);
            }
            catch (Exception ex)
            {
                if (ex.GetType().Name == "SkipException")
                {
                    return(ExitCode.TestSkipped);
                }

                Console.Error.WriteLine("Test failed.");
                Console.Error.WriteLine(ex);
                return(ExitCode.TestFailed);
            }
        }
Exemplo n.º 17
0
        internal static bool TryGet_Constructor_GenericType([NotNullWhen(true)] out ConstructorInfo?constructorInfo,
                                                            Type openGenericType, Type[] typeTypeArguments, Type[] constructorArguments)
        {
            var key = Tuple.Create(openGenericType, typeTypeArguments, constructorArguments);

            if (Constructors.TryGetValue(key, out constructorInfo))
            {
                return(true);
            }
            if (NoConstructors.Contains(key) == true)
            {
                return(false);
            }
            var typeToCreate = openGenericType;

            if (typeTypeArguments.Length != 0)
            {
                typeToCreate = typeToCreate.MakeGenericType(typeTypeArguments);
            }
            constructorInfo = typeToCreate.GetConstructor(constructorArguments);
            return(constructorInfo != default);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Loads a native procedure from a DLL.
        /// </summary>
        /// <param name="dllPath">The path to the DLL.</param>
        /// <param name="procName">The name of the procedure.</param>
        /// <param name="returnType">The return type of the procedure.</param>
        /// <param name="parameterTypes">The parameter types of the procedure.</param>
        /// <param name="callConv">The <see cref="CallConv"/> of the native procedure.</param>
        /// <returns>The <see cref="MethodInfo"/> of the procedure.</returns>
        public static MethodInfo LoadNativeProcedure(
            string dllPath,
            string procName,
            Type returnType,
            Type[] parameterTypes,
            CallConv callConv)
        {
            var asmName     = new AssemblyName("TempAssembly");
            var asmBuilder  = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
            var modBuilder  = asmBuilder.DefineDynamicModule("TempModule");
            var typeBuilder = modBuilder.DefineType("TempType", TypeAttributes.Class | TypeAttributes.Public);

            // Optional: Use if you need to set properties on DllImportAttribute
            ConstructorInfo?dllImportCtor = typeof(DllImportAttribute).GetConstructor(new Type[] { typeof(string) });

            Debug.Assert(dllImportCtor != null);
            var dllImportBuilder = new CustomAttributeBuilder(dllImportCtor, new object[] { dllPath });

            var pinvokeBuilder = typeBuilder.DefinePInvokeMethod(
                name: procName,
                dllName: dllPath,
                entryName: procName,
                attributes: MethodAttributes.Static | MethodAttributes.Public,
                callingConvention: CallingConventions.Standard,
                returnType: returnType,
                parameterTypes: parameterTypes,
                nativeCallConv: ToCallingConvention(callConv),
                nativeCharSet: CharSet.Unicode);

            pinvokeBuilder.SetCustomAttribute(dllImportBuilder);

            Type?tempType = typeBuilder.CreateType();

            Debug.Assert(tempType != null);
            MethodInfo?result = tempType.GetMethod(procName, BindingFlags.Static | BindingFlags.Public);

            Debug.Assert(result != null);
            return(result);
        }
Exemplo n.º 19
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            string data = bindingContext.HttpContext.Request.Form[bindingContext.FieldName];

            if (string.IsNullOrEmpty(data))
            {
                return(Task.CompletedTask);
            }
            Type type = bindingContext.ModelType;
            // 判断是否包含 string 构造,如果存在则调用构造转换
            ConstructorInfo?constructor = type.GetConstructor(new[] { typeof(string) });

            if (constructor != null)
            {
                bindingContext.Result = ModelBindingResult.Success(constructor.Invoke(new[] { data }));
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Success(JsonConvert.DeserializeObject(data, type));
            }
            return(Task.CompletedTask);
        }
Exemplo n.º 20
0
        private static bool TryFindConstructorWithSingleParameterOfType(
            this Type type,
            Type parameterType,
            [NotNullWhen(true)] out ConstructorInfo?ctor)
        {
            var(x, y) = type.GetConstructors()
                        .Select(c => (ctor: c, parameters: c.GetParameters()))
                        .SingleOrDefault(tuple => tuple.ctor.IsPublic &&
                                         tuple.parameters.Length == 1 &&
                                         tuple.parameters[0].ParameterType == parameterType);

            if (x != null)
            {
                ctor = x;
                return(true);
            }
            else
            {
                ctor = null;
                return(false);
            }
        }
Exemplo n.º 21
0
        public override object?ConvertTo(ITypeDescriptorContext?context, CultureInfo?culture, object?value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException(nameof(destinationType));
            }

            if (value is Point pt)
            {
                if (destinationType == typeof(string))
                {
                    if (culture == null)
                    {
                        culture = CultureInfo.CurrentCulture;
                    }

                    string        sep          = culture.TextInfo.ListSeparator + " ";
                    TypeConverter intConverter = TypeDescriptor.GetConverterTrimUnsafe(typeof(int));

                    // Note: ConvertFromString will raise exception if value cannot be converted.
                    var args = new string?[]
                    {
                        intConverter.ConvertToString(context, culture, pt.X),
                        intConverter.ConvertToString(context, culture, pt.Y)
                    };
                    return(string.Join(sep, args));
                }
                else if (destinationType == typeof(InstanceDescriptor))
                {
                    ConstructorInfo?ctor = typeof(Point).GetConstructor(new Type[] { typeof(int), typeof(int) });
                    if (ctor != null)
                    {
                        return(new InstanceDescriptor(ctor, new object[] { pt.X, pt.Y }));
                    }
                }
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Exemplo n.º 22
0
    private static ConstructorInfo GetGreediestConstructor(Type type)
    {
        ConstructorInfo?current = null;
        var             count   = -1;

        foreach (var constructor in type.GetTypeInfo().GetConstructors())
        {
            var parameters = constructor.GetParameters();
            if (parameters.Length > count)
            {
                count   = parameters.Length;
                current = constructor;
            }
        }

        if (current == null)
        {
            throw new InvalidOperationException($"Could not find a constructor for '{type.FullName}'.");
        }

        return(current);
    }
Exemplo n.º 23
0
        /// <summary>
        ///     Retrieves the constructor of the given type based on the given delegate type
        /// </summary>
        /// <param name="type"></param>
        /// <param name="delegateType"></param>
        /// <returns></returns>
        public static Delegate GetConstructorDelegate(this Type type, Type delegateType)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (delegateType == null)
            {
                throw new ArgumentNullException(nameof(delegateType));
            }

            Type[] genericArguments = delegateType.GetGenericArguments();
            Type[] argTypes         = genericArguments.Length > 1 ? genericArguments.Take(genericArguments.Length - 1).ToArray() : Type.EmptyTypes;

            ConstructorInfo?constructor = type.GetConstructor(argTypes);

            if (constructor == null)
            {
                if (argTypes.Length == 0)
                {
                    throw new InvalidOperationException($"Type '{type.Name}' doesn't have a parameterless constructor.");
                }

                throw new InvalidOperationException($"Type '{type.Name}' doesn't have the requested constructor.");
            }

            var         dynamicMethod = new DynamicMethod("DM$OBJ_FACTORY_" + type.Name, type, argTypes, type);
            ILGenerator ilGen         = dynamicMethod.GetILGenerator();

            for (int i = 0; i < argTypes.Length; i++)
            {
                ilGen.Emit(OpCodes.Ldarg, i);
            }

            ilGen.Emit(OpCodes.Newobj, constructor);
            ilGen.Emit(OpCodes.Ret);
            return(dynamicMethod.CreateDelegate(delegateType));
        }
Exemplo n.º 24
0
        public ObjectBuilder(Type? target)
        {
            if (target == null) return;

            var count = -1;
            ConstructorInfo? info = null;

            foreach (var con in target.GetConstructors())
            {
                count = con.GetParameters().Count();
                info = count switch
                {
                    0 => con,
                    1 => con,
                    _ => info
                };
            }

            if (info == null) return;

            SetConstructor(info, count);
        }
        private static ConstructorInfo?GetCompatibleConstructor(
            Type type,
            IReadOnlyDictionary <string, PropertyInfo> properties)
        {
            ConstructorInfo[] constructors = type.GetConstructors(
                BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            ConstructorInfo?defaultConstructor = constructors.FirstOrDefault(
                t => t.GetParameters().Length == 0);

            if (properties.Values.All(t => t.CanWrite))
            {
                if (defaultConstructor is not null)
                {
                    return(defaultConstructor);
                }
                else if (constructors.Length == 0)
                {
                    return(null);
                }
            }

            var required = new HashSet <string>();

            foreach (ConstructorInfo constructor in
                     constructors.OrderByDescending(t => t.GetParameters().Length))
            {
                if (IsCompatibleConstructor(constructor, properties, required))
                {
                    return(constructor);
                }
            }

            throw new InvalidOperationException(
                      $"No compatible constructor found for input type type `{type.FullName}`.\r\n" +
                      "Either you have to provide a public constructor with settable properties or " +
                      "a public constructor that allows to pass in values for read-only properties." +
                      $"There was no way to set the following properties: {string.Join(", ", required)}.");
        }
        protected sealed override ConstructorInfo ComputeConstructor()
        {
            EntityHandle ctorHandle = CustomAttribute.Constructor;

            switch (ctorHandle.Kind)
            {
            case HandleKind.MethodDefinition:
            {
                MethodDefinitionHandle mh            = (MethodDefinitionHandle)ctorHandle;
                EcmaDefinitionType     declaringType = mh.GetMethodDefinition(Reader).GetDeclaringType().ResolveTypeDef(_module);
                return(new RoDefinitionConstructor <EcmaMethodDecoder>(declaringType, new EcmaMethodDecoder(mh, _module)));
            }

            case HandleKind.MemberReference:
            {
                TypeContext              typeContext = default;
                MemberReference          mr          = ((MemberReferenceHandle)ctorHandle).GetMemberReference(Reader);
                MethodSignature <RoType> sig         = mr.DecodeMethodSignature(_module, typeContext);
                Type[]             parameterTypes    = sig.ParameterTypes.ToArray();
                Type               declaringType     = mr.Parent.ResolveTypeDefRefOrSpec(_module, typeContext);
                const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.ExactBinding;
                ConstructorInfo?   ci = declaringType.GetConstructor(bf, null, parameterTypes, null);
                if (ci == null)
                {
                    throw new MissingMethodException(SR.Format(SR.MissingCustomAttributeConstructor, declaringType));
                }
                return(ci);
            }

            // Constructors can not be generic methods so this should never occur. (Not to be confused with constructors on generic types and we do now
            // support generic attributes. But that comes in as a MemberReference, not a MethodSpec.)
            case HandleKind.MethodSpecification:
                throw new BadImageFormatException();

            default:
                throw new BadImageFormatException();
            }
        }
Exemplo n.º 27
0
        private IEnumerable <ImportDefinition> GetImportDefinitions()
        {
            List <ImportDefinition> imports = new List <ImportDefinition>();

            foreach (MemberInfo member in GetImportMembers(_type))
            {
                ReflectionMemberImportDefinition importDefinition = AttributedModelDiscovery.CreateMemberImportDefinition(member, this);
                imports.Add(importDefinition);
            }

            ConstructorInfo?constructor = GetConstructor();

            if (constructor != null)
            {
                foreach (ParameterInfo parameter in constructor.GetParameters())
                {
                    ReflectionParameterImportDefinition importDefinition = AttributedModelDiscovery.CreateParameterImportDefinition(parameter, this);
                    imports.Add(importDefinition);
                }
            }

            return(imports);
        }
Exemplo n.º 28
0
        TestableTestClassRunner(
            _ITestClass testClass,
            _IReflectionTypeInfo @class,
            IEnumerable <_ITestCase> testCases,
            List <_MessageSinkMessage> diagnosticMessages,
            IMessageBus messageBus,
            ITestCaseOrderer testCaseOrderer,
            ExceptionAggregator aggregator,
            CancellationTokenSource cancellationTokenSource,
            ConstructorInfo?constructor,
            object[] availableArguments,
            RunSummary result,
            bool cancelInRunTestMethodAsync)
            : base(testClass, @class, testCases, SpyMessageSink.Create(messages: diagnosticMessages), messageBus, testCaseOrderer, aggregator, cancellationTokenSource)
        {
            DiagnosticMessages = diagnosticMessages;
            TokenSource        = cancellationTokenSource;

            this.constructor                = constructor;
            this.availableArguments         = availableArguments;
            this.result                     = result;
            this.cancelInRunTestMethodAsync = cancelInRunTestMethodAsync;
        }
Exemplo n.º 29
0
        public ConstructorInfo?GetConstructor()
        {
            if (_constructor == null)
            {
                ConstructorInfo[]? constructors = null;
                constructors = GetImports()
                               .OfType <ReflectionParameterImportDefinition>()
                               .Select(parameterImport => parameterImport.ImportingLazyParameter.Value.Member)
                               .OfType <ConstructorInfo>()
                               .Distinct()
                               .ToArray();

                if (constructors.Length == 1)
                {
                    _constructor = constructors[0];
                }
                else if (constructors.Length == 0)
                {
                    _constructor = GetPartType().GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                }
            }
            return(_constructor);
        }
Exemplo n.º 30
0
            public override MethodBase?ProjectMethodBase(MethodBase?value)
            {
                if (value == null)
                {
                    return(null);
                }

                MethodInfo?method = value as MethodInfo;

                if (method != null)
                {
                    return(ProjectMethod(method));
                }

                ConstructorInfo?constructor = value as ConstructorInfo;

                if (constructor != null)
                {
                    return(ProjectConstructor(constructor));
                }

                throw new InvalidOperationException(SR.Format(SR.InvalidOperation_InvalidMethodType, value.GetType()));
            }