Пример #1
0
        public void TestSetField()
        {
            ReflectionHelper<DummyClass> helper = helper = new ReflectionHelper<DummyClass>(
                new DummyClass(new DummyClass(new DummyClass())));

            helper.SetField("mPrivateInt", 123);
            helper.SetField("mPrivateString", "abc");
            Assert.AreEqual(123, (int)helper.GetFieldValue("mPrivateInt"));
            Assert.AreEqual("abc", (string)helper.GetFieldValue("mPrivateString"));

            helper.SetField("mProtectedInt", 123);
            helper.SetField("mProtectedString", "abc");
            Assert.AreEqual(123, (int)helper.GetFieldValue("mProtectedInt"));
            Assert.AreEqual("abc", (string)helper.GetFieldValue("mProtectedString"));

            helper.SetField("mPublicInt", 123);
            helper.SetField("mPublicString", "abc");
            Assert.AreEqual(123, (int)helper.GetFieldValue("mPublicInt"));
            Assert.AreEqual("abc", (string)helper.GetFieldValue("mPublicString"));

            helper.SetField("mSub.mPrivateString", "aaa1");
            helper.SetField("mSub.mSub.mPrivateString", "aaa2");
            Assert.AreEqual("aaa1", (string)helper.GetFieldValue("mSub.mPrivateString"));
            Assert.AreEqual("aaa2", (string)helper.GetFieldValue("mSub.mSub.mPrivateString"));

            helper.SetField("*.mPrivateString", "bbb1");
            helper.SetField("*.*.mPrivateString", "bbb2");
            Assert.AreEqual("bbb1", (string)helper.GetFieldValue("mSub.mPrivateString"));
            Assert.AreEqual("bbb2", (string)helper.GetFieldValue("mSub.mSub.mPrivateString"));

            helper.SetField("**.mPrivateString", "ccc1");
            helper.SetField("**.mSub.**.mPrivateString", "ccc2");
            Assert.AreEqual("ccc1", (string)helper.GetFieldValue("mPrivateString"));
            Assert.AreEqual("ccc2", (string)helper.GetFieldValue("mSub.mPrivateString"));
        }
Пример #2
0
		public ReflectionController (ModuleDefinition module)
		{
			m_reader = new AggressiveReflectionReader (module);
			m_writer = new ReflectionWriter (module);
			m_helper = new ReflectionHelper (module);
			m_importer = new DefaultImporter (module);
		}
Пример #3
0
        public void SetUp()
        {
            mForm = new MainForm();
            mForm.Show();
            mHelper = new ReflectionHelper<MainForm>(mForm);

            Console.WriteLine("Application.StartupPath=" + Application.StartupPath);
        }
Пример #4
0
        protected override void OnVisibleRangeChanged(VisibleRangeChangedArgs a)
        {
            var reflectionHelper = new ReflectionHelper<DayPilotTimeslotInfo>();
            DataStartField = reflectionHelper.GetPropertyName(ev => ev.StartDate);
            DataEndField = reflectionHelper.GetPropertyName(ev => ev.EndDate);
            DataIdField = reflectionHelper.GetPropertyName(ev => ev.Id);

            Events = _provider.LoadData();
        }
Пример #5
0
        public override void OnModify(DbPropertyValues originalValues, DbPropertyValues currentValues)
        {
            base.OnModify(originalValues, currentValues);

            var reflectionHelper = new ReflectionHelper<IncidentDO>();
            var priorityPropertyName = reflectionHelper.GetPropertyName(i => i.Priority);
            if (!MiscUtils.AreEqual(originalValues[priorityPropertyName], currentValues[priorityPropertyName])
                && IsHighPriority)
            {
                AlertManager.HighPriorityIncidentCreated(Id);
            }
        }
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            ReflectionHelper reflectionHelper = new ReflectionHelper();

            Assembly businessAssembly = reflectionHelper.GetAssemblyFromType(typeof(IoCBusiness));
            Assembly dataAssembly = reflectionHelper.GetAssemblyFromType(typeof(IIoCRepository<>));

            //Data Registration
            IContextRegistration<PivotEntities> contextRegistration = new PivotContextRegistration<PivotEntities>();
            contextRegistration.RegisterContext();

            //Non UnityIoCFactory Registration
            UnityIoCFactory.Instance.RegisterByConvention(businessAssembly, "Business");
            UnityIoCFactory.Instance.RegisterGenericByConvention(dataAssembly, "Repository");

            return base.CreateServiceHost(serviceType, baseAddresses);
        }
        public void IfTypeNotFoundCreatedInCache()
        {
            CreateCacheMock();

            _objectType = typeof(SampleValue);
            object outHelper = new ReflectionHelper<SampleValue>(_objectType);

            _cacheMock.Expect(v => v.TryGetValue(_objectType, out outHelper)).OutRef(outHelper).Return(false);

            var expectedHelper = new ReflectionHelper<SampleValue>(_objectType);

            _cacheMock.Expect(v => v.Add(_objectType, expectedHelper));

            var restultHelper = RunTestAction();

            restultHelper.ObjectType.Should().Be(typeof(SampleValue));
        }
Пример #8
0
        protected override void OnFinish()
        {
            // only load the data if an update was requested by an Update() call
            if (UpdateType == CallBackUpdateType.None)
            {
                return;
            }

            var reflectionHelper = new ReflectionHelper<DayPilotTimeslotInfo>();
            DataStartField = reflectionHelper.GetPropertyName(ev => ev.StartDate);
            DataEndField = reflectionHelper.GetPropertyName(ev => ev.EndDate);
            DataTextField = reflectionHelper.GetPropertyName(ev => ev.Text);
            DataIdField = reflectionHelper.GetPropertyName(ev => ev.Id);
            DataAllDayField = reflectionHelper.GetPropertyName(ev => ev.IsAllDay);
            DataTagFields = reflectionHelper.GetPropertyName(ev => ev.CalendarID);

            Events = _provider.LoadData();
        }
Пример #9
0
        public void TestGetField()
        {
            ReflectionHelper<DummyClass> helper = helper = new ReflectionHelper<DummyClass>(
                new DummyClass(new DummyClass(new DummyClass())));

            Assert.AreEqual(0, (int)helper.GetFieldValue("mPrivateInt"));
            Assert.AreEqual(null, (string)helper.GetFieldValue("mPrivateString"));

            Assert.AreEqual(0, (int)helper.GetFieldValue("mProtectedInt"));
            Assert.AreEqual(null, (string)helper.GetFieldValue("mProtectedString"));

            Assert.AreEqual(0, (int)helper.GetFieldValue("mPublicInt"));
            Assert.AreEqual(null, (string)helper.GetFieldValue("mPublicString"));

            Assert.AreEqual(null, (string)helper.GetFieldValue("mSub.mPrivateString"));
            Assert.AreEqual(null, (string)helper.GetFieldValue("mSub.mSub.mPrivateString"));

            Assert.AreEqual(null, (string)helper.GetFieldValue("*.mPrivateString"));
            Assert.AreEqual(null, (string)helper.GetFieldValue("*.*.mPrivateString"));

            Assert.AreEqual(null, (string)helper.GetFieldValue("**.mPrivateString"));
            Assert.AreEqual(null, (string)helper.GetFieldValue("**.mSub.**.mPrivateString"));
        }
