Exemplo n.º 1
0
        /*******************************/
        /// <summary>
        /// Creates an instance of a received Type.
        /// </summary>
        /// <param name="classType">The Type of the new class instance to return.</param>
        /// <returns>An Object containing the new instance.</returns>
        public static object CreateNewInstance(System.Type classType)
        {
            if (classType == null) throw new Exception("Class not found");
            object instance = null;
            System.Type[] constructor = new System.Type[] {};
            ConstructorInfo[] constructors = null;

            constructors = classType.GetConstructors();

            if (constructors.Length == 0)
                throw new UnauthorizedAccessException();
            else
            {
                for (int i = 0; i < constructors.Length; i++)
                {
                    ParameterInfo[] parameters = constructors[i].GetParameters();

                    if (parameters.Length == 0)
                    {
                        instance = classType.GetConstructor(constructor).Invoke(new Object[] {});
                        break;
                    }
                    else if (i == constructors.Length - 1)
                        throw new MethodAccessException();
                }
            }
            return instance;
        }
		/// <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 );
			}
		}
        /// <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, System.Type parentType)
        {
            var module = targetType.Module;
            var voidType = module.Import(typeof(void));
            var methodAttributes = Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig
                                   | Mono.Cecil.MethodAttributes.SpecialName | Mono.Cecil.MethodAttributes.RTSpecialName;

            var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
            var objectConstructor = parentType.GetConstructor(flags, null, new System.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 System.Type[0]);

            var baseConstructor = module.Import(objectConstructor);

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

            var il = ctor.Body.GetILProcessor();

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

            targetType.Methods.Add(ctor);

            return ctor;
        }
Exemplo n.º 4
0
		private CreateInstanceInvoker CreateCreateInstanceMethod(System.Type type) {
			DynamicMethod method = new DynamicMethod(string.Empty, typeof(object), null, type, true);
			ILGenerator il = method.GetILGenerator();

			ConstructorInfo constructor = type.GetConstructor(EmitHelper.AnyVisibilityInstance, null, CallingConventions.HasThis, System.Type.EmptyTypes, null);
			il.Emit(OpCodes.Newobj, constructor);
			il.Emit(OpCodes.Ret);
			return (CreateInstanceInvoker)method.CreateDelegate(typeof(CreateInstanceInvoker));
		}
