Пример #1
0
        public static List <ColumnDescriptor> GetColumnDescriptors(Type typeOfModel)
        {
            return(TableColumns.GetOrAdd(typeOfModel, n =>
            {
                var properties = n.GetProperties();
                var columns = new List <ColumnDescriptor>(properties.Length);
                foreach (var propertyInfo in properties)
                {
                    if (Types.Contains(propertyInfo.PropertyType) &&
                        !(propertyInfo.GetCustomAttribute(typeof(IgnoreAttribute)) is IgnoreAttribute))
                    {
                        var customAttribute = propertyInfo.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;

                        var isPrimaryKey = false;
                        var autoIncrement = false;
                        Action <object, object> setPrimaryKey = null;
                        var keyAttribute = propertyInfo.GetCustomAttribute(typeof(KeyAttribute)) as KeyAttribute;
                        if (keyAttribute != null)
                        {
                            isPrimaryKey = true;
                            autoIncrement = keyAttribute.AutoIncrement;
                            if (autoIncrement)
                            {
                                setPrimaryKey = MethodInfoUtil.MakeFastPropertySetter(n, propertyInfo);
                            }
                        }
                        var column = new ColumnDescriptor
                        {
                            IsPrimaryKey = isPrimaryKey,
                            AutoIncrement = autoIncrement,
                            SetPrimaryKey = setPrimaryKey,
                            Name = propertyInfo.Name,
                            DbName = propertyInfo.Name
                        };
                        if (customAttribute?.Name != null)
                        {
                            column.DbName = customAttribute.Name;
                        }
                        columns.Add(column);
                    }
                }

                if (columns.Count == 0)
                {
                    throw new ArgumentException($"{n.FullName} no cols");
                }

                var pkCount = columns.Count(m => m.IsPrimaryKey);
                if (pkCount == 0)
                {
                    throw new ArgumentException($"{n.FullName} no PrimaryKey");
                }

                if (pkCount > 1)
                {
                    throw new ArgumentException($"{n.FullName} PrimaryKey Only Support One ");
                }
                return columns;
            }));
        }
Пример #2
0
        // ------------------------------
        // private
        // ------------------------------
        private InsertionOrderedDictionary <string, KeyActionInfo <T> > CreateIdToInfos(IEnumerable <Type> types)
        {
            var ret = new InsertionOrderedDictionary <string, KeyActionInfo <T> >();

            foreach (var type in types)
            {
                var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static);
                foreach (var meth in methods)
                {
                    var paras = meth.GetParameters();
                    if (paras != null && paras.Length == 1 && paras[0].ParameterType == typeof(T))
                    {
                        var attr = Attribute.GetCustomAttribute(meth, typeof(KeyActionAttribute)) as KeyActionAttribute;
                        if (attr != null)
                        {
                            var id   = StringUtil.IsNullOrWhitespace(attr.Id) ? meth.Name : attr.Id;
                            var info = new KeyActionInfo <T>(id, attr.Description, MethodInfoUtil.ToStaticAction <T>(meth));
                            ret[id] = info;
                        }
                    }
                }
            }

            return(ret);
        }
Пример #3
0
        public void AppendCallInformation()
        {
            var invocationStub = Substitute.For <IInvocation>();

            var methodInfo =
                MethodInfoUtil.GetMethodInfo <DummyObjectWithGenerics <int> >(
                    obj => obj.DoSomething(1, "value"));
            var args = new object[]
            {
                1,
                "value"
            };

            logUtil.AppendCallInformation(stringBuilder, methodInfo, args);

            var actual = stringBuilder.ToString();

            Assert.That(actual, Does.Contain(
                            "YetiCommon.Tests.Logging.DummyObjectWithGenerics`1[System.Int32]"));
            Assert.That(actual, Does.Contain(
                            "Void DoSomething[Int32,String](Int32, System.String)"));
            Assert.That(actual, Does.Contain("Args [ToString]:"));
            Assert.That(actual, Does.Contain("param1=1"));
            Assert.That(actual, Does.Contain("param2=value"));
            Assert.That(actual, Does.Contain("Args [Json]:"));
            Assert.That(actual, Does.Contain(JoinLines(
                                                 @"(",
                                                 @"{",
                                                 @"  ""param1"": 1,",
                                                 @"  ""param2"": ""value""",
                                                 @"}",
                                                 @")",
                                                 @"")));
        }
        public void ShouldForwardNullReturnValueOnInterfaceFunction()
        {
            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo <DummyObject.Factory>(factory => factory.Create()));
            mockInvocation.ReturnValue.Returns(null);

            classUnderTest.Intercept(mockInvocation);
            Assert.Null(mockInvocation.ReturnValue);
        }
Пример #5
0
        public void SetUp()
        {
            methodInfo     = MethodInfoUtil.GetMethodInfo <DummyObject>(x => x.SetValue(1));
            mockInvocation = Substitute.For <IInvocation>();
            mockInvocation.MethodInvocationTarget.Returns(methodInfo);

            mockRecorder            = Substitute.For <IExceptionRecorder>();
            exceptionRecorderAspect = new ExceptionRecorderAspect(mockRecorder);
        }
