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;
        }
Exemplo n.º 2
0
        public IMethodReturn Invoke(
            IMethodInvocation input, 
            GetNextHandlerDelegate getNext)
        {
            if (this.allowedRoles.Length > 0)
            {
                IPrincipal currentPrincipal = Thread.CurrentPrincipal;

                if (currentPrincipal != null)
                {
                    bool allowed = false;
                    foreach (string role in this.allowedRoles)
                    {
                        if (allowed = currentPrincipal.IsInRole(role))
                        {
                            break;
                        }
                    }

                    if (!allowed)
                    {
                        // short circuit the call
                        return input.CreateExceptionMethodReturn(
                            new UnauthorizedAccessException(
                                "User not allowed to invoke the method"));
                    }
                }
            }

            return getNext()(input, getNext);
        }
    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;
    }
Exemplo n.º 4
0
        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;
        }
Exemplo n.º 5
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            Console.WriteLine($"Called: {input.Target.GetType()}.{input.MethodBase.Name}");

            if (input.Arguments.Count > 0)
            {
                Console.WriteLine("\tWith Arguments");

                for (var i = 0; i < input.Arguments.Count; i++)
                {
                    Console.WriteLine($"\tName: {input.Arguments.GetParameterInfo(i)}");
                }
            }

            var handlerDelegate = getNext();

            Console.WriteLine("Execute...");

            var methodReturn = handlerDelegate(input, getNext);

            var result = methodReturn.ReturnValue?.ToString() ?? "(void)";

            if (methodReturn.Exception != null)
            {
                Console.WriteLine($"Exception: {methodReturn.Exception}");
            }

            Console.WriteLine($"Result: {result}");

            return methodReturn;
        }
Exemplo n.º 6
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     var results = input.Arguments.Cast<object>().SelectMany(entity => validator.Validate(entity));
     return !results.Any()
         ? getNext()(input, getNext) //no errors
         : input.CreateExceptionMethodReturn(new ValidationFailedException(results));
 }
		public object Invoke(IMethodInvocation invocation)
		{
			Log("Intercepted call : about to invoke method '{0}'", invocation.Method.Name);
			object returnValue = invocation.Proceed();
			Log("Intercepted call : returned '{0}'", returnValue);
			return returnValue;
		}
Exemplo n.º 8
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;
        }
Exemplo n.º 9
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var cacheAttr = GetAttribute(input);
            if (cacheAttr == null) return getNext()(input, getNext);
            string cacheKey = GetCacheKey(cacheAttr, input);

            ICache cacheHandler = CacheProxy.GetCacheHandler(cacheAttr.CacheMode);

            switch (cacheAttr.CacheType)
            {
                case CacheType.Fetch:
                    if (cacheHandler.Contain(cacheAttr.Group, cacheKey))
                    {
                        return input.CreateMethodReturn(cacheHandler.Get(cacheAttr.Group, cacheKey));
                    }
                    else
                    {
                        var r = getNext()(input, getNext);
                        cacheHandler.Add(cacheAttr.Group, cacheKey, r.ReturnValue);
                        return r;
                    }
                case CacheType.Clear:
                    cacheHandler.Remove(cacheAttr.Group, cacheKey);
                    return getNext()(input, getNext);
            }
            return getNext()(input, getNext);
        }
        /// <summary>
        /// Implement this method to perform extra treatments before and after
        /// the call to the supplied <paramref name="invocation"/>.
        /// </summary>
        /// <param name="invocation">The method invocation that is being intercepted.</param>
        /// <returns>
        /// The result of the call to the
        /// <see cref="M:AopAlliance.Intercept.IJoinpoint.Proceed"/> method of
        /// the supplied <paramref name="invocation"/>; this return value may
        /// well have been intercepted by the interceptor.
        /// </returns>
        /// <remarks>
        /// 	<p>
        /// Polite implementations would certainly like to invoke
        /// <see cref="M:AopAlliance.Intercept.IJoinpoint.Proceed"/>.
        /// </p>
        /// </remarks>
        /// <exception cref="T:System.Exception">
        /// If any of the interceptors in the chain or the target object itself
        /// throws an exception.
        /// </exception>
        public object Invoke(IMethodInvocation invocation)
        {
            MethodInfo m = invocation.Method;
            if (m.Name.StartsWith("set_") || m.Name.StartsWith("get_"))
                return invocation.Proceed();

            string name = m.Name;

            object[] attribs = m.GetCustomAttributes(typeof(DefinitionAttribute), true);
            if (attribs.Length > 0)
            {

            }

            if (IsCurrentlyInCreation(name))
            {
                if (LOG.IsDebugEnabled)
                {
                    LOG.Debug(name + " currently in creation, created one.");
                }
                return invocation.Proceed();
            }
            if (LOG.IsDebugEnabled)
            {
                LOG.Debug(name + " not in creation, asked the application context for one");
            }

            return _configurableListableObjectFactory.GetObject(name);
        }
 public object Invoke(IMethodInvocation invocation)
 {
     LOG.Debug("Advice executing; calling the advised method [" + invocation.Method.Name + "]");
     object returnValue = invocation.Proceed();
     LOG.Debug("Advice executed; advised method [" + invocation.Method.Name + "] returned " + returnValue);
     return returnValue;
 }
