public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var stopwatch = new Stopwatch();

            var logger = LogManager.GetLogger(input.MethodBase.ReflectedType);

            var declaringType = input.MethodBase.DeclaringType;
            var className = declaringType != null ? declaringType.Name : string.Empty;
            var methodName = input.MethodBase.Name;
            var generic = declaringType != null && declaringType.IsGenericType
                              ? string.Format("<{0}>", string.Join<Type>(", ", declaringType.GetGenericArguments()))
                              : string.Empty;

            var argumentWriter = new List<string>();
            for (var i = 0; i < input.Arguments.Count; i++)
            {
                var argument = input.Arguments[i];
                var argumentInfo = input.Arguments.GetParameterInfo(i);
                argumentWriter.Add(argumentInfo.Name);
            }
            var methodCall = string.Format("{0}{1}.{2}\n{3}", className, generic, methodName, string.Join(",", argumentWriter));

            logger.InfoFormat(@"Entering {0}", methodCall);

            stopwatch.Start();
            var returnMessage = getNext()(input, getNext);
            stopwatch.Stop();

            logger.InfoFormat(@"Exited {0} after {1}ms", methodName, stopwatch.ElapsedMilliseconds);

            return returnMessage;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            /* Call the method that was intercepted */
            string className = input.MethodBase.DeclaringType.Name;
            string methodName = input.MethodBase.Name;
            string generic = input.MethodBase.DeclaringType.IsGenericType ? string.Format("<{0}>", input.MethodBase.DeclaringType.GetGenericArguments().ToStringList()) : string.Empty;
            string arguments = input.Arguments.ToStringList();

            string preMethodMessage = string.Format("{0}{1}.{2}({3})", className, generic, methodName, arguments);
            this.log.Debug("PreMethodCalling: " + preMethodMessage);
            //Logging
            this.log.Debug(preMethodMessage);
            //Invoke method
            IMethodReturn msg = null;
        
            msg = getNext()(input, getNext);
            //loggin exception
            if (msg.Exception != null)
            {
                this.log.Error(msg.Exception);
            }

            //Post method calling
            string postMethodMessage = string.Format("{0}{1}.{2}() -> {3}", className, generic, methodName, msg.ReturnValue);
            this.log.Debug("PostMethodCalling: " + postMethodMessage);
            //Logging
            this.log.Debug(postMethodMessage);
            return msg;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (!Thread.CurrentPrincipal.IsInRole("ADMIN"))
                throw new SecurityException("Access Denied");

            return getNext()(input, getNext);
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            this.log.Debug("Before call to: {0}.{1}, parameters: {2}",
                    input.Target,
                    input.MethodBase.Name,
                    this.GetParameters(input));

            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                this.log.Error("Exception while calling: {0}, parameters: {1}, ex: {2}",
                    input.MethodBase.Name,
                    this.GetParameters(input),
                    result.Exception);
            }
            else
            {
                this.log.Debug("Call finished: {0}, parameters: {1}, result: {2}",
                    input.MethodBase.Name,
                    this.GetParameters(input),
                    result.ReturnValue);
            }

            return result;
        }
    public IMethodReturn Invoke(IMethodInvocation input,
      GetNextInterceptionBehaviorDelegate getNext)
    {
      // Before invoking the method on the original target.
      WriteLog(String.Format(
        "Invoking method {0} at {1}",
        input.MethodBase, DateTime.Now.ToLongTimeString()));

      // Invoke the next behavior in the chain.
      var result = getNext()(input, getNext);

      // After invoking the method on the original target.
      if (result.Exception != null)
      {
        WriteLog(String.Format(
          "Method {0} threw exception {1} at {2}",
          input.MethodBase, result.Exception.Message,
          DateTime.Now.ToLongTimeString()));
      }
      else
      {
        WriteLog(String.Format(
          "Method {0} returned {1} at {2}",
          input.MethodBase, result.ReturnValue,
          DateTime.Now.ToLongTimeString()));
      }

      return result;
    }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var methodReturn = InvokeINotifyPropertyChangedMethod(input);

            if (methodReturn != null)
            {
                return methodReturn;
            }

            methodReturn = getNext()(input, getNext);

            if (methodReturn.Exception == null && input.MethodBase.IsSpecialName)
            {
                var property = GetPropertyInfoForSetMethod(input);

                if (property != null)
                {
                    var currentHandler = this.handler;
                    if (currentHandler != null)
                    {
                        try
                        {
                            currentHandler(input.Target, new PropertyChangedEventArgs(property.Name));
                        }
                        catch (Exception e)
                        {
                            return input.CreateExceptionMethodReturn(e);
                        }
                    }
                }
            }

            return methodReturn;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var className = input.Target.ToString().Split('.').Last();
            var methodName = input.MethodBase.Name;

            // Before invoking the method on the original target.
            _log.Debug("{className}: {function} started.", className, methodName);
            var timer = new Stopwatch();
            timer.Start();

            // Invoke the next behavior in the chain.
            var result = getNext()(input, getNext);

            timer.Stop();

            // After invoking the method on the original target.
            if (result.Exception != null)
            {
                _log.Warning("--- {className}: {function} threw exception {exception}.", className, methodName, result.Exception);
            }
            else
            {
                _log.Debug("--- {className}: {function} returned {returnValue}.", className, methodName, result);
            }
            _log.Information("--- {className}: {function} executed in {executionTime} (in Milliseconds).", className, methodName, timer.Elapsed.TotalMilliseconds);
            return result;
        }
 /// <summary>
 /// Implement this method to execute your behavior processing.
 /// </summary>
 /// <param name="input">Inputs to the current call to the target.</param>
 /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
 /// <returns>Return value from the target.</returns>
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     if (input.MethodBase == DoNothingMethod)
     {
         return ExecuteDoNothing(input);
     }
     return getNext()(input, getNext);
 }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (!this.IsValidUser())
            {
                return input.CreateExceptionMethodReturn(new UnauthorizedAccessException("..."));
            }

            return getNext()(input, getNext);
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            //检查参数是否存在
            if (input == null)
                throw new ArgumentNullException("input");
            if (getNext == null)
                throw new ArgumentNullException("getNext");

            IMethodReturn methodReturn = null;

            if (this.IsIntercption(input))
            {
                Debug.WriteLine("开始准备拦截调用");
                this.BeforeInvoke(input);

                Debug.WriteLine("开始执行调用");
                methodReturn = this.ExcuteInvoke(input, getNext);

                Debug.WriteLine("完成方法执行后调用");
                this.AfterInvoke(input);

                #region 组装-拦截消息IntercptionMessage
                //IntercptionMessage message = new IntercptionMessage();
                //message.Method = input.MethodBase as System.Reflection.MethodInfo;

                //message.RealClassType = input.Target.GetType();
                //System.Reflection.ParameterInfo[] parameterInfos = input.MethodBase.GetParameters();

                //if (parameterInfos != null)
                //{
                //    message.Parameters = new Dictionary<int, object>();

                //    int i = 0;
                //    foreach (var parameterInfo in parameterInfos)
                //    {
                //        i++;
                //        message.Parameters.Add(i, input.Arguments[parameterInfo.Name]);
                //    }
                //}

                //requestID = Guid.NewGuid().ToString();

                ////添加请求标识
                //message.Parameters.Add(message.Parameters.Count + 1, requestID);
                //message.Parameters.Add(message.Parameters.Count + 1, message.Method.ReturnType.FullName);
                #endregion

                //methodReturn= input.CreateMethodReturn(methodCallResult);
            }
            else
            {
                methodReturn= getNext()(input, getNext);
            }
            return methodReturn;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            this.LoggerService.LogVerbose(string.Format("Start method: {0} with params {1}", input.MethodBase.ToString(), string.Empty));
            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                this.LoggerService.LogVerbose(result.Exception.ToString());
            }

            return(result);
        }