Пример #6
0
        public void ValidUnconventionalFactoryShouldIntercept()
        {
            var sut = new CreateFunctionProxyHook();

            Assert.True(sut.ShouldInterceptMethod(
                            typeof(UnconventionalFactory),
                            MethodInfoUtil.GetMethodInfo <UnconventionalFactory>(
                                factory => factory.ValidCreate()
                                )));
        }
Пример #7
0
        public void ShouldInterceptVirtualCreateMethodWithInterfaceReturnType()
        {
            var sut = new CreateFunctionProxyHook();

            Assert.True(sut.ShouldInterceptMethod(
                            typeof(DummyObject.Factory),
                            MethodInfoUtil.GetMethodInfo <DummyObject.Factory>(
                                factory => factory.Create()
                                )));
        }
Пример #8
0
        public void SetUp()
        {
            methodInfo     = MethodInfoUtil.GetMethodInfo <DummyObject>(x => x.SetValue(1));
            mockInvocation = Substitute.For <IInvocation>();
            mockInvocation.MethodInvocationTarget.Returns(methodInfo);

            fakeTimeSource = new MonotonicTimeSource();
            mockMethodInvocationRecorder = Substitute.For <IMethodInvocationRecorder>();
            metricsCollectionAspect      = new MetricsCollectionAspect(
                mockMethodInvocationRecorder, fakeTimeSource);
        }
Пример #9
0
 /// <summary>
 /// Find the parameter of the specified <see cref="MethodInfo"/> with the specified name.
 /// </summary>
 /// <returns>A <see cref="ParameterRef"/> to the parameter, or an <see cref="UnresolvedRef"/> if no match was found.</returns>
 public static SymbolicRef Find(MethodInfo methodInfo, string name, bool isFirstOnLine)
 {
     if (methodInfo != null)
     {
         ParameterInfo parameterInfo = MethodInfoUtil.GetParameter(methodInfo, name);
         if (parameterInfo != null)
         {
             return(new ParameterRef(parameterInfo, isFirstOnLine));
         }
     }
     return(new UnresolvedRef(name, isFirstOnLine));
 }
Пример #10
0
        public void ShouldSendEventInfoToLogger()
        {
            var mockInvocation = Substitute.For <IInvocation>();

            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo <DummyObject>(x => x.SetValue(1)));
            mockInvocation.TargetType.Returns(typeof(DummyObject));

            _classUnderTest.Intercept(mockInvocation);
            _mockTraceLogger.Received().TraceEvent("SetValue", EventType.Sync, typeof(DummyObject),
                                                   Arg.Is <long>(1), Arg.Is <long>(1),
                                                   Arg.Any <int>());
        }
Пример #11
0
        public void ShouldThrowArgumentExceptionForVoidCreateMethod()
        {
            var exceptionThrown = Assert.Throws <ArgumentException>(() =>
            {
                var sut = new CreateFunctionProxyHook();
                sut.ShouldInterceptMethod(typeof(DummyObject.FactoryWithVoidCreateMethod),
                                          MethodInfoUtil.GetMethodInfo <DummyObject.FactoryWithVoidCreateMethod>(
                                              factory => factory.CreateNothing()
                                              ));
            });

            Assert.That(exceptionThrown.Message, Does.Contain("System.Void"));
        }
        public void ShouldThrowInvalidOperationWhenProxyingVoidFunction()
        {
            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo <DummyObject.FactoryWithVoidCreateMethod>(
                    factory => factory.CreateNothing()));

            var exceptionThrown = Assert.Throws(typeof(InvalidOperationException), () =>
            {
                classUnderTest.Intercept(mockInvocation);
            });

            Assert.That(exceptionThrown.Message, Does.Contain("System.Void"));
        }
Пример #13
0
        public void ShouldThrowArgumentExceptionForClassCreateMethod()
        {
            var exceptionThrown = Assert.Throws <ArgumentException>(() =>
            {
                var sut = new CreateFunctionProxyHook();
                sut.ShouldInterceptMethod(typeof(DummyObject.FactoryWithConcreteCreate),
                                          MethodInfoUtil.GetMethodInfo <DummyObject.FactoryWithConcreteCreate>(
                                              factory => factory.CreateConcrete()
                                              ));
            });

            Assert.That(exceptionThrown.Message, Does.Contain("DummyObject"));
        }
        public void ShouldThrowInvalidOperationWhenProxyingPrimativeReturnTypeFunction()
        {
            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo <DummyObject.FactoryWithCreateReturnType <int> >(
                    factory => factory.CreateWithGivenReturnType()));

            var exceptionThrown = Assert.Throws(typeof(InvalidOperationException), () =>
            {
                classUnderTest.Intercept(mockInvocation);
            });

            Assert.That(exceptionThrown.Message, Does.Contain("System.Int32"));
        }
