GetConstructor() public method

Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
is null.-or- One of the elements in is null. is multidimensional.-or- is multidimensional.-or- and do not have the same length.
public GetConstructor ( BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type types, ParameterModifier modifiers ) : ConstructorInfo
bindingAttr BindingFlags A bitmask comprised of one or more that specify how the search is conducted.-or- Zero, to return null.
binder Binder An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.-or- A null reference (Nothing in Visual Basic), to use the .
callConvention CallingConventions The object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and the stack is cleaned up.
types Type An array of objects representing the number, order, and type of the parameters for the constructor to get.-or- An empty array of the type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
modifiers ParameterModifier An array of objects representing the attributes associated with the corresponding element in the array. The default binder does not process this parameter.
return ConstructorInfo
Exemplo n.º 1
5
 /// <summary>
 /// Создает на основе типа фильтр
 /// </summary>
 /// <param name="lib"></param>
 /// <param name="type"></param>
 public Filter(string lib, Type type)
 {
     libname = lib;
     if (type.BaseType == typeof(AbstractFilter))
     {
         Exception fullex = new Exception("");
         ConstructorInfo ci = type.GetConstructor(System.Type.EmptyTypes);
         filter = ci.Invoke(null);
         PropertyInfo everyprop;
         everyprop = type.GetProperty("Name");
         name = (string)everyprop.GetValue(filter, null);
         everyprop = type.GetProperty("Author");
         author = (string)everyprop.GetValue(filter, null);
         everyprop = type.GetProperty("Ver");
         version = (Version)everyprop.GetValue(filter, null);
         help = type.GetMethod("Help");
         MethodInfo[] methods = type.GetMethods();
         filtrations = new List<Filtration>();
         foreach (MethodInfo mi in methods)
             if (mi.Name == "Filter")
             {
                 try
                 {
                     filtrations.Add(new Filtration(mi));
                 }
                 catch (TypeLoadException)
                 {
                     //Не добавляем фильтрацию.
                 }
             }
         if (filtrations == null) throw new TypeIncorrectException("Класс " + name + " не содержит ни одной фильтрации");
     }
     else
         throw new TypeLoadException("Класс " + type.Name + " не наследует AbstractFilter");
 }
Exemplo n.º 2
1
 public NullableMembers(Type elementType)
 {
     NullableType = NullableTypeDefinition.MakeGenericType(elementType);
     Constructor = NullableType.GetConstructor(new[] { elementType });
     GetHasValue = NullableType.GetProperty("HasValue").GetGetMethod();
     GetValue = NullableType.GetProperty("Value").GetGetMethod();
 }
Exemplo n.º 3
0
        /// <summary>创建</summary>
        /// <param name="type"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        public static ConstructorInfoX Create(Type type, Type[] types)
        {
            ConstructorInfo constructor = type.GetConstructor(types);
            if (constructor == null) constructor = type.GetConstructor(DefaultBinding, null, types, null);
            if (constructor != null) return Create(constructor);

            //ListX<ConstructorInfo> list = TypeX.Create(type).Constructors;
            //if (list != null && list.Count > 0)
            //{
            //    if (types == null || types.Length <= 1) return list[0];

            //    ListX<ConstructorInfo> list2 = new ListX<ConstructorInfo>();
            //    foreach (ConstructorInfo item in list)
            //    {
            //        ParameterInfo[] ps = item.GetParameters();
            //        if (ps == null || ps.Length < 1 || ps.Length != types.Length) continue;

            //        for (int i = 0; i < ps.Length; i++)
            //        {

            //        }
            //    }
            //}

            //// 基本不可能的错误,因为每个类都会有构造函数
            //throw new Exception("无法找到构造函数!");

            return null;
        }
 public override object Deserialize(Stream serializationStream, Type t)
 {
     var arrayField = t.BaseType.GetField("_data", BindingFlags.NonPublic | BindingFlags.Instance);
     var arrayType = arrayField.FieldType.GetElementType();
     var sizeType = (Type) t.GetField("SizeType").GetValue(null);
     var sizeFormatter = _typeFormatterFactory.GetFormatter(sizeType);
     var rawSize = sizeFormatter.Deserialize(serializationStream, sizeType);
     var arraySize = PrimitiveSupport.TypeToInt(rawSize);
     if (arrayType == typeof (Byte))
     {
         var arrayData = new byte[arraySize];
         serializationStream.Read(arrayData, 0, arraySize);
         var ret = t.GetConstructor(new Type[] {typeof (Byte[])}).Invoke(new object[] {arrayData});
         return ret;
     }
     else
     {
         var ret = t.GetConstructor(new Type[] {typeof (ulong)}).Invoke(new object[] {(ulong)arraySize});
         var array = (Array)arrayField.GetValue(ret);
         var subFormatter = _typeFormatterFactory.GetFormatter(arrayType);
         for (var i = 0; i < arraySize; i++)
         {
             array.SetValue(subFormatter.Deserialize(serializationStream, arrayType), i);
         }
         return ret;
     }
 }
Exemplo n.º 5
0
            public object GetService(System.Type serviceType)
            {
                if (_singletonObjects.TryGetValue(serviceType, out var service))
                {
                    return(service);
                }

                var ctor = serviceType.GetConstructor(new System.Type[0]);

                if (ctor != null)
                {
                    return(ctor.Invoke(new object[0]));
                }

                ctor = serviceType.GetConstructor(new[] { typeof(DefaultQuerySettings) });
                if (ctor != null)
                {
                    return(ctor.Invoke(new object[] { GetService(typeof(DefaultQuerySettings)) }));
                }

                ctor = serviceType.GetConstructor(new[] { typeof(IServiceProvider) });
                if (ctor != null)
                {
                    return(ctor.Invoke(new object[] { this }));
                }

                return(null);
            }