Пример #10
0
        public void AsQueryable()
        {
            var simpleEntityReflection = new ReflectionHelper<IEntity>(typeof(SimpleEntity).FullName, new Mocks.DomainObjectModelMock(), null);

            {
                var entityList = new List<IEntity>() { new DerivedEntity { Data = "d" } };
                var q = simpleEntityReflection.AsQueryable(entityList);
                Console.WriteLine(q.GetType());
                Assert.IsTrue(q is IQueryable<SimpleEntity>);
                Assert.AreEqual("d", ((DerivedEntity)q.Single()).Data);
                Assert.IsFalse(object.ReferenceEquals(entityList, q));
            }
            {
                var derivedList = new List<DerivedEntity>() { new DerivedEntity { Data = "d" } };
                var q = simpleEntityReflection.AsQueryable(derivedList);
                Console.WriteLine(q.GetType());
                Assert.IsTrue(q is IQueryable<SimpleEntity>);
                Assert.AreEqual("d", ((DerivedEntity)q.Single()).Data);
                Assert.IsFalse(object.ReferenceEquals(derivedList, q));
            }
            {
                var simpleQueryable = new List<SimpleEntity>() { new DerivedEntity { Data = "d" } }.AsQueryable();
                var q = simpleEntityReflection.AsQueryable(simpleQueryable);
                Console.WriteLine(q.GetType());
                Assert.IsTrue(q is IQueryable<SimpleEntity>);
                Assert.AreEqual("d", ((DerivedEntity)q.Single()).Data);
                Assert.IsTrue(object.ReferenceEquals(simpleQueryable, q), "Optimized.");
            }
            {
                var derivedQueryable = new List<DerivedEntity>() { new DerivedEntity { Data = "d" } }.AsQueryable();
                var q = simpleEntityReflection.AsQueryable(derivedQueryable);
                Console.WriteLine(q.GetType());
                Assert.IsTrue(q is IQueryable<SimpleEntity>);
                Assert.AreEqual("d", ((DerivedEntity)q.Single()).Data);
                Assert.IsTrue(object.ReferenceEquals(derivedQueryable, q), "Optimized.");
            }
        }
Пример #11
0
 private object GetValue(string property)
 {
     return(ReflectionHelper.CreateDelegateForGetterProperty(View.GetType().GetProperty(property), View.GetType()).DynamicInvoke(View));
 }
 public static string[] GetAll()
 {
     return(ReflectionHelper.GetPublicConstantsRecursively(typeof(ProductPermissions)));
 }
Пример #13
0
        /// <summary>
        /// Validate a table to determine if any errors or warnings exist.
        /// </summary>
        /// <param name="t">Class for which a table should be validated.</param>
        /// <param name="errors">List of human-readable errors.</param>
        /// <param name="warnings">List of human-readable warnings.</param>
        /// <returns>True if the table will initialize successfully.</returns>
        public bool ValidateTable(Type t, out List <string> errors, out List <string> warnings)
        {
            if (!_Initialized)
            {
                throw new InvalidOperationException("Initialize WatsonORM and database using the .InitializeDatabase() method first.");
            }
            if (t == null)
            {
                throw new ArgumentNullException(nameof(t));
            }

            errors   = new List <string>();
            warnings = new List <string>();

            string        tableName = ReflectionHelper.GetTableNameFromType(t);
            string        primaryKeyPropertyName = ReflectionHelper.GetPrimaryKeyPropertyName(t);
            List <Column> columns = ReflectionHelper.GetColumnsFromType(t);

            bool success = true;

            if (String.IsNullOrEmpty(tableName))
            {
                errors.Add("Type '" + t.Name + "' does not have a 'Table' attribute.");
                success = false;
            }

            if (String.IsNullOrEmpty(primaryKeyPropertyName))
            {
                errors.Add("Type '" + t.Name + "' with table name '" + tableName + "' does not have a property with the 'PrimaryKey' attribute.");
                success = false;
            }

            if (columns == null || columns.Count < 1)
            {
                errors.Add("Type '" + t.Name + "' with table name '" + tableName + "' does not have any properties with a 'Column' attribute.");
                success = false;
            }

            if (!_Database.TableExists(tableName))
            {
                warnings.Add("Type '" + t.Name + "' with table name '" + tableName + "' has not yet been created and will be created upon initialization.");
            }
            else
            {
                List <Column> existingColumns = _Database.DescribeTable(tableName);

                foreach (Column column in columns)
                {
                    if (!existingColumns.Exists(c => c.Name.Equals(column.Name)))
                    {
                        errors.Add("Type '" + t.Name + "' with table name '" + tableName + "' exists but column '" + column.Name + "' does not.");
                        success = false;
                    }
                }

                List <string> existingColumnNames = existingColumns.Select(c => c.Name).ToList();
                List <string> definedColumnNames  = columns.Select(c => c.Name).ToList();
                List <string> delta = existingColumnNames.Except(definedColumnNames).ToList();
                if (delta != null && delta.Count > 0)
                {
                    foreach (string curr in delta)
                    {
                        warnings.Add("Type '" + t.Name + "' with table name '" + tableName + "' contains additional column '" + curr + "' which is not annotated in the type.");
                    }
                }
            }

            return(success);
        }
Пример #14
0
 public void can_convert_nullable_boolean_values()
 {
     new BooleanFamily().Matches(ReflectionHelper.GetProperty <DummyClass>(c => c.Thirsty)).ShouldBeTrue();
 }
Пример #15
0
 public void ParseScale_PercentSign()
 {
     Assert.AreEqual(43, ReflectionHelper.GetIntResult(
                         typeof(DomainImpl.CmPictureFactory),
                         "ParseScaleFactor", "43%"));
 }
Пример #16
0
 public void ParseScale_MultipleNumbers()
 {
     Assert.AreEqual(93, ReflectionHelper.GetIntResult(
                         typeof(DomainImpl.CmPictureFactory),
                         "ParseScaleFactor", "down 93, hut1, hut2, 34, 0, hike!"));
 }
