示例#1
0
 public override void Intercept(Castle.DynamicProxy.IInvocation invocation)
 {
     invocation.Proceed();
     if (invocation.ReturnValue == null)
     {
         Entity entity = invocation.InvocationTarget.CastToType <Entity>();
         if (entity.IsNotNull() || !invocation.Method.IsGetter())
         {
             var mInfo = entity.TypeDesription.Methods[invocation.Method.ToString()];
             if (mInfo != null && mInfo.RespositoryType.IsPresent())
             {
                 var repository = (IRelatedRepository)scope.Resolve(mInfo.RespositoryType.Get());
                 invocation.ReturnValue = repository.Get(entity);
                 if (mInfo.Property.SetMethod != null)
                 {
                     if (!mInfo.Property.SetMethod.Access.Setter.IsPresent())
                     {
                         throw new InvalidOperationException();
                     }
                     mInfo.Property.SetMethod.Access.Setter.Get()(entity, invocation.ReturnValue);
                 }
             }
             else
             {
                 throw new InvalidOperationException();
             }
         }
         else
         {
             throw new InvalidOperationException();
         }
     }
 }
示例#2
0
        public static IEnumerable <IPropertyInterceptor> FindPropertyInterceptors(this Castle.DynamicProxy.IInvocation invocation, DynamicProxyConfiguration proxyConfig, IServiceProvider serviceProvider)
        {
            var interceptors = new List <IPropertyInterceptor>();

            var methodName = invocation.Method.Name.Replace("set_", "").Replace("get_", "");
            var methodInfo = invocation.MethodInvocationTarget.DeclaringType.GetProperty(methodName);

            var attributes = methodInfo.GetCustomAttributes()
                             .Where(x => x.GetType().IsSubclassOf(typeof(PropertyInterceptorAttribute)))
                             .Cast <PropertyInterceptorAttribute>();

            foreach (var attribute in attributes)
            {
                var interceptorType = proxyConfig.Interceptors.FirstOrDefault(x => x.AttributeType == attribute.GetType())?.InterceptorType;

                if (interceptorType == null)
                {
                    throw new InvalidOperationException($"No suitable interceptor found for type {attribute}");
                }

                var interceptorInstance = (IPropertyInterceptor)ActivatorUtilities.CreateInstance(serviceProvider, interceptorType);

                interceptors.Add(interceptorInstance);
            }

            return(interceptors);
        }
 public InvocationComposite(IMethodInterceptor[] interceptors,
                            Castle.DynamicProxy.IInvocation innerInvocation, object[] arguments)
 {
     _interceptors    = interceptors;
     _innerInvocation = innerInvocation;
     _arguments       = arguments;
 }
        void ICastleInterceptor.Intercept(ICastleInterceptorInvocation invocation)
        {
            var instantiationData = _interceptorInstantiationDataFactory(invocation);
            var adapted           = _adaptedFactory(instantiationData);

            if (!typeof(Task).IsAssignableFrom(invocation.Method.ReturnType))
            {
                var adaptedInvocation = _invocationAdapterFactory(invocation);

                adapted.Intercept(adaptedInvocation);
            }
            else
            {
                Task adaptedContinuation = null;
                var  adaptedInvocation   = _asyncInvocationAdapterFactory(invocation);

                try
                {
                    adaptedContinuation = adapted.InterceptAsync(adaptedInvocation);
                }
                catch (Exception e)
                {
                    // NOTE: We can get here if the intercepted code throws an exception _before_ beginning an `await`
                    invocation.ReturnValue = Task.FromException(e);
                }

                if (adaptedContinuation != null)
                {
                    InterceptorTaskConnector.Connect(invocation, adaptedInvocation.ReturnValue, adaptedContinuation);
                }
            }
        }
示例#5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InvocationAdapter"/> class.
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        /// <param name="target">The target.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="invocation"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="target"/> is <c>null</c>.</exception>
        public InvocationAdapter(Castle.DynamicProxy.IInvocation invocation, object target)
        {
            Argument.IsNotNull("invocation", invocation);
            Argument.IsNotNull("target", target);

            _invocation = invocation;
            Target      = target;
        }
示例#6
0
        /// <summary>
        /// 调用拦截的方法
        /// </summary>
        /// <param name="invocation"></param>
        public void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            var invocate = new InnerInvocation(invocation);

            this.PreProceed(invocate);
            this.PerformProceed(invocate);
            this.PostProceed(invocate);
        }
