Inheritance: MethodBase, _ConstructorInfo
        public static string ToDescription(ConstructorInfo constructor)
        {
            var parameters = constructor.GetParameters();
            var paramList = parameters.Select(x => {
                if (x.ParameterType.IsSimple())
                {
                    return "{0} {1}".ToFormat(x.ParameterType.GetTypeName(), x.Name);
                }
                else
                {
                    if (parameters.Where(p => p.ParameterType == x.ParameterType).Count() > 1)
                    {
                        return "{0} {1}".ToFormat(x.ParameterType.GetTypeName(), x.Name);
                    }
                    else
                    {
                        return x.ParameterType.GetTypeName();
                    }
                }
            }).ToArray();



            return "new {0}({1})".ToFormat(constructor.DeclaringType.GetTypeName(), string.Join(", ", paramList));
        }
Example #2
1
 internal InterfaceObject(Type tp) : base(tp) {
     CoClassAttribute coclass = (CoClassAttribute) 
       Attribute.GetCustomAttribute(tp, cc_attr);
     if (coclass != null) {
         ctor = coclass.CoClass.GetConstructor(Type.EmptyTypes);
     }
 }
 internal CustomAttributeData(Module scope, CustomAttributeRecord caRecord)
 {
     this.m_scope = scope;
     this.m_ctor = (ConstructorInfo) RuntimeType.GetMethodBase(scope, (int) caRecord.tkCtor);
     ParameterInfo[] parametersNoCopy = this.m_ctor.GetParametersNoCopy();
     this.m_ctorParams = new CustomAttributeCtorParameter[parametersNoCopy.Length];
     for (int i = 0; i < parametersNoCopy.Length; i++)
     {
         this.m_ctorParams[i] = new CustomAttributeCtorParameter(InitCustomAttributeType(parametersNoCopy[i].ParameterType, scope));
     }
     FieldInfo[] fields = this.m_ctor.DeclaringType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
     PropertyInfo[] properties = this.m_ctor.DeclaringType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
     this.m_namedParams = new CustomAttributeNamedParameter[properties.Length + fields.Length];
     for (int j = 0; j < fields.Length; j++)
     {
         this.m_namedParams[j] = new CustomAttributeNamedParameter(fields[j].Name, CustomAttributeEncoding.Field, InitCustomAttributeType(fields[j].FieldType, scope));
     }
     for (int k = 0; k < properties.Length; k++)
     {
         this.m_namedParams[k + fields.Length] = new CustomAttributeNamedParameter(properties[k].Name, CustomAttributeEncoding.Property, InitCustomAttributeType(properties[k].PropertyType, scope));
     }
     this.m_members = new MemberInfo[fields.Length + properties.Length];
     fields.CopyTo(this.m_members, 0);
     properties.CopyTo(this.m_members, fields.Length);
     CustomAttributeEncodedArgument.ParseAttributeArguments(caRecord.blob, ref this.m_ctorParams, ref this.m_namedParams, this.m_scope);
 }
        protected override Expression VisitNew(NewExpression node)
        {
            var originalConstructorParameters = node.Arguments.Select(x => x.Type).ToList();
            var genericType = node.Constructor.DeclaringType.GetGenericTypeDefinition();
            var genericTypeParameters = genericType.GetTypeInfo().GenericTypeArguments.ToList();
            var originalGenericArgs = node.Constructor.DeclaringType.GetTypeInfo().GenericTypeArguments.ToList();

            if (genericTypeParameters.Count != _newGenericArgs.Length)
            {
                throw new InvalidOperationException("Wrong number of generic argument values specified. This type requires " + genericTypeParameters.Count + " generic type arguments");
            }
            for (int i = 0; i < _newGenericArgs.Length; i++)
            {
                var constraints = genericTypeParameters[i].GetTypeInfo().GetGenericParameterConstraints().ToList();
                foreach (var constraint in constraints)
                {
                    if (!constraint.GetTypeInfo().IsAssignableFrom(_newGenericArgs[i].GetTypeInfo()))
                    {
                        throw new InvalidOperationException("Generic type parameter " + i + " is constrained to type " + constraint + ". The supplied type " + _newGenericArgs[i] + " does not meet this constraint");
                    }
                }
            }

            result = genericType.MakeGenericType(_newGenericArgs.ToArray()).GetTypeInfo().DeclaredConstructors.Where(x => x == node.Constructor).Single();
            throw new VisitStoppedException();
        }
        private bool IsBetterChoice(ConstructorInfo current, ConstructorInfo candidate)
        {
            if (candidate.GetParameters().Any(x => x.ParameterType.IsSealed))
                return false;

            return current == null || current.GetParameters().Length < candidate.GetParameters().Length;
        }