Exemple #12
0
        public IMethodReturn Invoke(IMethodInvocation invocation,
                                    GetNextInterceptionBehaviorDelegate getNext)
        {
            var attr = GetAttribute(invocation);

            if (attr == null)
            {
                return(getNext()(invocation, getNext));
            }

            return(Invoke(() => getNext()(invocation, getNext), attr));
        }
Exemple #13
0
        //一切正常的  刷个1
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("LogAfterBehavior");
            foreach (var item in input.Inputs)
            {
                Console.WriteLine(item.ToString());//反射获取更多信息
            }
            IMethodReturn methodReturn = getNext()(input, getNext);

            Console.WriteLine("LogAfterBehavior" + methodReturn.ReturnValue);
            return(methodReturn);
        }
Exemple #14
0
            public IMethodReturn Invoke(IMethodInvocation input,
                                        GetNextInterceptionBehaviorDelegate getNext)
            {
                IMethodReturn result;

                if (ApplicationDbContext.applicationDbContext == null)
                {
                    using (var context = new ApplicationDbContext())
                    {
                        ApplicationDbContext.applicationDbContext = context;
                        using (var dbContextTransaction = context.Database.BeginTransaction())
                        {
                            try
                            {
                                result = getNext()(input, getNext);


                                if (result.Exception != null)
                                {
                                    throw result.Exception;
                                }
                                context.SaveChanges();

                                dbContextTransaction.Commit();
                            }
                            catch (NoEncontradoException e)
                            {
                                dbContextTransaction.Rollback();
                                ApplicationDbContext.applicationDbContext = null;
                                throw e;
                            }
                            catch (Exception e)
                            {
                                dbContextTransaction.Rollback();
                                ApplicationDbContext.applicationDbContext = null;
                                throw new Exception("He hecho rollback de la transaccion", e);
                            }
                        }
                    }
                    ApplicationDbContext.applicationDbContext = null;
                }
                else
                {
                    result = getNext()(input, getNext);


                    if (result.Exception != null)
                    {
                        throw result.Exception;
                    }
                }
                return(result);
            }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            this.LoggerService.LogVerbose(string.Format("Start method: {0} with params {1}", input.MethodBase.ToString(), string.Empty));
            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                this.LoggerService.LogVerbose(result.Exception.ToString());
            }

            return result;
        }
        private IMethodReturn InterceptPropertySet(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var propertyName = input.MethodBase.Name.Substring(4);

            var returnValue = getNext()(input, getNext);

            var subscribers = propertyChanged;

            subscribers?.Invoke(input.Target, new PropertyChangedEventArgs(propertyName));

            return(returnValue);
        }
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     var result = getNext()(input, getNext);
     var mi = input.MethodBase as MethodInfo;
     if ((mi != null)
         && (typeof(IEnumerable<ProductViewModel>).IsAssignableFrom(mi.ReturnType))
         && (result.ReturnValue == null))
     {
         result.ReturnValue = Enumerable.Empty<ProductViewModel>();
     }
     return result;
 }