Exemplo n.º 12
0
        object Proxi.IInterceptor.Run(IMethodInvocation mi)
        {
            // tries to find a registered method that matches...
            var interceptorState = FindInterceptorStateByMethodSignature(mi.Method.ExtractSignature());

            var hasInterceptorState = interceptorState != null;
            var hasTargetObject = mi.Target != null;
            var hasTargetMethod = hasInterceptorState && interceptorState.OnInvokeWasRegistered;
            var isOpenGenericMethod = mi.Method.IsGenericMethodDefinition;

            Func<IMethodInvocation, object> call = x => mi.Method.Invoke(mi.Target, mi.Arguments);
            // method wasn't registered but can be inferred from context if a target exist
            if (!hasTargetMethod && hasTargetObject && hasInterceptorState)
            {
                interceptorState.CallbackCollection.Add(new OnInvokeCallback(call));
                hasTargetMethod = true;
            }

            #region Execution
            // executes interceptor...
            if (hasInterceptorState && hasTargetMethod) return interceptorState.Run(mi);
            // executes target: method wasn't registered but target exists, method will be inferred from context and executed on target directly...
            if (!hasTargetMethod && hasTargetObject) return call(mi);
            // unable to execute any operation...
            else throw new InvalidOperationException("Unable to execute method: " + mi.Method.Name + ". Speficy a target object or a target method utilizing Target() or OnInvoke() method.");
            #endregion
        }
        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;
        }
Exemplo n.º 14
0
 public object Invoke(IMethodInvocation invocation)
 {
     Console.Out.WriteLine("Intercepted call : about to invoke next item in chain...");
     object returnValue = invocation.Proceed();
     Console.Out.WriteLine("Intercepted call : returned " + returnValue);
     return returnValue;
 }
 /// <summary>
 /// 根据指定的<see cref="CachingAttribute"/>以及<see cref="IMethodInvocation"/>实例,
 /// 获取与某一特定参数值相关的键名。
 /// </summary>
 /// <param name="cachingAttribute"><see cref="CachingAttribute"/>实例。</param>
 /// <param name="input"><see cref="IMethodInvocation"/>实例。</param>
 /// <returns>与某一特定参数值相关的键名。</returns>
 private string GetValueKey(CachingAttribute cachingAttribute, IMethodInvocation input)
 {
     switch (cachingAttribute.Method)
     {
         // 如果是Remove,则不存在特定值键名,所有的以该方法名称相关的缓存都需要清除
         case CachingMethod.Remove:
             return null;
         // 如果是Get或者Put,则需要产生一个针对特定参数值的键名
         case CachingMethod.Get:
         case CachingMethod.Put:
             if (input.Arguments != null &&
                 input.Arguments.Count > 0)
             {
                 var sb = new StringBuilder();
                 for (int i = 0; i < input.Arguments.Count; i++)
                 {
                     sb.Append(input.Arguments[i].ToString());
                     if (i != input.Arguments.Count - 1)
                         sb.Append("_");
                 }
                 return sb.ToString();
             }
             else
                 return "NULL";
         default:
             throw new InvalidOperationException("无效的缓存方式。");
     }
 }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn methodReturn;

            using (var transaction = this.Factory.GetCurrentSession().BeginTransaction())
            {
                // Here next attribute is called or original method, if no more attributes exist on operation
                methodReturn = getNext()(input, getNext);

                if (methodReturn.Exception == null || ShouldCommitDespiteOf(methodReturn.Exception))
                {
                    transaction.Commit();
                }
                else
                {
                    transaction.Rollback();
                }
            }

            // Required in cases (exceptions>) when instead of normal values NHibernate returns lazy proxies.
            this.Factory.GetCurrentSession().GetSessionImplementation().PersistenceContext.Unproxy(methodReturn.ReturnValue);

            // Get back to previous attribute handler or back to caller
            return methodReturn;
        }
