Esempio n. 1
0
        public void ModifyType(MutableType mutableType)
        {
            var typeAspects = _declarationProvider.GetDeclarations(mutableType).ConvertToCollection();

            typeAspects.ForEach(x => _intertypeWeaver.Import(x, new JoinPoint(mutableType)));

            foreach (var event_ in mutableType.UnderlyingSystemType.GetEvents().Where(x => x.GetAddMethod().IsVirtual))
            {
                _eventMethodPreparer.Prepare(mutableType, event_);
            }

            foreach (var method in mutableType.AllMutableMethods.ToArray())
            {
                //method.SetBody (ctx => new MethodExecutionExpression (method));
                //continue;
                // TODO: remove UnderlyingSystemMethodInfo
                var methodAspects = _declarationProvider.GetDeclarations(method.UnderlyingSystemMethodInfo).ConvertToCollection();
                var allAspects    = typeAspects.Concat(methodAspects).ConvertToCollection();

                var joinPoint  = new JoinPoint(method, new MethodExecutionExpression(method));
                var allAdvices = _adviceComposer.Compose(allAspects, joinPoint).ToList();

                if (allAdvices.Any())
                {
                    _adviceWeaver.Weave(joinPoint, allAdvices);
                }
            }
        }
Esempio n. 2
0
        public virtual bool VisitAny(AnyPointcut pointcut, JoinPoint joinPoint)
        {
            ArgumentUtility.CheckNotNull("pointcut", pointcut);
            ArgumentUtility.CheckNotNull("joinPoint", joinPoint);

            return(pointcut.Pointcuts.Any(x => x.Accept(this, joinPoint)));
        }
Esempio n. 3
0
        public bool VisitType(TypePointcut pointcut, JoinPoint joinPoint)
        {
            ArgumentUtility.CheckNotNull("pointcut", pointcut);
            ArgumentUtility.CheckNotNull("joinPoint", joinPoint);

            return(pointcut.Type.IsAssignableFrom(joinPoint.DeclaringType));
        }
Esempio n. 4
0
        public bool VisitMemberName(MemberNamePointcut pointcut, JoinPoint joinPoint)
        {
            ArgumentUtility.CheckNotNull("pointcut", pointcut);
            ArgumentUtility.CheckNotNull("joinPoint", joinPoint);

            return(joinPoint.Method == null || joinPoint.Method.Name.IsMatchWildcard(pointcut.MethodName));
        }
Esempio n. 5
0
        public bool Accept(PointcutEvaluator evalutor, JoinPoint joinPoint)
        {
            ArgumentUtility.CheckNotNull("evalutor", evalutor);
            ArgumentUtility.CheckNotNull("joinPoint", joinPoint);

            return(evalutor.VisitMethod(this, joinPoint));
        }
        public FieldInfo Create(JoinPoint joinPoint, ParameterExpression context, Expression body)
        {
            var mutableType  = joinPoint.DeclaringType;
            var method       = joinPoint.Method;
            var delegateType = typeof(Action <>).MakeGenericType(context.Type);

            var newMethod = joinPoint.DeclaringType.AddMethod(
                "<aa>" + method.Name + _counter++,
                MethodAttributes.Private,
                typeof(void),
                new[] { new ParameterDeclaration(context.Type, "context") },
                ctx => body.Replace(new Dictionary <Expression, Expression> {
                { context, ctx.Parameters.Single() }
            }));

            var field = mutableType.AddField(newMethod.Name, delegateType);

            mutableType.AddInstanceInitialization(
                ctx =>
                Expression.Assign(
                    Expression.Field(ctx.This, field),
                    new NewDelegateExpression(delegateType, ctx.This, newMethod)));

            return(field);
        }
Esempio n. 7
0
        public virtual IStorage CreateStorage(Aspect aspect, JoinPoint joinPoint)
        {
            var mutableType    = joinPoint.DeclaringType;
            var initExpression = _aspectExpressionBuilder.CreateAspectInitExpressions(aspect.Construction);

            s_counter++;
            var name = "<aa>_Aspect" + s_counter + "_" + aspect.Type.Name;

            switch (aspect.Scope)
            {
            case AspectScope.PerType:
                var staticField = mutableType.AddField(name, aspect.Type, FieldAttributes.Private | FieldAttributes.Static);
                mutableType.AddTypeInitialization(ctx => Expression.Assign(Expression.Field(null, staticField), initExpression));
                return(new StaticStorage(staticField));

            case AspectScope.PerObject:
                var instanceField = mutableType.AddField(name, aspect.Type);
                mutableType.AddInstanceInitialization(ctx => Expression.Assign(Expression.Field(ctx.This, instanceField), initExpression));
                return(new InstanceStorage(instanceField));

            case AspectScope.Singleton:
            case AspectScope.PerDeclaration:
                return(new SingletonStorage(name, aspect.Type, initExpression));

            case AspectScope.Transient:
                return(new TransientStorage(initExpression));
            }
            throw new NotImplementedException();
        }