Exemple #18
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     Console.WriteLine("LogBeforeBehavior");
     Console.WriteLine(input.MethodBase.Name);
     foreach (var item in input.Inputs)
     {
         Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
         //TODO: get more info by reflection and serialization
     }
     //return getNext().Invoke(input, getNext);//
     return(getNext()(input, getNext)); // Equal to the line above
 }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                eventAggregator.GetEvent<SettingsExceptionEvent>().Publish(result.Exception);
                logger.Log(result.Exception.ToString(), Category.Exception, Priority.None);
                result.Exception = null;
            }
            return result;
        }
Exemple #20
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn methodReturn = getNext()(input, getNext);

            Console.WriteLine($"{input.MethodBase.Name} LogAfterBehavior..Start.");
            //foreach (var item in input.Inputs)
            //{
            //    Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
            //}
            Console.WriteLine($"{input.MethodBase.Name} LogAfterBehavior..  End.");
            return(methodReturn);
        }
 public virtual IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     using (TraceLog4Net trace = new TraceLog4Net(GetType(), input.Target.GetType(), input.MethodBase.Name))
     {
         GuardarLogActividad(input);
         var result = getNext()(input, getNext);
         if (result.Exception != null)
         {
             InterceptExceptions(result, input);
         }
         return(result);
     }
 }
