Exemplo n.º 1
0
        public void BaseMethodWithoutOverride()
        {
            var baseMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod <DomainTypeBase> (x => x.BaseMethod());

            var type = AssembleType <DomainType> (
                proxyType =>
            {
                var mutableMethod = proxyType.GetOrAddOverride(baseMethod);

                Assert.That(mutableMethod.BaseMethod, Is.EqualTo(baseMethod));
                Assert.That(mutableMethod.AddedExplicitBaseDefinitions, Is.Empty);

                CheckBodyOfAddedOverride(baseMethod, mutableMethod);

                mutableMethod.SetBody(ctx => ExpressionHelper.StringConcat(ctx.PreviousBody, Expression.Constant(" made mutable")));

                Assert.That(proxyType.GetOrAddOverride(baseMethod), Is.SameAs(mutableMethod));
            });

            var implicitOverride = type.GetMethod(baseMethod.Name);

            Assert.That(implicitOverride.DeclaringType, Is.SameAs(type));

            var instance = (DomainType)Activator.CreateInstance(type);
            var result   = implicitOverride.Invoke(instance, null);

            Assert.That(result, Is.EqualTo("Base made mutable"));
            Assert.That(instance.BaseMethod(), Is.EqualTo("Base made mutable"));
        }
        public void MakeSerializable_SerializableInterfaceType()
        {
            var proxyType = MutableTypeObjectMother.Create(typeof(SerializableInterfaceType), attributes: TypeAttributes.Serializable);

            _enabler.MakeSerializable(proxyType, _participantConfigurationID, _assembledTypeIdentifierProviderStub.Object, _typeID);

            Assert.That(proxyType.AddedInterfaces, Is.Empty);
            Assert.That(proxyType.AddedMethods, Has.Count.EqualTo(1));

            var baseMethod        = NormalizingMemberInfoFromExpressionUtility.GetMethod((SerializableInterfaceType o) => o.GetObjectData(null, new StreamingContext()));
            var method            = proxyType.AddedMethods.Single();
            var serializationInfo = method.ParameterExpressions[0];
            var expectedBody      = Expression.Block(
                Expression.Call(new ThisExpression(proxyType), new NonVirtualCallMethodInfoAdapter(baseMethod), method.ParameterExpressions.Cast <Expression>()),
                Expression.Block(
                    Expression.Call(serializationInfo, "SetType", Type.EmptyTypes, Expression.Constant(typeof(ObjectWithDeserializationConstructorProxy))),
                    Expression.Call(
                        serializationInfo,
                        "AddValue",
                        Type.EmptyTypes,
                        Expression.Constant("<tp>participantConfigurationID"),
                        Expression.Constant(_participantConfigurationID)),
                    Expression.Call(serializationInfo, "AddValue", Type.EmptyTypes, Expression.Constant("<tp>assembledTypeIDData"), _assembledTypeIDData)));

            ExpressionTreeComparer.CheckAreEqualTrees(expectedBody, method.Body);
        }
Exemplo n.º 3
0
        public void Static()
        {
            var type = AssembleType <DomainType> (
                proxyType =>
            {
                var staticField        = NormalizingMemberInfoFromExpressionUtility.GetField(() => DomainType.StaticDelegateField);
                var accessorAttributes = MethodAttributes.Private | MethodAttributes.Static;
                var method             = proxyType.AddMethod(
                    "StaticMethod",
                    accessorAttributes,
                    typeof(void),
                    new[] { new ParameterDeclaration(typeof(Action), "handler") },
                    ctx => Expression.Assign(Expression.Field(null, staticField), ctx.Parameters.Single()));
                proxyType.AddEvent("StaticEvent", EventAttributes.SpecialName, addMethod: method, removeMethod: method);
            });

            var event_ = type.GetEvent("StaticEvent", BindingFlags.NonPublic | BindingFlags.Static);

            Assertion.IsNotNull(event_);
            Assert.That(event_.Attributes, Is.EqualTo(EventAttributes.SpecialName));

            Assert.That(DomainType.StaticDelegateField, Is.Null);
            var handler = new Action(() => { });

            // event_.AddEventHandler(null, handler) // Does not work because add method is private.
            event_.GetAddMethod(true).Invoke(null, new object[] { handler });
            Assert.That(DomainType.StaticDelegateField, Is.SameAs(handler));
        }