Esempio n. 8
0
        public bool VisitMethod(MethodPointcut pointcut, JoinPoint joinPoint)
        {
            ArgumentUtility.CheckNotNull("pointcut", pointcut);
            ArgumentUtility.CheckNotNull("joinPoint", joinPoint);

            return((bool)pointcut.Method.Invoke(null, new object[0]));
        }
        public void Import(Aspect aspect, JoinPoint joinPoint)
        {
            var mutableType = joinPoint.DeclaringType;
            var storage     = _aspectStorageCache.GetOrAddStorage(aspect, joinPoint);

            foreach (var import in aspect.MemberImports)
            {
                var member = mutableType.GetMethod(import.Name);
                if (member == null)
                {
                    if (import.IsRequired)
                    {
                        throw new Exception(string.Format("Member '{0}' not found.", import.Name));
                    }
                    continue;
                }


                var import1 = import;
                var field   = Expression.Field(storage.CreateStorageExpression(joinPoint.This), import.Field);
                mutableType.AddInstanceInitialization(
                    ctx =>
                    Expression.Assign(field, new NewDelegateExpression(import1.Type, joinPoint.This, member)));
            }
            //aspect.MemberImports.Single(x => x.)
        }
Esempio n. 10
0
        public virtual bool VisitNot(NotPointcut pointcut, JoinPoint joinPoint)
        {
            ArgumentUtility.CheckNotNull("pointcut", pointcut);
            ArgumentUtility.CheckNotNull("joinPoint", joinPoint);

            return(!pointcut.Pointcut.Accept(this, joinPoint));
        }
Esempio n. 11
0
        public void TypeNamePointcut()
        {
            var joinPoint = new JoinPoint(typeof(string));

            CheckMatches(new TypeNamePointcut("String"), joinPoint);
            CheckMatchesNot(new TypeNamePointcut("int"), joinPoint);
            CheckMatches(new TypeNamePointcut("Str*"), joinPoint);
        }
        /// <summary>
        /// Gets the connector.
        /// </summary>
        /// <param name="point">The point.</param>
        /// <param name="drawer">The drawer.</param>
        /// <returns>ConnectorDefinition.</returns>
        private ConnectorDefinition getConnector(JoinPoint point, InstanceDrawer drawer)
        {
            var instance = drawer.GetInstanceDrawing(point.Instance.Component);

            var connector = instance.GetJoinPoint(point.Point);

            return(connector);
        }
Esempio n. 13
0
        public Expression CreateBlock(JoinPoint joinPoint, Expression innerExpression, ParameterExpression context, IEnumerable <WeaveTimeAdvice> advices)
        {
            var advicesAsList = advices.ConvertToCollection();

            var beforeCalls         = CreateBlock(advicesAsList, AdviceExecution.Before, context);
            var afterThrowingCalls  = CreateBlock(advicesAsList, AdviceExecution.AfterThrowing, context);
            var afterReturningCalls = CreateBlock(advicesAsList, AdviceExecution.AfterReturning, context);
            var afterCalls          = CreateBlock(advicesAsList, AdviceExecution.After, context);

            var block = innerExpression;

            if (afterReturningCalls != null)
            {
                block = Expression.Block(block, afterReturningCalls);
            }
            if (afterThrowingCalls != null && afterCalls != null)
            {
                block = Expression.TryCatchFinally(block, afterCalls, Expression.Catch(typeof(Exception), afterThrowingCalls));
            }
            else if (afterThrowingCalls != null)
            {
                block = Expression.TryCatch(block, Expression.Catch(typeof(Exception), afterThrowingCalls));
            }
            else if (afterCalls != null)
            {
                block = Expression.TryFinally(block, afterCalls);
            }
            if (beforeCalls != null)
            {
                block = Expression.Block(beforeCalls, block);
            }

            var around = advicesAsList.SingleOrDefault(x => x.Advice.Execution == AdviceExecution.Around);

            if (around != null)
            {
                var field = _trampolineMethodBuilder.Create(joinPoint, context, block);
                //var newMethodBody = block;
                //var newMethod = joinPoint.DeclaringType.AddMethod (
                //    joinPoint.Method.Name + _counter++,
                //    MethodAttributes.Private,
                //    typeof(void),
                //    new[] { new ParameterDeclaration (context.Type, "context") },
                //    ctx => newMethodBody.Replace (new Dictionary<Expression, Expression> { { context, ctx.Parameters.Single() } }));
                var invocationType   = typeof(StaticInvocation <>).MakeGenericType(context.Type);
                var invocation       = Expression.Variable(invocationType, "invocation");
                var constructor      = invocationType.GetConstructors().Single();
                var invocationCreate = Expression.New(
                    constructor,
                    context,
                    Expression.Field(joinPoint.This, field));
                var invocationAssign = Expression.Assign(invocation, invocationCreate);
                var call             = _adviceCallExpressionBuilder.CreateExpression(around, context, invocation);
                block = Expression.Block(new[] { invocation }, invocationAssign, call);
            }

            return(block);
        }