Exemple #22
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn result = null;

            if (input.MethodBase.Name == "Empty")
            {
                Console.WriteLine($"(VirtualLog)呼叫這個方法之前:{input.MethodBase.DeclaringType.Name}.{input.MethodBase.Name}");
                result = getNext()(input, getNext);
                Console.WriteLine($"(VirtualLog)呼叫這個方法之後:{input.MethodBase.DeclaringType.Name}{input.MethodBase.Name}");
                return(result);
            }
            return(getNext()(input, getNext));
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var result = getNext()(input, getNext);
            var mi     = input.MethodBase as MethodInfo;

            if ((mi != null) &&
                (typeof(IEnumerable <ProductViewModel>).IsAssignableFrom(mi.ReturnType)) &&
                (result.ReturnValue == null))
            {
                result.ReturnValue = Enumerable.Empty <ProductViewModel>();
            }
            return(result);
        }
Exemple #24
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase.Name == "DoNothing")
            {
                return input.CreateMethodReturn(100);
            }
            if (input.MethodBase.Name == "DoNothing1")
            {
                return input.CreateMethodReturn(200);
            }

            return getNext()(input, getNext);
        }
Exemple #25
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn result = null;

            if (input.MethodBase.Name == "Write")
            {
                Console.WriteLine($"(AppLog) Before:{input.MethodBase.DeclaringType.Name}.{input.MethodBase.Name}");
                result = getNext()(input, getNext);
                Console.WriteLine($"(AppLog) After:{input.MethodBase.DeclaringType.Name}{input.MethodBase.Name}");
                return(result);
            }
            return(getNext()(input, getNext));
        }
Exemple #26
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 呼叫方法之前
            Console.WriteLine("正要執行方法:" + input.MethodBase.Name);

            // 呼叫方法
            var result = getNext()(input, getNext);

            // 呼叫方法之後
            Console.WriteLine("方法執行完畢於:" + DateTime.Now.ToString());

            return result;
        }
Exemple #27
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     Console.WriteLine("检查当前用户的权限");
     if (true)
     {
         Console.WriteLine("经检查当前用户拥有权限操作");
         return(getNext()(input, getNext));//执行后面的全部动作
     }
     else
     {
         return(input.CreateExceptionMethodReturn(new Exception("没有权限")));
     }
 }
Exemple #28
0
 /// <summary>
 /// Implement this method to execute your behavior processing.
 /// </summary>
 /// <param name="input">Inputs to the current call to the target.</param>
 /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
 /// <returns>Return value from the target.</returns>
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     if (_IAdditionalInterfaces.Exists(q => q == input.MethodBase.DeclaringType))
     {
         object[] __args = new object[input.Arguments.Count];
         input.Arguments.CopyTo(__args, 0);
         var __result = _action(input.MethodBase, input.Target, __args);
         return(input.CreateMethodReturn(__result.Item1, __result.Item2));
         //var __result = input.MethodBase.Invoke(input.Target, __args);
         //return input.CreateMethodReturn(__result);
     }
     return(getNext()(input, getNext));
 }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase.Name == "DoNothing")
            {
                return(input.CreateMethodReturn(100));
            }
            if (input.MethodBase.Name == "DoNothing1")
            {
                return(input.CreateMethodReturn(200));
            }

            return(getNext()(input, getNext));
        }
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     Console.WriteLine("Check the authorization of the user role ");
     if (true)
     {
         Console.WriteLine("The user pass the authorization check");
         return(getNext()(input, getNext));
     }
     else
     {
         return(input.CreateExceptionMethodReturn(new Exception("Authorization check failed.")));
     }
 }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 呼叫方法之前
            Console.WriteLine("正要執行方法:" + input.MethodBase.Name);

            // 呼叫方法
            var result = getNext()(input, getNext);

            // 呼叫方法之後
            Console.WriteLine("方法執行完畢於:" + DateTime.Now.ToString());

            return(result);
        }
Exemple #32
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 呼叫方法之前
            Console.WriteLine("2 before");

            // 呼叫目標方法(被攔截的方法)
            var result = getNext()(input, getNext);

            // 呼叫方法之後
            Console.WriteLine("2 after");

            return(result);
        }
Exemple #33
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            using (ProfilingSession.Current.Step($"[{this.GetType().Name}] {input.Target} - {input.MethodBase.Name}"))
            {
                Debug.WriteLine($"[{this.GetType().Name}] {input.Target} - {input.MethodBase.Name} 執行前");

                var result = getNext()(input, getNext);

                Debug.WriteLine($"[{this.GetType().Name}] {input.Target} - {input.MethodBase.Name} 執行後");

                return(result);
            }
        }