Пример #17
0
            void DefineEventSupport(EventInfo e, ProxyOptions generationOptions)
            {
                // Defines the hook field: Delegate _dXXX;
                FieldBuilder dField = _typeBuilder.DefineField("_d" + e.Name, typeof(Delegate), FieldAttributes.Private);

                // Defines the event field: <EventHandler> _hookXXX;
                FieldBuilder hField = _typeBuilder.DefineField("_hook" + e.Name, e.EventHandlerType, FieldAttributes.Private);

                int eventMetaRef = RegisterRef(_eRefs, e);

                // Implements our hook method.
                MethodBuilder mHookB;
                {
                    MethodInfo mCall      = e.EventHandlerType.GetMethod("Invoke");
                    Type[]     parameters = ReflectionHelper.CreateParametersType(mCall.GetParameters());
                    mHookB = _typeBuilder.DefineMethod("_realService_" + e.Name, MethodAttributes.Private, CallingConventions.HasThis, typeof(void), parameters);
                    {
                        SetDebuggerStepThroughAttribute(mHookB);
                        ILGenerator  g          = mHookB.GetILGenerator();
                        LocalBuilder logOptions = g.DeclareLocal(typeof(ServiceLogEventOptions));
                        LocalBuilder logger     = g.DeclareLocal(typeof(LogEventEntry));

                        g.Emit(OpCodes.Ldarg_0);
                        g.LdInt32(eventMetaRef);
                        g.Emit(OpCodes.Ldloca_S, logger);
                        g.Emit(OpCodes.Ldloca_S, logOptions);
                        string getLoggerName;
                        switch (generationOptions.RuntimeCheckStatus)
                        {
                        case ProxyOptions.CheckStatus.None: getLoggerName = "GetLoggerEventForAnyCall"; break;

                        case ProxyOptions.CheckStatus.NotDisabled: getLoggerName = "GetLoggerEventForNotDisabledCall"; break;

                        default: getLoggerName = "GetLoggerEventForRunningCall"; break;     //ProxyOptions.CheckStatus.Running
                        }
                        g.EmitCall(OpCodes.Call, _definition.ProxyBase.GetMethod(getLoggerName, BindingFlags.NonPublic | BindingFlags.Instance), null);

                        Label doRaise = g.DefineLabel();
                        g.Emit(OpCodes.Brtrue_S, doRaise);
                        g.Emit(OpCodes.Ret);
                        g.MarkLabel(doRaise);

                        LocalBuilder client     = g.DeclareLocal(typeof(Delegate));
                        LocalBuilder exception  = generationOptions.CatchExceptions ? g.DeclareLocal(typeof(Exception)) : null;
                        LocalBuilder list       = g.DeclareLocal(typeof(Delegate[]));
                        LocalBuilder listLength = g.DeclareLocal(typeof(int));
                        LocalBuilder index      = g.DeclareLocal(typeof(int));
                        // Maps actual parameters.
                        for (int i = 0; i < parameters.Length; ++i)
                        {
                            if (parameters[i].IsAssignableFrom(_definition.TypeInterface))
                            {
                                g.LdArg(i + 1);
                                g.Emit(OpCodes.Ldarg_0);
                                g.Emit(OpCodes.Ldfld, _implField);
                                Label notTheSender = g.DefineLabel();
                                g.Emit(OpCodes.Bne_Un_S, notTheSender);
                                g.Emit(OpCodes.Ldarg_0);
                                g.StArg(i + 1);
                                g.MarkLabel(notTheSender);
                            }
                        }
                        // Should we log parameters?
                        if (parameters.Length > 0)
                        {
                            Label skipLogParam = g.DefineLabel();
                            g.LdLoc(logOptions);
                            g.LdInt32((int)ServiceLogEventOptions.LogParameters);
                            g.Emit(OpCodes.And);
                            g.Emit(OpCodes.Brfalse, skipLogParam);

                            LocalBuilder paramsArray = g.DeclareLocal(typeof(object[]));
                            g.CreateObjectArrayFromInstanceParameters(paramsArray, parameters);

                            g.LdLoc(logger);
                            g.LdLoc(paramsArray);
                            g.Emit(OpCodes.Stfld, typeof(LogEventEntry).GetField("_parameters", BindingFlags.Instance | BindingFlags.NonPublic));

                            g.MarkLabel(skipLogParam);
                        }


                        // Gets all the delegate to call in list.
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, dField);
                        g.EmitCall(OpCodes.Callvirt, _delegateGetInvocationList, null);
                        g.StLoc(list);
                        // listLength = list.Length;
                        g.LdLoc(list);
                        g.Emit(OpCodes.Ldlen);
                        g.Emit(OpCodes.Conv_I4);
                        g.StLoc(listLength);
                        // index = 0;
                        g.Emit(OpCodes.Ldc_I4_0);
                        g.StLoc(index);

                        Label beginOfLoop = g.DefineLabel();
                        Label endOfLoop   = g.DefineLabel();
                        g.Emit(OpCodes.Br_S, endOfLoop);

                        g.MarkLabel(beginOfLoop);
                        // client = list[index];
                        g.LdLoc(list);
                        g.LdLoc(index);
                        g.Emit(OpCodes.Ldelem_Ref);
                        g.StLoc(client);

                        if (generationOptions.CatchExceptions)
                        {
                            g.BeginExceptionBlock();
                        }
                        g.LdLoc(client);
                        g.Emit(OpCodes.Castclass, e.EventHandlerType);
                        g.RepushActualParameters(false, parameters.Length);
                        g.EmitCall(OpCodes.Callvirt, mCall, null);

                        if (generationOptions.CatchExceptions)
                        {
                            Label bottomOfLoop = g.DefineLabel();
                            g.Emit(OpCodes.Leave_S, bottomOfLoop);

                            g.BeginCatchBlock(typeof(Exception));
                            g.StLoc(exception);

                            g.Emit(OpCodes.Ldarg_0);
                            g.LdInt32(eventMetaRef);
                            g.LdLoc(client);
                            g.EmitCall(OpCodes.Callvirt, _delegateGetMethod, null);

                            g.LdLoc(exception);
                            g.Emit(OpCodes.Ldloca_S, logger);
                            g.EmitCall(OpCodes.Call, _definition.ProxyBase.GetMethod("OnEventHandlingException", BindingFlags.NonPublic | BindingFlags.Instance), null);

                            Label continueDispatch = g.DefineLabel();
                            g.Emit(OpCodes.Brtrue_S, continueDispatch);
                            g.Emit(OpCodes.Rethrow);
                            g.MarkLabel(continueDispatch);

                            g.Emit(OpCodes.Leave_S, bottomOfLoop);
                            g.EndExceptionBlock();

                            g.MarkLabel(bottomOfLoop);
                        }
                        // ++index;
                        g.LdLoc(index);
                        g.Emit(OpCodes.Ldc_I4_1);
                        g.Emit(OpCodes.Add);
                        g.StLoc(index);

                        // Checks whether we must continue the loop.
                        g.MarkLabel(endOfLoop);
                        g.LdLoc(index);
                        g.LdLoc(listLength);
                        g.Emit(OpCodes.Blt_S, beginOfLoop);

                        // if( (o & LogMethodOptions.Leave) != 0 )
                        // {
                        g.LdLoc(logOptions);
                        g.LdInt32((int)ServiceLogEventOptions.EndRaise);
                        g.Emit(OpCodes.And);
                        Label skipLogPostCall = g.DefineLabel();
                        g.Emit(OpCodes.Brfalse, skipLogPostCall);

                        g.Emit(OpCodes.Ldarg_0);
                        g.LdLoc(logger);
                        g.EmitCall(OpCodes.Call, _definition.ProxyBase.GetMethod("LogEndRaise", BindingFlags.NonPublic | BindingFlags.Instance), null);
                        g.MarkLabel(skipLogPostCall);
                        // }

                        g.Emit(OpCodes.Ret);
                    }
                }
                // Defines the event property itself: <EventHandler> XXX;
                EventBuilder eB = _typeBuilder.DefineEvent(e.Name, e.Attributes, e.EventHandlerType);

                // Implements the add_
                MethodInfo mAdd = e.GetAddMethod(true);

                if (mAdd != null)
                {
                    // Registers the method to skip its processing.
                    _processedMethods.Add(mAdd);

                    Type[]        parameters = ReflectionHelper.CreateParametersType(mAdd.GetParameters());
                    MethodBuilder mAddB      = _typeBuilder.DefineMethod(mAdd.Name,
                                                                         MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.Virtual,
                                                                         CallingConventions.HasThis, mAdd.ReturnType, parameters);
                    {
                        SetDebuggerStepThroughAttribute(mAddB);
                        ILGenerator g = mAddB.GetILGenerator();

                        Label dFieldOK = g.DefineLabel();

                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, dField);
                        g.Emit(OpCodes.Brtrue_S, dFieldOK);

                        Label hFieldOK = g.DefineLabel();
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, hField);
                        g.Emit(OpCodes.Brtrue_S, hFieldOK);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldftn, mHookB);
                        g.Emit(OpCodes.Newobj, e.EventHandlerType.GetConstructor(new Type[] { typeof(Object), typeof(IntPtr) }));
                        g.Emit(OpCodes.Stfld, hField);

                        g.MarkLabel(hFieldOK);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, _implField);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, hField);
                        g.Emit(OpCodes.Callvirt, mAdd);

                        g.MarkLabel(dFieldOK);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, dField);
                        g.Emit(OpCodes.Ldarg_1);
                        g.Emit(OpCodes.Call, _delegateCombine);
                        g.Emit(OpCodes.Stfld, dField);

                        g.Emit(OpCodes.Ret);
                    }
                    eB.SetAddOnMethod(mAddB);
                }

                // Implements the remove_
                MethodInfo mRemove = e.GetRemoveMethod(true);

                if (mRemove != null)
                {
                    // Registers the method to skip its processing.
                    _processedMethods.Add(mRemove);

                    Type[]        parameters = ReflectionHelper.CreateParametersType(mRemove.GetParameters());
                    MethodBuilder mRemoveB   = _typeBuilder.DefineMethod(mRemove.Name,
                                                                         MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.Virtual,
                                                                         CallingConventions.HasThis,
                                                                         mRemove.ReturnType, parameters);
                    {
                        SetDebuggerStepThroughAttribute(mRemoveB);
                        ILGenerator g = mRemoveB.GetILGenerator();

                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, dField);
                        g.Emit(OpCodes.Ldarg_1);
                        g.Emit(OpCodes.Call, _delegateRemove);
                        g.Emit(OpCodes.Stfld, dField);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, dField);
                        Label end = g.DefineLabel();
                        g.Emit(OpCodes.Brtrue_S, end);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, _implField);
                        g.Emit(OpCodes.Ldarg_0);
                        g.Emit(OpCodes.Ldfld, hField);
                        g.Emit(OpCodes.Callvirt, mRemove);
                        g.MarkLabel(end);

                        g.Emit(OpCodes.Ret);
                    }
                    eB.SetRemoveOnMethod(mRemoveB);
                }
            }
