public GuardPropertyEqualityTransformation(AspectWeaver aspectWeaver)
            : base(aspectWeaver)
        {
            //Initialize Transformation fields
            var module = AspectInfrastructureTask.Project.Module;
            _assets = module.Cache.GetItem(() => new TransformationAssets(module));

            this.Effects.Add(PostEdgeStandardEffects.GuardPropertyEquality);
            this.Dependencies.Add(
                new AspectDependency(
                    AspectDependencyAction.Order,
                    AspectDependencyPosition.Before,
                    new OrDependencyCondition(
                        new AspectEffectDependencyCondition(StandardEffects.ChangeControlFlow)
                        )
                    )
                );
            this.Dependencies.Add(
                new AspectDependency(
                    AspectDependencyAction.Order,
                    AspectDependencyPosition.After,
                    new OrDependencyCondition(
                        new AspectEffectDependencyCondition(PostEdgeStandardEffects.RaisesPropertyChangedEvent)
                        )
                    )
                );
        }
Example #2
0
        public OnThrowTransformation(AspectWeaver aspectWeaver)
            : base(aspectWeaver)
        {
            var module = AspectInfrastructureTask.Project.Module;

            assets = module.Cache.GetItem(() => new Assets(module));
        }
 public EnhancePropertySetterMethodBodyTransformation(AspectWeaver aspectWeaver)
     : base(aspectWeaver)
 {
     this.Effects.Add(PostEdgeStandardEffects.RaisesPropertyChangedEvent);
     this.Dependencies.Add(
         new AspectDependency(
             AspectDependencyAction.Order,
             AspectDependencyPosition.Before,
             new AndDependencyCondition(
                 new AspectEffectDependencyCondition(StandardEffects.ChangeControlFlow)
                 )
             )
         );
     this.Dependencies.Add(
         new AspectDependency(
             AspectDependencyAction.Order,
             AspectDependencyPosition.Before,
             new AndDependencyCondition(
                 new AspectEffectDependencyCondition(PostEdgeStandardEffects.GuardPropertyEquality)
                 )
             )
         );
     this.Dependencies.Add(
         new AspectDependency(
             AspectDependencyAction.Commute,
             AspectDependencyPosition.Before,
             new AndDependencyCondition(
                 new SameAspectInstanceDependencyCondition()
                 )
             )
         );
 }
Example #4
0
        public void TestBeforeAdviceChangeParam()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()))
            .Callback(() => throw new InvalidOperationException());
            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <string, ValueTuple> >()))
            .Callback((Invocation <string, ValueTuple> invoc) => invoc.Parameter = "Changed");
            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <string, string> >()))
            .Callback((Invocation <string, string> invoc) => invoc.Parameter = "Changed 2");

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            weaver.Advice("Not Changed", arg => Assert.AreEqual("Changed", arg));
            Assert.AreEqual("Return", weaver.Advice("Not Changed", arg => {
                Assert.AreEqual("Changed 2", arg);
                return("Return");
            }));

            config = new AspectConfiguration();
            weaver = new AspectWeaver(config, this);

            weaver.Advice("Not Changed", arg => Assert.AreEqual("Not Changed", arg));
            Assert.AreEqual("Return", weaver.Advice("Not Changed", arg => {
                Assert.AreEqual("Not Changed", arg);
                return("Return");
            }));
        }
Example #5
0
        public void TestBasicBeforeAdvice()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            string value = "";

            weaver.Advice(() => { value = "called"; });
            Assert.AreEqual("called", value);

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);

            weaver.Advice("called2", arg => { value = arg; });
            Assert.AreEqual("called2", value);

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);

            weaver.Advice(() => { value = "called3"; });
            Assert.AreEqual("called3", value);

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
        }