Esempio n. 14
0
 /// <summary>
 /// Initializes a new instance of of <see cref="IWeavingRecord"/>.
 /// </summary>
 /// <param name="joinPoint">Join point</param>
 /// <param name="aspectName">Name of the aspect, which is also the key of aspect which is involved in the weaving process.</param>
 /// <param name="methodFullName">Full name of the method weaved.</param>
 /// <param name="methodSignature">Signature of the method weaved.</param>
 /// <param name="sequence">Sequence of the join point.</param>
 /// <returns>The <see cref="IWeavingRecord"/> initialized.</returns>
 public static IWeavingRecord InitializeWeavingRecord(
     JoinPoint joinPoint,
     string aspectName,
     string methodFullName,
     string methodSignature,
     int sequence)
 {
     return(new WeavingRecord(joinPoint, aspectName, methodFullName, methodSignature, sequence));
 }
Esempio n. 15
0
        public void MemberNamePointcut()
        {
            var method    = ObjectMother.GetMethodInfo("Method");
            var joinPoint = new JoinPoint(method);

            CheckMatches(new MemberNamePointcut("Method"), joinPoint);
            CheckMatchesNot(new MemberNamePointcut("Field"), joinPoint);
            CheckMatches(new MemberNamePointcut("Meth*"), joinPoint);
        }
Esempio n. 16
0
        public void ArgumentTypesPointcut()
        {
            var method    = ObjectMother.GetMethodInfo(parameterTypes: new[] { typeof(int) });
            var joinPoint = new JoinPoint(method);

            CheckMatches(new ArgumentTypesPointcut(new[] { typeof(int) }), joinPoint);
            CheckMatchesNot(new ArgumentTypesPointcut(new[] { typeof(string) }), joinPoint);
            CheckMatches(new ArgumentTypesPointcut(new[] { typeof(object) }), joinPoint);
        }
Esempio n. 17
0
        public bool VisitReturnType(ReturnTypePointcut pointcut, JoinPoint joinPoint)
        {
            ArgumentUtility.CheckNotNull("pointcut", pointcut);
            ArgumentUtility.CheckNotNull("joinPoint", joinPoint);

            var method = joinPoint.Method as MethodInfo;

            return(method != null && pointcut.ReturnType.IsAssignableFrom(method.ReturnType));
        }
Esempio n. 18
0
        public void ReturnTypePointcut()
        {
            var method    = ObjectMother.GetMethodInfo(returnType: typeof(DomainType));
            var joinPoint = new JoinPoint(method);

            CheckMatches(new ReturnTypePointcut(typeof(DomainType)), joinPoint);
            CheckMatchesNot(new ReturnTypePointcut(typeof(int)), joinPoint);
            CheckMatches(new ReturnTypePointcut(typeof(DomainTypeBase)), joinPoint);
            CheckMatches(new ReturnTypePointcut(typeof(IDomainInterface)), joinPoint);
        }