Exemplo n.º 5
0
 public SubDrawerAttribute( System.Type type, params object[] objects )
 {
     if ( !type.IsSubclassOf( typeof( PropertyAttribute ) ) ) return;
     System.Type[] paramTypes = objects == null ? Type.EmptyTypes : new Type[ objects.Length];
     for ( int i = 0; i < objects.Length; i++ ) {
         paramTypes[ i ] = objects[ i ].GetType();
     }
     ConstructorInfo ci = type.GetConstructor( paramTypes );
     if( ci == null ){
         Debug.Log( "GetConstructor Error" );
     }
     else{
         SecondAttribute = ci.Invoke( objects ) as PropertyAttribute;
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Creates an instance of a received Type
        /// </summary>
        /// <param name="classType">The Type of the new class instance to return</param>
        /// <returns>An Object containing the new instance</returns>
        public static System.Object CreateNewInstance(System.Type classType)
        {
            System.Reflection.ConstructorInfo[] constructors = classType.GetConstructors();

            if (constructors.Length == 0)
                return null;

            System.Reflection.ParameterInfo[] firstConstructor = constructors[0].GetParameters();
            int countParams = firstConstructor.Length;

            System.Type[] constructor = new System.Type[countParams];
            for( int i = 0; i < countParams; i++)
                constructor[i] = firstConstructor[i].ParameterType;

            return classType.GetConstructor(constructor).Invoke(new System.Object[]{});
        }
Exemplo n.º 7
0
        /// <summary>
        /// 根据类型信息创建对象,该对象即使没有公有的构造方法,也可以创建实例
        /// </summary>
        /// <param name="type">创建类型时的类型信息</param>
        /// <param name="constructorParams">创建实例的初始化参数</param>
        /// <returns>实例对象</returns>
        /// <remarks>运用晚绑定方式动态创建一个实例</remarks>
        public static object CreateInstance(System.Type type, params object[] 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;
        }
 private Com2DataTypeToManagedDataTypeConverter CreateOleTypeConverter(System.Type t)
 {
     if (t == null)
     {
         return null;
     }
     ConstructorInfo constructor = t.GetConstructor(new System.Type[] { typeof(Com2PropertyDescriptor) });
     if (constructor != null)
     {
         return (Com2DataTypeToManagedDataTypeConverter) constructor.Invoke(new object[] { this });
     }
     return (Com2DataTypeToManagedDataTypeConverter) Activator.CreateInstance(t);
 }
        //While there is a similar method in EditorUtils, due to layouting and especialy no prefix name, this has to be redone a bit differently
        static object EditorField(object o, System.Type t, bool isPersistent, GUILayoutOption[] layoutOptions)
        {
            //Check scene object type for UnityObjects. Consider Interfaces as scene object type. Assumpt that user uses interfaces with UnityObjects
            var isSceneObjectType = (typeof(Component).IsAssignableFrom(t) || t == typeof(GameObject) || t.IsInterface);
            if (typeof(UnityEngine.Object).IsAssignableFrom(t) || t.IsInterface){
                return UnityEditor.EditorGUILayout.ObjectField((UnityEngine.Object)o, t, isSceneObjectType, layoutOptions);
            }

            //Check Type second
            if (t == typeof(System.Type)){
                return EditorUtils.Popup<System.Type>(null, (System.Type)o, UserTypePrefs.GetPreferedTypesList(typeof(object), false), true, layoutOptions );
            }

            t = o != null? o.GetType() : t;
            if (t.IsAbstract){
                GUILayout.Label( string.Format("({0})", t.FriendlyName()), layoutOptions );
                return o;
            }

            if (o == null && !t.IsAbstract && !t.IsInterface && (t.GetConstructor(System.Type.EmptyTypes) != null || t.IsArray ) ){
                if (GUILayout.Button("(null) Create", layoutOptions)){
                    if (t.IsArray)
                        return System.Array.CreateInstance(t.GetElementType(), 0);
                    return System.Activator.CreateInstance(t);
                }
                return o;
            }

            if (t == typeof(bool))
                return UnityEditor.EditorGUILayout.Toggle((bool)o, layoutOptions);
            if (t == typeof(Color))
                return UnityEditor.EditorGUILayout.ColorField((Color)o, layoutOptions);
            if (t == typeof(AnimationCurve))
                return UnityEditor.EditorGUILayout.CurveField((AnimationCurve)o, layoutOptions);
            if (t.IsSubclassOf(typeof(System.Enum) ))
                return UnityEditor.EditorGUILayout.EnumPopup((System.Enum)o, layoutOptions);
            if (t == typeof(float)){
                GUI.backgroundColor = UserTypePrefs.GetTypeColor(t);
                return UnityEditor.EditorGUILayout.FloatField((float)o, layoutOptions);
            }
            if (t == typeof(int)){
                GUI.backgroundColor = UserTypePrefs.GetTypeColor(t);
                return UnityEditor.EditorGUILayout.IntField((int)o, layoutOptions);
            }
            if (t == typeof(string)){
                GUI.backgroundColor = UserTypePrefs.GetTypeColor(t);
                return UnityEditor.EditorGUILayout.TextField((string)o, layoutOptions);
            }

            if (t == typeof(Vector2))
                return UnityEditor.EditorGUILayout.Vector2Field("", (Vector2)o, layoutOptions);
            if (t == typeof(Vector3))
                return UnityEditor.EditorGUILayout.Vector3Field("", (Vector3)o, layoutOptions);
            if (t == typeof(Vector4))
                return UnityEditor.EditorGUILayout.Vector4Field("", (Vector4)o, layoutOptions);

            if (t == typeof(Quaternion)){
                var q = (Quaternion)o;
                var v = new Vector4(q.x, q.y, q.z, q.w);
                v = UnityEditor.EditorGUILayout.Vector4Field("", v, layoutOptions);
                return new Quaternion(v.x, v.y, v.z, v.w);
            }

            //If some other type, show it in the generic object editor window
            if (GUILayout.Button( string.Format("{0} {1}", t.FriendlyName(), (o is IList)? ((IList)o).Count.ToString() : "" ), layoutOptions))
                GenericInspectorWindow.Show(o, t);

            return o;
        }
Exemplo n.º 10
0
		private static ConstructorInfo GetCollectionConstructor(System.Type collectionType, System.Type elementType)
		{
			if (collectionType.IsInterface)
			{
				if (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(ISet<>))
				{
					return typeof(HashSet<>).MakeGenericType(elementType).GetConstructor(new[] { typeof(IEnumerable<>).MakeGenericType(elementType) });
				}
				return null;
			}

			return collectionType.GetConstructor(new[] { typeof(IEnumerable<>).MakeGenericType(elementType) });
		}
Exemplo n.º 11
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;
        }
 /// <summary> Create a channel with the given capacity and 
 /// semaphore implementations instantiated from the supplied class
 /// </summary>
 public SemaphoreControlledChannel(int capacity, System.Type semaphoreClass)
 {
     if (capacity <= 0)
         throw new System.ArgumentException();
     capacity_ = capacity;
     System.Type[] longarg = new System.Type[]{System.Type.GetType("System.Int64")};
     System.Reflection.ConstructorInfo ctor = semaphoreClass.GetConstructor(System.Reflection.BindingFlags.DeclaredOnly, null, longarg, null);
     object [] cap = new object [] {(System.Int64) capacity};
     putGuard_ = (Semaphore) (ctor.Invoke(cap));
     object [] zero = new object []{(System.Int64) 0};
     takeGuard_ = (Semaphore) (ctor.Invoke(zero));
 }
		public CompositionException(System.Type Type,string message, System.Exception innerException):this(String.Format("Exception:{0}\r\nAssembly:{1}\r\n{2}:{3}\r\n",message,Type.AssemblyQualifiedName,Type.GetConstructor(new System.Type[0]{}).MemberType.ToString(),Type.GetConstructor(new System.Type[0]{}).Name),innerException)
		{
			
		}
Exemplo n.º 14
0
 public static void SetPackageItemExtension(string url, System.Type type)
 {
     packageItemExtensions[url.Substring(5)] = type.GetConstructor(System.Type.EmptyTypes);
 }
				public System.Object NewInstanceOf(System.Type clazz)
		        {
		            
		                System.Reflection.ConstructorInfo constructor = null;
		                constructor = classPool.GetConstrutor(OdbClassUtil.GetFullName(clazz));
		                if (constructor == null)
		                {
		                    // Checks if exist a default constructor - with no parameters
		                    constructor = clazz.GetConstructor(Type.EmptyTypes);
		                    //UPGRADE_ISSUE: Method 'java.lang.reflect.AccessibleObject.setAccessible' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangreflectAccessibleObject'"
		                    //c by cristi
		                    //constructor.setAccessible(true);
		                    if(constructor!=null)
		                    {
		                    	classPool.AddConstrutor(OdbClassUtil.GetFullName( clazz), constructor);
		                    }
		                }
		                if (constructor != null)
		                {
		                    System.Object o = constructor.Invoke(new System.Object[0]);
		                    return o;
		                }
		
		                if (clazz.IsValueType)
		                {
		                    return Activator.CreateInstance(clazz);
		                }
		                else
		                {
		                    // else take the constructer with the smaller number of parameters
		                    // and call it will null values
		                    // @TODO Put this info in 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(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly);
		
		                    if (clazz.IsInterface)
		                    {
		                        //@TODO This is not a good solution to manage interface
		                        return null;
		                    }
		
		                    if (constructors.Length == 0)
		                    {
		                            throw new ODBRuntimeException(NeoDatisError.ClassWithoutConstructor.AddParameter(clazz.AssemblyQualifiedName));
		                    }
		                    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;
		                        }
		                    }
		                    constructor = constructors[bestConstructorIndex];
		                    //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'"
		                    System.Object[] nulls = new System.Object[constructor.GetParameters().Length];
		                    for (int i = 0; i < nulls.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'"
		                        //m by cristi
		                        if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int32"))
		                        {
		                            nulls[i] = 0;
		                        }
		                        else
		                        {
		                            //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 (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int64"))
		                            {
		                                nulls[i] = 0;
		                            }
		                            else
		                            {
		                                //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 (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Int16"))
		                                {
		                                    nulls[i] = System.Int16.Parse("0");
		                                }
		                                else
		                                {
		                                    //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'"
		                                    //main by cristi
		                                    if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.SByte"))
		                                    {
		                                        nulls[i] = System.SByte.Parse("0");
		                                    }
		                                    else
		                                    {
		                                        //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'"
		                                        //m by cristi
		                                        if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Single"))
		                                        {
		                                            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
		                                            nulls[i] = System.Single.Parse("0");
		                                        }
		                                        else
		                                        {
		                                            //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'"
		                                            //m by cristi
		                                            if (constructor.GetParameters()[i].ParameterType == System.Type.GetType("System.Double"))
		                                            {
		                                                //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
		                                                nulls[i] = System.Double.Parse("0");
		                                            }
		                                            else
		                                            {
		                                                nulls[i] = null;
		                                            }
		                                        }
		                                    }
		                                }
		                            }
		                        }
		                    }
		                    System.Object object_Renamed = null;
		
		                    //UPGRADE_ISSUE: Method 'java.lang.reflect.AccessibleObject.setAccessible' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangreflectAccessibleObject'"
		                    //c by cristi
		                    //constructor.setAccessible(true);
		                    try
		                    {
		                        object_Renamed = constructor.Invoke(nulls);
		                    }
		                    catch (System.Exception e2)
		                    {
		                             throw new ODBRuntimeException(NeoDatisError.NoNullableConstructor.AddParameter("[" + DisplayUtility.ObjectArrayToString(constructor.GetParameters()) + "]").AddParameter(clazz.AssemblyQualifiedName), e2);
		                    }
		                    return object_Renamed;
		
		
		                }
		        
		        }
 private static IEntityTuplizer BuildEntityTuplizer(System.Type implClass, PersistentClass pc, EntityMetamodel em)
 {
     try
     {
         return (IEntityTuplizer)implClass.GetConstructor(entityTuplizerCTORSignature).Invoke(new object[] { em, pc });
     }
     catch (Exception t)
     {
         throw new HibernateException("Could not build tuplizer [" + implClass.FullName + "]", t);
     }
 }