Пример #18
0
        public void get_the_flag_name_for_a_property_with_an_alias()
        {
            var property = ReflectionHelper.GetProperty <InputModel>(x => x.AliasedFlag);

            InputParser.ToFlagName(property).ShouldEqual("-a");
        }
Пример #19
0
        public void get_the_flag_name_for_a_property()
        {
            var property = ReflectionHelper.GetProperty <InputModel>(x => x.OrderFlag);

            InputParser.ToFlagName(property).ShouldEqual("-order");
        }
Пример #20
0
        public void return_a_null_converter()
        {
            var property = ReflectionHelper.GetProperty <TargetHolder>(x => x.Target);

            new ValueConverterRegistry(new IConverterFamily[0]).FindConverter(property).ShouldBeNull();
        }
Пример #21
0
        static ITypeReference ParseTypeName(string typeName, ref int pos)
        {
            string reflectionTypeName = typeName;

            if (pos == typeName.Length)
            {
                throw new ReflectionNameParseException(pos, "Unexpected end");
            }
            ITypeReference result;

            if (reflectionTypeName[pos] == '`')
            {
                // type parameter reference
                pos++;
                if (pos == reflectionTypeName.Length)
                {
                    throw new ReflectionNameParseException(pos, "Unexpected end");
                }
                if (reflectionTypeName[pos] == '`')
                {
                    // method type parameter reference
                    pos++;
                    int index = ReflectionHelper.ReadTypeParameterCount(reflectionTypeName, ref pos);
                    result = TypeParameterReference.Create(SymbolKind.Method, index);
                }
                else
                {
                    // class type parameter reference
                    int index = ReflectionHelper.ReadTypeParameterCount(reflectionTypeName, ref pos);
                    result = TypeParameterReference.Create(SymbolKind.TypeDefinition, index);
                }
            }
            else
            {
                // not a type parameter reference: read the actual type name
                List <ITypeReference> typeArguments = new List <ITypeReference>();
                int    typeParameterCount;
                string typeNameWithoutSuffix = ReadTypeName(typeName, ref pos, true, out typeParameterCount, typeArguments);
                result = new GetPotentiallyNestedClassTypeReference(typeNameWithoutSuffix, typeParameterCount);
                while (pos < typeName.Length && typeName[pos] == '.')
                {
                    pos++;
                    string nestedTypeName = ReadTypeName(typeName, ref pos, false, out typeParameterCount, typeArguments);
                    result = new NestedTypeReference(result, nestedTypeName, typeParameterCount);
                }
                if (typeArguments.Count > 0)
                {
                    result = new ParameterizedTypeReference(result, typeArguments);
                }
            }
            while (pos < typeName.Length)
            {
                switch (typeName[pos])
                {
                case '[':
                    int dimensions = 1;
                    do
                    {
                        pos++;
                        if (pos == typeName.Length)
                        {
                            throw new ReflectionNameParseException(pos, "Unexpected end");
                        }
                        if (typeName[pos] == ',')
                        {
                            dimensions++;
                        }
                    } while (typeName[pos] != ']');
                    result = new ArrayTypeReference(result, dimensions);
                    break;

                case '*':
                    result = new PointerTypeReference(result);
                    break;

                case '@':
                    result = new ByReferenceTypeReference(result);
                    break;

                default:
                    return(result);
                }
                pos++;
            }
            return(result);
        }
Пример #22
0
        /// <summary>
        /// Define a primitive setter property by specifying the property name with
        /// an expression
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public PropertyExpression <SmartInstance <T> > WithProperty(Expression <Func <T, object> > expression)
        {
            string propertyName = ReflectionHelper.GetProperty(expression).Name;

            return(WithProperty(propertyName));
        }
Пример #23
0
        /// <summary>
        /// The actual repacking process, called by main after parsing arguments.
        /// When referencing this assembly, call this after setting the merge properties.
        /// </summary>
        public void Repack()
        {
            Options.Validate();
            PrintRepackVersion();
            _reflectionHelper = new ReflectionHelper(this);
            ResolveSearchDirectories();

            // Read input assemblies only after all properties are set.
            ReadInputAssemblies();
            GlobalAssemblyResolver.RegisterAssemblies(MergedAssemblies);

            _platformFixer = new PlatformFixer(this, PrimaryAssemblyMainModule.Runtime);
            _mappingHandler = new MappingHandler();
            bool hadStrongName = PrimaryAssemblyDefinition.Name.HasPublicKey;

            ModuleKind kind = PrimaryAssemblyMainModule.Kind;
            if (Options.TargetKind.HasValue)
            {
                switch (Options.TargetKind.Value)
                {
                    case Kind.Dll: kind = ModuleKind.Dll; break;
                    case Kind.Exe: kind = ModuleKind.Console; break;
                    case Kind.WinExe: kind = ModuleKind.Windows; break;
                }
            }
            TargetRuntime runtime = ParseTargetPlatform();

            // change assembly's name to correspond to the file we create
            string mainModuleName = Path.GetFileNameWithoutExtension(Options.OutputFile);

            if (TargetAssemblyDefinition == null)
            {
                AssemblyNameDefinition asmName = Clone(PrimaryAssemblyDefinition.Name);
                asmName.Name = mainModuleName;
                TargetAssemblyDefinition = AssemblyDefinition.CreateAssembly(asmName, mainModuleName,
                    new ModuleParameters()
                    {
                        Kind = kind,
                        Architecture = PrimaryAssemblyMainModule.Architecture,
                        AssemblyResolver = GlobalAssemblyResolver,
                        Runtime = runtime
                    });
            }
            else
            {
                // TODO: does this work or is there more to do?
                TargetAssemblyMainModule.Kind = kind;
                TargetAssemblyMainModule.Runtime = runtime;

                TargetAssemblyDefinition.Name.Name = mainModuleName;
                TargetAssemblyMainModule.Name = mainModuleName;
            }
            // set the main module attributes
            TargetAssemblyMainModule.Attributes = PrimaryAssemblyMainModule.Attributes;
            TargetAssemblyMainModule.Win32ResourceDirectory = MergeWin32Resources(PrimaryAssemblyMainModule.Win32ResourceDirectory);

            if (Options.Version != null)
                TargetAssemblyDefinition.Name.Version = Options.Version;

            _lineIndexer = new IKVMLineIndexer(this, Options.LineIndexation);
            var signingStep = new SigningStep(this, Options);

            List<IRepackStep> repackSteps = new List<IRepackStep>
            {
                signingStep,
                new ReferencesRepackStep(Logger, this),
                new TypesRepackStep(Logger, this, _repackImporter, Options),
                new ResourcesRepackStep(Logger, this, Options),
                new AttributesRepackStep(Logger, this, _repackImporter, Options),
                new ReferencesFixStep(Logger, this, _repackImporter, Options),
                new XamlResourcePathPatcherStep(Logger, this)
            };

            foreach (var step in repackSteps)
            {
                step.Perform();
            }

            var parameters = new WriterParameters
            {
                StrongNameKeyPair = signingStep.KeyPair,
                WriteSymbols = Options.DebugInfo
            };
            // create output directory if it does not exist
            var outputDir = Path.GetDirectoryName(Options.OutputFile);
            if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir))
            {
                Logger.Info("Output directory does not exist. Creating output directory: " + outputDir);
                Directory.CreateDirectory(outputDir);
            }
            TargetAssemblyDefinition.Write(Options.OutputFile, parameters);
            Logger.Info("Writing output assembly to disk");
            // If this is an executable and we are on linux/osx we should copy file permissions from
            // the primary assembly
            if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix)
            {
                Stat stat;
                Logger.Info("Copying permissions from " + PrimaryAssemblyFile);
                Syscall.stat(PrimaryAssemblyFile, out stat);
                Syscall.chmod(Options.OutputFile, stat.st_mode);
            }
            if (hadStrongName && !TargetAssemblyDefinition.Name.HasPublicKey)
                Options.StrongNameLost = true;

            // nice to have, merge .config (assembly configuration file) & .xml (assembly documentation)
            ConfigMerger.Process(this);
            if (Options.XmlDocumentation)
                DocumentationMerger.Process(this);
        }