Exemplo n.º 6
0
        private object ConstructOverrideInstance(Type overrideType, string overrideTypeName)
        {
            object overideStepsInstance = null;

            // Invoke the override 
            var containerConstructor = overrideType.GetConstructor(new[] {typeof(IObjectContainer)});

            if (containerConstructor == null)
            {
                var defaultConstructor = overrideType.GetConstructor(Type.EmptyTypes);

                if (defaultConstructor == null)
                {
                    throw new NotSupportedException(string.Format(
                        "No suitable constructor found on steps override type '{0}'. Type must either provide a default constructor, or a constructor that takes an IObjectContainer parameter.",
                        overrideTypeName));
                }

                // Create target type using default constructor
                overideStepsInstance = defaultConstructor.Invoke(null);
            }
            else
            {
                var container = ScenarioContext.Current.GetBindingInstance(typeof(IObjectContainer)) as IObjectContainer;
                overideStepsInstance = containerConstructor.Invoke(new object[] {container});
            }
            return overideStepsInstance;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Shows the specified tool window by provide it's type.  This function
        /// has no effect if the tool window is already visible.
        /// </summary>
        /// <param name="window">The type of tool window to be shown.</param>
        public void Show(Type window)
        {
            foreach (Tool d in this.m_Windows)
            {
                if (d.GetType() == window)
                    return;
            }

            System.Reflection.ConstructorInfo constructor = null;
            Tool c = null;

            // Construct the new tool window.
            constructor = window.GetConstructor(new Type[] { });
            if (constructor == null)
            {
                constructor = window.GetConstructor(new Type[] { typeof(Tools.Manager) });
                c = constructor.Invoke(new object[] { this }) as Tool;
            }
            else
                c = constructor.Invoke(null) as Tool;

            // Add the solution loaded/unloaded events.
            Central.Manager.SolutionLoaded += new EventHandler((sender, e) =>
                {
                    c.OnSolutionLoaded();
                });
            Central.Manager.SolutionUnloaded += new EventHandler((sender, e) =>
                {
                    c.OnSolutionUnloaded();
                });

            Central.Manager.IDE.ShowDock(c, c.DefaultState);
            this.m_Windows.Add(c);
        }
Exemplo n.º 8
0
 private static void Parse(Type Match, NetIncomingMessage Message)
 {
     if (Match.GetConstructor(new Type[0]) == null) {
         throw new Exception("Message '" + Match.Name + "' Does not have an empty constructor!");
     }
     Message msg = (Message)Match.GetConstructor(new Type[0]).Invoke(new object[0]);
     msg.Receive(Message);
 }
Exemplo n.º 9
0
 public ContentType(Type type)
 {
     Type = type.AssertNotNull();
     Type.HasAttr<ContentTypeAttribute>().AssertTrue();
     (Type.Attr<ContentTypeAttribute>().Token != "binary").AssertTrue();
     Type.HasAttr<ContentTypeLocAttribute>().AssertTrue();
     Type.GetConstructor(typeof(IBranch).MkArray());
     Type.GetConstructor(typeof(IValue).MkArray());
 }
Exemplo n.º 10
0
			public ProviderInfo( Assembly assembly, Type type )
			{
				this.assembly = assembly;
				providerType = type;
				// find normal constructor (connectionstring only)
				providerConstructor = type.GetConstructor( new[] { typeof(string) } );
				Check.VerifyNotNull( providerConstructor, Error.InvalidProviderLibrary, assembly.FullName );
				// also try to find a constructor for when schema is specified
				providerSchemaConstructor = type.GetConstructor( new[] { typeof(string), typeof(string) } );
			}
Exemplo n.º 11
0
        public static ICollectionPersister Create(System.Type persisterClass, Mapping.Collection model,
                                                  ICacheConcurrencyStrategy cache, ISessionFactoryImplementor factory, Configuration cfg)
        {
            ConstructorInfo pc;
            var             use4Parameters = false;

            try
            {
                pc = persisterClass.GetConstructor(CollectionPersisterConstructorArgs);
                if (pc == null)
                {
                    use4Parameters = true;
                    pc             = persisterClass.GetConstructor(CollectionPersisterConstructor2Args);
                }
            }
            catch (Exception e)
            {
                throw new MappingException("Could not get constructor for " + persisterClass.Name, e);
            }
            if (pc == null)
            {
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine("Could not find a public constructor for " + persisterClass.Name + ";");
                messageBuilder.AppendLine("- The ctor may have " + CollectionPersisterConstructorArgs.Length + " parameters of types (in order):");
                System.Array.ForEach(CollectionPersisterConstructorArgs, t => messageBuilder.AppendLine(t.FullName));
                messageBuilder.AppendLine();
                messageBuilder.AppendLine("- The ctor may have " + CollectionPersisterConstructor2Args.Length + " parameters of types (in order):");
                System.Array.ForEach(CollectionPersisterConstructor2Args, t => messageBuilder.AppendLine(t.FullName));
                throw new MappingException(messageBuilder.ToString());
            }
            try
            {
                if (!use4Parameters)
                {
                    return((ICollectionPersister)pc.Invoke(new object[] { model, cache, factory }));
                }
                return((ICollectionPersister)pc.Invoke(new object[] { model, cache, cfg, factory }));
            }
            catch (TargetInvocationException tie)
            {
                Exception e = tie.InnerException;
                if (e is HibernateException)
                {
                    throw e;
                }
                else
                {
                    throw new MappingException("Could not instantiate collection persister " + persisterClass.Name, e);
                }
            }
            catch (Exception e)
            {
                throw new MappingException("Could not instantiate collection persister " + persisterClass.Name, e);
            }
        }
Exemplo n.º 12
0
 public void setParser(Type lexerclass, Type parserclass, String mainmethodname, Type tokentypesclass)
 {
     lexerStreamConstructorInfo = lexerclass.GetConstructor(new Type[] { typeof(Stream) });
     if (lexerStreamConstructorInfo == null) throw new ArgumentException("Lexer class invalid (no constructor for Stream)");
     lexerStringConstructorInfo = lexerclass.GetConstructor(new Type[] { typeof(TextReader) });
     if (lexerStringConstructorInfo == null) throw new ArgumentException("Lexer class invalid (no constructor for TextReader)");
     parserConstructorInfo = parserclass.GetConstructor(new Type[] { typeof(TokenStream) });
     if (parserConstructorInfo == null) throw new ArgumentException("Parser class invalid (no constructor for TokenStream)");
     mainParsingMethodInfo = parserclass.GetMethod(mainmethodname);
     typeMap = GetTypeMap(tokentypesclass);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionMappingAttribute"/> class.
        /// </summary>
        /// <param name="exceptionType">Type of the exception.</param>
        /// <param name="faultDetailType">Type of the fault detail.</param>
        public ExceptionMappingAttribute(Type exceptionType,
            Type faultDetailType)
        {
            ExceptionType = exceptionType;
            FaultType = faultDetailType;

            exceptionConstructor = FaultType.GetConstructor(new Type[] { exceptionType });

            if (exceptionConstructor == null)
                parameterlessConstructor = FaultType.GetConstructor(Type.EmptyTypes);
        }
Exemplo n.º 14
0
 public override bool Load(Queue<Token> tokens, Type tokenizerType, TemplateGroup group)
 {
     Token t = tokens.Dequeue();
     Match m = _reg.Match(t.Content);
     Tokenizer tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { m.Groups[2].Value });
     _eval = tok.TokenizeStream(group)[0];
     tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { m.Groups[4].Value });
     _search = tok.TokenizeStream(group)[0];
     tok = (Tokenizer)tokenizerType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { m.Groups[6].Value });
     _replace = tok.TokenizeStream(group)[0];
     return true;
 }