Exemple #34
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn methodReturn = getNext()(input, getNext);//执行后面的全部动作

            Console.WriteLine("LogAfterBehavior2");
            //Console.WriteLine(input.MethodBase.Name);
            //foreach (var item in input.Inputs)
            //{
            //    Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item));
            //}
            //Console.WriteLine("LogAfterBehavior" + methodReturn.ReturnValue);
            return(methodReturn);
        }
Exemple #35
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 呼叫方法之前
            Console.WriteLine("正要執行此方法:{0}", input.MethodBase.Name);

            // 呼叫目標方法(被攔截的方法)
            var result = getNext()(input, getNext);

            // 呼叫方法之後
            Console.WriteLine("正要離開此方法:{0},時間:{1}", input.MethodBase.Name, DateTime.Now.ToString());

            return(result);
        }
Exemple #36
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if ((HouseVisiter)input.Inputs[0] != HouseVisiter.Owner && input.MethodBase.Name.Equals("OpenTheDoor"))
            {
                Console.WriteLine("Illegal invasion");
            }

            if ((HouseVisiter)input.Inputs[0] == HouseVisiter.Owner && input.MethodBase.Name.Equals("BurnTheHouse"))
            {
                Console.WriteLine("The Houser-owner is crazy!");
            }
            return(getNext()(input, getNext));
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                var request = (HttpRequestMessage)input.Inputs[1];
                result.ReturnValue = request.CreateErrorResponse(HttpStatusCode.BadRequest, result.Exception.Message);
                result.Exception   = null;
            }

            return(result);
        }
Exemple #38
0
        /// <summary>
        /// virtualなメソッドの呼び出しをラップする
        /// </summary>
        /// <param name="input"></param>
        /// <param name="getNext"></param>
        /// <returns></returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            ILog log = LogManager.GetLogger(input.MethodBase.DeclaringType);

            log.Info($"# -> {input.MethodBase.Name}({string.Join(", ", input.Arguments.Cast<object>())})");

            // この行でvirtualなメソッドが呼び出され、戻り値が返却される
            var result = getNext()(input, getNext);

            log.Info($"# <- {input.MethodBase.Name}, result: {result.ReturnValue}");

            return(result);
        }
Exemple #39
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 呼叫方法之前
            Console.WriteLine("2 before");

            // 呼叫目標方法(被攔截的方法)
            var result = getNext()(input, getNext);

            // 呼叫方法之後
            Console.WriteLine("2 after");

            return result;
        }
Exemple #40
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 呼叫方法之前
            Console.WriteLine("正要執行此方法:{0}", input.MethodBase.Name);

            // 呼叫目標方法(被攔截的方法)
            var result = getNext()(input, getNext);

            // 呼叫方法之後
            Console.WriteLine("正要離開此方法:{0},時間:{1}", input.MethodBase.Name, DateTime.Now.ToString());

            return result;
        }