Example #6
0
        public void Stuff()
        {
            var createShipFactory =
                AspectWeaver.Of(() => new Ship())
                .WeaveAspects(
                    new AspectProvider(new DoStuffAspect(), new CrazyAspect()),
                    t => t.Methods(
                        s => s.LockOnTarget(null),
                        s => s.RecieveMessage(null, false),
                        s => s.FullStop()),
                    t => t.Properties(
                        s => s.Armor,
                        s => s.Captain)
                    )
                .WeaveAspects(
                    new AspectProvider(new CrazyAspect()),
                    t => t.Properties(
                        s => s.HullIntegrity
                        )
                    )
                .CreateFactory <IShip>();

            Catalog.Services.Register(_ => createShipFactory());
            var ship = Catalog.Factory.Resolve <IShip>();
        }
Example #7
0
 public Weaved(IComponentsStore components, Container simpleInjectorContainer,
               WindsorContainer windsorContainer, params DependencyPair[] dependency)
 {
     _dependency              = dependency ?? Array.Empty <DependencyPair>();
     _windsorContainer        = windsorContainer;
     _simpleInjectorContainer = simpleInjectorContainer;
     _aspectWeaver            = AspectWeaverFactory.Create(components);
 }
Example #8
0
        public void Setup()
        {
            _weaver    = AspectWeaverFactory.Create();
            _container = new WindsorContainer();

            _container.Register(
                Component.For <IServiceForBenchmark>()
                .ImplementedBy <ServiceForBenchmark>());
        }
Example #9
0
        public void TestKeyValueStore()
        {
            var watchAdvice = new MethodWatchAdvice();
            var config      = new AspectConfiguration()
                              .AddAspect(watchAdvice);

            var weaver = new AspectWeaver(config, this);

            weaver.Advice(() => { Thread.Sleep(10); });
            Assert.IsTrue(watchAdvice.TotalElapsed >= TimeSpan.FromMilliseconds(10));
        }
Example #10
0
        protected override bool Process(AssemblyStitcherContext context)
        {
            if (AlreadyProcessed(context))
            {
                return(false);
            }


#if DEBUG
            _logging = new MultiLogging(new DefaultLogging(Logging), new FileLogging("MrAdvice.log"));
            _logging.WriteDebug("Start");
#else
            _logging = Logging;
#endif
            if (context.Module == null)
            {
                _logging.WriteError("Target assembly {0} could not be loaded", context.AssemblyPath);
                return(false);
            }

            try
            {
                // instances are created here
                // please also note poor man's dependency injection (which is enough for us here)
                var assemblyResolver = context.AssemblyResolver;
                var typeResolver     = new TypeResolver(context.Module)
                {
                    Logging = _logging, AssemblyResolver = assemblyResolver
                };
                var typeLoader   = new TypeLoader(() => LoadWeavedAssembly(context, assemblyResolver));
                var aspectWeaver = new AspectWeaver {
                    Logging = _logging, TypeResolver = typeResolver, TypeLoader = typeLoader
                };

                BlobberHelper.Setup();

                //Assembly.Load("System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes");
                //Assembly.Load("System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes");
                Assembly.Load("MrAdvice, Version=2.0.0.0, Culture=neutral, PublicKeyToken=c0e7e6eab6f293d8");

                return(aspectWeaver.Weave(context.Module));
            }
            catch (Exception e)
            {
                _logging.WriteError("Internal error: {0}", e.ToString());
                for (var ie = e.InnerException; ie != null; ie = ie.InnerException)
                {
                    _logging.WriteError("Inner exception: {0}", e.ToString());
                }
            }
            return(false);
        }
Example #11
0
        public void TestDbCIntercept1()
        {
            AspectImpl aspect = new AspectImpl(
                new ConstraintInterceptor(),
                new ClassAttributePointcut(typeof(InvariantConditionAttribute)) |
                new MethodAttributePointcut(typeof(PreConditionAttribute)) |
                new MethodAttributePointcut(typeof(PostConditionAttribute)));

            AspectWeaver.Instance().Register(aspect);

            new DbCTest().Test1(-1);
            new DbCTest().Test2(-1);
        }