Exemplo n.º 17
0
		public object Invoke(IMethodInvocation invocation)
		{
            ConsoleLoggingAttribute[] consoleLoggingInfo =
                (ConsoleLoggingAttribute[])invocation.Method.GetCustomAttributes(typeof(ConsoleLoggingAttribute), false);

            if (consoleLoggingInfo.Length > 0)
            {
                Color = consoleLoggingInfo[0].Color;
            }

            ConsoleColor currentColor = Console.ForegroundColor;

            Console.ForegroundColor = Color;

            Console.Out.WriteLine(String.Format(
                "Intercepted call : about to invoke method '{0}'", invocation.Method.Name));

            Console.ForegroundColor = currentColor;

            object returnValue = invocation.Proceed();

            Console.ForegroundColor = Color;

            Console.Out.WriteLine(String.Format(
                "Intercepted call : returned '{0}'", returnValue));

            Console.ForegroundColor = currentColor;

			return returnValue;
		}
Exemplo n.º 18
0
        private void ThrowEntityException(IMethodInvocation invocation, Exception ex)
        {
            // just in case
            if (ex is EntityException)
            {
                throw ex;
            }

            RemoteService.CheckForDBValidationException(null, ex);

            object[] attrs =
                invocation.Method.GetCustomAttributes(typeof (AccessTypeAttribute), true);
            if (attrs == null || attrs.Length == 0)
            {
                log.Error(string.Format("Can't get AccessTypeAttribute for {0}", invocation.Method.Name));
                throw new EntityException(ex);
            }
            AccessType accessType = ((AccessTypeAttribute) attrs[0]).AccessType;
            switch (accessType)
            {
                case AccessType.FreeAccess:
                case AccessType.None:
                    throw new EntityException(ex);
                case AccessType.Read:
                case AccessType.Import:
                    throw new LoadException(ex);
                case AccessType.Write:
                    throw new SaveOrUpdateException(ex);
                default:
                    log.Error(
                        string.Format("Unknown AccessTypeAttribute for {0} ({1})", invocation.Method.Name,
                                      accessType.ToString()));
                    throw new EntityException(ex);
            }
        }
Exemplo n.º 19
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;
        }
Exemplo n.º 20
0
        /// <summary>
        /// Invokes the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="getNext">The get next.</param>
        /// <returns>Invoke the next handler in the chain</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var target = input.Target;

            // Before invoking the method on the original target
            var el = string.Format(
                "{0} {1}",
                // input.MethodBase.DeclaringType != null ? input.MethodBase.DeclaringType.AssemblyQualifiedName : "-",
                input.MethodBase.Module.ScopeName,
                input.MethodBase);

            this.WriteLog(target, string.Format("Invoking method {0} at {1}", el, DateTime.Now.ToLongTimeString()));

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

            var msg = result.Exception != null
                          ? string.Format(
                              "Method {0} threw exception {1} at {2}",
                              el,
                              result.Exception.Message,
                              DateTime.Now.ToLongTimeString())
                          : string.Format(
                              "Method {0} returned {1} at {2}",
                              el,
                              result.ReturnValue,
                              DateTime.Now.ToLongTimeString());

            // After invoking the method on the original target
            this.WriteLog(target, msg);

            return result;
        }
Exemplo n.º 21
0
        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;
        }
Exemplo n.º 22
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;
        }
        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;
        }
Exemplo n.º 24
0
		public object Invoke(IMethodInvocation invocation)
		{
			Console.WriteLine("Before {0} on {1}", invocation.Method.Name,  invocation.Method.DeclaringType);
			object returnVal = invocation.Proceed();
			Console.WriteLine("After {0} on {1}", invocation.Method.Name,  invocation.Method.DeclaringType);
			return returnVal;
		}