Exemplo n.º 17
0
 /// <summary> Attempts to create an instance of the given class and return 
 /// it as a Structure. 
 /// </summary>
 /// <param name="c">the Structure implementing class
 /// </param>
 /// <param name="name">an optional name of the structure (used by Generic structures; may be null)
 /// </param>
 private Structure tryToInstantiateStructure(System.Type c, System.String name)
 {
     Structure s = null;
     try
     {
         System.Object o = null;
         if (typeof(GenericSegment).IsAssignableFrom(c))
         {
             s = new GenericSegment(this, name);
         }
         else if (typeof(GenericGroup).IsAssignableFrom(c))
         {
             s = new GenericGroup(this, name, myFactory);
         }
         else
         {
             //first try to instantiate using contructor w/ Message arg ...
             try
             {
                 System.Type[] argClasses = new System.Type[]{typeof(Group), typeof(ModelClassFactory)};
                 System.Object[] argObjects = new System.Object[]{this, myFactory};
                 System.Reflection.ConstructorInfo con = c.GetConstructor(argClasses);
                 o = con.Invoke(argObjects);
             }
             catch (System.MethodAccessException)
             {
                 //UPGRADE_TODO: Method 'java.lang.Class.newInstance' was converted to 'System.Activator.CreateInstance' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangClassnewInstance'"
                 o = System.Activator.CreateInstance(c);
             }
             if (!(o is Structure))
             {
                 //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'"
                 throw new HL7Exception("Class " + c.FullName + " does not implement " + "ca.on.uhn.hl7.message.Structure", HL7Exception.APPLICATION_INTERNAL_ERROR);
             }
             s = (Structure) o;
         }
     }
     catch (System.Exception e)
     {
         if (e is HL7Exception)
         {
             throw (HL7Exception) e;
         }
         else
         {
             //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'"
             throw new HL7Exception("Can't instantiate class " + c.FullName, HL7Exception.APPLICATION_INTERNAL_ERROR, e);
         }
     }
     return s;
 }