Example #12
0
        public void TestInvocationMethod()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()))
            .Callback((Invocation <ValueTuple, string> invoc) => {
                Assert.AreEqual("TestInvocationMethod", invoc.MethodName);
                Assert.IsFalse(invoc.IsMethodLookupDone);
                Assert.AreEqual("TestInvocationMethod", invoc.Method.Name);
                Assert.IsTrue(invoc.IsMethodLookupDone);

                Assert.IsNotNull(invoc.GetAttribute <TestMethodAttribute>());
                Assert.IsNull(invoc.GetAttribute <TestClassAttribute>());

                Assert.AreEqual("AspectWeaverTests", invoc.TargetType.Name);
            });
            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <string, string> >()))
            .Callback((Invocation <string, string> invoc) => {
                Assert.AreEqual("TestInvocationMethodCall", invoc.MethodName);
                Assert.IsFalse(invoc.IsMethodLookupDone);
                Assert.AreEqual("TestInvocationMethodCall", invoc.Method.Name);
                Assert.IsTrue(invoc.IsMethodLookupDone);

                Assert.IsNull(invoc.GetAttribute <TestMethodAttribute>());
                Assert.IsNull(invoc.GetAttribute <TestClassAttribute>());

                Assert.AreEqual("AspectWeaverTests", invoc.TargetType.Name);
            });

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            string value = "";

            weaver.Advice(() => value = "2");
            Assert.AreEqual("2", value);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()), Times.Once);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, string> >()), Times.Never);

            value = weaver.Advice(() => "3");
            Assert.AreEqual("3", value);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, string> >()), Times.Never);

            value = weaver.Advice("4", (string a) => a, "TestInvocationMethodCall");
            Assert.AreEqual("4", value);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, string> >()), Times.Once);
        }
Example #13
0
        public void TestThrowExceptionIntercept()
        {
            AspectImpl aspect = new AspectImpl(
                new TestThrowExecptionInterceptor(),
                new ClassNamePointcut(".*") &
                new MethodAttributePointcut(typeof(TestInterceptAttribute)));

            AspectWeaver.Instance().Register(aspect);
            TestAspectWeavedClass wc = new TestAspectWeavedClass();

            Console.WriteLine("MethodAttrInterceptTest Start");
            wc.Hello();
            Console.WriteLine("MethodAttrInterceptTest End");
        }
Example #14
0
        /// <summary>
        /// Processes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">Ignore.</exception>
        protected override bool Process(AssemblyStitcherContext context)
        {
            BlobberHelper.Setup();

#if DEBUG
            _logging = new MultiLogging(new DefaultLogging(Logging), new FileLogging("MrAdvice.log"));
            _logging.WriteDebug("Start");
#else
            _logging = Logging;
#endif
            if (context.Module is null)
            {
                _logging.WriteError("Target assembly {0} could not be loaded", context.AssemblyPath);
                return(false);
            }

            try
            {
                // instances are created here
                // please also note poor man's dependency injection (which is enough for us here)
                var assemblyResolver = context.AssemblyResolver;
                var typeResolver     = new TypeResolver(context.Module)
                {
                    Logging = _logging, AssemblyResolver = assemblyResolver
                };
                var typeLoader   = new TypeLoader(() => LoadWeavedAssembly(context, assemblyResolver));
                var aspectWeaver = new AspectWeaver {
                    Logging = _logging, TypeResolver = typeResolver, TypeLoader = typeLoader
                };

                // second chance: someone had the marker file missing
                if (aspectWeaver.FindShortcutType(context.Module) is not null)
                {
                    return(false);
                }

                return(aspectWeaver.Weave(context.Module));
            }
            catch (Exception e)
            {
                _logging.WriteError("Internal error: {0}", e.ToString());
                for (var ie = e.InnerException; ie is not null; ie = ie.InnerException)
                {
                    _logging.WriteError("Inner exception: {0}", e.ToString());
                }
            }
            return(false);
        }