Exemplo n.º 25
0
    /// <summary>
    /// Invokes the specified input.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <param name="getNext">The get next.</param>
    /// <returns>The method return result.</returns>
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
      foreach (var argument in input.Arguments)
      {
        string target = argument as string;

        if (string.IsNullOrEmpty(target))
        {
          continue;
        }

        if (Regex.Match(target, @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?").Success)
        {
          continue;
        }

        ArgumentException argumentException = new ArgumentException("Invalid e-mail format", input.MethodBase.Name);

        Log.Error("Argument exception", argumentException, this);

        return input.CreateExceptionMethodReturn(argumentException);
      }

      return getNext()(input, getNext);
    }
Exemplo n.º 26
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var methodName = input.MethodBase.Name;
            var target = input.Target;

            return getNext()(input, getNext);
        }
Exemplo n.º 27
0
		public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
		{
			if (input.Arguments.Count > 0)
			{
				var arguments = new Argument[input.Arguments.Count];

				for (int i = 0; i < input.Arguments.Count; i++)
				{
					arguments[i] = new Argument
					               	{
					              		Name = input.Arguments.ParameterName(i),
					              		Value = input.Arguments[i]
					              	};
				}

				_tape.RecordRequest(arguments, input.MethodBase.ReflectedType, input.MethodBase.Name);
			}

			Console.WriteLine("> Intercepting " + input.MethodBase.Name);
			Console.WriteLine("> Intercepting " + input.MethodBase.ReflectedType);

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

			Console.WriteLine("> Intercepted return value: " + methodReturn.ReturnValue.GetType().Name);

			if (methodReturn.ReturnValue != null)
			{
				_tape.RecordResponse(methodReturn.ReturnValue, input.MethodBase.ReflectedType, input.MethodBase.Name);
			}

			return methodReturn;
		}
Exemplo n.º 28
0
 /// <exception cref="SapphireUserFriendlyException"><c>SapphireUserFriendlyException</c>.</exception>
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     var result = getNext()(input, getNext);
       if (result.Exception == null)
     return result;
       throw new SapphireUserFriendlyException();
 }
Exemplo n.º 29
0
        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;
        }
Exemplo n.º 30
0
        /// <summary>
        ///  Handle 'around' advice for services
        /// </summary>
        public object Invoke(IMethodInvocation invocation)
        {
            object returnValue = null;

            using (Repository repository = new Repository(Repository.SessionFactory))
            {
                repository.BeginTransaction();

                DomainRegistry.Repository = repository;
                DomainRegistry.Library = null;

                try
                {
                    returnValue = invocation.Proceed();

                    repository.CommitTransaction();
                }
                catch (Exception e)
                {
                    returnValue = ServiceResult.Error(invocation.Method.ReturnType, e);
                }
            }

            return returnValue;
        }
Exemplo n.º 31
0
 /// <summary>
 /// Creates the method invocation return that ends the current invocation for a non-void method.
 /// </summary>
 public static IMethodReturn CreateValueReturn <TResult>(this IMethodInvocation invocation, TResult result)
 => invocation.CreateValueReturn(result, invocation.Arguments);
Exemplo n.º 32
0
 /// <summary>
 /// Creates the method invocation return that ends the current invocation for a non-void method.
 /// </summary>
 public static IMethodReturn CreateValueReturn <TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(this IMethodInvocation invocation, TResult result, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16)
 => invocation.CreateValueReturn(result, ArgumentCollection.Create(invocation.MethodBase.GetParameters(), arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16));
Exemplo n.º 33
0
 /// <summary>
 /// Creates the method invocation return that ends the current invocation.
 /// </summary>
 public static IMethodReturn CreateReturn(this IMethodInvocation invocation)
 => invocation.CreateValueReturn(null, invocation.Arguments);
Exemplo n.º 34
0
 /// <summary>
 /// Creates the method invocation return that ends the current invocation for a non-void method.
 /// </summary>
 public static IMethodReturn CreateValueReturn <TResult, T1, T2, T3, T4, T5, T6, T7, T8>(this IMethodInvocation invocation, TResult result, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)
 => invocation.CreateValueReturn(result, ArgumentCollection.Create(invocation.MethodBase.GetParameters(), arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8));