示例#7
0
 public void Intercept(Castle.DynamicProxy.IInvocation invocation)
 {
     if (invocation.Arguments[0].GetType() == typeof(int))
     {
         invocation.Arguments[0] = (int)invocation.Arguments[0] + 1;
     }
     invocation.Proceed();
 }
示例#8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InvocationAdapter"/> class.
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        /// <param name="target">The target.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="invocation"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="target"/> is <c>null</c>.</exception>
        public InvocationAdapter(Castle.DynamicProxy.IInvocation invocation, object target)
        {
            Argument.IsNotNull("invocation", invocation);
            Argument.IsNotNull("target", target);

            _invocation = invocation;
            Target = target;
        }
示例#9
0
        /// <summary>
        /// Logs the join point (invocation) and supplied arguments before the join point is invoked
        /// </summary>
        /// <param name="invocation"></param>
        protected override void OnEntered(Castle.DynamicProxy.IInvocation invocation)
        {
            _invocationName      = $"{invocation.TargetType.Name}.{invocation.Method.Name}";
            _invocationArguments = string.Join(", ", invocation.Arguments.Select(arg => (arg ?? "").ToString()));

            _Logger?.LogInformation($"Call to: {_invocationName}");
            _Logger?.LogInformation($"   args: {_invocationArguments}");
        }
        /// <summary>
        /// Intercepts the specified invocation.
        /// </summary>
        /// <param name="castleInvocation">The invocation.</param>
        /// <returns>The return value of the invocation, once it is completed.</returns>
        public void Intercept(Castle.DynamicProxy.IInvocation castleInvocation)
        {
            IProxyRequest request    = CreateRequest(castleInvocation);
            IInvocation   invocation = CreateInvocation(request);

            invocation.Proceed();

            castleInvocation.ReturnValue = invocation.ReturnValue;
        }
    protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
    {
        var stringArray = (invocation.ReturnValue as string[]).Reverse().ToArray();                 // here will have the object typed as String[], so printing it should be no problem.

        foreach (var item in stringArray)
        {
            Console.WriteLine(item);
        }
        invocation.ReturnValue = stringArray; // and finally we reassign the result
    }
        private IProxyRequest CreateRequest(Castle.DynamicProxy.IInvocation castleInvocation)
        {
            var requestFactory = Context.Kernel.Components.Get <IProxyRequestFactory>();

            return(requestFactory.Create(
                       Context,
                       castleInvocation.Proxy,
                       Instance,
                       castleInvocation.GetConcreteMethod(),
                       castleInvocation.Arguments,
                       castleInvocation.GenericArguments));
        }
示例#13
0
        public override void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            base.Intercept(invocation);

            if (autoTransaction == null)
            {
                return;
            }
            autoTransaction.Commit();
            autoTransaction.Dispose();
            autoTransaction = null;
        }
        public override void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            var methodName = string.Format($"{invocation.Method.ReflectedType.FullName}.{invocation.Method.Name}");
            var arguments  = invocation.Arguments.ToList();
            var key        = $"{methodName}({string.Join(",", arguments.Select(x => x?.ToString() ?? "<Null>"))})";

            if (_cacheManager.IsAdd(key))
            {
                invocation.ReturnValue = _cacheManager.Get(key);
                return;
            }
            invocation.Proceed();
            _cacheManager.Add(key, invocation.ReturnValue, _duration);
        }