Exemplo n.º 18
0
 /// <summary> Attempts to create an instance of the given class and return 
 /// it as a Structure. 
 /// </summary>
 /// <param name="c">the Structure implementing class
 /// </param>
 /// <param name="name">an optional name of the structure (used by Generic structures; may be null)
 /// </param>
 private IStructure tryToInstantiateStructure(System.Type c, System.String name)
 {
     IStructure s = null;
     try
     {
         System.Object o = null;
         if (typeof(GenericSegment).IsAssignableFrom(c))
         {
             s = new GenericSegment(this, name);
         }
         else if (typeof(GenericGroup).IsAssignableFrom(c))
         {
             s = new GenericGroup(this, name, myFactory);
         }
         else
         {
             //first try to instantiate using contructor w/ Message arg ...
             try
             {
                 System.Type[] argClasses = new System.Type[] { typeof(IGroup), typeof(IModelClassFactory) };
                 System.Object[] argObjects = new System.Object[] { this, myFactory };
                 System.Reflection.ConstructorInfo con = c.GetConstructor(argClasses);
                 o = con.Invoke(argObjects);
             }
             catch (System.MethodAccessException)
             {
                 o = System.Activator.CreateInstance(c);
             }
             if (!(o is IStructure))
             {
                 throw new HL7Exception("Class " + c.FullName + " does not implement " + "ca.on.uhn.hl7.message.Structure", HL7Exception.APPLICATION_INTERNAL_ERROR);
             }
             s = (IStructure)o;
         }
     }
     catch (System.Exception e)
     {
         if (e is HL7Exception)
         {
             throw (HL7Exception)e;
         }
         else
         {
             throw new HL7Exception("Can't instantiate class " + c.FullName, HL7Exception.APPLICATION_INTERNAL_ERROR, e);
         }
     }
     return s;
 }