Exemplo n.º 35
0
 /// <summary>
 /// Creates the method invocation return that ends the current invocation for a non-void method.
 /// </summary>
 public static IMethodReturn CreateValueReturn <TResult, T1, T2, T3, T4>(this IMethodInvocation invocation, TResult result, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
 => invocation.CreateValueReturn(result, ArgumentCollection.Create(invocation.MethodBase.GetParameters(), arg1, arg2, arg3, arg4));
Exemplo n.º 36
0
 /// <summary>
 /// Registers a behavior in the pipeline that should be skipped during this invocation
 /// by adding it to the <see cref="IMethodInvocation.SkipBehaviors"/> list.
 /// </summary>
 public static void SkipBehavior <TBehavior>(this IMethodInvocation invocation)
 => invocation.SkipBehaviors.Add(typeof(TBehavior));
Exemplo n.º 37
0
 /// <summary>
 /// Creates the method invocation return that ends the current invocation for a non-void method.
 /// </summary>
 public static IMethodReturn CreateValueReturn <TResult, T>(this IMethodInvocation invocation, TResult result, T arg)
 => invocation.CreateValueReturn(result, ArgumentCollection.Create(invocation.MethodBase.GetParameters(), arg));
Exemplo n.º 38
0
 /// <summary>
 /// Throws <see cref="StrictMockException"/>.
 /// </summary>
 public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext) => throw new StrictMockException();
Exemplo n.º 39
0
 public override string GetFilePath(IMethodInvocation input, PropertyInfo property) => Path.GetFullPath(GetIniAttribute(property).File);
Exemplo n.º 40
0
 public MethodReturn(IMethodInvocation invocation, Exception exception)
 {
     Outputs   = new ArgumentCollection(new object[0], new ParameterInfo[0]);
     Exception = exception;
 }
Exemplo n.º 41
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            // 获得被拦截的方法
            var method = input.MethodBase;
            var key    = method.Name; // 获得拦截的方法名

            // 如果拦截的方法定义了Cache属性,说明需要对该方法的结果需要进行缓存
            if (!method.IsDefined(typeof(CacheAttribute), false))
            {
                return(getNext().Invoke(input, getNext));
            }

            var cachingAttribute = (CacheAttribute)method.GetCustomAttributes(typeof(CacheAttribute), false)[0];
            var valueKey         = GetValueKey(cachingAttribute, input);

            switch (cachingAttribute.Method)
            {
            case CachingMethod.Get:
                try
                {
                    // 如果缓存中存在该键值的缓存,则直接返回缓存中的结果退出
                    if (_cacheProvider.Exists(key, valueKey))
                    {
                        var value     = _cacheProvider.Get(key, valueKey);
                        var arguments = new object[input.Arguments.Count];
                        input.Arguments.CopyTo(arguments, 0);
                        return(new VirtualMethodReturn(input, value, arguments));
                    }
                    else     // 否则先调用方法,再把返回结果进行缓存
                    {
                        var methodReturn = getNext().Invoke(input, getNext);
                        _cacheProvider.Add(key, valueKey, methodReturn.ReturnValue);
                        return(methodReturn);
                    }
                }
                catch (Exception ex)
                {
                    return(new VirtualMethodReturn(input, ex));
                }

            case CachingMethod.Update:
                try
                {
                    var methodReturn = getNext().Invoke(input, getNext);
                    if (_cacheProvider.Exists(key))
                    {
                        if (cachingAttribute.IsForce)
                        {
                            _cacheProvider.Remove(key);
                            _cacheProvider.Add(key, valueKey, methodReturn.ReturnValue);
                        }
                        else
                        {
                            _cacheProvider.Update(key, valueKey, methodReturn);
                        }
                    }
                    else
                    {
                        _cacheProvider.Add(key, valueKey, methodReturn.ReturnValue);
                    }

                    return(methodReturn);
                }
                catch (Exception ex)
                {
                    return(new VirtualMethodReturn(input, ex));
                }

            case CachingMethod.Remove:
                try
                {
                    var removeKeys = cachingAttribute.CorrespondingMethodNames;
                    foreach (var removeKey in removeKeys)
                    {
                        if (_cacheProvider.Exists(removeKey))
                        {
                            _cacheProvider.Remove(removeKey);
                        }
                    }

                    // 执行具体截获的方法
                    var methodReturn = getNext().Invoke(input, getNext);
                    return(methodReturn);
                }
                catch (Exception ex)
                {
                    return(new VirtualMethodReturn(input, ex));
                }

            default: break;
            }

            return(getNext().Invoke(input, getNext));
        }