Esempio n. 19
0
        private void SetupForExpressionPointcut(JoinPoint joinPoint, bool first, bool second)
        {
            var pointcutMock1 = MockRepository.GenerateStrictMock <IPointcut>();
            var pointcutMock2 = MockRepository.GenerateStrictMock <IPointcut>();
            var pointcutMocks = new[] { pointcutMock1, pointcutMock2 };

            _pointcutParserMock.Expect(x => x.GetPointcuts("test")).Return(pointcutMocks);
            pointcutMock1.Expect(x => x.Accept(_pointcutEvaluator, joinPoint)).Return(first);
            pointcutMock2.Expect(x => x.Accept(_pointcutEvaluator, joinPoint)).Return(second);
        }
        /// <summary>
        /// Gets the connector.
        /// </summary>
        /// <param name="point">The point.</param>
        /// <param name="drawer">The drawer.</param>
        /// <returns>ConnectorDefinition.</returns>
        private ConnectorDefinition getConnector(JoinPoint point, InstanceDrawer drawer)
        {
            var instance = drawer.GetInstanceDrawing(point.Instance.Component);

            var connector = instance.GetJoinPoint(point.Point);

            connector.SetProperty("Error", point.Error);
            connector.SetProperty("Warning", point.Warning);

            return(connector);
        }
        public Tuple <ParameterExpression, BinaryExpression> CreateContextExpression(JoinPoint joinPoint, IStorage memberInfo)
        {
            var contextType = _invocationTypeProvider.GetInvocationType(joinPoint.Method);
            var parameter   = Expression.Variable(contextType, "ctx");

            var constructor = contextType.GetConstructors().Single();
            var arguments   = new[] { memberInfo.CreateStorageExpression(joinPoint.This), joinPoint.This }
            .Concat(joinPoint.Parameters.Cast <Expression>());
            var create = Expression.New(constructor, arguments);
            var assign = Expression.Assign(parameter, create);

            return(Tuple.Create(parameter, assign));
        }
Esempio n. 22
0
        public void ExpressionPointcut()
        {
            var joinPoint = new JoinPoint(typeof(int));
            var pointcut  = new ExpressionPointcut("test");

            SetupForExpressionPointcut(joinPoint, true, true);
            CheckMatches(pointcut, joinPoint);

            SetupForExpressionPointcut(joinPoint, true, false);
            CheckMatchesNot(pointcut, joinPoint);

            SetupForExpressionPointcut(joinPoint, false, false);
            CheckMatchesNot(pointcut, joinPoint);
        }
Esempio n. 23
0
        /// <summary>
        /// Validate an advice method based on the join point it is to be injected to.
        /// </summary>
        /// <param name="joinPoint">Join point that the advice method to be injected to.</param>
        /// <param name="advice">Advice method to be validated.</param>
        /// <returns>Flag for parameter pattern of the advice.</returns>
        public static AdviceParameterFlag Validate(JoinPoint joinPoint, MethodInfo advice)
        {
            GeneralMethodValidation(advice);
            switch (joinPoint)
            {
            case JoinPoint.Entry:
                return(ValidateParameters(advice, EntryValidParameterFlag));

            case JoinPoint.Exception:
                return(ValidateParameters(advice, ExceptionValidParameterFlag));

            case JoinPoint.Exit:
                return(ValidateParameters(advice, ExitValidParameterFlag));
            }

            throw new ArgumentException($"Unsupported join point type {joinPoint}", "joinPoint");
        }
Esempio n. 24
0
        public void PropertyPointcut()
        {
            var setPointcut          = new PropertySetPointcut();
            var getPointcut          = new PropertyGetPointcut();
            var setJoinPoint         = new JoinPoint(typeof(DomainType).GetMethod("set_Property"));
            var getJoinPoint         = new JoinPoint(typeof(DomainType).GetMethod("get_Property"));
            var methodJoinPoint      = new JoinPoint(ObjectMother.GetMethodInfo());
            var constructorJoinPoint = new JoinPoint(ObjectMother.GetConstructorInfo());

            CheckMatches(setPointcut, setJoinPoint);
            CheckMatches(getPointcut, getJoinPoint);
            CheckMatchesNot(setPointcut, getJoinPoint);
            CheckMatchesNot(getPointcut, setJoinPoint);
            CheckMatchesNot(setPointcut, methodJoinPoint);
            CheckMatchesNot(getPointcut, methodJoinPoint);
            CheckMatchesNot(setPointcut, constructorJoinPoint);
            CheckMatchesNot(getPointcut, constructorJoinPoint);
        }
Esempio n. 25
0
        public virtual object CreateCacheKey(Aspect aspect, JoinPoint joinPoint)
        {
            switch (aspect.Scope)
            {
            case AspectScope.Singleton:
                return(aspect.Type);

            case AspectScope.PerDeclaration:
                return(aspect);

            case AspectScope.PerObject:
            case AspectScope.PerType:
                return(joinPoint.DeclaringType);

            case AspectScope.Transient:
                return(null);

            default:
                throw new Exception(string.Format("Storage not implemented for {0}", aspect.Scope));
            }
        }