Exemple #41
0
        /// <summary>
        /// Implement this method to execute your behavior processing.
        /// </summary>
        /// <param name="input">Inputs to the current call to the target.</param>
        /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
        /// <returns>
        /// Return value from the target.
        /// </returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var result = getNext()(input, getNext);
            var logger = ServiceLocator.Current.GetInstance <ILogger>();

            // Log exception if any thrown
            if (result.Exception != null)
            {
                logger.LogException(result.Exception);
            }

            return(result);
        }
        public IMethodReturn Invoke(IMethodInvocation input,
          GetNextInterceptionBehaviorDelegate getNext)
        {
            // Invoke the next behavior in the chain.
            var result = getNext()(input, getNext);

            // After invoking the method on the original target.
            if (result.Exception != null)
            {
                Debug.Log( result.Exception.Message );
            }

            return result;
        }
        public IMethodReturn Invoke( IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext )
        {
            for ( var i = 0; i < input.Arguments.Count; i++ )
             {
            ParameterInfo parameterInfo = input.Arguments.GetParameterInfo( i );
            var doubleBoundsAttribute = parameterInfo.GetCustomAttribute<ValidateValueAttribute>();
            if ( doubleBoundsAttribute != null )
            {
               doubleBoundsAttribute.Validate( input.Inputs[i], parameterInfo.Name );
            }
             }

             return getNext()( input, getNext );
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            for (var i = 0; i < input.Arguments.Count; i++)
            {
                ParameterInfo parameterInfo         = input.Arguments.GetParameterInfo(i);
                var           doubleBoundsAttribute = parameterInfo.GetCustomAttribute <ValidateValueAttribute>();
                if (doubleBoundsAttribute != null)
                {
                    doubleBoundsAttribute.Validate(input.Inputs[i], parameterInfo.Name);
                }
            }

            return(getNext()(input, getNext));
        }
 public IMethodReturn Invoke(
     IMethodInvocation input,
     GetNextInterceptionBehaviorDelegate getNext)
 {
     var result = getNext()(input, getNext);
     if (result.Exception is CommunicationException
         || result.Exception is
             InvalidOperationException)
     {
         this.AlertUser(result.Exception.Message);
         return input.CreateMethodReturn(null);
     }
     return result;
 }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase.Name == "TargetMethod" || input.MethodBase.Name == "SecondTargetMethod" || input.MethodBase.Name == "ThirdTargetMethod")
            {
                PreCalled       = "CalledC";
                input.Inputs[0] = (string)input.Inputs[0] + "PreC";
                IMethodReturn returnValue = getNext()(input, getNext);
                input.Inputs[0] = (string)input.Inputs[0] + "PostC";

                PostCalled = "CalledC";
                return(returnValue);
            }
            return(getNext()(input, getNext));
        }
        /// <summary>
        /// 通过实现此方法来拦截调用并执行所需的拦截行为。
        /// </summary>
        /// <param name="input">调用拦截目标时的输入信息。</param>
        /// <param name="getNext">通过行为链来获取下一个拦截行为的委托。</param>
        /// <returns>从拦截目标获得的返回信息。</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn retvalue = getNext()(input, getNext);

            if (retvalue.Exception != null)
            {
                //记录异常的内容 比如Log4Net等
                KM.Common.LogHelper.WriteError(retvalue.Exception.ToString());
#if !DEBUG
                retvalue.Exception = null;
#endif
            }
            return(retvalue);
        }
Exemple #48
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (_logger.IsLoggingEnabled)
            {
                ICollection <LogCategory> logCategories = LogCategoryHelper.GetCategoriesAttribute(input.MethodBase.DeclaringType);
                string messageLog = string.Format("Invoking method {0} with this params {1}", input.MethodBase,
                                                  input.Arguments.ToString());
                _logger.WriteDebug(new LogMessage(messageLog), logCategories);
            }

            var result = getNext()(input, getNext);

            return(result);
        }
Exemple #49
0
        /// <summary>
        /// Implement this method to execute your behavior processing.
        /// </summary>
        /// <param name="input">Inputs to the current call to the target.</param>
        /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
        /// <returns>
        /// Return value from the target.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase.Name == "get_ChangeLog" && input.MethodBase.DeclaringType == typeof(IUnitOfWork))
            {
                return(input.CreateMethodReturn(ChangeLog.Values));
            }

            if (input.MethodBase.Name == "set_ChangeLog" && input.MethodBase.DeclaringType == typeof(IUnitOfWork))
            {
                IEnumerable <UnitOfWorkItem> items = input.Arguments[0] as IEnumerable <UnitOfWorkItem>;
                ChangeLog.Clear();
                if (items != null)
                {
                    foreach (UnitOfWorkItem item in items)
                    {
                        ChangeLog.Add(item.PropertyName, item);
                    }
                }
                return(input.CreateMethodReturn(null));
            }

            IBaseEntity entity = (IBaseEntity)input.Target;

            //Eine Statusänderung interessiert nur wenn das Objekt ungeändert oder verändert ist
            if (entity.State == Common.Constants.Constants.EntityState.Unchanged || entity.State == Common.Constants.Constants.EntityState.Modified)
            {
                if (IsRelevantProperty(input))
                {
                    var propertyName = input.MethodBase.Name.Substring(4);

                    object[] propertyIndex = input
                                             .Arguments.Cast <object>()
                                             .Where((a, index) => index < input.Arguments.Count - 1)
                                             .ToArray();

                    object oldValue = input.Target.GetType().GetProperty(propertyName).GetValue(input.Target, propertyIndex);

                    object newValue = input.Arguments[input.Arguments.Count - 1];

                    if (oldValue != newValue)
                    {
                        input.Target.GetType().GetProperty("State").SetValue(input.Target, Common.Constants.Constants.EntityState.Modified);
                        AddToChangeLog(input, propertyName, entity);
                    }
                }
            }

            return(getNext()(input, getNext));
        }