Exemplo n.º 19
0
        /// <summary>
        /// Helper function for <see cref="UpdateEverything"/>.
        /// Parses the child nodes of the specified XML element and sets the media object
        /// to match the metadata stored in the XML element. If specified, resources
        /// of the media object will also get updated. 
        /// 
        /// <para>
        /// The method will not update child media objects of a container because child
        /// objects are not "metadata" of this media object... however, the method can store
        /// a list of child media objects in an allocated <see cref="ArrayList"/> if
        /// instructed to do so.
        /// </para>
        /// </summary>
        /// <param name="xmlElement">
        /// The xml element representing the media object with its child elements, including resources and child media objects.
        /// </param>
        /// <param name="isItem">true, if the media object is an item</param>
        /// <param name="isContainer">true, if the media object is a container</param>
        /// <param name="updateResources">true, if we are to add resources found in the xml element</param>
        /// <param name="proposedResources">store found resources here</param>
        /// <param name="updateChildren">true, if we are to add child media objects found in the xml element</param>
        /// <param name="proposedChildren">store found child media objects here</param>
        /// <param name="instantiateTheseForResources">
        /// If we encounter a resource element in the XML and we want to instantiate an object to represent it,
        /// instantiate the type specified by this argument.
        /// </param>
        /// <param name="instantiateTheseForChildItems">
        /// If we encounter a media item element in the XML and we want to instantiate an object to represent it,
        /// instantiate the type specified by this argument.
        /// </param>
        /// <param name="instantiateTheseForChildContainers">
        /// If we encounter a media container element in the XML and we want to instantiate an object to represent it,
        /// instantiate the type specified by this argument.
        /// </param>
        private void UpdateEverything_SetChildNodes(
			XmlElement xmlElement, 
			bool isItem, 
			bool isContainer, 
			bool updateResources,
			ArrayList proposedResources,
			bool updateChildren, 
			ArrayList proposedChildren, 
			System.Type instantiateTheseForResources,
			System.Type instantiateTheseForChildItems,
			System.Type instantiateTheseForChildContainers
			)
        {
            // Iterate through the child nodes (eg, metadata)

            foreach (XmlNode childNode in xmlElement.ChildNodes)
            {
                XmlElement child = childNode as XmlElement;

                if (child != null)
                {

                    bool goAhead = true;

                    if (
                        (isItem) &&
                        (
                        (string.Compare (child.Name, T[CommonPropertyNames.createClass], true) == 0) ||
                        (string.Compare (child.Name, T[CommonPropertyNames.searchClass], true) == 0)
                        )
                        )
                    {
                        goAhead = false;
                    }
                    else if (string.Compare(child.Name, T[_DIDL.Desc], true) == 0)
                    {
                        // push desc elements for now and do nothing with them
                        this.AddDescNode(child.OuterXml);
                        goAhead = false;
                    }
                    else if (string.Compare(child.Name, T[_DIDL.Res], true) == 0)
                    {
                        if (updateResources)
                        {
                            IMediaResource newRes;

                            Type[] argTypes = new Type[1];
                            argTypes[0] = typeof(XmlElement);
                            ConstructorInfo ci = instantiateTheseForResources.GetConstructor(argTypes);

                            object[] args = new object[1];
                            args[0] = child;

                            newRes = (IMediaResource) ci.Invoke(args);

                            proposedResources.Add(newRes);
                        }
                        goAhead = false;
                    }
                    else if (isContainer)
                    {
                        if (string.Compare(child.Name, T[_DIDL.Item], true) == 0)
                        {
                            if (updateChildren)
                            {
                                IMediaItem newObj = null;

                                Type[] argTypes = new Type[1];
                                argTypes[0] = typeof(XmlElement);
                                ConstructorInfo ci = instantiateTheseForChildItems.GetConstructor(argTypes);

                                object[] args = new object[1];
                                args[0] = child;

                                newObj = (IMediaItem) ci.Invoke(args);

                                proposedChildren.Add(newObj);
                            }
                            goAhead = false;
                        }
                        else if (string.Compare(child.Name, T[_DIDL.Container], true) == 0)
                        {
                            if (updateChildren)
                            {
                                IMediaContainer newObj;

                                Type[] argTypes = new Type[1];
                                argTypes[0] = typeof(XmlElement);
                                ConstructorInfo ci = instantiateTheseForChildContainers.GetConstructor(argTypes);

                                object[] args = new object[1];
                                args[0] = child;

                                newObj = (IMediaContainer) ci.Invoke(args);

                                proposedChildren.Add(newObj);
                            }
                            goAhead = false;
                        }
                    }

                    if (goAhead)
                    {
                        this.UpdateProperty(child);
                    }
                }
            }
        }