Exemplo n.º 4
0
        public void ModifyingNonVirtualAndStaticAndFinalMethods_Throws()
        {
            var nonVirtualMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType obj) => obj.PublicMethod());
            var staticMethod     = NormalizingMemberInfoFromExpressionUtility.GetMethod(() => DomainType.PublicStaticMethod());
            var finalMethod      = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType obj) => obj.FinalMethod());

            var type = AssembleType <DomainType> (
                proxyType =>
            {
                var message = "Only virtual methods can be overridden.";
                Assert.That(
                    () => proxyType.GetOrAddOverride(nonVirtualMethod),
                    Throws.TypeOf <ArgumentException>().With.Message.StartsWith(message));

                Assert.That(
                    () => proxyType.GetOrAddOverride(staticMethod),
                    Throws.TypeOf <ArgumentException>().With.Message.StartsWith(message));

                Assert.That(
                    () => proxyType.GetOrAddOverride(finalMethod),
                    Throws.TypeOf <NotSupportedException>().With.Message.EqualTo("Cannot override final method 'DomainType.FinalMethod'."));
            });

            var instance = (DomainType)Activator.CreateInstance(type);

            Assert.That(instance.PublicMethod(), Is.EqualTo(12));

            var method = type.GetMethod("PublicStaticMethod", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

            Assert.That(method.Invoke(null, null), Is.EqualTo(13));
        }
Exemplo n.º 5
0
        public override void SetUp()
        {
            base.SetUp();

            _signedType   = typeof(int);
            _unsignedType = CreateUnsignedType(TypeAttributes.Class, typeof(object));

            _signedInterfaceType   = typeof(IMarkerInterface);
            _unsignedInterfaceType = CreateUnsignedType(TypeAttributes.Interface | TypeAttributes.Abstract, baseType: null);

            _signedDelegateType   = typeof(Action);
            _unsignedDelegateType = typeof(Action <>).MakeGenericType(_unsignedType);

            var attributeCtor = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new AbcAttribute(null));

            _signedAttribute   = new CustomAttributeDeclaration(attributeCtor, new object[] { _signedType });
            _unsignedAttribute = new CustomAttributeDeclaration(attributeCtor, new object[] { _unsignedType });

            _signedField   = NormalizingMemberInfoFromExpressionUtility.GetField(() => DomainType.Field);
            _unsignedField = _unsignedType.GetField("field");

            _signedCtor   = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new DomainType());
            _unsignedCtor = _unsignedType.GetConstructors().Single();

            _signedMethod   = NormalizingMemberInfoFromExpressionUtility.GetMethod(() => DomainType.Method());
            _unsignedMethod = _unsignedType.GetMethod("method");

            _signedVarArgsMethod   = typeof(DomainType).GetMethod("VarArgsMethod");
            _unsignedVarArgsMethod = _unsignedType.GetMethod("varargs");
        }
Exemplo n.º 6
0
        private IPipeline CreatePipeline()
        {
            var field       = NormalizingMemberInfoFromExpressionUtility.GetField((DomainType obj) => obj.String);
            var participant = CreateParticipant(
                proxyType =>
            {
                Assert.That(proxyType.Initialization.Expressions, Is.Empty);

                proxyType.AddInitialization(
                    ctx =>
                {
                    Assert.That(ctx.IsStatic, Is.False);

                    var fieldExpr = Expression.Field(ctx.This, field);
                    return(Expression.Assign(
                               fieldExpr,
                               ExpressionHelper.StringConcat(
                                   fieldExpr,
                                   Expression.Condition(
                                       Expression.Equal(ctx.InitializationSemantics, Expression.Constant(InitializationSemantics.Construction)),
                                       Expression.Constant("construction"),
                                       Expression.Constant(" deserialization")))));
                });

                Assert.That(proxyType.Initialization.Expressions, Is.Not.Empty);
            });

            return(CreatePipeline(new[] { participant }));
        }
Exemplo n.º 7
0
        public override void SetUp()
        {
            base.SetUp();

            _invokeLambda = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType obj) => obj.InvokeLambda(7));
            _returnLambda = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType obj) => obj.ReturnLambda(7));
        }