示例#15
0
 public void Intercept(IInvocation invocation) {
     if (currentElement.Value.Value != null)
         currentElement.Value.Value.Stop();
     var sw = new Stopwatch();
     var newChild = currentElement.AddChild(KV.Create(invocation.MethodInvocationTarget, sw));
     currentElement = newChild;
     sw.Start();
     try {
         invocation.Proceed();
     } finally {
         sw.Stop();
         currentElement = currentElement.Parent;
         if (currentElement.Value.Value != null)
             currentElement.Value.Value.Start();
     }
 }
        public static void Connect(ICastleInterceptorInvocation invocation, object returnValue, Task task)
        {
            var returnType = invocation.Method.ReturnType;

            if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>))
            {
                var resultType = returnType.GetGenericArguments()[0];
                var methodInfo = ConnectMethodInfo.MakeGenericMethod(resultType);
                methodInfo.Invoke(null, new object[] { invocation, returnValue, task });
            }
            else
            {
#pragma warning disable CA2008 // Do not create tasks without passing a TaskScheduler
                invocation.ReturnValue = task.ContinueWith(x => returnValue);
#pragma warning restore CA2008 // Do not create tasks without passing a TaskScheduler
            }
        }
        public void BeforeEach()
        {
            var methodInfo1 = GetType().GetMethod("Execute");
            var methodInfo2 = GetType().GetMethod("NoExecute");

            invocation1 = Mock.Of <Castle.DynamicProxy.IInvocation>();
            Mock.Get(invocation1).Setup(i => i.Method).Returns(methodInfo1);
            Mock.Get(invocation1).Setup(i => i.Proceed()).Callback(Execute);
            invocation2 = Mock.Of <Castle.DynamicProxy.IInvocation>();
            Mock.Get(invocation2).Setup(i => i.Method).Returns(methodInfo2);
            Mock.Get(invocation2).Setup(i => i.Proceed()).Callback(NoExecute);

            appSemaphoreSlim = Mock.Of <IAppSemaphoreSlim>();
            hasExecuted      = default;

            semaphoreInteractionInterceptor = new SemaphoreInteractionInterceptor(appSemaphoreSlim);
        }
示例#18
0
            public void Intercept(Castle.DynamicProxy.IInvocation invocation)
            {
                var behavoir = _Behaviors.First(b => b.IsMatch(invocation));
                var request  = behavoir.CreateHttpWebRequest(invocation.Arguments);

                var    response = new HttpResponse((System.Net.HttpWebResponse)request.GetResponse(), behavoir.ResponseEncoding);
                object result   = null;

                if (response.TryConvert(behavoir.ReturnType, out result))
                {
                    invocation.ReturnValue = result;
                }
                else
                {
                    throw new Exception("不支持此返回类型:" + behavoir.ReturnType.ToString());
                }
            }
示例#19
0
 public bool IsMatch(Castle.DynamicProxy.IInvocation invocation)
 {
     if (_MethodInfo != invocation.Method)
     {
         return(false);
     }
     if (_ParameterInfos.Length != invocation.Arguments.Length)
     {
         return(false);
     }
     for (int i = 0; i < _ParameterInfos.Length; i++)
     {
         if (!_ParameterInfos[i].IsMatch(invocation.Arguments[i]))
         {
             return(false);
         }
     }
     return(true);
 }
示例#20
0
            public void Intercept(IInvocation invocation)
            {
                if (currentElement.Value.Value != null)
                {
                    currentElement.Value.Value.Stop();
                }
                var sw       = new Stopwatch();
                var newChild = currentElement.AddChild(KV(invocation.MethodInvocationTarget, sw));

                currentElement = newChild;
                sw.Start();
                try {
                    invocation.Proceed();
                } finally {
                    sw.Stop();
                    currentElement = currentElement.Parent;
                    if (currentElement.Value.Value != null)
                    {
                        currentElement.Value.Value.Start();
                    }
                }
            }
        /// <summary>
        /// Attempts to perform argument data validation before the join point is executed.
        /// In the event of an model validation error, the join point will not be invoked and
        /// the interception will throw a ValidationException
        /// </summary>
        /// <param name="invocation">The join point or point of invocation</param>
        protected override void OnEntered(Castle.DynamicProxy.IInvocation invocation)
        {
            var isErrored = false;
            var messages  = new List <string>();

            // Setup validation for every argument
            foreach (var arg in invocation.Arguments)
            {
                var results = arg.ValidateObject(out bool isValid);
                if (!isValid)
                {
                    results.ForEach(result => messages.Add($"{result.MemberNames} -> {result.ErrorMessage}"));
                    isErrored = true;
                }
            }

            // Report out errors if they occured
            if (isErrored)
            {
                var message = string.Join(System.Environment.NewLine, messages);
                throw new ValidationException(message);
            }
        }
示例#22
0
        public void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            bool initTransaction = NHSessionManager.Instance.BeginTransaction();

            try
            {
                invocation.Proceed();

                if (invocation.ReturnValue is INHibernateProxy)
                {
                    NHSessionManager.Instance.GetSession().GetSessionImplementation().PersistenceContext.Unproxy(invocation.ReturnValue);
                }

                if (initTransaction)
                {
                    NHSessionManager.Instance.CommitTransaction();
                }
            }
            catch (ApplicationException)
            {
                if (initTransaction)
                {
                    NHSessionManager.Instance.RollbackTransaction();
                }

                throw;
            }
            catch (Exception e)
            {
                if (initTransaction)
                {
                    NHSessionManager.Instance.RollbackTransaction();
                }

                throw e;
            }
        }