Пример #24
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="methodName"></param>
 /// <param name="genericType"></param>
 /// <param name="parameters"></param>
 /// <returns></returns>
 private static object DynamicCall(string methodName, Type genericType, object[] parameters, BindingFlags flags = BindingFlags.Public | BindingFlags.Static)
 {
     return ReflectionHelper.MakeGenericDynamicCall(typeof(TestDataRepository), methodName, flags, genericType, parameters: parameters);
 }
Пример #25
0
 public static HandlerCall For <T>(Expression <Action <T> > method)
 {
     return(new HandlerCall(typeof(T), ReflectionHelper.GetMethod(method)));
 }
Пример #26
0
 public void ParseScale_HumongousNumber()
 {
     Assert.AreEqual(1000, ReflectionHelper.GetIntResult(
                         typeof(DomainImpl.CmPictureFactory),
                         "ParseScaleFactor", "100000"));
 }
Пример #27
0
 /// <summary>
 /// New generic entity manager.
 /// </summary>
 /// <param name="externalEntityType">The type of entity that will be controlled by the manager.</param>
 /// <param name="connectionName">Name of the connection string.</param>
 public EntityGateAgent(Type externalEntityType, string connectionName = null) : base(ReflectionHelper.MakeInstance <IEntityObjectIdentifier>(externalEntityType), connectionName)
 {
 }
Пример #28
0
        public virtual void AddLocals(IEnumerable <ParameterDeclaration> declarations, AstNode statement)
        {
            var visitor = new ReferenceArgumentVisitor(this.Emitter);

            statement.AcceptVisitor(visitor);

            declarations.ToList().ForEach(item =>
            {
                var rr    = item.Parent != null ? (LocalResolveResult)this.Emitter.Resolver.ResolveNode(item, this.Emitter) : null;
                var name  = this.Emitter.GetParameterName(item);
                var vName = this.AddLocal(item.Name, item, item.Type, name);

                if (item.Parent == null && item.Name == "value" && visitor.DirectionExpression.Any(expr => expr is IdentifierExpression && ((IdentifierExpression)expr).Identifier == "value"))
                {
                    return;
                }

                if (item.ParameterModifier == ParameterModifier.Out || item.ParameterModifier == ParameterModifier.Ref)
                {
                    this.Emitter.LocalsMap[rr != null ? rr.Variable : new DefaultVariable(ReflectionHelper.FindType(this.Emitter.Resolver.Compilation, TypeCode.Object), name)] = vName + ".v";
                }
                else
                {
                    this.Emitter.LocalsMap[rr != null ? rr.Variable : new DefaultVariable(ReflectionHelper.FindType(this.Emitter.Resolver.Compilation, TypeCode.Object), name)] = vName;
                }
            });

            foreach (var expr in visitor.DirectionExpression)
            {
                var rr = this.Emitter.Resolver.ResolveNode(expr, this.Emitter);

                IdentifierExpression identifierExpression;
                var lrr = rr as LocalResolveResult;
                if (lrr != null && ((identifierExpression = expr as IdentifierExpression) != null))
                {
                    var name = identifierExpression.Identifier;
                    if (Helpers.IsReservedWord(this.Emitter, name))
                    {
                        name = Helpers.ChangeReservedWord(name);
                    }
                    this.Emitter.LocalsMap[lrr.Variable] = name + ".v";
                }
            }

            foreach (var variable in visitor.DirectionVariables)
            {
                var name = variable.Name;

                if (Helpers.IsReservedWord(this.Emitter, name))
                {
                    name = Helpers.ChangeReservedWord(name);
                }
                this.Emitter.LocalsMap[variable] = name + ".v";
            }
        }
Пример #29
0
 /// <summary>
 /// 获取描述,使用System.ComponentModel.Description特性设置描述
 /// </summary>
 /// <typeparam name="T">枚举</typeparam>
 /// <param name="member">成员名、值、实例均可</param>
 public static string GetDescription <T>(object member)
 {
     return(ReflectionHelper.GetDescription <T>(GetName <T>(member)));
 }