Exemplo n.º 20
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.º 21
0
        /// <summary> 
        /// Creates a new object of the given type, provided that the type has a default (parameterless) 
        /// constructor. If it does not have such a constructor, an exception will be thrown. 
        /// </summary> 
        /// <param name="type">the type of the object to construct</param> 
        /// <returns>a new instance of the given type</returns> 
        private object Construct(System.Type type)
        {
            if (!constructorCache.ContainsKey(type))
            {
                lock (this)
                {
                    if (!constructorCache.ContainsKey(type))
                    {
                        ConstructorInfo constructorInfo = type.GetConstructor(NoTypeParams);
                        if (constructorInfo == null)
                        {
                            throw new Exception(string.Format(CultureInfo.InvariantCulture, "Unable to construct instance, no parameterless constructor found in type {0}", type.FullName));

                        }
                        constructorCache.Add(type, constructorInfo);
                    }
                }
            }
            return constructorCache[type].Invoke(NoParams);
        }
 private PropertyTab CreateTab(System.Type tabType, IDesignerHost host)
 {
     PropertyTab tab = this.CreatePropertyTab(tabType);
     if (tab == null)
     {
         ConstructorInfo constructor = tabType.GetConstructor(new System.Type[] { typeof(IServiceProvider) });
         object site = null;
         if (constructor == null)
         {
             constructor = tabType.GetConstructor(new System.Type[] { typeof(IDesignerHost) });
             if (constructor != null)
             {
                 site = host;
             }
         }
         else
         {
             site = this.Site;
         }
         if ((site != null) && (constructor != null))
         {
             tab = (PropertyTab) constructor.Invoke(new object[] { site });
         }
         else
         {
             tab = (PropertyTab) Activator.CreateInstance(tabType);
         }
     }
     if (tab != null)
     {
         Bitmap original = tab.Bitmap;
         if (original == null)
         {
             throw new ArgumentException(System.Windows.Forms.SR.GetString("PropertyGridNoBitmap", new object[] { tab.GetType().FullName }));
         }
         Size size = original.Size;
         if ((size.Width != 0x10) || (size.Height != 0x10))
         {
             original = new Bitmap(original, new Size(0x10, 0x10));
         }
         string tabName = tab.TabName;
         if ((tabName == null) || (tabName.Length == 0))
         {
             throw new ArgumentException(System.Windows.Forms.SR.GetString("PropertyGridTabName", new object[] { tab.GetType().FullName }));
         }
     }
     return tab;
 }
		protected virtual bool HasVisibleDefaultConstructor(System.Type type)
		{
			ConstructorInfo constructor =
				type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
									System.Type.EmptyTypes, null);

			return constructor != null && !constructor.IsPrivate;
		}