Exemplo n.º 8
0
        public void Initialization()
        {
            var constructor = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new DomainAttribute((ValueType)null));
            var property    = NormalizingMemberInfoFromExpressionUtility.GetProperty((DomainAttribute obj) => obj.Property);
            var field       = NormalizingMemberInfoFromExpressionUtility.GetField((DomainAttribute obj) => obj.Field);

            var declaration = new CustomAttributeDeclaration(
                constructor,
                new object[] { 7 },
                new NamedArgumentDeclaration(property, 7),
                new NamedArgumentDeclaration(field, "value"));

            Assert.That(declaration.Type, Is.SameAs(typeof(DomainAttribute)));
            Assert.That(declaration.Constructor, Is.SameAs(constructor));
            Assert.That(declaration.ConstructorArguments, Is.EqualTo(new[] { 7 }));
            var actualNamedArguments   = declaration.NamedArguments.Select(na => new { na.MemberInfo, na.Value });
            var expectedNamedArguments =
                new[]
            {
                new { MemberInfo = (MemberInfo)property, Value = (object)7 },
                new { MemberInfo = (MemberInfo)field, Value = (object)"value" }
            };

            Assert.That(actualNamedArguments, Is.EqualTo(expectedNamedArguments));
        }
Exemplo n.º 9
0
        public void Initialization_MemberDeclaringTypesAreAssignable()
        {
            var constructor = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new DomainAttribute());
            var property    = typeof(DomainAttribute).GetProperty("Property");

            new CustomAttributeDeclaration(constructor, new object[0], new NamedArgumentDeclaration(property, 7));
        }
Exemplo n.º 10
0
        public void CreateMethod_ImplicitOverride()
        {
            var fakeOverridenMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((B obj) => obj.OverrideHierarchy(7));

            _relatedMethodFinderMock
            .Setup(mock => mock.GetMostDerivedVirtualMethod("Method", new MethodSignature(typeof(int), Type.EmptyTypes, 0), _mutableType.BaseType))
            .Returns(fakeOverridenMethod)
            .Verifiable();

            Func <MethodBodyCreationContext, Expression> bodyProvider = ctx =>
            {
                Assert.That(ctx.HasBaseMethod, Is.True);
                Assert.That(ctx.BaseMethod, Is.SameAs(fakeOverridenMethod));

                return(Expression.Default(typeof(int)));
            };
            var method = CallCreateMethod(
                _mutableType,
                "Method",
                MethodAttributes.Public | MethodAttributes.Virtual,
                typeof(int),
                ParameterDeclaration.None,
                bodyProvider);

            _relatedMethodFinderMock.Verify();
            Assert.That(method.BaseMethod, Is.EqualTo(fakeOverridenMethod));
            Assert.That(method.GetBaseDefinition(), Is.EqualTo(fakeOverridenMethod.GetBaseDefinition()));
        }
Exemplo n.º 11
0
        public void Initialization_InvalidMemberDeclaringType()
        {
            var constructor = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new DomainAttribute());
            var property    = NormalizingMemberInfoFromExpressionUtility.GetProperty((DerivedAttribute attr) => attr.PropertyInDerivedType);

            new CustomAttributeDeclaration(constructor, new object[0], new NamedArgumentDeclaration(property, 7));
        }
Exemplo n.º 12
0
        public void WriteOnly_Public_Instance()
        {
            var type = AssembleType <DomainType> (
                proxyType =>
            {
                var field     = NormalizingMemberInfoFromExpressionUtility.GetField((DomainType o) => o.PublicField);
                var setMethod = proxyType.AddMethod(
                    "InstanceSetMethod",
                    MethodAttributes.Public,
                    typeof(void),
                    new[] { new ParameterDeclaration(typeof(string), "value") },
                    ctx => Expression.Assign(Expression.Field(ctx.This, field), ctx.Parameters[0]));
                proxyType.AddProperty("InstanceProperty", PropertyAttributes.None, getMethod: null, setMethod: setMethod);
            });

            var nonExistingStaticProperty = type.GetProperty("InstanceProperty", BindingFlags.Public | BindingFlags.Static);

            Assert.That(nonExistingStaticProperty, Is.Null);

            var property = type.GetProperty("InstanceProperty", BindingFlags.Public | BindingFlags.Instance);

            CheckSignature(property, CallingConventions.HasThis | CallingConventions.Standard);

            var instance = (DomainType)Activator.CreateInstance(type);

            property.SetValue(instance, "test", null);
            Assert.That(instance.PublicField, Is.EqualTo("test"));
        }