Пример #30
0
        protected virtual bool WriteObject(string objectName, List <TypeConfigItem> members, string format, string interfaceFormat)
        {
            bool        hasProperties = HasProperties(objectName, members);
            int         pos           = 0;
            IWriterInfo writer        = null;
            bool        beginBlock    = false;

            if (hasProperties && objectName != null && !IsObjectLiteral)
            {
                beginBlock = true;
                pos        = Emitter.Output.Length;
                writer     = SaveWriter();
                EnsureComma();
                Write(objectName);

                WriteColon();
                BeginBlock();
            }

            bool isProperty = JS.Fields.PROPERTIES == objectName;
            bool isField    = JS.Fields.FIELDS == objectName;
            int  count      = 0;

            foreach (var member in members)
            {
                object constValue  = null;
                bool   isPrimitive = false;
                bool   write       = false;
                bool   writeScript = false;

                if (member.Initializer is PrimitiveExpression primitiveExpr)
                {
                    //isPrimitive = true;
                    constValue = primitiveExpr.Value;

                    ResolveResult rr = null;
                    if (member.VarInitializer != null)
                    {
                        rr = Emitter.Resolver.ResolveNode(member.VarInitializer);
                    }
                    else
                    {
                        rr = Emitter.Resolver.ResolveNode(member.Entity);
                    }

                    if (rr != null && rr.Type.Kind == TypeKind.Enum)
                    {
                        constValue  = Helpers.GetEnumValue(Emitter, rr.Type, constValue);
                        writeScript = true;
                    }
                }

                if (constValue is RawValue)
                {
                    constValue  = constValue.ToString();
                    write       = true;
                    writeScript = false;
                }

                var isNull = member.Initializer.IsNull || member.Initializer is NullReferenceExpression || member.Initializer.Parent == null;

                if (!isNull && !isPrimitive)
                {
                    var constrr = Emitter.Resolver.ResolveNode(member.Initializer);
                    if (constrr != null && constrr.IsCompileTimeConstant)
                    {
                        //isPrimitive = true;
                        constValue = constrr.ConstantValue;

                        var expectedType = Emitter.Resolver.Resolver.GetExpectedType(member.Initializer);
                        if (!expectedType.Equals(constrr.Type) && expectedType.Kind != TypeKind.Dynamic)
                        {
                            try
                            {
                                constValue = Convert.ChangeType(constValue, ReflectionHelper.GetTypeCode(expectedType));
                            }
                            catch (Exception)
                            {
                                Logger.ZLogWarning("FieldBlock: Convert.ChangeType is failed. Value type: {0}, Target type: {1}", constrr.Type.FullName, expectedType.FullName);
                            }
                        }

                        if (constrr.Type.Kind == TypeKind.Enum)
                        {
                            constValue = Helpers.GetEnumValue(Emitter, constrr.Type, constrr.ConstantValue);
                        }

                        writeScript = true;
                    }
                }

                var isNullable = false;

                if (isPrimitive && constValue is AstType)
                {
                    var itype = Emitter.Resolver.ResolveNode((AstType)constValue);

                    if (NullableType.IsNullable(itype.Type))
                    {
                        isNullable = true;
                    }
                }

                string              tpl            = null;
                IMember             templateMember = null;
                MemberResolveResult init_rr        = null;
                if (isField && member.VarInitializer != null)
                {
                    init_rr = Emitter.Resolver.ResolveNode(member.VarInitializer) as MemberResolveResult;
                    tpl     = init_rr != null?Emitter.GetInline(init_rr.Member) : null;

                    if (tpl != null)
                    {
                        templateMember = init_rr.Member;
                    }
                }

                bool isAutoProperty = false;

                if (isProperty)
                {
                    var member_rr = Emitter.Resolver.ResolveNode(member.Entity) as MemberResolveResult;
                    var property  = (IProperty)member_rr.Member;
                    isAutoProperty = Helpers.IsAutoProperty(property);
                }

                bool written = false;
                if (!isNull && (!isPrimitive || constValue is AstType || tpl != null) && !(isProperty && !IsObjectLiteral && !isAutoProperty))
                {
                    string value        = null;
                    bool   needContinue = false;
                    string defValue     = "";
                    if (!isPrimitive)
                    {
                        var oldWriter = SaveWriter();
                        NewWriter();
                        member.Initializer.AcceptVisitor(Emitter);
                        value = Emitter.Output.ToString();
                        RestoreWriter(oldWriter);

                        ResolveResult rr      = null;
                        AstType       astType = null;
                        if (member.VarInitializer != null)
                        {
                            rr = Emitter.Resolver.ResolveNode(member.VarInitializer);
                        }
                        else
                        {
                            astType = member.Entity.ReturnType;
                            rr      = Emitter.Resolver.ResolveNode(member.Entity);
                        }

                        constValue = Inspector.GetDefaultFieldValue(rr.Type, astType);
                        if (rr.Type.Kind == TypeKind.Enum)
                        {
                            constValue = Helpers.GetEnumValue(Emitter, rr.Type, constValue);
                        }
                        isNullable   = NullableType.IsNullable(rr.Type);
                        needContinue = constValue is IType;
                        writeScript  = true;

                        /*if (needContinue && !(member.Initializer is ObjectCreateExpression))
                         * {
                         *  defValue = " || " + Inspector.GetStructDefaultValue((IType)constValue, this.Emitter);
                         * }*/
                    }
                    else if (constValue is AstType)
                    {
                        value = isNullable
                            ? "null"
                            : Inspector.GetStructDefaultValue((AstType)constValue, Emitter);
                        constValue   = value;
                        write        = true;
                        needContinue = !isProperty && !isNullable;
                    }

                    var name = member.GetName(Emitter);

                    bool isValidIdentifier = Helpers.IsValidIdentifier(name);

                    if (isProperty && isPrimitive)
                    {
                        constValue = "null";

                        if (IsObjectLiteral)
                        {
                            written = true;
                            if (isValidIdentifier)
                            {
                                Write(string.Format("this.{0} = {1};", name, value));
                            }
                            else
                            {
                                Write(string.Format("this[{0}] = {1};", ToJavaScript(name, Emitter), value));
                            }

                            WriteNewLine();
                        }
                        else
                        {
                            Injectors.Add(string.Format(name.StartsWith("\"") || !isValidIdentifier ? "this[{0}] = {1};" : "this.{0} = {1};", isValidIdentifier ? name : ToJavaScript(name, Emitter), value));
                        }
                    }
                    else
                    {
                        if (IsObjectLiteral)
                        {
                            written = true;
                            if (isValidIdentifier)
                            {
                                Write(string.Format("this.{0} = {1};", name, value + defValue));
                            }
                            else
                            {
                                Write(string.Format("this[{0}] = {1};", ToJavaScript(name, Emitter), value + defValue));
                            }
                            WriteNewLine();
                        }
                        else if (tpl != null)
                        {
                            if (!tpl.Contains("{0}"))
                            {
                                tpl = tpl + " = {0};";
                            }

                            string v = null;
                            if (!isNull && (!isPrimitive || constValue is AstType))
                            {
                                v = value + defValue;
                            }
                            else
                            {
                                if (write)
                                {
                                    v = constValue != null?constValue.ToString() : "";
                                }
                                else if (writeScript)
                                {
                                    v = ToJavaScript(constValue, Emitter);
                                }
                                else
                                {
                                    var oldWriter = SaveWriter();
                                    NewWriter();
                                    member.Initializer.AcceptVisitor(Emitter);
                                    v = Emitter.Output.ToString();
                                    RestoreWriter(oldWriter);
                                }
                            }

                            tpl = Helpers.ConvertTokens(Emitter, tpl, templateMember);
                            tpl = tpl.Replace("{this}", "this").Replace("{0}", v);

                            if (!tpl.EndsWith(";"))
                            {
                                tpl += ";";
                            }
                            Injectors.Add(tpl);
                        }
                        else
                        {
                            bool isDefaultInstance = Emitter.Resolver.ResolveNode(member.Initializer) is CSharpInvocationResolveResult rr &&
                                                     rr.Member.SymbolKind == SymbolKind.Constructor &&
                                                     rr.Arguments.Count == 0 &&
                                                     rr.InitializerStatements.Count == 0 &&
                                                     rr.Type.Kind == TypeKind.Struct;

                            if (!isDefaultInstance)
                            {
                                if (isField && !isValidIdentifier)
                                {
                                    Injectors.Add(string.Format("this[{0}] = {1};", name.StartsWith("\"") ? name : ToJavaScript(name, Emitter), value + defValue));
                                }
                                else
                                {
                                    Injectors.Add(string.Format(name.StartsWith("\"") ? interfaceFormat : format, name, value + defValue));
                                }
                            }
                        }
                    }
                }

                count++;

                if (written)
                {
                    continue;
                }
                bool withoutTypeParams   = true;
                MemberResolveResult m_rr = null;
                if (member.Entity != null)
                {
                    m_rr = Emitter.Resolver.ResolveNode(member.Entity) as MemberResolveResult;
                    if (m_rr != null)
                    {
                        withoutTypeParams = OverloadsCollection.ExcludeTypeParameterForDefinition(m_rr);
                    }
                }

                var mname = member.GetName(Emitter, withoutTypeParams);

                if (TypeInfo.IsEnum && m_rr != null)
                {
                    mname = Emitter.GetEntityName(m_rr.Member);
                }

                bool isValid = Helpers.IsValidIdentifier(mname);
                if (!isValid)
                {
                    if (IsObjectLiteral)
                    {
                        mname = "[" + ToJavaScript(mname, Emitter) + "]";
                    }
                    else
                    {
                        mname = ToJavaScript(mname, Emitter);
                    }
                }

                if (IsObjectLiteral)
                {
                    WriteThis();
                    if (isValid)
                    {
                        WriteDot();
                    }
                    Write(mname);
                    Write(" = ");
                }
                else
                {
                    EnsureComma();
                    XmlToJsDoc.EmitComment(this, member.Entity, null, member.Entity is FieldDeclaration ? member.VarInitializer : null);
                    Write(mname);
                    WriteColon();
                }

                bool close = false;
                if (isProperty && !IsObjectLiteral && !isAutoProperty)
                {
                    var oldTempVars = Emitter.TempVariables;
                    BeginBlock();
                    new VisitorPropertyBlock(Emitter, (PropertyDeclaration)member.Entity).Emit();
                    WriteNewLine();
                    EndBlock();
                    Emitter.Comma         = true;
                    Emitter.TempVariables = oldTempVars;
                    continue;
                }

                if (constValue is AstType || constValue is IType)
                {
                    Write("null");

                    if (!isNullable)
                    {
                        var  name = member.GetName(Emitter);
                        bool isValidIdentifier = Helpers.IsValidIdentifier(name);
                        var  value             = constValue is AstType?Inspector.GetStructDefaultValue((AstType)constValue, Emitter) : Inspector.GetStructDefaultValue((IType)constValue, Emitter);

                        if (!isValidIdentifier)
                        {
                            Injectors.Insert(BeginCounter++, string.Format("this[{0}] = {1};", name.StartsWith("\"") ? name : ToJavaScript(name, Emitter), value));
                        }
                        else
                        {
                            Injectors.Insert(BeginCounter++, string.Format(name.StartsWith("\"") ? interfaceFormat : format, name, value));
                        }
                    }
                }
                else if (write)
                {
                    Write(constValue);
                }
                else if (writeScript)
                {
                    WriteScript(constValue);
                }
                else
                {
                    member.Initializer.AcceptVisitor(Emitter);
                }

                if (close)
                {
                    Write(" }");
                }

                if (IsObjectLiteral)
                {
                    WriteSemiColon(true);
                }

                Emitter.Comma = true;
            }

            if (count > 0 && objectName != null && !IsObjectLiteral)
            {
                WriteNewLine();
                EndBlock();
            }
            else if (beginBlock)
            {
                Emitter.IsNewLine = writer.IsNewLine;
                Emitter.ResetLevel(writer.Level);
                Emitter.Comma = writer.Comma;

                Emitter.Output.Length = pos;
            }

            return(count > 0);
        }