Exemplo n.º 24
0
 private object InternalParseParam(System.Type type, object data)
 {
   if (data == null)
     return (object) null;
   IList list;
   if ((list = data as IList) != null)
   {
     if (!type.IsArray)
       throw new InvalidOperationException("Not an array " + type.FullName);
     System.Type elementType = type.GetElementType();
     ArrayList arrayList = new ArrayList();
     for (int index = 0; index < list.Count; ++index)
     {
       object obj = this.InternalParseParam(elementType, list[index]);
       arrayList.Add(obj);
     }
     return (object) arrayList.ToArray(elementType);
   }
   IDictionary dictionary;
   if ((dictionary = data as IDictionary) != null)
   {
     if (!type.IsClass)
       throw new InvalidOperationException("Not a class " + type.FullName);
     ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, (Binder) null, CallingConventions.Any, new System.Type[0], (ParameterModifier[]) null);
     if (constructor == null)
       throw new InvalidOperationException("Cannot find a default constructor for " + type.FullName);
     object obj1 = constructor.Invoke(new object[0]);
     using (List<System.Reflection.FieldInfo>.Enumerator enumerator = ((IEnumerable<System.Reflection.FieldInfo>) type.GetFields(BindingFlags.Instance | BindingFlags.Public)).ToList<System.Reflection.FieldInfo>().GetEnumerator())
     {
       while (enumerator.MoveNext())
       {
         System.Reflection.FieldInfo current = enumerator.Current;
         try
         {
           object obj2 = this.InternalParseParam(current.FieldType, dictionary[(object) current.Name]);
           current.SetValue(obj1, obj2);
         }
         catch (KeyNotFoundException ex)
         {
         }
       }
     }
     using (List<PropertyInfo>.Enumerator enumerator = ((IEnumerable<PropertyInfo>) type.GetProperties(BindingFlags.Instance | BindingFlags.Public)).ToList<PropertyInfo>().GetEnumerator())
     {
       while (enumerator.MoveNext())
       {
         PropertyInfo current = enumerator.Current;
         try
         {
           object obj2 = this.InternalParseParam(current.PropertyType, dictionary[(object) current.Name]);
           MethodInfo setMethod = current.GetSetMethod();
           if (setMethod != null)
             setMethod.Invoke(obj1, new object[1]{ obj2 });
         }
         catch (KeyNotFoundException ex)
         {
         }
         catch (TargetInvocationException ex)
         {
         }
       }
     }
     return Convert.ChangeType(obj1, type);
   }
   string str;
   if ((str = data as string) != null)
     return (object) str;
   if (data is bool)
     return (object) (bool) data;
   if (data is double)
     return (object) (double) data;
   if (data is int || data is short || (data is int || data is long) || data is long)
     return Convert.ChangeType(data, type);
   throw new InvalidOperationException("Cannot parse " + Json.Serialize(data));
 }
 void EnsureConstructorExists(System.Type type, System.Type[] constructorParams)
 {
     Assert.IsNotNull(type.GetConstructor(constructorParams));
 }
		/// <summary>
		/// Gets a view of the current collection, sorted using the given <i>sortExpression</i>.
		/// </summary>
		/// <overload>Gets a view of the current collection.</overload>
		/// <param name="collectionType">The type of collection to return.</param>
		/// <param name="sortExpression"></param>
		/// <returns>A collection of the specified <i>collectionType</i>
		/// that contains a shallow copy of the items in this collection.</returns>
		/// <remarks>
		/// Constraints: A <see cref="NotSupportedException"/> will 
		/// be thrown if any are not met.
		/// <ul>
		///		<li>The <i>collectionType</i> must implement a 
		///			default constructor ("new" constraint).</li>
		///		<li>The <i>collectionType</i> must inherit from the 
		///			<see cref="SortableCollectionBase"/> class.</li>
		/// </ul>
		/// </remarks>
		public System.Collections.IList GetNewView(System.Type collectionType, string sortExpression)
		{
			System.Reflection.ConstructorInfo ctor;
			// retrieve the property info for the specified property
			ctor = collectionType.GetConstructor(new System.Type[0]);
			if (ctor == null)
				throw new NotSupportedException(
					String.Format("The '{0}' type must have a public default constructor.", 
					collectionType.FullName));
			// get an instance of the collection type
			SortableCollectionBase view =
				ctor.Invoke(new object[] {}) as SortableCollectionBase;
			if (view == null)
				throw new NotSupportedException(
					String.Format("The '{0}' type must inherit from SortableCollectionBase.", 
					collectionType.FullName));
			for (int i = 0; i < this.List.Count; i++)
				view.InnerList.Add(base.List[i]);
			if (sortExpression != null)
				view.Sort(sortExpression);
			return view;
		}