Exemplo n.º 13
0
        public void OverrideExisting_AddCustomAttribute()
        {
            var type = AssembleType <DomainType> (
                proxyType =>
            {
                var existingProperty = NormalizingMemberInfoFromExpressionUtility.GetProperty((DomainType obj) => obj.ExistingProperty);
                var getMethod        = proxyType.GetOrAddOverride(existingProperty.GetGetMethod());
                var setMethod        = proxyType.GetOrAddOverride(existingProperty.GetSetMethod());
                var property         = proxyType.AddProperty(existingProperty.Name, PropertyAttributes.None, getMethod, setMethod);

                var attributeCtor    = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new AbcAttribute(""));
                var customAttributes = new CustomAttributeDeclaration(attributeCtor, new object[] { "derived" });
                property.AddCustomAttribute(customAttributes);
            });

            var newProperty = type.GetProperty("ExistingProperty");
            var instance    = (DomainType)Activator.CreateInstance(type);

            Assert.That(instance.ExistingProperty, Is.Null);
            Assert.That(newProperty.GetValue(instance, null), Is.Null);
            newProperty.SetValue(instance, "Test", null);
            Assert.That(instance.ExistingProperty, Is.EqualTo("Test"));
            Assert.That(newProperty.GetValue(instance, null), Is.EqualTo("Test"));

            var attributeArgs = Attribute.GetCustomAttributes(newProperty, inherit: true).Cast <AbcAttribute>().Select(a => a.Arg);

            Assert.That(attributeArgs, Is.EquivalentTo(new[] { "base", "derived" }));
        }
Exemplo n.º 14
0
        public void IndexParameters()
        {
            var type = AssembleType <DomainType> (
                proxyType =>
            {
                var field = NormalizingMemberInfoFromExpressionUtility.GetField((DomainType o) => o.PublicField);
                proxyType.AddProperty(
                    "Property",
                    typeof(string),
                    new[] { new ParameterDeclaration(typeof(string), "index0"), new ParameterDeclaration(typeof(string), "index1") },
                    MethodAttributes.Public,
                    getBodyProvider: ctx =>
                {
                    Assert.That(ctx.ReturnType, Is.SameAs(typeof(string)));
                    Assert.That(ctx.Parameters.Count, Is.EqualTo(2));
                    return(ExpressionHelper.StringConcat(ctx.Parameters[0], ctx.Parameters[1]));
                },
                    setBodyProvider: ctx =>
                {
                    Assert.That(ctx.ReturnType, Is.SameAs(typeof(void)));
                    Assert.That(ctx.Parameters.Count, Is.EqualTo(3));
                    var value = ExpressionHelper.StringConcat(ExpressionHelper.StringConcat(ctx.Parameters[0], ctx.Parameters[1]), ctx.Parameters[2]);
                    return(Expression.Assign(Expression.Field(ctx.This, field), value));
                });
            });

            var property = type.GetProperty("Property");
            var instance = (DomainType)Activator.CreateInstance(type);

            Assert.That(property.GetValue(instance, new object[] { "a ", "b" }), Is.EqualTo("a b"));
            property.SetValue(instance, "value", new object[] { "a ", "b " });
            Assert.That(instance.PublicField, Is.EqualTo("a b value"));
        }
Exemplo n.º 15
0
        public void GenericParameters()
        {
            var method1 = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType o) => o.ReferenceType());
            var method2 = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType o) => o.ValueType());
            var method3 = NormalizingMemberInfoFromExpressionUtility.GetGenericMethodDefinition((DomainType o) => o.Unconstrained <Dev.T>());
            var method4 = NormalizingMemberInfoFromExpressionUtility.GetGenericMethodDefinition((DomainType o) => o.ReferenceTypeConstraint <Dev.T>());
            var method5 = NormalizingMemberInfoFromExpressionUtility.GetGenericMethodDefinition((DomainType o) => o.NotNuallableValueTypeConstraint <int>());
            var method6 = NormalizingMemberInfoFromExpressionUtility.GetGenericMethodDefinition((DomainType o) => o.ClassBaseTypeConstraint <DomainType>());

            var type = AssembleType <DomainType> (
                proxyType =>
            {
                proxyType.GetOrAddOverride(method1).SetBody(ctx => Expression.Default(typeof(string)));
                proxyType.GetOrAddOverride(method2).SetBody(ctx => Expression.Default(typeof(int)));
                proxyType.GetOrAddOverride(method3).SetBody(ctx => Expression.Default(ctx.GenericParameters[0]));
                proxyType.GetOrAddOverride(method4).SetBody(ctx => Expression.Default(ctx.GenericParameters[0]));
                proxyType.GetOrAddOverride(method5).SetBody(ctx => Expression.Default(ctx.GenericParameters[0]));
                proxyType.GetOrAddOverride(method6).SetBody(ctx => Expression.Default(ctx.GenericParameters[0]));
            });

            var instance = (DomainType)Activator.CreateInstance(type);

            Assert.That(instance.ReferenceType(), Is.Null);
            Assert.That(instance.Unconstrained <string>(), Is.Null);
            Assert.That(instance.ReferenceTypeConstraint <string>(), Is.Null);
            Assert.That(instance.NotNuallableValueTypeConstraint <int>(), Is.EqualTo(0));
            Assert.That(instance.ClassBaseTypeConstraint <DomainType>(), Is.Null);
        }