Exemplo n.º 42
0
 public override string GetSection(IMethodInvocation input, PropertyInfo property) => GetIniAttribute(property).Section;
        FaultException TransformException(
            IMethodInvocation input,
            Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            Exception outException = null;

            try
            {
                if (!Facility.ExceptionManager.HandleException(exception, ExceptionHandlingPolicyName, out outException))
                {
                    return(null);
                }
            }
            catch (Exception x)
            {
                Facility.LogWriter.LogError(
                    $@"
Facility.ExceptionManager.HandleException throws:
{x.DumpString(1)}
when processing
{exception.DumpString(1)}");

                if (ExceptionHandlingPolicyName == ExceptionPolicyProvider.LogAndSwallowPolicyName)
                {
                    return(null);
                }

                if (outException == null)
                {
                    outException = exception;
                }
            }

            var faultException = outException as FaultException;

            // try to get the fault, if any
            var fault = (faultException != null &&
                         faultException.GetType().IsGenericType)
                            ? faultException
                        .GetType()
                        .GetProperty(nameof(FaultException <Fault> .Detail))
                        ?.GetValue(faultException) as Fault
                            : null;

            // can we return the faultException as we got it
            if (fault != null && IsFaultSupported(input, fault.GetType()))
            {
                return(faultException);
            }

            // if the base fault is supported one with all fields copied either to properties or to the Data collection.
            // Send it with status code 500 to indicate that the fault must be added to the protocol
            if (IsFaultSupported(input, typeof(Fault)))
            {
                fault = Fault.FaultFactory <Exception>(exception);
                return(new WebFaultException <Fault>(fault, HttpStatusCode.InternalServerError));
            }

            // otherwise construct base WebFaultException with some debug data in the Data property that will be dumped in the logs
            var exceptionToReturn = new WebFaultException(HttpStatusCode.InternalServerError);

            if (fault != null)
            {
                return(exceptionToReturn
                       .PopulateData(
                           new SortedDictionary <string, string>
                {
                    ["HandlingInstanceId"] = fault.HandlingInstanceId.ToString(),
                    ["Fault"] = fault.DumpString(),
                }));
            }

            return(exceptionToReturn
                   .PopulateData(
                       new SortedDictionary <string, string>
            {
                ["Exception"] = exception.DumpString(),
            }));
        }
Exemplo n.º 44
0
 public abstract void InterceptExceptions(IMethodReturn result, IMethodInvocation input);
Exemplo n.º 45
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     Console.WriteLine("CachingBehavior");
     return(getNext().Invoke(input, getNext));
 }
        static bool IsFaultSupported(
            IMethodInvocation input,
            Type faultType)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (faultType == null)
            {
                return(false);
            }

            ICollection <Type> contracts;

            using (_sync.UpgradableReaderLock())
            {
                var method = input.MethodBase;

                if (_faultContracts.TryGetValue(method, out contracts))
                {
                    return(contracts.Contains(faultType));
                }

                if (method.GetCustomAttribute <OperationContractAttribute>() == null)
                {
                    method = input
                             .Target
                             .GetType()
                             .GetInterfaces()
                             .Where(i => i.GetCustomAttribute <ServiceContractAttribute>() != null)
                             .SelectMany(i => i.GetMethods())
                             .FirstOrDefault(m => m.GetCustomAttribute <OperationContractAttribute>() != null &&
                                             m.Name == input.MethodBase.Name)
                    ;
                }

                if (method == null)
                {
                    Facility.LogWriter.TraceError($"Could not find operation contract {input.MethodBase.Name}.");
                    return(false);
                }

                contracts = new HashSet <Type>(method.GetCustomAttributes <FaultContractAttribute>().Select(a => a.DetailType));

                using (_sync.WriterLock())
                    _faultContracts[input.MethodBase] = contracts;
            }

            if (contracts.Count() == 0)
            {
                Facility.LogWriter.TraceError($"The operation contract {input.MethodBase.Name} does not define any fault contracts.");
                return(false);
            }

            if (!contracts.Contains(faultType))
            {
                Facility.LogWriter.TraceError($"The operation contract {input.MethodBase.Name} does not define the fault contract {faultType.Name}.");
                return(false);
            }

            return(true);
        }