Пример #31
0
        public List<PropertyValues> GenerateDynamicViewModel(Type type)
        {
            if (type != null)
            {
                var message = new List<PropertyValues>();

                var fact = new ReflectionHelper();
                var theList = fact.GetMessageProperties(type);
                var propertyValue = theList.Select(name => new PropertyValues { Name = name, Value = string.Empty }).ToList();

                message.AddRange(propertyValue);

                return message;
            }
            return null;
        }
Пример #32
0
        /// <summary>
        /// Create table (if it doesn't exist) for a given class.
        /// Adding a table that has already been added will throw an ArgumentException.
        /// </summary>
        /// <param name="t">Class for which a table should be created.</param>
        public void InitializeTable(Type t)
        {
            if (!_Initialized)
            {
                throw new InvalidOperationException("Initialize WatsonORM and database using the .InitializeDatabase() method first.");
            }
            if (t == null)
            {
                throw new ArgumentNullException(nameof(t));
            }

            string        tableName = ReflectionHelper.GetTableNameFromType(t);
            string        primaryKeyPropertyName = ReflectionHelper.GetPrimaryKeyPropertyName(t);
            List <Column> columns = ReflectionHelper.GetColumnsFromType(t);

            if (String.IsNullOrEmpty(tableName))
            {
                throw new InvalidOperationException("Type '" + t.Name + "' does not have a 'Table' attribute.");
            }

            if (String.IsNullOrEmpty(primaryKeyPropertyName))
            {
                throw new InvalidOperationException("Type '" + t.Name + "' with table name '" + tableName + "' does not have a property with the 'PrimaryKey' attribute.");
            }

            if (columns == null || columns.Count < 1)
            {
                throw new InvalidOperationException("Type '" + t.Name + "' with table name '" + tableName + "' does not have any properties with a 'Column' attribute.");
            }

            if (!_Database.TableExists(tableName))
            {
                _Database.CreateTable(tableName, columns);
            }
            else
            {
                List <Column> existingColumns = _Database.DescribeTable(tableName);

                foreach (Column column in columns)
                {
                    if (!existingColumns.Exists(c => c.Name.Equals(column.Name)))
                    {
                        throw new InvalidOperationException("Type '" + t.Name + " with table name '" + tableName + "' exists but column '" + column.Name + "' does not.");
                    }
                }

                List <string> existingColumnNames = existingColumns.Select(c => c.Name).ToList();
                List <string> definedColumnNames  = columns.Select(c => c.Name).ToList();
                List <string> delta = existingColumnNames.Except(definedColumnNames).ToList();
                if (delta != null && delta.Count > 0)
                {
                    string deltaStr = "";
                    foreach (string currDelta in delta)
                    {
                        if (!String.IsNullOrEmpty(deltaStr))
                        {
                            deltaStr = deltaStr + ", ";
                        }
                        deltaStr += currDelta;
                    }

                    _Logger?.Invoke(_Header + "table " + tableName + " contains additional columns not decorated in the class definition: " + deltaStr);
                }
            }

            _TypeMetadataMgr.Add(t, new TypeMetadata(tableName, primaryKeyPropertyName, columns));

            _Logger?.Invoke(_Header + "initialized table " + tableName + " for type " + t.Name + " with " + columns.Count + " column(s)");
        }
 private static Maybe <TransactionalAttribute> FindTransactionalAttribute(MemberInfo methodInfo)
 {
     return(ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault <TransactionalAttribute>(
                methodInfo));
 }
Пример #34
0
        public void matches_positive_if_no_attribute()
        {
            var property = ReflectionHelper.GetProperty <FakeTarget>(x => x.Color1);

            new AttributePropertyBinder().Matches(property).ShouldBeTrue();
        }
        public void ManagerWillReadFromCache()
        {
            CreateCacheMock();

            _objectType = typeof(SampleValue);

            object outHelper = new ReflectionHelper<SampleValue>(_objectType);

            object fakeHelper = new ReflectionHelper<SampleValue>(_objectType);

            _cacheMock.Expect(v => v.TryGetValue(_objectType, out outHelper)).OutRef(fakeHelper).Return(true);

            var restultHelper = RunTestAction();

            MockRepository.ReplayAll();

            restultHelper.ObjectType.Should().Be(typeof(SampleValue));
        }
Пример #36
0
        public static ParserResult <T> Build <T>(
            Maybe <Func <T> > factory,
            Func <IEnumerable <string>, IEnumerable <OptionSpecification>, Result <IEnumerable <Token>, Error> > tokenizer,
            IEnumerable <string> arguments,
            StringComparer nameComparer,
            bool ignoreValueCase,
            CultureInfo parsingCulture,
            IEnumerable <ErrorType> nonFatalErrors)
        {
            var typeInfo = factory.MapValueOrDefault(f => f().GetType(), typeof(T));

            var specProps = typeInfo.GetSpecifications(pi => SpecificationProperty.Create(
                                                           Specification.FromProperty(pi), pi, Maybe.Nothing <object>()));

            var specs = from pt in specProps select pt.Specification;

            var optionSpecs = specs
                              .ThrowingValidate(SpecificationGuards.Lookup)
                              .OfType <OptionSpecification>();

            Func <T> makeDefault = () =>
                                   typeof(T).IsMutable()
                    ? factory.MapValueOrDefault(f => f(), Activator.CreateInstance <T>())
                    : ReflectionHelper.CreateDefaultImmutableInstance <T>(
                (from p in specProps select p.Specification.ConversionType).ToArray());

            Func <IEnumerable <Error>, ParserResult <T> > notParsed =
                errs => new NotParsed <T>(makeDefault().GetType().ToTypeInfo(), errs);

            Func <ParserResult <T> > buildUp = () =>
            {
                var tokenizerResult = tokenizer(arguments, optionSpecs);

                var tokens = tokenizerResult.SucceededWith();

                var partitions = TokenPartitioner.Partition(
                    tokens,
                    name => TypeLookup.FindTypeDescriptorAndSibling(name, optionSpecs, nameComparer));
                var optionsPartition = partitions.Item1;
                var valuesPartition  = partitions.Item2;
                var errorsPartition  = partitions.Item3;

                var optionSpecPropsResult =
                    OptionMapper.MapValues(
                        (from pt in specProps where pt.Specification.IsOption() select pt),
                        optionsPartition,
                        (vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, parsingCulture, ignoreValueCase),
                        nameComparer);

                var valueSpecPropsResult =
                    ValueMapper.MapValues(
                        (from pt in specProps where pt.Specification.IsValue() select pt),
                        valuesPartition,
                        (vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, parsingCulture, ignoreValueCase));

                var missingValueErrors = from token in errorsPartition
                                         select
                                         new MissingValueOptionError(
                    optionSpecs.Single(o => token.Text.MatchName(o.ShortName, o.LongName, nameComparer))
                    .FromOptionSpecification());

                var specPropsWithValue =
                    optionSpecPropsResult.SucceededWith().Concat(valueSpecPropsResult.SucceededWith());

                Func <T> buildMutable = () =>
                {
                    var mutable = factory.MapValueOrDefault(f => f(), Activator.CreateInstance <T>());
                    mutable =
                        mutable.SetProperties(specPropsWithValue, sp => sp.Value.IsJust(), sp => sp.Value.FromJustOrFail())
                        .SetProperties(
                            specPropsWithValue,
                            sp => sp.Value.IsNothing() && sp.Specification.DefaultValue.IsJust(),
                            sp => sp.Specification.DefaultValue.FromJustOrFail())
                        .SetProperties(
                            specPropsWithValue,
                            sp =>
                            sp.Value.IsNothing() && sp.Specification.TargetType == TargetType.Sequence &&
                            sp.Specification.DefaultValue.MatchNothing(),
                            sp => sp.Property.PropertyType.GetGenericArguments().Single().CreateEmptyArray());
                    return(mutable);
                };

                Func <T> buildImmutable = () =>
                {
                    var ctor   = typeInfo.GetConstructor((from sp in specProps select sp.Property.PropertyType).ToArray());
                    var values = (from prms in ctor.GetParameters()
                                  join sp in specPropsWithValue on prms.Name.ToLower() equals sp.Property.Name.ToLower()
                                  select
                                  sp.Value.GetValueOrDefault(
                                      sp.Specification.DefaultValue.GetValueOrDefault(
                                          sp.Specification.ConversionType.CreateDefaultForImmutable()))).ToArray();
                    var immutable = (T)ctor.Invoke(values);
                    return(immutable);
                };

                var instance = typeInfo.IsMutable() ? buildMutable() : buildImmutable();

                var validationErrors = specPropsWithValue.Validate(SpecificationPropertyRules.Lookup(tokens));

                var allErrors =
                    tokenizerResult.SuccessfulMessages()
                    .Concat(missingValueErrors)
                    .Concat(optionSpecPropsResult.SuccessfulMessages())
                    .Concat(valueSpecPropsResult.SuccessfulMessages())
                    .Concat(validationErrors)
                    .Memorize();

                var warnings = from e in allErrors where nonFatalErrors.Contains(e.Tag) select e;

                return(allErrors.Except(warnings).ToParserResult(instance));
            };

            var preprocessorErrors = arguments.Any()
                ? arguments.Preprocess(PreprocessorGuards.Lookup(nameComparer))
                : Enumerable.Empty <Error>();

            var result = arguments.Any()
                ? preprocessorErrors.Any()
                    ? notParsed(preprocessorErrors)
                    : buildUp()
                : buildUp();

            return(result);
        }