Exemplo n.º 16
0
        private CustomAttributeDeclaration CreateMultipleAttribute(string value)
        {
            var constructor = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new MultipleAttribute());
            var field       = NormalizingMemberInfoFromExpressionUtility.GetField((MultipleAttribute obj) => obj.String);

            return(new CustomAttributeDeclaration(constructor, new object[0], new NamedArgumentDeclaration(field, value)));
        }
Exemplo n.º 17
0
        public override void Participate(object id, IProxyTypeAssemblyContext proxyTypeAssemblyContext)
        {
            var constructor = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new ModifiedAssembledTypeAttribute());
            var attribute   = new CustomAttributeDeclaration(constructor, new object[0]);

            proxyTypeAssemblyContext.ProxyType.AddCustomAttribute(attribute);
        }
Exemplo n.º 18
0
        public void ComputeMapping_AddedInterface_NotFullyImplemented_AllowPartial()
        {
            _mutableType.AddInterface(typeof(IDisposable));
            var interfaceMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((IDisposable obj) => obj.Dispose());

            CallComputeMappingAndCheckResult(_mutableType, typeof(IDisposable), Tuple.Create(interfaceMethod, (MethodInfo)null));
        }
Exemplo n.º 19
0
        public void ReImplement()
        {
            var interfaceMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((IInterfaceWithMethod o) => o.Method());
            var type            = AssembleType <DomainTypeWithMethod> (
                proxyType =>
            {
                proxyType.AddInterface(typeof(IInterfaceWithMethod));
                var mutableMethod = AddEquivalentMethod(
                    proxyType,
                    interfaceMethod,
                    MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot,
                    ctx =>
                {
                    Assert.That(ctx.HasBaseMethod, Is.False);
                    return(Expression.Constant("new implementation"));
                });

                Assert.That(mutableMethod.BaseMethod, Is.Null);
                Assert.That(mutableMethod.GetBaseDefinition(), Is.EqualTo(mutableMethod));
            });

            var instance = (DomainTypeWithMethod)Activator.CreateInstance(type);

            Assert.That(instance.Method(), Is.EqualTo("original implementation"));
            Assert.That(((IInterfaceWithMethod)instance).Method(), Is.EqualTo("new implementation"));
        }
Exemplo n.º 20
0
        public void ComputeMapping_ExistingInterface()
        {
            var implicitImplementation1 = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType obj) => obj.Method11());
            var implicitImplementation2 = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType obj) => obj.Method12());
            var explicitImplementation  = _mutableType.AddMethod("ExplicitImpl", MethodAttributes.Virtual);

            explicitImplementation.AddExplicitBaseDefinition(_existingInterfaceMethod2);

            _interfaceMapProviderMock
            .Setup(mock => mock.Get(typeof(IExistingInterface)))
            .Returns(
                new InterfaceMapping
            {
                InterfaceType    = typeof(IExistingInterface),
                InterfaceMethods = new[] { _existingInterfaceMethod1, _existingInterfaceMethod2 },
                TargetMethods    = new[] { implicitImplementation1, implicitImplementation2 }
            })
            .Verifiable();

            CallComputeMappingAndCheckResult(
                _mutableType,
                typeof(IExistingInterface),
                Tuple.Create(_existingInterfaceMethod1, implicitImplementation1),
                Tuple.Create(_existingInterfaceMethod2, (MethodInfo)explicitImplementation));
        }