Exemple #50
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            String className  = input.MethodBase.DeclaringType.FullName;
            String methodName = input.MethodBase.Name;
            var    attrs      = input.MethodBase.GetCustomAttributes(false);

            if (attrs == null)
            {
                return(getNext()(input, getNext));
            }
            foreach (var item in attrs)
            {
                if (!(item is CacheAttribute))
                {
                    continue;
                }
                else
                {
                    CacheAttribute attr     = item as CacheAttribute;
                    String         keyParam = GetKeyParam(attr.CacheMethod, input.Inputs);
                    switch (attr.CacheMethod)
                    {
                    case CacheMethod.GetCollection:
                        var retValue = _cache.Get(attr.Key, methodName + "-" + keyParam);
                        if (retValue == null)
                        {
                            var getValue = getNext()(input, getNext);
                            _cache.Add(attr.Key, methodName + "-" + keyParam, getValue);
                            return(getValue);
                        }
                        else
                        {
                            //var args = new object[input.Arguments.Count];
                            //input.Arguments.CopyTo(args, 0);
                            //return new VirtualMethodReturn(input, retValue, args);
                            return((IMethodReturn)retValue);
                        }

                    case CacheMethod.RemoveCollection:
                        _cache.Remove(attr.Key);
                        break;

                    default: break;
                    }
                    break;
                }
            }
            return(getNext()(input, getNext));
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            _logger.Log(string.Format("Interceptor->Before running {0}", BuildMethodSignature(input)));
            var result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                _logger.Error(result.Exception);
            }
            else
            {
                _logger.Log(string.Format("Interceptor->After running {0}", BuildMethodSignature(input)));
            }
            return result;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // Before invoking the method on the original target.
            WriteLog($"Invoking method {input.MethodBase} at {DateTime.Now.ToLongTimeString()}");

            // Invoke the next behavior in the chain.
            var result = getNext()(input, getNext);

            // After invoking the method on the original target.
            WriteLog(
                result.Exception != null
                    ? $"Method {input.MethodBase} threw exception {result.Exception.Message} at {DateTime.Now.ToLongTimeString()}"
                    : $"Method {input.MethodBase} returned {result.ReturnValue} at {DateTime.Now.ToLongTimeString()}");

            return result;
        }
Exemple #53
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn result = null;
            Type exceptionHandler = VerifyEspecificHandler(input);

            result = getNext().Invoke(input, getNext);
            if (result.Exception != null)
            {
                if (exceptionHandler == null)
                {
                    ExceptionHandler excepManager = new DefaultExceptionHandler();
                    Type defaultHandler = this.context.Resolve(typeof(ExceptionHandler));
                    if (defaultHandler != null)
                    {
                        excepManager = (ExceptionHandler)Activator.CreateInstance(defaultHandler);
                    }

                    excepManager.Handle(result.Exception);
                }
                else
                {
                    ExceptionHandler exHandler = (ExceptionHandler)Activator.CreateInstance(exceptionHandler);
                    exHandler.Handle(result.Exception);
                    exHandler = null;
                }
            }
            result.Exception = null;
            return result;
        }