Exemplo n.º 15
0
        public override bool IsCollection(Type collectionType)
        {
            // Implements ICollection and has a constructor that takes a single element of type ICollection
            if ((typeof(ICollection).IsAssignableFrom(collectionType)
                && (collectionType.GetConstructor(new Type[] { typeof(ICollection) }) != null)))
                return true;

            Type ienumGeneric = collectionType.GetInterface(typeof(IEnumerable<>).Name);
            if (ienumGeneric != null && collectionType.GetConstructor(new Type[] { ienumGeneric }) != null)
                return true;
            else
                return false;
        }
        internal static object CreateInstanceOf(Type type, Random rndGen, CreatorSettings creatorSettings)
        {
            if (!creatorSettings.EnterRecursion())
            {
                return null;
            }

            if (rndGen.NextDouble() < creatorSettings.NullValueProbability && !type.IsValueType)
            {
                return null;
            }

            // Test convention #1: if the type has a .ctor(Random), call it and the
            // type will initialize itself.
            ConstructorInfo randomCtor = type.GetConstructor(new Type[] { typeof(Random) });
            if (randomCtor != null)
            {
                return randomCtor.Invoke(new object[] { rndGen });
            }

            // Test convention #2: if the type has a static method CreateInstance(Random, CreatorSettings), call it and
            // an new instance will be returned
            var createInstanceMtd = type.GetMethod("CreateInstance", BindingFlags.Static | BindingFlags.Public);
            if (createInstanceMtd != null)
            {
                return createInstanceMtd.Invoke(null, new object[] { rndGen, creatorSettings });
            }

            object result = null;
            if (type.IsValueType)
            {
                result = Activator.CreateInstance(type);
            }
            else
            {
                ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
                if (defaultCtor == null)
                {
                    throw new ArgumentException("Type " + type.FullName + " does not have a default constructor.");
                }

                result = defaultCtor.Invoke(new object[0]);
            }

            SetPublicProperties(type, result, rndGen, creatorSettings);
            SetPublicFields(type, result, rndGen, creatorSettings);
            creatorSettings.LeaveRecursion();
            return result;
        }
Exemplo n.º 17
0
 object CreateInstance(Type type, UnitOfWork uow) {
     Func<UnitOfWork, object> creator;
     if (!objectsCreatorDictionary.TryGetValue(type, out creator)) {
         ConstructorInfo ci = type.GetConstructor(new[] { typeof(Session) });
         if (ci == null) {
             ci = type.GetConstructor(new[] { typeof(UnitOfWork) });
             if (ci == null) throw new InvalidOperationException("ci");
             creator = Expression.Lambda<Func<UnitOfWork, object>>(Expression.Convert(Expression.New(ci, _uowParameter), typeof(object)), _uowParameter).Compile();
         } else {
             creator = Expression.Lambda<Func<UnitOfWork, object>>(Expression.Convert(Expression.New(ci, Expression.Convert(_uowParameter, typeof(Session))), typeof(object)), _uowParameter).Compile();
         }
         objectsCreatorDictionary.Add(type, creator);
     }
     return creator(uow);
 }
Exemplo n.º 18
0
 public void BuildEntityClasses(EntityModel model)
 {
     _model = model;
       //Initialize static fields
       if (_baseEntityClass == null) {
     _baseEntityClass = typeof(EntityBase);
     _baseDefaultConstructor = _baseEntityClass.GetConstructor(Type.EmptyTypes);
     _baseConstructor = _baseEntityClass.GetConstructor(new Type[] { typeof(EntityRecord) });
     _entityBase_Record = typeof(EntityBase).GetField("Record");
     _entityRecord_GetValue = typeof(EntityRecord).GetMethods().First(m => m.Name == "GetValue" && m.GetParameters()[0].ParameterType == typeof(int));
     _entityRecord_SetValue = typeof(EntityRecord).GetMethods().First(m => m.Name == "SetValue" && m.GetParameters()[0].ParameterType == typeof(int));
       }
       //Build classes
       BuildClasses();
 }
        static NameValueMultipleSectionHandler()
        {
            readOnlyNameValueCollectionType = typeof(NameValueCollection).
                Assembly.GetType("System.Configuration.ReadOnlyNameValueCollection");
            if (readOnlyNameValueCollectionType != null)
            {
                readOnlyNameValueCollectionConstructor1 =
                    readOnlyNameValueCollectionType.GetConstructor(
                    new Type[] {readOnlyNameValueCollectionType});

                readOnlyNameValueCollectionConstructor2 =
                    readOnlyNameValueCollectionType.GetConstructor(
                    new Type[] {typeof(IHashCodeProvider), typeof(IComparer)});
            }
        }
Exemplo n.º 20
0
    static public object CreateFromString(string typeName, Type[] arrParamTypes = null, object[] parameters = null)
    {
        System.Type     type            = Assembly.GetCallingAssembly().GetType(typeName);
        ConstructorInfo constructorInfo = type.GetConstructor(arrParamTypes == null ? new Type[] { } : arrParamTypes);

        return(constructorInfo.Invoke(parameters == null? new object[] { } : parameters));
    }
		public IAggregate Build(Type type, Guid id, IMemento snapshot)
		{
			ConstructorInfo constructor = type.GetConstructor(
				BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(Guid) }, null);

			return constructor.Invoke(new object[] { id }) as IAggregate;
		}
Exemplo n.º 22
0
        private static void AssertThatEndpointConfigurationTypeHasDefaultConstructor(Type type)
        {
            var constructor = type.GetConstructor(Type.EmptyTypes);

            if (constructor == null)
                throw new InvalidOperationException("Endpoint configuration type needs to have a default constructor: " + type.FullName);
        }
		private void EnsureValidBaseType(Type type)
		{
			if (type == null)
			{
				throw new ArgumentException(
					"Base type for proxy is null reference. Please set it to System.Object or some other valid type.");
			}

			if (!type.IsClass)
			{
				ThrowInvalidBaseType(type, "it is not a class type");
			}

			if(type.IsSealed)
			{
				ThrowInvalidBaseType(type, "it is sealed");
			}

			var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
			                                      null, Type.EmptyTypes, null);

			if (constructor == null || constructor.IsPrivate)
			{
				ThrowInvalidBaseType(type, "it does not have accessible parameterless constructor");
			}
		}
Exemplo n.º 24
0
 public System.Reflection.ConstructorInfo GetConstructorOf(System.String fullClassName)
 {
     System.Type clazz = classPool.GetClass(fullClassName);
     try
     {
         // Checks if exist a default constructor - with no parameters
         System.Reflection.ConstructorInfo constructor = clazz.GetConstructor(new System.Type[0]);
         return(constructor);
     }
     catch (System.MethodAccessException e)
     {
         // else take the constructer with the smaller number of parameters
         // and call it will null values
         // @TODO Put this inf oin cache !
         if (OdbConfiguration.IsDebugEnabled(LogId))
         {
             DLogger.Debug(clazz + " does not have default constructor! using a 'with parameter' constructor will null values");
         }
         System.Reflection.ConstructorInfo[] constructors = clazz.GetConstructors();
         int numberOfParameters   = 1000;
         int bestConstructorIndex = 0;
         for (int i = 0; i < constructors.Length; i++)
         {
             //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Constructor.getParameterTypes' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
             if (constructors[i].GetParameters().Length < numberOfParameters)
             {
                 bestConstructorIndex = i;
             }
         }
         System.Reflection.ConstructorInfo constructor = constructors[bestConstructorIndex];
         return(constructor);
     }
 }