Exemplo n.º 21
0
        public void CreateBody_BuildsCorrectBody_UsingAbstractTemplateMembers()
        {
            var accessorImplementationMethod =
                NormalizingMemberInfoFromExpressionUtility.GetGenericMethodDefinition((PropertyAccessor a) => a.SetValue <object> (null));
            var arguments = new Expression[] { Expression.Parameter(typeof(int), "param") };
            var ctx       = new MethodBodyModificationContext(_proxyType, false, new ParameterExpression[0], Type.EmptyTypes, typeof(int), null, null);

            _interceptorPartialMock
            .Stub(stub => PrivateInvoke.GetNonPublicProperty(stub, "AccessorImplementationMethod"))
            .Return(accessorImplementationMethod);
            _interceptorPartialMock
            .Stub(stub => PrivateInvoke.InvokeNonPublicMethod(stub, "GetArguments", Arg <MethodBaseBodyContextBase> .Is.Anything))
            .WhenCalled(mi => Assert.That(mi.Arguments[0], Is.SameAs(ctx)))
            .Return(arguments);

            var result = (Expression)PrivateInvoke.InvokeNonPublicMethod(_interceptorPartialMock, "CreateBody", ctx);

            var expectedbody =
                Expression.Call(
                    Expression.Call(
                        Expression.Property(
                            new ThisExpression(_proxyType),
                            typeof(DomainObject).GetProperty("Properties", BindingFlags.Instance | BindingFlags.NonPublic)),
                        "get_Item",
                        null,
                        Expression.Constant("abc")),
                    "SetValue",
                    new[] { typeof(int) },
                    arguments);

            ExpressionTreeComparer.CheckAreEqualTrees(expectedbody, result);
        }
        public void NoBase_Implement()
        {
            var interfaceMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((IAddedInterface o) => o.AddedMethod());
            var type            = AssembleType <DomainType> (
                p =>
            {
                p.AddInterface(typeof(IAddedInterface));

                var method = p.GetOrAddImplementation(interfaceMethod);
                Assert.That(method, Is.SameAs(p.GetOrAddImplementation(interfaceMethod)));

                method.SetBody(
                    ctx =>
                {
                    Assert.That(ctx.HasBaseMethod, Is.False);
                    Assert.That(ctx.HasPreviousBody, Is.False);

                    return(Expression.Constant("added"));
                });
            });

            var instance = (IAddedInterface)Activator.CreateInstance(type);

            Assert.That(instance.AddedMethod(), Is.EqualTo("added"));
        }
        public void GetAdviceBuilders_Inheriting()
        {
            var method     = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType obj) => obj.InheritMethod());
            var baseMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainTypeBase obj) => obj.InheritMethod());

            _customAttributeDataHelperMock
            .Stub(x => x.AllowsMultiple(Arg <ICustomAttributeData> .Is.Anything))
            .Return(true).Repeat.Any();
            _customAttributeDataHelperMock
            .Stub(x => x.IsAspectAttribute(Arg <ICustomAttributeData> .Is.Anything))
            .Return(true).Repeat.Any();
            _customAttributeDataHelperMock
            .Expect(x => x.IsInheriting(Arg <ICustomAttributeData> .Matches(y => y.Constructor.DeclaringType == typeof(InheritingAttribute))))
            .Return(true);
            _customAttributeDataHelperMock
            .Expect(x => x.IsInheriting(Arg <ICustomAttributeData> .Matches(y => y.Constructor.DeclaringType == typeof(NotInheritingAttribute))))
            .Return(false);
            _attributeDeclarationProviderMock
            .Expect(x => x.GetAdviceBuilders(Arg <ICustomAttributeData> .Matches(y => y.Constructor.DeclaringType == typeof(InheritingAttribute))))
            .Return(new[] { _fakeAdviceBuilder1 });

            var result = _provider.GetAdviceBuilders(method, new[] { method, baseMethod }).ToArray();

            _customAttributeDataHelperMock.VerifyAllExpectations();
            _attributeDeclarationProviderMock.VerifyAllExpectations();
            Assert.That(result, Is.EquivalentTo(new[] { _fakeAdviceBuilder1 }));
        }
        public void VirtualBase_Overrides()
        {
            var interfaceMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((IMyInterface o) => o.Method1());
            var baseMethod      = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType o) => o.Method1());
            var type            = AssembleType <DomainType> (
                p =>
            {
                var method = p.GetOrAddImplementation(interfaceMethod);
                Assert.That(method, Is.SameAs(p.GetOrAddImplementation(interfaceMethod)));

                method.SetBody(ctx =>
                {
                    Assert.That(ctx.BaseMethod, Is.EqualTo(baseMethod));
                    Assert.That(ctx.DeclaringType.AddedInterfaces, Is.Empty);

                    return(ExpressionHelper.StringConcat(ctx.PreviousBody, Expression.Constant(" override")));
                });
            });

            var overrideMethod = GetDeclaredMethod(type, "Method1");

            Assert.That(overrideMethod.Attributes.IsSet(MethodAttributes.VtableLayoutMask, MethodAttributes.ReuseSlot), Is.True);
            var instance = (DomainType)Activator.CreateInstance(type);

            var result1 = instance.Method1();
            var result2 = instance.As <IMyInterface>().Method1();

            Assert.That(result1, Is.EqualTo("1 override"));
            Assert.That(result2, Is.EqualTo("1 override"));
        }