Esempio n. 26
0
        public void Weave(JoinPoint joinPoint, IEnumerable <Advice> advices)
        {
            ArgumentUtility.CheckNotNull("advices", advices);

            var mutableMethod = joinPoint.Method;

            mutableMethod.SetBody(
                ctx =>
            {
                var memberInfo       = _contextArgumentStorageProvider.AddMemberInfo(mutableMethod);
                var weaveTimeAdvices = advices
                                       .Reverse()
                                       .Select(x => new WeaveTimeAdvice(x, _aspectStorageCache.GetOrAddStorage(x.Aspect, joinPoint).CreateStorageExpression(ctx.This)))
                                       .ConvertToCollection();

                var contextTuple  = _joinPointExpressionBuilder.CreateContextExpression(joinPoint, memberInfo);
                var context       = contextTuple.Item1;
                var contextAssign = contextTuple.Item2;

                var innerExpression = _joinPointExpressionBuilder.CreateCallExpression(joinPoint, context);

                while (weaveTimeAdvices.Any())
                {
                    var nextBlocksAdvices   = weaveTimeAdvices.SkipWhile(x => x.Advice.Execution != AdviceExecution.Around).Skip(1);
                    var currentBlockAdvices = weaveTimeAdvices.Except(nextBlocksAdvices).Reverse();
                    weaveTimeAdvices        = nextBlocksAdvices.ToList();

                    innerExpression = _weaveBlockBuilder.CreateBlock(joinPoint, innerExpression, context, currentBlockAdvices);
                }

                var returnValue = _joinPointExpressionBuilder.CreateReturnExpression(joinPoint, context);

                var blockExpression = Expression.Block(
                    new[] { context },
                    contextAssign,
                    innerExpression,
                    returnValue);
                return(blockExpression);
            });
        }
Esempio n. 27
0
        public IStorage GetOrAddStorage(Aspect aspect, JoinPoint joinPoint)
        {
            ArgumentUtility.CheckNotNull("aspect", aspect);
            ArgumentUtility.CheckNotNull("joinPoint", joinPoint);

            var cacheKey = _aspectCacheKeyProvider.CreateCacheKey(aspect, joinPoint);

            if (cacheKey == null)
            {
                return(_aspectStorageBuilder.CreateStorage(aspect, joinPoint));
            }

            IStorage storage;

            if (!_storageDictionary.TryGetValue(cacheKey, out storage))
            {
                storage = _aspectStorageBuilder.CreateStorage(aspect, joinPoint);
                _storageDictionary.Add(cacheKey, storage);
            }

            return(storage);
        }
        public Expression CreateCallExpression(JoinPoint joinPoint, ParameterExpression context)
        {
            var arguments = joinPoint.Method.GetParameters().Select((x, i) => _valueMapper.GetIndexMapping(context, i));
            var call      = joinPoint.Method.Body;

            if (call is OriginalBodyExpression)
            {
                call = Expression.Call(joinPoint.This, new NonVirtualCallMethodInfoAdapter(joinPoint.Method.UnderlyingSystemMethodInfo), arguments);
            }
            else
            {
                call = BodyContextUtility.ReplaceParameters(joinPoint.Method.ParameterExpressions, call, arguments);
            }
            //call = call.

            if (joinPoint.Method.ReturnType != typeof(void))
            {
                var returnValue = _valueMapper.GetReturnMapping(context);
                call = Expression.Assign(returnValue, call);
            }

            return(call);
        }
Esempio n. 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WeavingRecord"/> class.
        /// </summary>
        /// <param name="joinPoint">Join point.</param>
        /// <param name="aspectName">Name of the aspect, also serves as key of the aspect.</param>
        /// <param name="methodFullName">Full name of the method weaved.</param>
        /// <param name="methodSignature">Signature of the method weaved.</param>
        /// <param name="sequence">Sequence of the join point.</param>
        internal WeavingRecord(JoinPoint joinPoint, string aspectName, string methodFullName, string methodSignature, int sequence)
        {
#if DEBUG
            if (string.IsNullOrWhiteSpace(aspectName))
            {
                throw new ArgumentNullException("aspectName");
            }

            if (string.IsNullOrWhiteSpace(methodFullName))
            {
                throw new ArgumentNullException("methodFullName");
            }

            if (string.IsNullOrWhiteSpace(methodSignature))
            {
                throw new ArgumentNullException("methodSignature");
            }
#endif
            JoinPoint       = joinPoint;
            AAspectName     = aspectName;
            MethodFullName  = methodFullName;
            MethodSignature = methodSignature;
            Sequence        = sequence;
        }
Esempio n. 30
0
 public bool VisitArgumentName(ArgumentNamePointcut pointcut, JoinPoint joinPoint)
 {
     return(joinPoint.Method.GetParameters()
            .Any(x => x.ParameterType.IsAssignableFrom(pointcut.ArgumentType) && x.Name.IsMatchWildcard(pointcut.Name)));
 }