Exemplo n.º 25
0
        public AggregateRoot CreateAggregateRoot(Type aggregateRootType)
        {
            ConstructorInfo constructor;

            if (_constructorInfoDict.ContainsKey(aggregateRootType))
            {
                constructor = _constructorInfoDict[aggregateRootType];
            }
            else
            {
                if (!typeof(AggregateRoot).IsAssignableFrom(aggregateRootType))
                {
                    throw new Exception(string.Format("Invalid aggregate root type {0}", aggregateRootType.FullName));
                }

                constructor = aggregateRootType.GetConstructor(_flags, null, Type.EmptyTypes, null);
                if (constructor == null)
                {
                    throw new Exception(string.Format("Could not found a default constructor on aggregate root type {0}", aggregateRootType.FullName));
                }

                _constructorInfoDict[aggregateRootType] = constructor;
            }

            return constructor.Invoke(null) as AggregateRoot;
        }
Exemplo n.º 26
0
        static StackObject *GetConstructor_29(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 5);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.ParameterModifier[] @modifiers = (System.Reflection.ParameterModifier[]) typeof(System.Reflection.ParameterModifier[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type[] @types = (System.Type[]) typeof(System.Type[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Reflection.Binder @binder = (System.Reflection.Binder) typeof(System.Reflection.Binder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 4);
            System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags) typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 5);
            System.Type instance_of_this_method = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetConstructor(@bindingAttr, @binder, @types, @modifiers);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Exemplo n.º 27
0
        public void SetResponder(System.Type responder)
        {
            if (responder == null)
            {
                responder_type = responder;
                return;
            }

            if (!typeof(IResponder).IsAssignableFrom(responder))
            {
                throw new ArgumentException(
                          Strings.Server_ResponderDoesNotImplement,
                          "responder");
            }

            // Checks that the correct constructor is available.
            if (responder.GetConstructor(new System.Type[]
                                         { typeof(ResponderRequest) }) == null)
            {
                string msg = string.Format(
                    CultureInfo.CurrentCulture,
                    Strings.Server_ResponderLacksProperConstructor,
                    responder);

                throw new ArgumentException(msg, "responder");
            }

            responder_type = responder;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initializes this lexer reflection
        /// </summary>
        /// <param name="lexerType">The lexer's type</param>
        public LexerReflection(System.Type lexerType)
        {
            ConstructorInfo ctor  = lexerType.GetConstructor(new [] { typeof(string) });
            BaseLexer       lexer = ctor.Invoke(new object[] { "" }) as BaseLexer;

            string[] resources = lexerType.Assembly.GetManifestResourceNames();
            Stream   stream    = null;

            foreach (string existing in resources)
            {
                if (existing.EndsWith(lexerType.Name + ".bin"))
                {
                    stream = lexerType.Assembly.GetManifestResourceStream(existing);
                    break;
                }
            }

            BinaryReader reader    = new BinaryReader(stream);
            Automaton    automaton = new Automaton(reader);

            reader.Close();

            LoadTerminals(lexer);
            LoadDFA(automaton);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Instantiates an object and passes in IObjectStore information
        /// If no constructor with IObjectStore data is available but there is
        /// an empty Constructor it will utilize that
        /// </summary>
        /// <param name="type"></param>
        /// <param name="constructor"></param>
        /// <returns></returns>
        public static T Instantiate <T>(this System.Type type, params IObjectStore[] constructor)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            try
            {
                if (constructor.Length > 0)
                {
                    var types = constructor.Select(x => x.GetType()).ToArray();
                    ShortLog.DebugFormat("type is {0}", type.ToString());
                    var matchConstructor = type.GetConstructor(types);

                    //Could not find a matching constructor, just try for an empty one
                    if (matchConstructor == null)
                    {
                        return((T)Activator.CreateInstance(type));
                    }
                }
                return((T)Activator.CreateInstance(type, constructor));
            }
            catch
            {
                ShortLog.ErrorFormat("Failed to created type: {0}", type.ToString());
                throw;
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// set program name and creates AssemblyBuilder, ModuleBuilder and debug Document
        /// </summary>
        /// <param name="n">N.</param>
        public void DefineProgram(string n)
        {
            this.ProgramName = n.ToUpper();

            // create AssemblyBuilder for RunAndSave
            AssemblyName aName = new AssemblyName(this.ProgramName);

            ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName,
                                                               AssemblyBuilderAccess.RunAndSave);

            // mark generated code as debuggable
            System.Type            daType    = typeof(DebuggableAttribute);
            ConstructorInfo        daCtor    = daType.GetConstructor(new System.Type[] { typeof(DebuggableAttribute.DebuggingModes) });
            CustomAttributeBuilder daBuilder = new CustomAttributeBuilder(daCtor, new object[] {
                DebuggableAttribute.DebuggingModes.DisableOptimizations |
                DebuggableAttribute.DebuggingModes.Default
            });

            ab.SetCustomAttribute(daBuilder);

            // For a single-module assembly, the module name is usually
            // the assembly name plus an extension.
            module = ab.DefineDynamicModule(this.ProgramName, this.ProgramName + ".dll", true);

            // Tell Emit about the source file that we want to associate this with.
            FileInfo info = new FileInfo(this.ProgramName + ".abap");

            doc = module.DefineDocument(info.FullName, Guid.Empty, Guid.Empty, Guid.Empty);
        }
        private static void ImplementConstructor(TypeBuilder typeBuilder, System.Type parentType, FieldInfo lazyInitializerField, FieldInfo proxyInfoField)
        {
            var constructor = typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, new[] { LazyInitializerType, typeof(NHibernateProxyFactoryInfo) });

            var baseConstructor = parentType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, System.Type.EmptyTypes, null);

            // if there is no default constructor, or the default constructor is private/internal, call System.Object constructor
            // this works, but the generated assembly will fail PeVerify (cannot use in medium trust for example)
            if (baseConstructor == null || baseConstructor.IsPrivate || baseConstructor.IsAssembly)
            {
                baseConstructor = ObjectConstructor;
            }

            var IL = constructor.GetILGenerator();

            constructor.SetImplementationFlags(MethodImplAttributes.IL | MethodImplAttributes.Managed);

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Call, baseConstructor);

            // __lazyInitializer == lazyInitializer;
            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Ldarg_1);
            IL.Emit(OpCodes.Stfld, lazyInitializerField);

            // __proxyInfo == proxyInfo;
            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Ldarg_2);
            IL.Emit(OpCodes.Stfld, proxyInfoField);

            IL.Emit(OpCodes.Ret);
        }
 public ArrayArgumentHandler(Object aObj, MemberInfo aInfo, Type aType, int aMin, int aMax)
     : base(aObj, aInfo, aType, aMin, aMax)
 {
     elementType = type.GetElementType();
       listType = typeof(List<>).MakeGenericType(new Type[] { elementType });
       list = listType.GetConstructor(new Type[] { }).Invoke(null);
 }