Example #6
1
		internal NewExpression (ConstructorInfo constructor, ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<MemberInfo> members)
			: base (ExpressionType.New, constructor.DeclaringType)
		{
			this.constructor = constructor;
			this.arguments = arguments;
			this.members = members;
		}
Example #7
1
 public NullableMembers(Type elementType)
 {
     NullableType = NullableTypeDefinition.MakeGenericType(elementType);
     Constructor = NullableType.GetConstructor(new[] { elementType });
     GetHasValue = NullableType.GetProperty("HasValue").GetGetMethod();
     GetValue = NullableType.GetProperty("Value").GetGetMethod();
 }
Example #8
1
 /// <summary>
 /// Gets the number of parameters that the system recognizes
 /// </summary>
 /// <param name="Constructor">Constructor to check</param>
 /// <param name="MappingManager">Mapping manager</param>
 /// <returns>The number of parameters that it has knoweledge of</returns>
 private static int GetParameterCount(ConstructorInfo Constructor, MappingManager MappingManager)
 {
     int Count = 0;
     ParameterInfo[] Parameters = Constructor.GetParameters();
     foreach (ParameterInfo Parameter in Parameters)
     {
         bool Inject = true;
         object[] Attributes = Parameter.GetCustomAttributes(false);
         if (Attributes.Length > 0)
         {
             foreach (Attribute Attribute in Attributes)
             {
                 if (MappingManager.GetMapping(Parameter.ParameterType, Attribute.GetType()) != null)
                 {
                     ++Count;
                     Inject = false;
                     break;
                 }
             }
         }
         if (Inject)
         {
             if (MappingManager.GetMapping(Parameter.ParameterType) != null)
                 ++Count;
         }
     }
     if (Count == Parameters.Length)
         return Count;
     return int.MinValue;
 }
		public AliasToBeanResultTransformer(System.Type resultClass)
		{
			if (resultClass == null)
			{
				throw new ArgumentNullException("resultClass");
			}
			this.resultClass = resultClass;

			constructor = resultClass.GetConstructor(flags, null, System.Type.EmptyTypes, null);

			// if resultClass is a ValueType (struct), GetConstructor will return null... 
			// in that case, we'll use Activator.CreateInstance instead of the ConstructorInfo to create instances
			if (constructor == null && resultClass.IsClass)
			{
				throw new ArgumentException("The target class of a AliasToBeanResultTransformer need a parameter-less constructor",
				                            "resultClass");
			}

			propertyAccessor =
				new ChainedPropertyAccessor(new[]
				                            	{
				                            		PropertyAccessorFactory.GetPropertyAccessor(null),
				                            		PropertyAccessorFactory.GetPropertyAccessor("field")
				                            	});
		}
Example #10
1
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.DataContext == null)
                return;
            Type objtype = null;
            try
            {
                objtype = (this.DataContext as PropertyValueConverter.PropertyInfo).PropertyValue.GetType().GetMethod("Add").GetParameters().FirstOrDefault().ParameterType;
            }catch(AmbiguousMatchException)
            {
                //WPFHelper.InvalidateControl(this, ex.Message);
                    AddItemButton.IsEnabled = false;
                    AddItemButton.Content = "[no suitable add]";
                return;
            }
            ci = objtype.GetConstructor(Type.EmptyTypes);

            if (ci == null)
            {
                //last chance for strings
                Type[] types = {typeof(char[])};
                ci = objtype.GetConstructor(types);
                if (ci == null)
                {
                    AddItemButton.IsEnabled = false;
                    AddItemButton.Content = "[no default constructor]";
                }
            }
        }
 public void Init()
 {
     m_PropInstance = new PropertiesTestType();
     m_DefaultConstructor = m_TypeUnderTest.GetConstructor(Type.EmptyTypes);
     m_PropInstanceMeta  = new ObjectInstance(m_PropInstance, new ObjectCreationData(m_DefaultConstructor));
     m_ConstructorTest = new ConstructorTest(TimeSpan.FromMilliseconds(1), m_DefaultConstructor, m_PropInstance);
 }