Пример #15
0
        public void ShouldThrowArgumentExceptionForPrimitiveCreateMethod()
        {
            var exceptionThrown = Assert.Throws <ArgumentException>(() =>
            {
                var sut = new CreateFunctionProxyHook();
                sut.ShouldInterceptMethod(typeof(DummyObject.FactoryWithCreateReturnType <int>),
                                          MethodInfoUtil.GetMethodInfo <DummyObject.FactoryWithCreateReturnType <int> >(
                                              factory => factory.CreateWithGivenReturnType()
                                              ));
            });

            Assert.That(exceptionThrown.Message, Does.Contain("System.Int32"));
        }
Пример #16
0
        public void InvalidUnconventionalFactoryShouldFail()
        {
            var sut             = new CreateFunctionProxyHook();
            var exceptionThrown = Assert.Throws <ArgumentException>(() =>
                                                                    sut.ShouldInterceptMethod(
                                                                        typeof(UnconventionalFactory),
                                                                        MethodInfoUtil.GetMethodInfo <UnconventionalFactory>(
                                                                            factory => factory.InvalidCreate()
                                                                            )));

            Assert.That(exceptionThrown.Message,
                        Does.Contain(nameof(CreateFunctionProxyHook.ShouldInterceptAttribute)));
        }
        public void TargetSelfIsSetToProxy()
        {
            var factory   = new Factory();
            var targetObj = factory.Create();

            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo(() => factory.Create()));
            mockInvocation.ReturnValue.Returns(targetObj);

            Assert.AreEqual(targetObj, mockInvocation.ReturnValue);
            classUnderTest.Intercept(mockInvocation);
            Assert.AreNotEqual(targetObj, mockInvocation.ReturnValue);
            Assert.AreSame(((TargetObjImpl)targetObj).Self, mockInvocation.ReturnValue);
        }
        public void ShouldReturnInterfaceProxy()
        {
            var          dummyObjectFactory = new DummyObject.Factory();
            IDummyObject dummyObject        = dummyObjectFactory.Create();

            mockInvocation.Method.Returns(
                MethodInfoUtil.GetMethodInfo(() => dummyObjectFactory.Create()));
            mockInvocation.ReturnValue.Returns(dummyObject);

            Assert.AreEqual(dummyObject, mockInvocation.ReturnValue);
            classUnderTest.Intercept(mockInvocation);
            Assert.AreNotEqual(dummyObject, mockInvocation.ReturnValue);

            IDummyObject proxy = mockInvocation.ReturnValue as IDummyObject;

            Assert.NotNull(proxy);
            Assert.AreEqual(0, aspect.CallCount);
            proxy.SetValue(0);
            Assert.AreEqual(1, aspect.CallCount);
        }
Пример #19
0
        // === IInterceptor ==========
        public void Intercept(IInvocation invocation)
        {
            if (_needRealInvocation)
            {
                invocation.Proceed();
                return;
            }

            var method = invocation.Method;

            _persistenceMaintainer.EnsureLoaded(_target);

            var service = TypeService.Instance;

            if (_persistenceMaintainer.State == PersistentState.Discarded)
            {
                throw new InvalidOperationException("Discarded entity must not be used");
            }
            else if (ProceedOnlyMethods.Contains(method))
            {
                invocation.Proceed();
            }
            else if (ProceedAndDirtyMethods.Contains(method))
            {
                if (_container.IsReadonly)
                {
                    throw new InvalidOperationException("readonly");
                }
                invocation.Proceed();
                _persistenceMaintainer.Dirty();
            }
            else if (service.IsDirtyDefined(method))
            {
                if (_container.IsReadonly)
                {
                    throw new InvalidOperationException("readonly");
                }
                invocation.Proceed();
                _persistenceMaintainer.Dirty();
                ProceedAndDirtyMethods.Add(method);
            }
            else if (MethodInfoUtil.IsPropertySetter(method))
            {
                if (_container.IsReadonly)
                {
                    throw new InvalidOperationException("readonly");
                }
                invocation.Proceed();
                _persistenceMaintainer.Dirty();
                ProceedAndDirtyMethods.Add(method);
            }
            else if (MethodInfoUtil.IsPropertyGetter(method))
            {
                if (method.ReturnType.IsArray)
                {
                    /// ここで場合分けしておかないとICollectionの分岐条件にマッチしてしまう
                    invocation.Proceed();
                    ProceedOnlyMethods.Add(method);
                }
                else if (MethodInfoUtil.IsICollectionPropertyGetter(method))
                {
                    ReturnCollectionWrapperIfPossible(invocation, _target);
                }
                else
                {
                    invocation.Proceed();
                    ProceedOnlyMethods.Add(method);
                }
            }
            else
            {
                invocation.Proceed();
                ProceedOnlyMethods.Add(method);
            }
        }