Exemplo n.º 27
0
 public static void SetLoaderExtension(System.Type type)
 {
     loaderConstructor = type.GetConstructor(System.Type.EmptyTypes);
 }
Exemplo n.º 28
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.º 29
0
        /// <summary>
        /// Gets the default no arg constructor for the <see cref="System.Type"/>.
        /// </summary>
        /// <param name="type">The <see cref="System.Type"/> to find the constructor for.</param>
        /// <returns>
        /// The <see cref="ConstructorInfo"/> for the no argument constructor, or <see langword="null" /> if the
        /// <c>type</c> is an abstract class.
        /// </returns>
        /// <exception cref="InstantiationException">
        /// Thrown when there is a problem calling the method GetConstructor on <see cref="System.Type"/>.
        /// </exception>
        public static ConstructorInfo GetDefaultConstructor(System.Type type)
        {
            if (IsAbstractClass(type))
                return null;

            try
            {
                ConstructorInfo constructor =
                    type.GetConstructor(AnyVisibilityInstance, null, CallingConventions.HasThis, NoClasses, null);
                return constructor;
            }
            catch (Exception e)
            {
                throw new InstantiationException("A default (no-arg) constructor could not be found for: ", e, type);
            }
        }
        private static object GetSection(string sectionName, System.Type type, bool permitNull) {
            object sectionObject = null;

            // Check to see if we are running on the server without loading system.web.dll
            if (Thread.GetDomain().GetData(".appDomain") != null) {
                HttpContext context = HttpContext.Current;
                if (context != null) {
                    sectionObject = context.GetSection(sectionName);
                }
            }

            if (sectionObject == null) {
                sectionObject = ConfigurationManager.GetSection(sectionName);
            }

            if (sectionObject == null) {
                if (!permitNull) {
                    throw new ConfigurationErrorsException(SR.ConfigurationSectionErrorFormat(sectionName));
                }

                if (type != null) {
                    sectionObject = type.GetConstructor(new System.Type[0]).Invoke(new object[0]);
                }
            }
            else if (type != null && !type.IsAssignableFrom(sectionObject.GetType())) {
                throw new ConfigurationErrorsException(SR.ConfigurationSectionErrorFormat(sectionName));
            }

            return sectionObject;
        }