Exemplo n.º 33
0
        /// <summary>
        /// Создает произвольный диалог для класса из доменной модели приложения.
        /// </summary>
        /// <returns>Виджет с интерфейсом ITdiDialog</returns>
        /// <param name="objectClass">Класс объекта для которого нужно создать диалог.</param>
        /// <param name="parameters">Параметры конструктора диалога.</param>
        public static ITdiDialog CreateObjectDialog(System.Type objectClass, params object[] parameters)
        {
            System.Type dlgType = GetDialogType(objectClass);
            if (dlgType == null)
            {
                InvalidOperationException ex = new InvalidOperationException(
                    String.Format("Для класса {0} нет привязанного диалога.", objectClass));
                logger.Error(ex);
                throw ex;
            }
            Type[] paramTypes = new Type[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                paramTypes[i] = parameters[i].GetType();
            }

            System.Reflection.ConstructorInfo ci = dlgType.GetConstructor(paramTypes);
            if (ci == null)
            {
                InvalidOperationException ex = new InvalidOperationException(
                    String.Format("Конструктор для диалога {0} с параметрами({1}) не найден.", dlgType.ToString(), NHibernate.Util.CollectionPrinter.ToString(paramTypes)));
                logger.Error(ex);
                throw ex;
            }
            logger.Debug("Вызываем конструктор диалога {0} c параметрами {1}.", dlgType.ToString(), NHibernate.Util.CollectionPrinter.ToString(paramTypes));
            return((ITdiDialog)ci.Invoke(parameters));
        }
        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")
            });
        }
Exemplo n.º 35
0
        public object CreateObject(string typeName, object[] arguments)
        {
            object createdObject = null;

            System.Type[] argumentTypes = null;
            if (arguments == null || arguments.GetLength(0) == 0)
            {
                argumentTypes = System.Type.EmptyTypes;
            }
            else
            {
                argumentTypes = arguments.Select(p => p.GetType()).ToArray();
            }
            System.Type typeToConstruct = Assembly.GetType(typeName);
            System.Reflection.ConstructorInfo constructorInfoObj = typeToConstruct.GetConstructor(argumentTypes);

            if (constructorInfoObj == null)
            {
                Debug.Assert(false, "DynamicAssembly.CreateObject Failed to get the constructorInfoObject");
            }
            else
            {
                createdObject = constructorInfoObj.Invoke(arguments);
            }
            Debug.Assert(createdObject != null);
            return(createdObject);
        }
Exemplo n.º 36
0
 private static ISettingsProvider CreateProvider(Type type) {
    var ci = type.GetConstructor(Type.EmptyTypes);
    if(ci != null) {
       return ci.Invoke(new object[] { }) as ISettingsProvider;
    }
    return null;
 }
Exemplo n.º 37
0
        public void Create_Returns_Secondary_View_For_Compound_Elements(Type elementType, Type expectedType)
        {
            //Arrange
            Guid typeId = ElementAttributeGrabber.GetTypeId(elementType);

            // mock up the element definition so it returns the correct type id
            var mockDef = new Mock<IElementDefinition>();
            mockDef.Setup(m => m.ElementTypeId).Returns(typeId);

            var ctor = elementType.GetConstructor(new Type[] { typeof(Guid), typeof(IElementDefinition)});
            var el = ctor.Invoke(new object[] {typeId, mockDef.Object}) as ICompoundElement;

            var svf = new SecondaryViewFactory();

            //Act
            ISecondaryView view = svf.Create(el);

            //Assert
            Assert.NotNull(view);

            ISecondaryFxView fxView = view.SecondaryFxView;

            Assert.NotNull(fxView);
            Assert.IsType(expectedType, fxView);
        }
Exemplo n.º 38
0
        protected override bool TryConvertMap(IReferenceMap referenceMap, TypeReference elementTypeInstance, object value, out object result)
        {
            if (value == null || (value as JToken)?.Type == JTokenType.Null)
            {
                result = null;
                return(true);
            }

            if (value is JObject jsonObject)
            {
                System.Type elementType    = _types.GetFrameworkType(elementTypeInstance, false);
                System.Type dictionaryType = typeof(Dictionary <,>).MakeGenericType(typeof(string), elementType);

                ConstructorInfo dictionaryConstructor = dictionaryType.GetConstructor(new System.Type[] { });
                MethodInfo      dictionaryAddMethod   = dictionaryType.GetMethod("Add", new System.Type[] { typeof(string), elementType });
                object          dictionary            = dictionaryConstructor.Invoke(new object[] { });

                foreach (JProperty property in jsonObject.Properties())
                {
                    if (!TryConvert(elementTypeInstance, referenceMap, property.Value, out object convertedElement))
                    {
                        throw new ArgumentException("Could not convert all elements of map", nameof(value));
                    }

                    dictionaryAddMethod.Invoke(dictionary, new object[] { property.Name, convertedElement });
                }

                result = dictionary;
                return(true);
            }

            result = null;
            return(false);
        }
Exemplo n.º 39
0
        /// <summary>
        /// judge if Type t is a loadable singleton
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool Loadable(System.Type t)
        {
            PropertyInfo    pi = t.GetProperty(InstancePropertyName, BindingFlags.Static | BindingFlags.Public);
            ConstructorInfo ci = t.GetConstructor(new System.Type[0]);

            return(ci != null || pi != null);
        }
        /// <summary>
        /// Creates a metadata workspace for the specified context.
        /// </summary>
        /// <param name="contextType">The type of the object context.</param>
        /// <param name="isDbContext">Set to <c>true</c> if context is a database context.</param>
        /// <returns>The metadata workspace.</returns>
        public static MetadataWorkspace CreateMetadataWorkspace(Type contextType, bool isDbContext)
        {
            MetadataWorkspace metadataWorkspace;

            if (!isDbContext)
                metadataWorkspace = CreateMetadataWorkspaceFromResources(contextType, typeof (ObjectContext));
            else {
                metadataWorkspace = CreateMetadataWorkspaceFromResources(contextType, typeof (DbContext));
                if (metadataWorkspace == null && typeof (DbContext).IsAssignableFrom(contextType)) {
                    if (contextType.GetConstructor(Type.EmptyTypes) == null)
                        throw Error.InvalidOperation(Resource.DefaultCtorNotFound, contextType.FullName);

                    try {
                        var dbContext = Activator.CreateInstance(contextType) as DbContext;
                        var objectContext = (dbContext as IObjectContextAdapter).ObjectContext;
                        metadataWorkspace = objectContext.MetadataWorkspace;
                    }
                    catch (Exception efException) {
                        throw Error.InvalidOperation(efException, Resource.MetadataWorkspaceNotFound, contextType.FullName);
                    }
                }
            }
            if (metadataWorkspace == null)
                throw Error.InvalidOperation(Resource.LinqToEntitiesProvider_UnableToRetrieveMetadata, contextType.Name);
            return metadataWorkspace;
        }