Exemplo n.º 47
0
 private IMethodReturn DoInvoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     return(getNext()(input, getNext));
 }
Exemplo n.º 48
0
 public object Invoke(IMethodInvocation invocation)
 {
     CapturedCalls.Add(invocation);
     return(invocation.Proceed());
 }
Exemplo n.º 49
0
Arquivo: Fakes.cs Projeto: v-prla/moq
 public bool Equals(IMethodInvocation other) => base.Equals(other);
Exemplo n.º 50
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn result = input.CreateMethodReturn(null);

            return(result);
        }
Exemplo n.º 51
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     return(this.invoke(input, getNext));
 }
Exemplo n.º 52
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     ++callCount;
     return(getNext()(input, getNext));
 }
Exemplo n.º 53
0
 protected bool IsSpecifiedOutsideSql(IMethodInvocation invocation)
 {
     return(typeof(OutsideSqlDao).IsAssignableFrom(GetComponentDef(invocation).ComponentType));
 }
Exemplo n.º 54
0
Arquivo: Fakes.cs Projeto: v-prla/moq
 bool IMockSetup.AppliesTo(IMethodInvocation actualInvocation) => AppliesTo(actualInvocation);
Exemplo n.º 55
0
        protected virtual object DispatchInvoking(IMethodInvocation invocation)
        {
            MethodBase method = invocation.Method;

            if (!method.IsAbstract)
            {
                return(invocation.Proceed());
            }
            bool logEnabled = IsLogEnabled();

            // - - - - - - - - - - - - -
            // Initialize DAO meta data
            // - - - - - - - - - - - - -
            if (method.Name.Equals("InitializeDaoMetaData"))
            {
                InitializeSqlCommand(invocation);
                return(null); // The end! (Initilization Only)
            }

            // - - - - - - - - - - -
            // Preprocess outsideSql
            // - - - - - - - - - - -
            PreprocessOutsideSql(invocation);

            // - - - - - - - - - - - - -
            // Preprocess conditionBean
            // - - - - - - - - - - - - -
            ConditionBean cb = PreprocessConditionBean(invocation);

            // - - - - - - - - -
            // Set up sqlCommand
            // - - - - - - - - -
            ISqlCommand cmd = null;

            try {
                DateTime?beforeCmd = null;
                if (logEnabled)
                {
                    beforeCmd = DateTime.Now;
                }
                cmd = FindSqlCommand(invocation);
                if (logEnabled)
                {
                    DateTime afterCmd = DateTime.Now;
                    if (!afterCmd.Equals(beforeCmd.Value))
                    {
                        LogSqlCommand(invocation, cmd, beforeCmd.Value, afterCmd);
                    }
                }
            } finally {
                if (IsLogEnabled())
                {
                    LogInvocation(invocation);
                }
            }

            SqlResultHandler sqlResultHandler       = GetSqlResultHander();
            bool             existsSqlResultHandler = sqlResultHandler != null;
            DateTime?        before = null;

            if (logEnabled || existsSqlResultHandler)
            {
                before = DateTime.Now; // for performance view
            }

            // - - - - - - - - - -
            // Execute sqlCommand!
            // - - - - - - - - - -
            object ret = null;

            try {
                ret = cmd.Execute(invocation.Arguments);
            } catch (Exception e) {
                if (e.GetType().Equals(typeof(NotSingleRowUpdatedRuntimeException)))
                {
                    throw new EntityAlreadyUpdatedException((NotSingleRowUpdatedRuntimeException)e);
                }
                throw;
            } finally {
                PostprocessConditionBean(invocation, cb);
            }

            // - - - - - - - - - -
            // Convert and Return!
            // - - - - - - - - - -
            Type retType = ((MethodInfo)method).ReturnType;

            ret = Seasar.Framework.Util.ConversionUtil.ConvertTargetType(ret, retType);

            if (logEnabled || existsSqlResultHandler)
            {
                DateTime after = DateTime.Now; // for performance view
                if (logEnabled)
                {
                    LogReturn(invocation, retType, ret, before.Value, after);
                }
                if (existsSqlResultHandler)
                {
                    SqlResultInfo info = new SqlResultInfo();
                    info.Result         = ret;
                    info.CommandName    = method.Name;
                    info.DisplaySql     = (String)InternalMapContext.GetObject("df:DisplaySql");
                    info.BeforeDateTime = before.Value;
                    info.AfterDateTime  = after;
                    sqlResultHandler.Invoke(info);
                }
            }
            return(ret);
        }