示例#23
0
 public void Intercept(Castle.DynamicProxy.IInvocation invocation)
 {
     throw new NotImplementedException();
 }
 public void Intercept(Castle.DynamicProxy.IInvocation invocation)
 {
 }
示例#25
0
 public void Intercept(Castle.DynamicProxy.IInvocation invocation)
 {
     invocation.ReturnValue = -3;
     //invocation.Proceed();
 }
示例#26
0
 protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
 {
     invocation.ReturnValue = (invocation.ReturnValue as string[]).Reverse().ToArray();
 }
示例#27
0
        public void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            EntityRow entity = invocation.InvocationTarget.CastToType <EntityRow>();

            if (entity.IsNotNull() && entity.Row.IsNotNull())
            {
                string propertyName = invocation.Method.Name;
                if (propertyName.StartsWith("get_") || propertyName.StartsWith("set_"))
                {
                    propertyName = propertyName.Substring(4, propertyName.Length - 4);
                }
                if (invocation.Method.Name.StartsWith("get_"))
                {
                    KeyValuePair <string, EntityProperty> column = entity.GetDataTableColumn(propertyName);
                    if (!string.IsNullOrEmpty(column.Key))
                    {
                        if (entity.Row.Table.Columns.Contains(column.Key))
                        {
                            if (entity.Row[column.Key] != System.DBNull.Value)
                            {
                                invocation.ReturnValue = entity.Row[column.Key];
                            }
                            else
                            {
                                invocation.ReturnValue = column.Value.PropertyType.GetDefaultValue();
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    else
                    {
                        invocation.Proceed();
                    }
                }
                else if (invocation.Method.Name.StartsWith("set_") && invocation.Arguments.Count() > 0)
                {
                    KeyValuePair <string, EntityProperty> column = entity.GetDataTableColumn(propertyName);
                    if (!string.IsNullOrEmpty(column.Key))
                    {
                        if (entity.Row.Table.Columns.Contains(column.Key))
                        {
                            if (invocation.Arguments[0] != null)
                            {
                                entity.Row[column.Key] = invocation.Arguments[0];
                            }
                            else
                            {
                                entity.Row[column.Key] = System.DBNull.Value;
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    else
                    {
                        invocation.Proceed();
                    }
                }
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
示例#28
0
        /// <summary>
        /// Intercept
        /// </summary>
        /// <param name="invocation"></param>
        public virtual void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            var startTime = new System.Diagnostics.Stopwatch();

            startTime.Start();
            var meta       = this.MetaData[invocation.Method.Name];
            var methodName = meta.FullName;
            var argsObj    = invocation.Arguments;
            //var argsObjLog = new System.Collections.Generic.Dictionary<string, System.Tuple<dynamic, MetaLogger>>(argsObj.Length);
            //var argsObjLog = new System.Collections.Generic.List<argsLog>(argsObj.Length);
            //var argsObjLog = argsObj.Select(c => new argsLog { }).ToList();
            //var argsObjLogHasIArg = new System.Collections.Generic.Dictionary<string, bool>(argsObj.Length);
            var logType = LoggerType.Record;
            //==================================//
            var iArgGroup = meta.GroupDefault;
            var iArgs     = Bind.GetIArgs(meta.IArgs, argsObj, iArgGroup);

            if (0 < iArgs.Count)
            {
                var group = iArgs[meta.IArgs[0].Position].Group;
                if (!System.String.IsNullOrEmpty(group))
                {
                    iArgGroup = group;
                }
            }

            var args = meta.ArgAttrs[iArgGroup];

            //var argsObjLog = args.Args.Select(c => new argsLog {Key = c.Name, Value = c.HasIArg ? iArgs[c.Position] : argsObj[c.Position], Logger = c.MetaLogger }).ToList();

            try
            {
                foreach (var item in args.Args)
                {
                    IResult result = null;
                    var     value  = argsObj[item.Position];
                    var     iArgIn = item.HasIArg ? iArgs[item.Position].In : null;
                    //argsObjLog.Add(item.Name, System.Tuple.Create(item.HasIArg ? iArgs[item.Position] : value, item.MetaLogger));
                    //argsObjLog.Add(new argsLog { Key = item.Name, Value = item.HasIArg ? iArgs[item.Position] : value, Logger = item.MetaLogger });
                    //argsObjLogHasIArg.Add(item.Name, item.HasIArg);

                    for (int i = 0; i < item.ArgAttr.Count; i++)
                    {
                        var argAttr = item.ArgAttr[i];

                        result = argAttr.Proces(item.HasIArg ? iArgIn : value);

                        if (1 > result.State)
                        {
                            invocation.ReturnValue = Bind.GetReturnValue(result, meta); logType = LoggerType.Error; return;
                        }

                        //========================================//

                        if (result.HasData)
                        {
                            if (!item.HasIArg)
                            {
                                argsObj[item.Position] = result.Data;
                            }
                            else
                            {
                                if (i < item.ArgAttr.Count - 1)
                                {
                                    iArgIn = result.Data;
                                }
                                else
                                {
                                    iArgs[item.Position].Out = result.Data;
                                }
                            }
                        }
                    }

                    //========================================//
                    object currentValue = item.HasIArg ?
                                          ((null != result && result.HasData) ? result.Data : iArgs[item.Position].Out) :
                                          ((null != result && result.HasData) ? result.Data : value);
                    //========================================//
                    //item.HasIArg &&
                    if (null == currentValue)
                    {
                        continue;
                    }

                    var isUpdate = false;

                    result = ArgsResult(item.ArgAttrChild, args.CommandAttr.OnlyName, ref currentValue, ref isUpdate);
                    if (null != result)
                    {
                        invocation.ReturnValue = Bind.GetReturnValue(result, meta); logType = LoggerType.Error; return;
                    }

                    if (item.HasIArg && isUpdate)
                    {
                        iArgs[item.Position].Out = currentValue;
                    }
                }

                //===============================//
                startTime.Restart();
                invocation.Proceed();
            }
            catch (System.Exception ex)
            {
                invocation.ReturnValue = Bind.GetReturnValue(0, System.Convert.ToString(Utils.Help.ExceptionWrite(ex)), meta, ResultType); logType = LoggerType.Exception;
            }
            finally
            {
                startTime.Stop();
                var total = Utils.Help.Scale(startTime.Elapsed.TotalSeconds, 3);

                if (null != this.Logger)
                {
                    if (meta.HasIResult && 0 > ((IResult)invocation.ReturnValue).State)
                    {
                        logType = LoggerType.Error;
                    }

                    var argsObjLog = args.Args.Select(c => new ArgsLog {
                        name = c.Name, value = c.HasIArg ? iArgs[c.Position] : argsObj[c.Position], logger = c.MetaLogger, hasIArg = c.HasIArg
                    }).ToList();

                    var logObjs = LoggerSet(logType, meta.MetaLogger, argsObjLog, argsObjLog.ToDictionary(c => c.name, c => c.hasIArg), out bool canWrite, out bool canResult);

                    if (canWrite)
                    {
                        System.Threading.Tasks.Task.Run(() => this.Logger(new LoggerData {
                            Type = logType, Value = logObjs, Result = canResult ? invocation.ReturnValue : null, Time = total, Member = methodName, Group = args.CommandAttr.Group
                        }));
                    }
                }
            }
        }
示例#29
0
 public void Intercept(Castle.DynamicProxy.IInvocation invocation)
 {
     _memberInvocationHandler(invocation);
 }
示例#30
0
        /// <summary>
        /// Intercepts the specified invocation.
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="invocation"/> is <c>null</c>.</exception>
        public void Intercept(Castle.DynamicProxy.IInvocation invocation)
        {
            Argument.IsNotNull("invocation", invocation);

            invocation.ReturnValue = _interceptor.Intercept(new InvocationAdapter(invocation, _target));
        }
示例#31
0
 public InvocationContext(Castle.DynamicProxy.IInvocation invocation)
 {
     this.invocation = invocation;
 }
示例#32
0
 public CastleInterceptionContext(Castle.DynamicProxy.IInvocation invocation)
     : base(invocation.InvocationTarget, invocation.Method, invocation.Arguments)
 {
     this.invocation = invocation;
     this.Process    = this.ProcessInvocation;
 }
 public InnerInvocation(Castle.DynamicProxy.IInvocation invocation)
 {
     this.invocation = invocation;
 }