Example #12
1
 public NewExpr(Type type, List<HostArg> args, IPersistentMap spanMap)
 {
     _args = args;
     _type = type;
     _spanMap = spanMap;
     _ctor = ComputeCtor();
 }
 public void Check(ConstructorInfo info, Dependency parent)
 {
     if (info.IsPrivate && !info.ReflectedType.IsAbstract)
     {
         parent.Add(new ProblemDependency(string.Format("This is a private constructor")));
     }
 }
        internal SerializableImplementor(EntityType ospaceEntityType)
        {
            _baseClrType = ospaceEntityType.ClrType;
            _baseImplementsISerializable = _baseClrType.IsSerializable && typeof(ISerializable).IsAssignableFrom(_baseClrType);

            if (_baseImplementsISerializable)
            {
                // Determine if interface implementation can be overridden.
                // Fortunately, there's only one method to check.
                var mapping = _baseClrType.GetInterfaceMap(typeof(ISerializable));
                _getObjectDataMethod = mapping.TargetMethods[0];

                // Members that implement interfaces must be public, unless they are explicitly implemented, in which case they are private and sealed (at least for C#).
                var canOverrideMethod = (_getObjectDataMethod.IsVirtual && !_getObjectDataMethod.IsFinal) && _getObjectDataMethod.IsPublic;

                if (canOverrideMethod)
                {
                    // Determine if proxied type provides the special serialization constructor.
                    // In order for the proxy class to properly support ISerializable, this constructor must not be private.
                    _serializationConstructor =
                        _baseClrType.GetConstructor(
                            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
                            new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);

                    _canOverride = _serializationConstructor != null
                                   &&
                                   (_serializationConstructor.IsPublic || _serializationConstructor.IsFamily
                                    || _serializationConstructor.IsFamilyOrAssembly);
                }

                Debug.Assert(
                    !(_canOverride && (_getObjectDataMethod == null || _serializationConstructor == null)),
                    "Both GetObjectData method and Serialization Constructor must be present when proxy overrides ISerializable implementation.");
            }
        }
Example #15
1
        public ConstructorMap(ConstructorInfo ctor, IEnumerable<ConstructorParameterMap> ctorParams)
        {
            Ctor = ctor;
            CtorParams = ctorParams;

            _runtimeCtor = DelegateFactory.CreateCtor(ctor, CtorParams);
        }
        public DataRowKeyInfoHelper(Type type)
        {
            this.type = type;

            this.properties = type
                .GetProperties()
                .Select(p => new {
                    Property = p,
                    Attribute = p.GetCustomAttributes(false)
                        .OfType<DataRowPropertyAttribute>()
                        .SingleOrDefault()
                })
                .Where(x => x.Attribute != null)
                .OrderBy(x => x.Attribute.Index)
                .Select(x => x.Property)
                .ToArray();

            this.ctor = type
                .GetConstructors()
                .Single();

            this.isLarge = this.type
                .GetCustomAttributes(false)
                .OfType<LargeDataRowAttribute>()
                .Any();
        }
        public ConstructorMethod GetConstructor(ConstructorInfo constructor)
        {
            DynamicMethod dynamicConstructor = CreateDynamicConstructor(constructor);
            ILGenerator il = dynamicConstructor.GetILGenerator();
            ParameterInfo[] parameters = constructor.GetParameters();
            for (int i = 0; i < parameters.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_0);
                switch (i)
                {
                    case 0: il.Emit(OpCodes.Ldc_I4_0); break;
                    case 1: il.Emit(OpCodes.Ldc_I4_1); break;
                    case 2: il.Emit(OpCodes.Ldc_I4_2); break;
                    case 3: il.Emit(OpCodes.Ldc_I4_3); break;
                    case 4: il.Emit(OpCodes.Ldc_I4_4); break;
                    case 5: il.Emit(OpCodes.Ldc_I4_5); break;
                    case 6: il.Emit(OpCodes.Ldc_I4_6); break;
                    case 7: il.Emit(OpCodes.Ldc_I4_7); break;
                    case 8: il.Emit(OpCodes.Ldc_I4_8); break;
                    default: il.Emit(OpCodes.Ldc_I4, i); break;
                }
                il.Emit(OpCodes.Ldelem_Ref);
                Type paramType = parameters[i].ParameterType;
                il.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType);
            }
            il.Emit(OpCodes.Newobj, constructor);
            il.BoxIfNeeded(constructor.DeclaringType);
            il.Emit(OpCodes.Ret);

            return (ConstructorMethod)dynamicConstructor.CreateDelegate(typeof(ConstructorMethod));
        }