Exemplo n.º 56
0
 // - - - - - - - - - -
 //              Select
 //               - - -
 protected bool IsOutsideSqlDaoMethodSelect(IMethodInvocation invocation)
 {
     return(invocation.Method.Name.StartsWith("Select"));
 }
Exemplo n.º 57
0
        // ===============================================================================
        //                                                                   Determination
        //                                                                   =============
        protected bool IsSelectCountIgnoreFetchScopeMethod(IMethodInvocation invocation)
        {
            String name = invocation.Method.Name;

            return(name.StartsWith("ReadCount") || name.StartsWith("SelectCount"));
        }
Exemplo n.º 58
0
 // ===============================================================================
 //                                                                  Log SqlCommand
 //                                                                  ==============
 protected void LogSqlCommand(IMethodInvocation invocation, ISqlCommand cmd, DateTime beforeCmd, DateTime afterCmd)
 {
     Log("SqlCommand Initialization Cost: [" + TraceViewUtil.ConvertToPerformanceView(beforeCmd, afterCmd) + "]");
 }
Exemplo n.º 59
0
 public bool AppliesTo(IMethodInvocation invocation) => targetMethods.ContainsKey(GetHashCode(invocation.MethodBase as MethodInfo));
Exemplo n.º 60
0
        protected String buildInvocationExpressionWithoutKakko(IMethodInvocation invocation, String invokeClassName, String invokeMethodName)
        {
            if (invokeClassName.Contains("OutsideSql") && invokeClassName.Contains("Executor"))   // OutsideSql Executor Handling and CSharp Only Contains
            {
                try {
                    String originalName = invokeClassName;
                    if (IsSpecifiedOutsideSql())
                    {
                        OutsideSqlContext outsideSqlContext = GetOutsideSqlContext();
                        String            tableDbName       = outsideSqlContext.TableDbName;
                        DBMeta            dbmeta            = DBMetaInstanceHandler.FindDBMeta(tableDbName);
                        String            behaviorTypeName  = dbmeta.BehaviorTypeName;
                        String            behaviorClassName = behaviorTypeName.Substring(behaviorTypeName.LastIndexOf(".") + ".".Length);
                        invokeClassName = behaviorClassName + ".OutsideSql()";
                        if (originalName.Contains("OutsideSqlEntityExecutor"))   // CSharp Only Contains
                        {
                            invokeClassName = invokeClassName + ".EntityHandling()";
                        }
                        else if (originalName.Contains("OutsideSqlPagingExecutor"))     // CSharp Only Contains
                        {
                            if (outsideSqlContext.IsAutoPagingLogging)
                            {
                                invokeClassName = invokeClassName + ".AutoPaging()";
                            }
                            else
                            {
                                invokeClassName = invokeClassName + ".ManualPaging()";
                            }
                        }
                        else if (originalName.Contains("OutsideSqlCursorExecutor"))     // CSharp Only Contains
                        {
                            invokeClassName = invokeClassName + ".CursorHandling()";
                        }
                    }
                    else
                    {
                        invokeClassName = "OutsideSql";
                    }
                } catch (Exception ignored) {
                    Log("Ignored exception occurred: msg=" + ignored.Message);
                }
            }
            String invocationExpressionWithoutKakko = invokeClassName + "." + invokeMethodName;

            if ("SelectPage".Equals(invokeMethodName))   // Special Handling!
            {
                bool resultTypeInteger = false;
                if (IsSpecifiedOutsideSql())
                {
                    OutsideSqlContext outsideSqlContext = GetOutsideSqlContext();
                    Type resultType = outsideSqlContext.ResultType;
                    if (resultType != null)
                    {
                        if (typeof(int).IsAssignableFrom(resultType))
                        {
                            resultTypeInteger = true;
                        }
                    }
                }
                if (resultTypeInteger || "SelectCount".Equals(invocation.Method.Name))
                {
                    invocationExpressionWithoutKakko = invocationExpressionWithoutKakko + "():count";
                }
                else
                {
                    invocationExpressionWithoutKakko = invocationExpressionWithoutKakko + "():paging";
                }
            }
            return(invocationExpressionWithoutKakko);
        }