Example #15
0
    /// <summary>
    /// Executes this instance.
    /// </summary>
    // ReSharper disable once UnusedMember.Global
    public void Execute()
    {
        // instances are created here
        // please also note poor man's dependency injection (which is enough for us here)
        Logger.LogInfo    = LogInfo;
        Logger.LogWarning = LogWarning;
        Logger.LogError   = LogError;
        var typeResolver = new TypeResolver {
            AssemblyResolver = AssemblyResolver
        };
        var typeLoader   = new TypeLoader(() => LoadWeavedAssembly());
        var aspectWeaver = new AspectWeaver {
            TypeResolver = typeResolver, TypeLoader = typeLoader
        };

        aspectWeaver.Weave(ModuleDefinition);
    }
Example #16
0
        public void TestBasicAfterAdvice()
        {
            var adviceMock = new Mock <IAfterAdvice>();

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            string value = "";

            weaver.Advice(() => { value = "called"; });
            Assert.AreEqual("called", value);

            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Never);

            weaver.Advice("called2", arg => { value = arg; });
            Assert.AreEqual("called2", value);

            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Never);

            weaver.Advice(() => { value = "called3"; });
            Assert.AreEqual("called3", value);
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Never);

            weaver.Advice(() => { return(value = "called3"); });
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, string> >()), Times.Once);
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Never);

            Assert.ThrowsException <Exception>(() => {
                weaver.Advice(() => { throw new Exception(); });
            });
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, string> >()), Times.Once);
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Once);
        }
Example #17
0
        public void TestBeforeAdviceAbort()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()))
            .Callback(() => throw new InvalidOperationException());
            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <int, ValueTuple> >()))
            .Callback(() => { });

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            weaver.Advice(15, n => { });
            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(() => { });
            });
        }
Example #18
0
        public void TestThrowException()
        {
            var adviceMock = new Mock <IAfterAdvice>();
            var config     = new AspectConfiguration()
                             .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(() => throw new InvalidOperationException());
            });
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Once);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(0, p => throw new InvalidOperationException());
            });
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <int, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Once);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(() => {
                    int a = 0;
                    if (a == 0)
                    {
                        throw new InvalidOperationException();
                    }
                    return(0);
                });
            });
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, int> >(), ref It.Ref <Exception> .IsAny), Times.Once);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(0, p => {
                    if (p == 0)
                    {
                        throw new InvalidOperationException();
                    }
                    return(0);
                });
            });
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <int, int> >(), ref It.Ref <Exception> .IsAny), Times.Once);
        }
Example #19
0
        protected override bool Process(AssemblyStitcherContext context)
        {
            if (AlreadyProcessed(context))
            {
                return(false);
            }

#if DEBUG
            _logging = new MultiLogging(new DefaultLogging(Logging), new FileLogging("MrAdvice.log"));
            _logging.WriteDebug("Start");
#else
            _logging = Logging;
#endif
            try
            {
                // instances are created here
                // please also note poor man's dependency injection (which is enough for us here)
                var assemblyResolver = context.AssemblyResolver;
                var typeResolver     = new TypeResolver {
                    Logging = _logging, AssemblyResolver = assemblyResolver
                };
                var typeLoader   = new TypeLoader(() => LoadWeavedAssembly(context, assemblyResolver));
                var aspectWeaver = new AspectWeaver {
                    Logging = _logging, TypeResolver = typeResolver, TypeLoader = typeLoader
                };
                // TODO: use blobber's resolution (WTF?)
                AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
                BlobberHelper.Setup();

                return(aspectWeaver.Weave(context.Module));
            }
            catch (Exception e)
            {
                _logging.WriteError("Internal error: {0}", e.ToString());
                for (var ie = e.InnerException; ie != null; ie = ie.InnerException)
                {
                    _logging.WriteError("Inner exception: {0}", e.ToString());
                }
            }
            return(false);
        }