Пример #37
0
		public void setup() {
			_h = new ReflectionHelper();
			_t = typeof (membercontainer);
			_c = new membercontainer();
		}
Пример #38
0
        private void AddArgument(PropertyInfo prop,
                                 ArgumentAttribute argumentAttr,
                                 ConventionContext convention,
                                 SortedList <int, CommandArgument> argOrder,
                                 Dictionary <int, PropertyInfo> argPropOrder)
        {
            var argument = argumentAttr.Configure(prop);

            foreach (var attr in prop.GetCustomAttributes().OfType <ValidationAttribute>())
            {
                argument.Validators.Add(new AttributeValidator(attr));
            }

            argument.MultipleValues =
                prop.PropertyType.IsArray ||
                (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(prop.PropertyType) &&
                 prop.PropertyType != typeof(string));

            if (argPropOrder.TryGetValue(argumentAttr.Order, out var otherProp))
            {
                throw new InvalidOperationException(
                          Strings.DuplicateArgumentPosition(argumentAttr.Order, prop, otherProp));
            }

            argPropOrder.Add(argumentAttr.Order, prop);
            argOrder.Add(argumentAttr.Order, argument);

            var setter = ReflectionHelper.GetPropertySetter(prop);

            if (argument.MultipleValues)
            {
                var collectionParser = CollectionParserProvider.Default.GetParser(
                    prop.PropertyType,
                    convention.Application.ValueParsers);
                if (collectionParser == null)
                {
                    throw new InvalidOperationException(Strings.CannotDetermineParserType(prop));
                }

                convention.Application.OnParsingComplete(r =>
                {
                    if (argument.Values.Count == 0)
                    {
                        return;
                    }

                    if (r.SelectedCommand is IModelAccessor cmd)
                    {
                        setter.Invoke(cmd.GetModel(), collectionParser.Parse(argument.Name, argument.Values));
                    }
                });
            }
            else
            {
                var parser = convention.Application.ValueParsers.GetParser(prop.PropertyType);
                if (parser == null)
                {
                    throw new InvalidOperationException(Strings.CannotDetermineParserType(prop));
                }

                convention.Application.OnParsingComplete(r =>
                {
                    if (argument.Values.Count == 0)
                    {
                        return;
                    }

                    if (r.SelectedCommand is IModelAccessor cmd)
                    {
                        setter.Invoke(
                            cmd.GetModel(),
                            parser.Parse(
                                argument.Name,
                                argument.Value,
                                convention.Application.ValueParsers.ParseCulture));
                    }
                });
            }
        }
Пример #39
0
 public ImportContext(ReflectionHelper helper, IGenericParameterProvider provider)
 {
     m_helper = helper;
     m_genContext = new GenericContext (provider);
 }
Пример #40
0
 /// <summary>
 /// 获取描述,使用System.ComponentModel.Description特性设置描述
 /// </summary>
 /// <param name="type">枚举类型</param>
 /// <param name="member">成员名、值、实例均可</param>
 public static string GetDescription(Type type, object member)
 {
     return(ReflectionHelper.GetDescription(type, GetName(type, member)));
 }
Пример #41
0
 public void ParseScale_Normal()
 {
     Assert.AreEqual(34, ReflectionHelper.GetIntResult(
                         typeof(DomainImpl.CmPictureFactory),
                         "ParseScaleFactor", "34"));
 }
Пример #42
0
 private void LoadAssembly()
 {
     var factory = new ReflectionHelper();
     //var messageList = factory.GetMessageList(txtText.Text);
     var messageList = factory.GetMessageList("Messages.dll");
     MessageList = messageList;
 }
Пример #43
0
 public void ParseScale_Null()
 {
     Assert.AreEqual(100, ReflectionHelper.GetIntResult(
                         typeof(DomainImpl.CmPictureFactory),
                         "ParseScaleFactor", new object[] { null }));
 }
Пример #44
0
 public ImportContext(ReflectionHelper helper)
     : this()
 {
     m_helper = helper;
 }
Пример #45
0
 public void ParseScale_Empty()
 {
     Assert.AreEqual(100, ReflectionHelper.GetIntResult(
                         typeof(DomainImpl.CmPictureFactory),
                         "ParseScaleFactor", String.Empty));
 }
Пример #46
0
 public void ParseScale_Negative()
 {
     Assert.AreEqual(53, ReflectionHelper.GetIntResult(
                         typeof(DomainImpl.CmPictureFactory),
                         "ParseScaleFactor", "-53"));
 }
Пример #47
0
 public void ParseScale_TextAndNumber()
 {
     Assert.AreEqual(53, ReflectionHelper.GetIntResult(
                         typeof(DomainImpl.CmPictureFactory),
                         "ParseScaleFactor", "scale=53"));
 }
Пример #48
0
        internal MethodReference Fix(MethodReference method)
        {
            TypeReference declaringType = Fix(method.DeclaringType);
            if (method.IsGenericInstance)
            {
                return Fix((GenericInstanceMethod)method);
            }
            // if declaring type is in our new merged module, return the definition
            if (declaringType.IsDefinition && !method.IsDefinition)
            {
                MethodDefinition def = new ReflectionHelper(repack).FindMethodDefinitionInType((TypeDefinition)declaringType, method);
                if (def != null)
                    return def;
            }
            method.DeclaringType = declaringType;
            method.ReturnType = Fix(method.ReturnType);

            FixReferences(method.Parameters);
            FixReferences(method.GenericParameters);

            if (!method.IsDefinition &&
                !method.DeclaringType.IsGenericInstance &&
                !method.DeclaringType.IsArray &&
                (method.ReturnType.IsDefinition || method.Parameters.Any(x => x.ParameterType.IsDefinition)))
            {
                var culprit = method.ReturnType.IsDefinition
                                     ? method.ReturnType
                                     : method.Parameters.First(x => x.ParameterType.IsDefinition).ParameterType;
                // warn about invalid merge assembly set, as this method is not gonna work fine (peverify would warn as well)
                repack.WARN("Method reference is used with definition return type / parameter. Indicates a likely invalid set of assemblies, consider one of the following");
                repack.WARN(" - Remove the assembly defining " + culprit + " from the merge");
                repack.WARN(" - Add assembly defining " + method + " to the merge");

                // one case where it'll work correctly however (but doesn't seem common):
                // A references B
                // C references A
                // C is merged into B
            }
            return method;
        }
Пример #49
0
 public void TestConstructor()
 {
     ReflectionHelper<DummyClass> helper = new ReflectionHelper<DummyClass>(new DummyClass());
 }