Example #18
1
        private static ResolvedConstructor ResolveConstructorArguments(ConstructorInfo constructor, IDummyValueCreationSession session)
        {
            Logger.Debug("Beginning to resolve constructor with {0} arguments.", constructor.GetParameters().Length);

            var resolvedArguments = new List<ResolvedArgument>();

            foreach (var argument in constructor.GetParameters())
            {
                object result = null;

                var resolvedArgument = new ResolvedArgument
                                           {
                                               WasResolved = session.TryResolveDummyValue(argument.ParameterType, out result),
                                               ResolvedValue = result,
                                               ArgumentType = argument.ParameterType
                                           };

                Logger.Debug("Was able to resolve {0}: {1}.", argument.ParameterType, resolvedArgument.WasResolved);
                resolvedArguments.Add(resolvedArgument);
            }

            return new ResolvedConstructor
                       {
                           Arguments = resolvedArguments.ToArray()
                       };
        }
		protected override ArgumentReference[] GetCtorArgumentsAndBaseCtorToCall(Type targetFieldType, ProxyGenerationOptions proxyGenerationOptions,out ConstructorInfo baseConstructor)
		{
			if (proxyGenerationOptions.Selector == null)
			{
				baseConstructor = InvocationMethods.CompositionInvocationConstructorNoSelector;
				return new[]
				{
					new ArgumentReference(targetFieldType),
					new ArgumentReference(typeof(object)),
					new ArgumentReference(typeof(IInterceptor[])),
					new ArgumentReference(typeof(MethodInfo)),
					new ArgumentReference(typeof(object[])),
				};
			}

			baseConstructor = InvocationMethods.CompositionInvocationConstructorWithSelector;
			return new[]
			{
				new ArgumentReference(targetFieldType),
				new ArgumentReference(typeof(object)),
				new ArgumentReference(typeof(IInterceptor[])),
				new ArgumentReference(typeof(MethodInfo)),
				new ArgumentReference(typeof(object[])),
				new ArgumentReference(typeof(IInterceptorSelector)),
				new ArgumentReference(typeof(IInterceptor[]).MakeByRefType())
			};
		}
Example #20
1
 private static void DemandMemberAccessIfNeeded(ConstructorInfo constructor)
 {
     if (!constructor.IsVisible())
     {
         DemandMemberAccess(constructor);
     }
 }
 internal void InvokeBaseConstructor(ConstructorInfo constructor, params ArgumentReference[] arguments)
 {
     AddStatement(
         new ExpressionStatement(
             new ConstructorInvocationExpression(constructor,
                                                 ArgumentsUtil.ConvertArgumentReferenceToExpression(arguments))));
 }
Example #22
1
        public RecordInfo(Type type)
        {
            if (!typeof(Record).IsAssignableFrom(type))
            {
                throw new ArgumentException("Record type is not derived from Record: " + type.FullName);
            }

            var attribute = type.GetCustomAttributes(typeof(RecordAttribute), false).Cast<RecordAttribute>().FirstOrDefault();// .NET 4.5: type.GetCustomAttribute<RecordAttribute>();
            if (attribute == null)
            {
                throw new ArgumentException("Record type is missing required atribute: " + type.FullName);
            }
            signature = attribute.Signature;

            var va = type.GetCustomAttributes(typeof(VersionAttribute), false).Cast<VersionAttribute>().FirstOrDefault();// .NET 4.5: type.GetCustomAttribute<RecordAttribute>();
            if (va != null)
            {
                version = va.Version;
            }

            var da = type.GetCustomAttributes(typeof(DummyAttribute), false).Cast<DummyAttribute>().FirstOrDefault();
            isDummyRecord = da != null;

            ctor = type.GetConstructor(paramlessTypes);
            compound = InfoProvider.GetCompoundInfo(type);
        }
 // public constructor to form the custom attribute with constructor and constructor
 // parameters.
 public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
                               PropertyInfo[] namedProperties, Object[] propertyValues,
                               FieldInfo[] namedFields, Object[] fieldValues)
 {
     InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
                                propertyValues, namedFields, fieldValues);
 }
Example #24
0
		/// <summary>
		/// Generates one public constructor receiving 
		/// the <see cref="IInterceptor"/> instance and instantiating a hashtable
		/// </summary>
		protected virtual EasyConstructor GenerateConstructor( ConstructorInfo baseConstructor )
		{
			ArrayList arguments = new ArrayList();

			ArgumentReference arg1 = new ArgumentReference( Context.Interceptor );
			ArgumentReference arg2 = new ArgumentReference( typeof(object[]) );

			arguments.Add( arg1 );

			ParameterInfo[] parameters = baseConstructor.GetParameters();

			if (Context.HasMixins)
			{
				arguments.Add( arg2 );
			}

			ArgumentReference[] originalArguments = 
				ArgumentsUtil.ConvertToArgumentReference(parameters);

			arguments.AddRange(originalArguments);

			EasyConstructor constructor = MainTypeBuilder.CreateConstructor( 
				(ArgumentReference[]) arguments.ToArray( typeof(ArgumentReference) ) );

			GenerateConstructorCode(constructor.CodeBuilder, arg1, SelfReference.Self, arg2);

			constructor.CodeBuilder.InvokeBaseConstructor( baseConstructor, originalArguments );

			constructor.CodeBuilder.AddStatement( new ReturnStatement() );
			
			return constructor;
		}