Exemplo n.º 25
0
        public void Implement_InvalidCandidates()
        {
            var interfaceMethod1 = NormalizingMemberInfoFromExpressionUtility.GetMethod((IInvalidCandidates obj) => obj.NonPublicCandidate());
            var interfaceMethod2 = NormalizingMemberInfoFromExpressionUtility.GetMethod((IInvalidCandidates obj) => obj.NonVirtualCandidate());

            AssembleType <DomainType> (
                proxyType =>
            {
                proxyType.AddMethod(
                    "NonPublicCandidate", MethodAttributes.Assembly | MethodAttributes.Virtual, typeof(void), ParameterDeclaration.None, ctx => Expression.Empty());
                proxyType.AddMethod("NonVirtualCandidate", MethodAttributes.Public, typeof(void), ParameterDeclaration.None, ctx => Expression.Empty());

                proxyType.AddInterface(typeof(IInvalidCandidates));

                var messageFormat = "Interface method '{0}' cannot be implemented because a method with equal name and signature already exists. "
                                    + "Use AddExplicitOverride to create an explicit implementation.";
                Assert.That(
                    () => proxyType.GetOrAddImplementation(interfaceMethod1),
                    Throws.InvalidOperationException.With.Message.EqualTo(string.Format(messageFormat, interfaceMethod1.Name)));
                Assert.That(
                    () => proxyType.GetOrAddImplementation(interfaceMethod2),
                    Throws.InvalidOperationException.With.Message.EqualTo(string.Format(messageFormat, interfaceMethod2.Name)));

                // Implement the interface, otherwise the type is invalid and cannot be generated.
                proxyType.AddExplicitOverride(interfaceMethod1, ctx => Expression.Empty());
                proxyType.AddExplicitOverride(interfaceMethod2, ctx => Expression.Empty());
            });
        }
        public void NonVirtualBase_ReImplements_AndCallsBase()
        {
            var interfaceMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((IMyInterface o) => o.Method2());
            var type            = AssembleType <DomainType> (
                p =>
            {
                var method = p.GetOrAddImplementation(interfaceMethod);
                Assert.That(method, Is.SameAs(p.GetOrAddImplementation(interfaceMethod)));

                method.SetBody(ctx =>
                {
                    Assert.That(ctx.HasBaseMethod, Is.False);
                    Assert.That(p.AddedInterfaces, Is.EqualTo(new[] { typeof(IMyInterface) }));

                    return(ExpressionHelper.StringConcat(ctx.PreviousBody, Expression.Constant(" re-implementation")));
                });
            });

            var reImplementMethod = GetDeclaredMethod(type, "Method2");

            Assert.That(reImplementMethod.Attributes.IsSet(MethodAttributes.NewSlot), Is.True);
            var instance = (DomainType)Activator.CreateInstance(type);

            var result1 = instance.Method2();
            var result2 = instance.As <IMyInterface>().Method2();

            Assert.That(result1, Is.EqualTo("2"));
            Assert.That(result2, Is.EqualTo("2 re-implementation"));
        }
Exemplo n.º 27
0
        public void Override_UsingAccesssors()
        {
            var dummyRaiseMethod = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType o) => o.DummyRaiseMethod(7));
            var type             = AssembleType <DomainType> (
                proxyType =>
            {
                var existingEvent = proxyType.GetEvent("ExistingEvent");
                var addMethod     = proxyType.GetOrAddOverride(existingEvent.GetAddMethod());
                var removeMethod  = proxyType.GetOrAddOverride(existingEvent.GetRemoveMethod());
                Assert.That(existingEvent.GetRaiseMethod(true), Is.Null);
                var raiseMethod = proxyType.GetOrAddOverride(dummyRaiseMethod);

                proxyType.AddEvent(existingEvent.Name, EventAttributes.None, addMethod, removeMethod, raiseMethod);
            });

            var newEvent = type.GetEvent("ExistingEvent", BindingFlags.Public | BindingFlags.Instance);

            Assertion.IsNotNull(newEvent);
            var instance = (DomainType)Activator.CreateInstance(type);

            Assert.That(instance.AddCalled, Is.False);
            Assert.That(instance.RemoveCalled, Is.False);
            newEvent.AddEventHandler(instance, null);
            Assert.That(instance.AddCalled, Is.True);
            newEvent.RemoveEventHandler(instance, null);
            Assert.That(instance.RemoveCalled, Is.True);

            var newRaiseMethod = type.GetMethod("DummyRaiseMethod");

            Assert.That(newEvent.GetRaiseMethod(), Is.SameAs(newRaiseMethod));
        }