Exemplo n.º 41
0
        public AliasToBeanResultTransformer(System.Type resultClass)
        {
            _resultClass = resultClass ?? throw new ArgumentNullException("resultClass");

            const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

            _beanConstructor = resultClass.GetConstructor(bindingFlags, 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 (_beanConstructor == null && resultClass.IsClass)
            {
                throw new ArgumentException(
                          "The target class of a AliasToBeanResultTransformer need a parameter-less constructor",
                          nameof(resultClass));
            }

            var fields     = new List <RankedMember <FieldInfo> >();
            var properties = new List <RankedMember <PropertyInfo> >();

            FetchFieldsAndProperties(fields, properties);

            _fieldsByNameCaseSensitive       = GetMapByName(fields, StringComparer.Ordinal);
            _fieldsByNameCaseInsensitive     = GetMapByName(fields, StringComparer.OrdinalIgnoreCase);
            _propertiesByNameCaseSensitive   = GetMapByName(properties, StringComparer.Ordinal);
            _propertiesByNameCaseInsensitive = GetMapByName(properties, StringComparer.OrdinalIgnoreCase);
        }
Exemplo n.º 42
0
 /// <summary>User can override to do their own debugging
 /// </summary>
 protected internal virtual void  setupDebugging(TokenStream lexer, TokenBuffer tokenBuf)
 {
     setDebugMode(true);
     // default parser debug setup is ParseView
     try
     {
         try
         {
             System.Type.GetType("javax.swing.JButton");
         }
         catch (System.Exception)
         {
             System.Console.Error.WriteLine("Swing is required to use ParseView, but is not present in your CLASSPATH");
             System.Environment.Exit(1);
         }
         System.Type c = System.Type.GetType("antlr.parseview.ParseView");
         System.Reflection.ConstructorInfo constructor = c.GetConstructor(new System.Type[] { typeof(LLkDebuggingParser), typeof(TokenStream), typeof(TokenBuffer) });
         constructor.Invoke(new object[] { this, lexer, tokenBuf });
     }
     catch (System.Exception e)
     {
         System.Console.Error.WriteLine("Error initializing ParseView: " + e);
         System.Console.Error.WriteLine("Please report this to Scott Stanchfield, [email protected]");
         System.Environment.Exit(1);
     }
 }
Exemplo n.º 43
0
        public static tydisasm GetDisassembler(string arch)
        {
            System.Type[] types = typeof(tydisasm).Assembly.GetTypes();
            System.Type   t     = null;
            foreach (System.Type test in types)
            {
                if (test.Name == (arch + "_disasm"))
                {
                    t = test;
                    break;
                }
            }

            if (t == null)
            {
                return(null);
            }
            System.Reflection.ConstructorInfo ctor = t.GetConstructor(System.Type.EmptyTypes);
            if (ctor == null)
            {
                return(null);
            }
            tydisasm ret = ctor.Invoke(null) as tydisasm;

            return(ret);
        }
Exemplo n.º 44
0
        internal static bool IsClientInstantiatableType(System.Type t, JavaScriptSerializer serializer)
        {
            bool result;

            if (t == null || t.IsAbstract || t.IsInterface || t.IsArray)
            {
                result = false;
            }
            else if (t == typeof(object))
            {
                result = false;
            }
            else
            {
                JavaScriptConverter javaScriptConverter = null;
                if (serializer.ConverterExistsForType(t, out javaScriptConverter))
                {
                    result = true;
                }
                else if (t.IsValueType)
                {
                    result = true;
                }
                else
                {
                    System.Reflection.ConstructorInfo constructor = t.GetConstructor(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public, null, ObjectConverter.s_emptyTypeArray, null);
                    result = !(constructor == null);
                }
            }
            return(result);
        }
Exemplo n.º 45
0
        /// <summary>
        /// Adds a default constructor to the target type.
        /// </summary>
        /// <param name="parentType">The base class that contains the default constructor that will be used for constructor chaining..</param>
        /// <param name="targetType">The type that will contain the default constructor.</param>
        /// <returns>The default constructor.</returns>
        public static MethodDefinition AddDefaultConstructor(this TypeDefinition targetType, Type parentType)
        {
            var module = targetType.Module;
            var voidType = module.Import(typeof(void));
            var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig
                                   | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;

            var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
            var objectConstructor = parentType.GetConstructor(flags, null, new Type[0], null);

            // Revert to the System.Object constructor
            // if the parent type does not have a default constructor
            if (objectConstructor == null)
                objectConstructor = typeof(object).GetConstructor(new Type[0]);

            var baseConstructor = module.Import(objectConstructor);

            // Define the default constructor
            var ctor = new MethodDefinition(".ctor", methodAttributes, voidType)
                           {
                               CallingConvention = MethodCallingConvention.StdCall,
                               ImplAttributes = (MethodImplAttributes.IL | MethodImplAttributes.Managed)
                           };

            var IL = ctor.Body.CilWorker;

            // Call the constructor for System.Object, and exit
            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Call, baseConstructor);
            IL.Emit(OpCodes.Ret);

            targetType.Constructors.Add(ctor);

            return ctor;
        }
Exemplo n.º 46
0
    public static object CallDefaultConstructor(System.Type type)
    {
        var constructor = type.GetConstructor(System.Type.EmptyTypes);

        Assert.IsNotNull(constructor);
        return(constructor.Invoke(null));
    }
Exemplo n.º 47
0
    static public T CreateFromString <T>(string typeName, Type[] arrParamTypes = null, object[] arrParams = null) where T : class
    {
        System.Type     type            = Assembly.GetCallingAssembly().GetType(typeName);
        ConstructorInfo constructorInfo = type.GetConstructor(arrParamTypes == null ? new Type[] { } : arrParamTypes);

        return(constructorInfo.Invoke(arrParams == null ? new object[] { } : arrParams) as T);
    }