Example #25
0
        private Func<object[], object> InitializeInvoker(ConstructorInfo constructorInfo)
        {
            // Target: (object)new T((T0)parameters[0], (T1)parameters[1], ...)

            // parameters to execute
            var parametersParameter = Expression.Parameter(typeof(object[]), "parameters");

            // build parameter list
            var parameterExpressions = new List<Expression>();
            var paramInfos = constructorInfo.GetParameters();
            for (int i = 0; i < paramInfos.Length; i++)
            {
                // (Ti)parameters[i]
                var valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i));
                var valueCast = Expression.Convert(valueObj, paramInfos[i].ParameterType);

                parameterExpressions.Add(valueCast);
            }

            // new T((T0)parameters[0], (T1)parameters[1], ...)
            var instanceCreate = Expression.New(constructorInfo, parameterExpressions);

            // (object)new T((T0)parameters[0], (T1)parameters[1], ...)
            var instanceCreateCast = Expression.Convert(instanceCreate, typeof(object));

            var lambda = Expression.Lambda<Func<object[], object>>(instanceCreateCast, parametersParameter);

            return lambda.Compile();
        }
        public IEnumerable<object> GetArguments(ConstructorInfo constructorInfo)
        {
            if (!_constructorArguments.ContainsKey(constructorInfo))
                return null;

            return _constructorArguments[constructorInfo];
        }
Example #27
0
        public ConstructorMap(ConstructorInfo ctor, IEnumerable<ConstructorParameterMap> ctorParams)
        {
            Ctor = ctor;
            CtorParams = ctorParams;

            _runtimeCtor = new Lazy<LateBoundParamsCtor>(() => DelegateFactory.CreateCtor(ctor, CtorParams));
        }
Example #28
0
        private bool MapDestinationCtorToSource(TypeMap typeMap, ConstructorInfo destCtor, TypeInfo sourceTypeInfo,
                                                IMappingOptions options)
        {
            var parameters = new List<ConstructorParameterMap>();
            var ctorParameters = destCtor.GetParameters();

            if (ctorParameters.Length == 0 || !options.ConstructorMappingEnabled)
                return false;

            foreach (var parameter in ctorParameters)
            {
                var members = new LinkedList<MemberInfo>();

                if (!MapDestinationPropertyToSource(members, sourceTypeInfo, parameter.Name, options))
                    return false;

                var resolvers = members.Select(mi => mi.ToMemberGetter());

                var param = new ConstructorParameterMap(parameter, resolvers.ToArray());

                parameters.Add(param);
            }

            typeMap.AddConstructorMap(destCtor, parameters);

            return true;
        }
Example #29
0
        public object[] GetParameters(IBuilderContext context, Type type, string id, ConstructorInfo constructor)
        {
            ParameterInfo[] parms = constructor.GetParameters();
            object[] parmsValueArray = new object[parms.Length];

            for (int i = 0; i < parms.Length; ++i)
            {
                if (typeof(IEnumerable).IsAssignableFrom(parms[i].ParameterType))
                {
                    Type genericList = typeof(List<>);
                    Type fullType = genericList.MakeGenericType(parms[i].ParameterType.GetGenericArguments()[0]);
                    parmsValueArray[i] = Activator.CreateInstance(fullType);

                    foreach (object o in Core.Objects.ObjectFactory.BuildAll(parms[i].ParameterType.GetGenericArguments()[0]))
                    {
                        ((IList)parmsValueArray[i]).Add(o);
                    }
                }
                else
                {
                    parmsValueArray[i] = Core.Objects.ObjectFactory.BuildUp(parms[i].ParameterType);
                }
            }
            return parmsValueArray;
        }
Example #30
0
        public static IEntity Build(Mobile from, ConstructorInfo ctor, object[] values, string[,] props, PropertyInfo[] realProps, ref bool sendError)
        {
            object built = ctor.Invoke(values);

            if (built != null && realProps != null)
            {
                bool hadError = false;

                for (int i = 0; i < realProps.Length; ++i)
                {
                    if (realProps[i] == null)
                        continue;

                    string result = Properties.InternalSetValue(from, built, built, realProps[i], props[i, 1], props[i, 1], false);

                    if (result != "Property has been set.")
                    {
                        if (sendError)
                            from.SendMessage(result);

                        hadError = true;
                    }
                }

                if (hadError)
                    sendError = false;
            }

            return (IEntity)built;
        }