Example #20
0
        public void TestSkipCall()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()))
            .Callback((Invocation <ValueTuple, ValueTuple> invoc) => invoc.SkipMethod());

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            weaver.Advice(() => throw new NotSupportedException());
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);

            Assert.ThrowsException <NotSupportedException>(() => {
                weaver.Advice(0, (int a) => throw new NotSupportedException());
            });
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <int, ValueTuple> >()), Times.Once);
        }
Example #21
0
 public void TestSignatureIntercept()
 {
     try
     {
         IAspect aspect = new AspectImpl(
             new TestInterceptor(),
             new ClassNamePointcut(".*\\+TestAspectWeavedClass") &
             new MethodNamePointcut("Hello"));
         AspectWeaver.Instance().Register(aspect);
         TestAspectWeavedClass wc = new TestAspectWeavedClass();
         Console.WriteLine("MethodSigInterceptTest Start");
         wc.Hello();
         Console.WriteLine("MethodSigInterceptTest End");
     }
     catch (Exception e)
     {
         Console.WriteLine(e.GetType().Name);
         Console.WriteLine(e.Message);
         Console.WriteLine(e.StackTrace);
         Assert.Fail();
     }
 }
Example #22
0
 public void TestInhelitAttributeIntercept()
 {
     try
     {
         IAspect aspect = new AspectImpl(
             new TestInterceptor(),
             new ClassNamePointcut(".*") &
             new MethodAttributePointcut(typeof(TestInterceptAttribute)));
         AspectWeaver.Instance().Register(aspect);
         TestAspectWeavedClass3 wc = new TestAspectWeavedClass3();
         Console.WriteLine("MethodAttrInterceptTest Start");
         wc.Hello();
         Console.WriteLine("MethodAttrInterceptTest End");
     }
     catch (Exception e)
     {
         Console.WriteLine(e.GetType().Name);
         Console.WriteLine(e.Message);
         Console.WriteLine(e.StackTrace);
         Assert.Fail();
     }
 }
Example #23
0
        public void TestNullThrownException()
        {
            var adviceMock = new Mock <IAfterAdvice>();

            adviceMock.Setup(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny))
            .Callback(new AfterThrowingCallBack((Invocation <ValueTuple, ValueTuple> _, ref Exception ex)
                                                => ex = null));

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(() => throw new NotSupportedException());
            });
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Never);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Once);

            weaver.Advice(() => { });
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Once);
        }
Example #24
0
        public void TestBeforeAdviceWithResult()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            Assert.AreEqual("called", weaver.Advice(() => "called"));

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()), Times.Once);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Never);

            Assert.AreEqual("called2", weaver.Advice("called2", arg => arg));

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, string> >()), Times.Once);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Never);

            Assert.AreEqual("called3", weaver.Advice(() => "called3"));

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()), Times.Exactly(2));
        }