Exemplo n.º 48
0
        public static Operator SUBSCRIPT     = new Operator(17, "Operator.SUBSCRIPT", null, Type.GetType("Flash.Tools.Debugger.Expression.SubscriptExp"));   // a[k]; see ASTBuilder.addOp() //$NON-NLS-1$

        /// <summary> We create an empty non-terminal node of the given type based on the
        /// operator.
        /// </summary>
        public NonTerminalExp createExpNode()     // throws UnknownOperationException
        {
            NonTerminalExp node = null;

            if (expressionNodeClass == null)
            {
                throw new UnknownOperationException(this);
            }
            else
            {
                try
                {
                    node = (NonTerminalExp)expressionNodeClass.GetConstructor(Type.EmptyTypes).Invoke(null);
                }
                catch (OutOfMemoryException e)
                {
                    // should never happen
                    if (Trace.error)
                    {
                        Trace.trace(e.Message);
                    }
                }
                catch (AccessViolationException e)
                {
                    // should never happen
                    if (Trace.error)
                    {
                        Trace.trace(e.Message);
                    }
                }
            }

            return(node);
        }
 private static void VerifyDefaultConstructor(Type binderType)
 {
     if (!binderType.IsValueType && binderType.GetConstructor(Type.EmptyTypes) == null)
     {
         throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "The class implementing {0} must provide a default constructor.", typeof(ICloudBlobStreamBinder<>).Name));
     }
 }
        /// <summary>
        /// 根据类型信息创建对象,该对象即使没有公有的构造方法,也可以创建实例
        /// </summary>
        /// <param name="type">创建类型时的类型信息</param>
        /// <param name="constructorParams">创建实例的初始化参数</param>
        /// <returns>实例对象</returns>
        /// <remarks>运用晚绑定方式动态创建一个实例</remarks>
        public static object CreateInstance(System.Type type, params object[] constructorParams)
        {
            ExceptionHelper.FalseThrow <ArgumentNullException>(type != null, "type");
            ExceptionHelper.FalseThrow <ArgumentNullException>(constructorParams != null, "constructorParams");

            BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;

            if (constructorParams.Length > 0)
            {
                Type[] types = new Type[constructorParams.Length];
                for (int i = 0; i < types.Length; i++)
                {
                    types[i] = constructorParams[i].GetType();
                }

                ConstructorInfo ci = type.GetConstructor(flags, null, CallingConventions.HasThis, types, null);
                if (ci != null)
                {
                    return(ci.Invoke(constructorParams));
                }
            }
            else
            {
                return(Activator.CreateInstance(type, true));
            }

            return(null);
        }
 public void DoAddButton(ReorderableList list)
 {
     if (list.serializedProperty != null)
     {
         ++list.serializedProperty.arraySize;
         list.index = list.serializedProperty.arraySize - 1;
     }
     else
     {
         System.Type elementType = list.list.GetType().GetElementType();
         if ((object)elementType == (object)typeof(string))
         {
             list.index = list.list.Add((object)"");
         }
         else if ((object)elementType != null && (object)elementType.GetConstructor(System.Type.EmptyTypes) == null)
         {
             Debug.LogError((object)("Cannot add element. Type " + elementType.ToString() + " has no default constructor. Implement a default constructor or implement your own add behaviour."));
         }
         else if ((object)list.list.GetType().GetGenericArguments()[0] != null)
         {
             list.index = list.list.Add(Activator.CreateInstance(list.list.GetType().GetGenericArguments()[0]));
         }
         else if ((object)elementType != null)
         {
             list.index = list.list.Add(Activator.CreateInstance(elementType));
         }
         else
         {
             Debug.LogError((object)"Cannot add element of type Null.");
         }
     }
 }
Exemplo n.º 52
0
 /// <summary>
 /// Reads or creates the requested object.
 /// Calls info.GetValue(key,type).
 /// If the object cannot be read, this method tries to invoke a constructor for the
 /// object with the given parameters. If the constructor invokation fails null will be returned.
 /// </summary>
 /// <param name="info">the SerializationInfo object</param>
 /// <param name="key">the name of the object</param>
 /// <param name="type">the type of the requested object</param>
 /// <param name="args">parameters for the constructor</param>
 /// <returns>the read or created object</returns>
 static public object ReadOrCreate(SerializationInfo info, string key, System.Type type, params object[] args)
 {
     try
     {
         return(info.GetValue(key, type));
     }
     catch (SerializationException)
     {
         System.Type[] types;
         if (args == null)
         {
             types = new Type[] { }
         }
         ;
         else
         {
             types = new Type[args.Length];
             for (int i = 0; i < args.Length; i++)
             {
                 types[i] = args[i].GetType();
             }
         }
         ConstructorInfo ci  = type.GetConstructor(types);
         object          res = null;
         if (ci != null)
         {
             res = ci.Invoke(args);
         }
         return(res);
     }
 }
Exemplo n.º 53
0
        protected T ExecuteWithExceptionHandledOperation <T>(Func <T> func, string errorText = null) where T : class
        {
            try
            {
                var result = func.Invoke();

                return(result);
            }
            catch (Exception ex)
            {
                ex.Data.Add("errorText-business", errorText);
                NLogLogger.Log(ex, "APPLICATION", LogPriorityEnum.High);

                if (string.IsNullOrEmpty(errorText))
                {
                    errorText = "Yapılan işlem sırasında hata oluştu.";
                }
                System.Type     type             = typeof(T);                                                                         //aynı tip oluşturulur.
                ConstructorInfo magicConstructor = type.GetConstructor(System.Type.EmptyTypes);                                       //constructure oluşturulur.
                object          magicClassObject = magicConstructor.Invoke(new object[] { });                                         //sınıf oluşturulur.
                MethodInfo      methodInfo       = type.GetMethod("Fail");                                                            //oluşturulan sınıfın Fail metodu bulunur.
                methodInfo.Invoke(magicClassObject, new object[] { 500, ex.HelpLink == "CustomException" ? ex.Message : errorText }); //ilgili metodu gelen parametrelerle çağırırız.

                return(magicClassObject as T);
            }
        }
Exemplo n.º 54
0
        /// <summary> Note that the validation context of the resulting message is set to this parser's validation
        /// context.  The validation context is used within Primitive.setValue().
        ///
        /// </summary>
        /// <param name="name">name of the desired structure in the form XXX_YYY
        /// </param>
        /// <param name="version">HL7 version (e.g. "2.3")
        /// </param>
        /// <param name="isExplicit">true if the structure was specified explicitly in MSH-9-3, false if it
        /// was inferred from MSH-9-1 and MSH-9-2.  If false, a lookup may be performed to find
        /// an alternate structure corresponding to that message type and event.
        /// </param>
        /// <returns> a Message instance
        /// </returns>
        /// <throws>  HL7Exception if the version is not recognized or no appropriate class can be found or the Message  </throws>
        /// <summary>      class throws an exception on instantiation (e.g. if args are not as expected)
        /// </summary>
        protected internal virtual Message instantiateMessage(System.String theName, System.String theVersion, bool isExplicit)
        {
            Message result = null;

            try
            {
                System.Type messageClass = myFactory.getMessageClass(theName, theVersion, isExplicit);
                if (messageClass == null)
                {
                    //UPGRADE_NOTE: Exception 'java.lang.ClassNotFoundException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
                    throw new System.Exception("Can't find message class in current package list: " + theName);
                }
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Class.getName' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                log.info("Instantiating msg of class " + messageClass.FullName);
                System.Reflection.ConstructorInfo constructor = messageClass.GetConstructor(new System.Type[] { typeof(ModelClassFactory) });
                result = (Message)constructor.Invoke(new System.Object[] { myFactory });
            }
            catch (System.Exception e)
            {
                throw new HL7Exception("Couldn't create Message object of type " + theName, HL7Exception.UNSUPPORTED_MESSAGE_TYPE, e);
            }

            result.ValidationContext = myContext;

            return(result);
        }