Exemplo n.º 28
0
        public void GetMostDerivedVirtualMethod_NonVirtualMethod()
        {
            var method = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType obj) => obj.NonVirtualMethod());
            var result = _finder.GetMostDerivedVirtualMethod(method.Name, _methodSignature, _typeToStartSearch);

            Assert.That(result, Is.Null);
        }
Exemplo n.º 29
0
        public void ProxyIsBaseTypeOfNewClass()
        {
            // public class Proxy : DomainType {
            //   public override string Method () { return base.Method() + " Proxy"; }
            // }
            // public class ProxyProxy : Proxy {
            //   public override string Method () { return base.Method() + " ProxyProxy"; }
            // }
            var    method       = NormalizingMemberInfoFromExpressionUtility.GetMethod((DomainType o) => o.Method());
            string newClassName = null;

            var type = AssembleType <DomainType> (
                typeContext =>
            {
                var proxy = typeContext.ProxyType;
                proxy.GetOrAddOverride(method).SetBody(ctx => ExpressionHelper.StringConcat(ctx.PreviousBody, Expression.Constant(" Proxy")));

                var proxyProxy = typeContext.CreateAddtionalProxyType(new object(), proxy);
                proxyProxy.GetOrAddOverride(method).SetBody(ctx => ExpressionHelper.StringConcat(ctx.PreviousBody, Expression.Constant(" ProxyProxy")));
                newClassName = proxyProxy.FullName;
            });

            var proxyProxyType     = type.Assembly.GetType(newClassName, throwOnError: true);
            var proxyInstance      = (DomainType)Activator.CreateInstance(type);
            var proxyProxyInstance = (DomainType)Activator.CreateInstance(proxyProxyType);

            Assert.That(proxyInstance.Method(), Is.EqualTo("DomainType Proxy"));
            Assert.That(proxyProxyInstance.Method(), Is.EqualTo("DomainType Proxy ProxyProxy"));
        }
Exemplo n.º 30
0
        public void BaseMethod_GenericMethod()
        {
            var baseMethod = NormalizingMemberInfoFromExpressionUtility.GetGenericMethodDefinition((DomainType obj) => obj.GenericMethod <Dev.T> (null));

            var type = AssembleType <DomainType> (
                proxyType =>
            {
                var mutableMethod = proxyType.GetOrAddOverride(baseMethod);

                Assert.That(mutableMethod.BaseMethod, Is.SameAs(baseMethod));
                Assert.That(mutableMethod.IsGenericMethodDefinition, Is.True);
                var mutableGenericParameter = mutableMethod.MutableGenericParameters.Single();
                Assert.That(mutableGenericParameter.Name, Is.EqualTo("TPar"));
                Assert.That(mutableGenericParameter.GenericParameterAttributes, Is.EqualTo(GenericParameterAttributes.None));
                Assert.That(mutableGenericParameter.GetGenericParameterConstraints(), Is.Empty);

                mutableMethod.SetBody(ctx => ExpressionHelper.StringConcat(ctx.PreviousBody, Expression.Constant(" made mutable")));
            });

            var method = GetDeclaredMethod(type, "GenericMethod");

            Assert.That(method.GetBaseDefinition(), Is.SameAs(baseMethod));
            Assert.That(method.IsGenericMethodDefinition, Is.True);
            var genericParameter = method.GetGenericArguments().Single();

            Assert.That(genericParameter.Name, Is.EqualTo("TPar"));
            Assert.That(genericParameter.GenericParameterAttributes, Is.EqualTo(GenericParameterAttributes.None));
            Assert.That(genericParameter.GetGenericParameterConstraints(), Is.EqualTo(new[] { typeof(object) }), "Why object and not empty?");

            var instance = (DomainType)Activator.CreateInstance(type);

            Assert.That(instance.GenericMethod("doesn't matter"), Is.EqualTo("DomainType String made mutable"));
        }