Example #25
0
 public Instance(AspectWeaver aspectWeaver, AspectInstanceInfo aspectInstanceInfo)
     : base(aspectWeaver, aspectInstanceInfo)
 {
 }
 public ImplementValidableAspectTransformation( AspectWeaver aspectWeaver ) : base( aspectWeaver )
 {
 }
        /// <summary>
        /// XML設定ファイルから、DependencyInjectionコンテナを生成して
        /// コンポーネントを登録し、そのインスタンスを返す
        /// </summary>
        /// <returns>生成されたDependencyInjectionコンテナ</returns>
        /// <exception cref="System.InvalidOperationException">
        /// XML設定ファイルがスキーマに準じていない場合はこの例外を投げる
        /// </exception>
        /// <exception cref="TypeNotFoundException">
        /// 指定された名前の型がみつからなかった場合に発生する例外
        /// </exception>
        public IComponentContainer Build()
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream
                                ("Kodama.DependencyInjection.Builder.Schema.ComponentConfig.xsd");
            XmlSchemaCollection schema = new XmlSchemaCollection();

            schema.Add(null, new XmlTextReader(stream));

            XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(configPath));

            reader.ValidationType = ValidationType.Schema;
            reader.Schemas.Add(schema);

            XmlSerializer serializer = new XmlSerializer(typeof(componentConfig));

            // XML設定ファイルの読み出し
            componentConfig config = null;

            try
            {
                config = (componentConfig)serializer.Deserialize(reader);
            }
            finally
            {
                reader.Close();
            }

            // 参照アセンブリのロード
            TypeLoader loader = new TypeLoader();

            foreach (object item in config.Items)
            {
                componentConfigAssembly assembly = item as componentConfigAssembly;
                if (assembly == null)
                {
                    continue;
                }
                loader.AddAssemblyFile(assembly.name);
            }

            // コンテナの作成
            IMutableComponentContainer container = new ComponentContainerImpl();

            // 子コンテナの作成
            foreach (object item in config.Items)
            {
                componentConfigInclude include = item as componentConfigInclude;
                if (include == null)
                {
                    continue;
                }
                container.AddChild(new XmlComponentContainerBuilder(include.path).Build());
            }

            // リモートオブジェクトの登録
            foreach (object item in config.Items)
            {
                componentConfigRemotingConfig remotingConfig = item as componentConfigRemotingConfig;
                if (remotingConfig == null)
                {
                    continue;
                }
                RemotingConfiguration.Configure(remotingConfig.path);
            }

            // コンポーネントの自動登録
            foreach (object item in config.Items)
            {
                componentConfigAutoDiscovery autoDiscovery = item as componentConfigAutoDiscovery;
                if (autoDiscovery == null)
                {
                    continue;
                }
                AutoComponentContainerBuilder builder = new AutoComponentContainerBuilder();
                builder.ComponentCategory = autoDiscovery.category;
                foreach (componentConfigAutoDiscoverySearchPath searchPath in autoDiscovery.Items)
                {
                    builder.AddAssemblyFolder(searchPath.path);
                }
                container.AddChild(builder.Build());
            }

            // アスペクトの登録
            foreach (object item in config.Items)
            {
                aspectType aspect = item as aspectType;
                if (aspect == null)
                {
                    continue;
                }

                Type         interceptorType = loader.LoadType(aspect.interceptor);
                IInterceptor interceptor     = (IInterceptor)Activator.CreateInstance(interceptorType);

                ComposiblePointcut classPointcut = null;
                if (aspect.classFilterType == filterType.name)
                {
                    classPointcut = new ClassNamePointcut(aspect.classFilter);
                }
                else
                {
                    Type attributeType = loader.LoadType(aspect.classFilter);
                    classPointcut = new ClassAttributePointcut(attributeType);
                }

                ComposiblePointcut methodPointcut = null;
                if (aspect.methodFilterType == filterType.name)
                {
                    methodPointcut = new MethodNamePointcut(aspect.methodFilter);
                }
                else
                {
                    Type attributeType = loader.LoadType(aspect.methodFilter);
                    methodPointcut = new MethodAttributePointcut(attributeType);
                }

                AspectWeaver.Instance().Register
                    (new AspectImpl(interceptor, classPointcut & methodPointcut));
            }

            // コンポーネントの登録
            foreach (object item in config.Items)
            {
                componentConfigComponent component = item as componentConfigComponent;
                if (component == null)
                {
                    continue;
                }

                // コンポーネント名が設定されていない場合はクラス名がデフォルト
                if (component.name == null || component.name == "")
                {
                    component.name = component.@class;
                }

                // コンポーネントのエントリを作成する
                IComponentEntry entry         = null;
                Type            componentType = loader.LoadType(component.@class);
                switch (component.instance)
                {
                case instanceType.prototype:
                    entry = new PrototypeComponentEntry
                                (container, componentType, component.name);
                    break;

                case instanceType.singleton:
                    entry = new SingletonComponentEntry
                                (container, componentType, component.name);
                    break;

                default:
                    throw new NotSupportedException("outer instance mode is not supported.");
                }

                // コンポーネントを登録する
                if (component.primary == null || component.primary == "")
                {
                    container.Register(entry);
                }
                else
                {
                    Type primaryType = loader.LoadType(component.primary);
                    container.Register(primaryType, entry);
                }

                // アスペクトの登録
                foreach (object componentItem in component.Items)
                {
                    componentAspectType aspect = componentItem as componentAspectType;
                    if (aspect == null)
                    {
                        continue;
                    }

                    Type         interceptorType = loader.LoadType(aspect.interceptor);
                    IInterceptor interceptor     = (IInterceptor)Activator.CreateInstance(interceptorType);

                    ComposiblePointcut classPointcut = new ClassNamePointcut(component.@class);

                    ComposiblePointcut methodPointcut = null;
                    if (aspect.methodFilterType == filterType.name)
                    {
                        methodPointcut = new MethodNamePointcut(aspect.methodFilter);
                    }
                    else
                    {
                        Type attributeType = loader.LoadType(aspect.methodFilter);
                        methodPointcut = new MethodAttributePointcut(attributeType);
                    }

                    AspectWeaver.Instance().Register
                        (new AspectImpl(interceptor, classPointcut & methodPointcut));
                }

                // コンストラクタインジェクションの設定
                foreach (object componentItem in component.Items)
                {
                    injectorArgument[] arguments = componentItem as injectorArgument[];
                    if (arguments == null)
                    {
                        continue;
                    }
                    ArrayList boundArguments = new ArrayList();
                    foreach (injectorArgument argument in arguments)
                    {
                        injectorArgumentInjectionName injectionName =
                            argument.Item as injectorArgumentInjectionName;
                        if (injectionName != null)
                        {
                            boundArguments.Add(new NamedArgumentComponentProvider
                                                   (container, injectionName.name));
                        }
                        injectorArgumentInjectionType injectionTypeName =
                            argument.Item as injectorArgumentInjectionType;
                        if (injectionTypeName != null)
                        {
                            Type injectionType = loader.LoadType(injectionTypeName.@class);
                            boundArguments.Add(new TypedArgumentComponentProvider
                                                   (container, injectionType));
                        }
                        string expression = argument.Item as string;
                        if (expression != null)
                        {
                            boundArguments.Add(Evaluator.Eval(expression));
                        }
                    }
                    entry.InjectionConstructor = BindUtility.CreateBindConstructor
                                                     (entry.ComponentType, boundArguments.ToArray());
                }

                // セッターインジェクションの設定
                foreach (object componentItem in component.Items)
                {
                    componentConfigComponentMethod method =
                        componentItem as componentConfigComponentMethod;
                    if (method == null)
                    {
                        continue;
                    }
                    ArrayList boundArguments = new ArrayList();
                    boundArguments.Add(new NotBoundArgument(0));
                    foreach (injectorArgument argument in method.argument)
                    {
                        injectorArgumentInjectionName injectionName =
                            argument.Item as injectorArgumentInjectionName;
                        if (injectionName != null)
                        {
                            boundArguments.Add(new NamedArgumentComponentProvider
                                                   (container, injectionName.name));
                        }
                        injectorArgumentInjectionType injectionTypeName =
                            argument.Item as injectorArgumentInjectionType;
                        if (injectionTypeName != null)
                        {
                            Type injectionType = loader.LoadType(injectionTypeName.@class);
                            boundArguments.Add(new TypedArgumentComponentProvider
                                                   (container, injectionType));
                        }
                        string expression = argument.Item as string;
                        if (expression != null)
                        {
                            boundArguments.Add(Evaluator.Eval(expression));
                        }
                    }
                    entry.AddInjectionFanctor(BindUtility.CreateBindMember(
                                                  entry.ComponentType,
                                                  method.name,
                                                  boundArguments.ToArray()));
                }

                // 初期化メソッドの設定
                foreach (object componentItem in component.Items)
                {
                    componentConfigComponentInitialize initialize =
                        componentItem as componentConfigComponentInitialize;
                    if (initialize == null)
                    {
                        continue;
                    }
                    ArrayList boundArguments = new ArrayList();
                    boundArguments.Add(new NotBoundArgument(0));
                    foreach (initializerArgument argument in initialize.argument)
                    {
                        string expression = argument.Item as string;
                        if (expression != null)
                        {
                            boundArguments.Add(Evaluator.Eval(expression));
                        }
                    }
                    entry.AddInitializationFactor(BindUtility.CreateBindMember(
                                                      entry.ComponentType,
                                                      initialize.name,
                                                      boundArguments.ToArray()));
                }
            } // コンポーネントの登録終了

            return(container);
        }
 protected MemberIntroductionTransformation(AspectWeaver aspectWeaver)
     : base(aspectWeaver)
 {
 }
 public ImplementCloneableAspectTransformation(AspectWeaver aspectWeaver)
     : base(aspectWeaver)
 {
 }
 public OnThrowTransformation(AspectWeaver aspectWeaver)
     : base(aspectWeaver)
 {
     var module = AspectInfrastructureTask.Project.Module;
     assets = module.Cache.GetItem(() => new Assets(module));
 }
 public Instance(AspectWeaver aspectWeaver, AspectInstanceInfo aspectInstanceInfo)
     : base(aspectWeaver, aspectInstanceInfo)
 {
 }