Exemple #54
0
        /// <summary>
        /// Implement this method to execute your behavior processing.
        /// </summary>
        /// <param name="input">
        /// Inputs to the current call to the target. 
        /// </param>
        /// <param name="getNext">
        /// Delegate to execute to get the next delegate in the behavior chain. 
        /// </param>
        /// <returns>
        /// Return value from the target. 
        /// </returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn methodReturn;

            try
            {
                Stopwatch stopwatch;
                string className;
                string methodName;

                className = input.MethodBase.DeclaringType.Name;
                methodName = input.MethodBase.Name;

                stopwatch = new Stopwatch();

                stopwatch.Start();

                methodReturn = getNext()(input, getNext);

                stopwatch.Stop();

                Debug.WriteLine(string.Format("Executing on object {0} method {1} took: {2}ms", className, methodName, stopwatch.ElapsedMilliseconds));
            }
            catch (Exception exception)
            {
                throw;
            }

            return methodReturn;
        }
Exemple #55
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            this.source.TraceInformation(
                "Invoking {0}",
                input.MethodBase.ToString());

            IMethodReturn methodReturn = getNext().Invoke(input, getNext);

            if (methodReturn.Exception == null)
            {
                this.source.TraceInformation(
                    "Successfully finished {0}",
                    input.MethodBase.ToString());
            }
            else
            {
                this.source.TraceInformation(
                    "Finished {0} with exception {1}: {2}",
                    input.MethodBase.ToString(),
                    methodReturn.Exception.GetType().Name,
                    methodReturn.Exception.Message);
            }

            this.source.Flush();

            return methodReturn;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn result = null;

            if (input.MethodBase.IsDefined(typeof(RequiresTransactionAttribute), true))
            {
                try
                {
                    transactionManager.OpenTransaction();
                    this.transactionManager.Connection.QueryFileKey = this.context.GetQueryFile();
                    this.FindAndInjectDataAccessProperties(input);
                    result = getNext().Invoke(input, getNext);
                    if (result.Exception != null){
                        throw result.Exception;
                    }
                    transactionManager.Commit();
                }
                catch (Exception)
                {
                    transactionManager.Rollback();
                    throw;
                }
                finally
                {
                    transactionManager.Release();
                }
            }
            else
            {
                result = getNext().Invoke(input, getNext); //proceed
            }
            return result;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            //execute the next chain
            var result = getNext().Invoke(input, getNext);

            //if the method name is Create
            if (input.MethodBase.Name == "Create")
            {
                //let's get the generic argument for Create i.e. T in Create<T>
                var interfaceType = input.MethodBase.GetGenericArguments()[0];

                //set up ourlifetime to be controlled by the target object's disposed event
                var lifeTime = new ExternallyControlledLifetimeManager();
                var target = (IMockRepository)input.Target;
                target.Disposed += (s, e) => lifeTime.RemoveValue();

                //let's get our mock object
                var obj = result.ReturnValue as Mock;

                //let's register our mock with the container.
                if (obj != null && obj.Object != null)
                {
                    _container.RegisterInstance(interfaceType, obj.Object, lifeTime);
                }
            }

            return result;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            _appLogger.Log(String.Format("Invoking method {0} at {1}", input.MethodBase, DateTime.Now.ToLongTimeString()));

            var result = getNext()(input, getNext);

            if (result.Exception != null)
                _appLogger.Log(String.Format("Method {0} threw exception {1} at {2}", input.MethodBase, result.Exception.Message, DateTime.Now.ToLongTimeString()));
            else
            {
                var returnValue = JsonConvert.SerializeObject(result.ReturnValue);

                _appLogger.Log(String.Format("Method {0} returned {1} at {2}", input.MethodBase, returnValue, DateTime.Now.ToLongTimeString()));
            }

            return result;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            SLog.Red($"In LoggerInterceptionBehavor - Before executing {input.MethodBase}");

            var res = getNext()(input, getNext);

            if (res.Exception == null)
            {
                SLog.Red($"In LoggerInterceptionBehavor - After executing {input.MethodBase}");
            }
            else
            {
                SLog.Red($"In LoggerInterceptionBehavor - Exception {res.Exception.Message} executing {input.MethodBase}");
            }

            return res;
        }
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     Console.WriteLine("Before: {0}", input.MethodBase.Name);
     var returnMethod = getNext().Invoke(input, getNext);
     returnMethod.ReturnValue = (int)returnMethod.ReturnValue*2; 
     Console.WriteLine("After: {0}", input.MethodBase.Name);
     return returnMethod;
 }