Exemplo n.º 55
0
 public ValidateAttribute(Type t)
 {
     if (t.BaseType == typeof(IValidator) || t.GetInterface("IValidator") is Type)
         Validator = (IValidator)t.GetConstructor(Type.EmptyTypes).Invoke(null);
     else
         throw new Exception(String.Format("The type {0} doesn't implements IValidator", t.FullName));
 }
Exemplo n.º 56
0
        private static ConstructorBuilder DefineConstructor(TypeBuilder typeBuilder, System.Type parentType)
        {
            const MethodAttributes constructorAttributes = MethodAttributes.Public |
                                                           MethodAttributes.HideBySig | MethodAttributes.SpecialName |
                                                           MethodAttributes.RTSpecialName;

            ConstructorBuilder constructor =
                typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, new System.Type[0]);

            var baseConstructor = parentType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new System.Type[0], null);

            // if there is no default constructor, or the default constructor is private/internal, call System.Object constructor
            // this works, but the generated assembly will fail PeVerify (cannot use in medium trust for example)
            if (baseConstructor == null || baseConstructor.IsPrivate || baseConstructor.IsAssembly)
            {
                baseConstructor = defaultBaseConstructor;
            }

            ILGenerator IL = constructor.GetILGenerator();

            constructor.SetImplementationFlags(MethodImplAttributes.IL | MethodImplAttributes.Managed);

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Call, baseConstructor);
            IL.Emit(OpCodes.Ret);

            return(constructor);
        }
Exemplo n.º 57
0
        /// <summary>
        /// Constructor stores group GUID and command identifier in local variables and 
        /// registers command handler in factory.
        /// </summary>
        /// <param name="groupID">Command group GUID.</param>
        /// <param name="commandID">Command identifier.</param>
        public CommandHandlerAttribute(string groupID, int commandID, Type handlerType)
        {
            if (String.IsNullOrEmpty(groupID))
                throw new ArgumentException(Resources.Error_InvalidGroupID, "groupID");
            if (handlerType == null)
                throw new ArgumentNullException("handlerType");
            
            // Check interface implementation
            if( !typeof(ICommand).IsAssignableFrom(handlerType) )
                throw new NotSupportedException(Resources.Error_NotImplementICommand);

            // Get default construction
            this.constructorRef = handlerType.GetConstructor(new Type[] { });
            if (this.constructorRef == null)
                throw new NotSupportedException(Resources.Error_NoDefaultConstructorForCommand);

            // Store handler identity information
            this.groupIDVal = new Guid(groupID);
            this.commandIDVal = commandID;

            // Register handler in the factory
            CommandFactory.Instance.RegisterCommandHandler(
                this.groupIDVal, 
                commandID, 
                new CommandFactory.CreateCommandMethod(CreateCommandHandler));
        } 
Exemplo n.º 58
0
        /// <param name="file">The file to load the List from</param>
        /// <param name="c">
        /// The Class to instantiate each member of the List. Must have a
        /// String constructor.
        /// </param>
        /// <exception cref="System.Exception"/>
        public static ICollection <T> LoadCollection <T>(File file, CollectionFactory <T> cf)
        {
            System.Type     c      = typeof(T);
            Constructor <T> m      = c.GetConstructor(new Type[] { typeof(string) });
            ICollection <T> result = cf.NewCollection();
            BufferedReader  @in    = new BufferedReader(new FileReader(file));
            string          line   = @in.ReadLine();

            while (line != null && line.Length > 0)
            {
                try
                {
                    T o = m.NewInstance(line);
                    result.Add(o);
                }
                catch (Exception e)
                {
                    log.Info("Couldn't build object from line: " + line);
                    Sharpen.Runtime.PrintStackTrace(e);
                }
                line = @in.ReadLine();
            }
            @in.Close();
            return(result);
        }
Exemplo n.º 59
0
        internal static Type makeRecord(String name,Type basetype)
        {
            if(assembly == null)
            {
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = "RecordAssembly";
            assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,AssemblyBuilderAccess.Run);
            module = assembly.DefineDynamicModule("RecordModule");
            }

            TypeBuilder tb = module.DefineType(name,TypeAttributes.Class|TypeAttributes.Public,basetype);
            Type[] paramTypes = Type.EmptyTypes;
            ConstructorBuilder cb = tb.DefineConstructor(MethodAttributes.Public,
                                                                    CallingConventions.Standard,
                                                                    paramTypes);
            ILGenerator constructorIL = cb.GetILGenerator();
            constructorIL.Emit(OpCodes.Ldarg_0);
            ConstructorInfo superConstructor = basetype.GetConstructor(Type.EmptyTypes);
            constructorIL.Emit(OpCodes.Call, superConstructor);
            constructorIL.Emit(OpCodes.Ret);

            Type t = tb.CreateType();
            //Import.AddType(t); //must do in lisp
            return t;
        }
Exemplo n.º 60
0
        /// <summary>
        /// Creates a specific Persister - could be a built in or custom persister.
        /// </summary>
        /// <param name="persisterClass"></param>
        /// <param name="model"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        public static IClassPersister Create(System.Type persisterClass, PersistentClass model, ISessionFactoryImplementor factory)
        {
            ConstructorInfo pc;

            try
            {
                pc = persisterClass.GetConstructor(PersisterFactory.PersisterConstructorArgs);
            }
            catch (Exception e)
            {
                throw new MappingException("Could not get constructor for " + persisterClass.Name, e);
            }

            try
            {
                return(( IClassPersister )pc.Invoke(new object[] { model, factory }));
            }
            catch (TargetInvocationException tie)
            {
                Exception e = tie.InnerException;
                if (e is HibernateException)
                {
                    throw e;
                }
                else
                {
                    throw new MappingException("Could not instantiate persister " + persisterClass.Name, e);
                }
            }
            catch (Exception e)
            {
                throw new MappingException("Could not instantiate persister " + persisterClass.Name, e);
            }
        }