Example #32
0
        protected override bool Process(AssemblyStitcherContext context)
        {
            BlobberHelper.Setup();

            if (AlreadyProcessed(context))
            {
                return(false);
            }

#if DEBUG
            _logging = new MultiLogging(new DefaultLogging(Logging), new FileLogging("MrAdvice.log"));
            _logging.WriteDebug("Start");
#else
            _logging = Logging;
#endif
            if (context.Module == null)
            {
                _logging.WriteError("Target assembly {0} could not be loaded", context.AssemblyPath);
                return(false);
            }

            try
            {
                try
                {
                    const string mrAdviceAssemblyName = "MrAdvice, Version=2.0.0.0, Culture=neutral, PublicKeyToken=c0e7e6eab6f293d8";
                    var          mrAdviceAssembly     = LoadEmbeddedAssembly(mrAdviceAssemblyName);
                    if (mrAdviceAssembly == null)
                    {
                        _logging.WriteError("Can't find/load embedded MrAdvice assembly (WTF?), exiting");
                        return(false);
                    }
                }
                catch (FileNotFoundException)
                {
                    _logging.WriteError("Can't load MrAdvice assembly (WTF?), exiting");
                    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        _logging.Write("Assembly in AppDomain: {0}", assembly.GetName());
                    }
                    return(false);
                }

                // instances are created here
                // please also note poor man's dependency injection (which is enough for us here)
                var assemblyResolver = context.AssemblyResolver;
                var typeResolver     = new TypeResolver(context.Module)
                {
                    Logging = _logging, AssemblyResolver = assemblyResolver
                };
                var typeLoader   = new TypeLoader(() => LoadWeavedAssembly(context, assemblyResolver));
                var aspectWeaver = new AspectWeaver {
                    Logging = _logging, TypeResolver = typeResolver, TypeLoader = typeLoader
                };

                // second chance: someone had the marker file missing
                if (aspectWeaver.FindShortcutType(context.Module) != null)
                {
                    return(false);
                }

                return(aspectWeaver.Weave(context.Module));
            }
            catch (Exception e)
            {
                _logging.WriteError("Internal error: {0}", e.ToString());
                for (var ie = e.InnerException; ie != null; ie = ie.InnerException)
                {
                    _logging.WriteError("Inner exception: {0}", e.ToString());
                }
            }
            return(false);
        }
 public Instance(AspectWeaver aspectWeaver, AspectInstanceInfo aspectInstanceInfo)
     : base(aspectWeaver, aspectInstanceInfo)
 {
     _concreteAspectWeaver = (NotifyPropertyChangedAspectWeaver) aspectWeaver;
 }