public void Intercept(IInvocation invocation)
        {
            // Only public methods can be logged
            if (!invocation.Method.IsPublic)
            {
                // Run the intercepted method as normal.
                Console.WriteLine("(Skipping logging due to private method)");
                invocation.Proceed();
            }
            // Attributes
            else if (AttributeExistsOnMethod <DoNotLog>(invocation))
            {
                // Run the intercepted method as normal.
                Console.WriteLine("(Skipping logging due to attribute)");
                invocation.Proceed();
            }
            else
            {
                // Log and continue
                Logger.LogMessage(invocation.GetType().Name, invocation.Method.Name, "Calculating stuff.", System.Diagnostics.TraceEventType.Information);

                try
                {
                    invocation.Proceed();
                }
                // If exception occurs in intercepted method, log exception as well
                catch (Exception ex)
                {
                    Logger.LogMessage(invocation.GetType().Name, invocation.Method.Name, string.Format("Whooops! Error: {0}", ex.Message), System.Diagnostics.TraceEventType.Error);
                    throw ex;
                }
            }
        }
        private static void OnException(IInvocation invocation, Exception ex)
        {
            var sb = new StringBuilder();

            sb.Append($"Class name :{invocation.GetType().Name}; Method name : {invocation.Method.Name}");
            var parameters = invocation.Method.GetParameters();

            for (int i = 0; i < invocation.Arguments.Length; i++)
            {
                sb.AppendFormat("{0}={1}", parameters[i].Name, invocation.Arguments[i]);
            }
            sb.AppendFormat(") {0} caught: {1})", ex.GetType().Name, ex.Message);
            NLogger.GetFor("memory").Setup(LogTarget.Memory);
            NLogLogging.GetFor("Error").Log(sb.ToString());
        }
        private void PreProceed(IInvocation invocation)
        {
            //使用反射读取Attribute
            System.Reflection.MemberInfo info = invocation.GetType(); //通过反射得到MyClass类的信息
            //得到施加在MyClass类上的定制Attribute
            AuthorizeAttribute attr =
                (AuthorizeAttribute)Attribute.GetCustomAttribute(info, typeof(AuthorizeAttribute));

            if (attr != null)
            {
                //TODO:权限判断
                //Console.WriteLine("代码检查人:{0}", att.Reviewer);
                //Console.WriteLine("检查时间:{0}", att.Date);
                //Console.WriteLine("注释:{0}", att.Comment);
            }
        }
        public static void Reset(this IInvocation invocation)
        {
            if (_resetInvocationInterceptorsCall == null)
            {
                Type invoc = FindBaseType(invocation.GetType(), typeof(AbstractInvocation));
                if (invoc == null)
                {
                    throw new InvalidOperationException("IInvocationExtensions - Cannot find AbstractInvocation as base class.");
                }

                _resetInvocationInterceptorsCall = invoc.GetField("currentInterceptorIndex", BindingFlags.Instance | BindingFlags.NonPublic);
            }
            // reinitialize the index of execution, so when we call Proceed() again
            // the whole chain of interceptors start again from the first element
            _resetInvocationInterceptorsCall.SetValue(invocation, -1);
        }
Example #5
0
        private static Type GetTypeWithGenericArgumentsForMethodParameters(IInvocation invocation)
        {
            Type genericType = invocation.GetType();

            if (genericType.IsGenericType)             //generic method
            {
                return(genericType);
            }
            //Generic class:

            Type type = MockRepository.GetMockedObject(invocation.Proxy).GetDeclaringType(invocation.Method);

            if (type == null)
            {
                throw new InvalidOperationException("BUG: Could not find a declaring type for method " + invocation.Method);
            }
            return(type);
        }
        public void Intercept(IInvocation invocation)
        {
            if (!IsAggregateRepository(invocation.TargetType))
            {
                throw new ApplicationException(
                          $"{invocation.GetType()} doesn't implement IAggregateRepository<,> interface");
            }

            invocation.Proceed();
            if (!IsSetAsyncMethod(invocation.Method))
            {
                return;
            }
            var aggregate = invocation.Arguments.First() as IAggregate;

            foreach (var aggregateEvent in aggregate.Events.ToList())
            {
                _dispatcher.Dispatch(aggregateEvent);
            }
            aggregate.ClearEvents();
        }
Example #7
0
        private static void ExecutePostIntercept(IInvocation invocation, List <VPostExecuteMehthodAttribute> postAttributes)
        {
            if (!postAttributes.Any())
            {
                return;
            }

            foreach (var item in postAttributes)
            {
                item.MethodeInfo = invocation.Method;
                item.ReturnValue = invocation.ReturnValue;
                item.Arguments   = invocation.Arguments;
                if (invocation.Method.Name.Contains("set_"))
                {
                    if (invocation.Method.GetParameters().Any())
                    {
                        item.ReturnType = invocation.Method.GetParameters()[0].ParameterType;
                        item.Parameters = invocation.Method.GetParameters();
                        item.Arguments  = invocation.Arguments;
                    }
                }
                item.Object = invocation.Proxy;

                var field = invocation.GetType().GetField("target",
                                                          System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic
                                                          | System.Reflection.BindingFlags.Instance
                                                          | System.Reflection.BindingFlags.SetField
                                                          | System.Reflection.BindingFlags.GetField
                                                          | System.Reflection.BindingFlags.CreateInstance);
                //   item.ReturnType = invocation.MethodInvocationTarget.
                if (field != null)
                {
                    item.Target = field.GetValue(invocation);
                }
                invocation.ReturnValue = item.ReturnValue;
                item.OnExecute();
            }
        }
        /// <summary>
        /// Puts the invocation response in the specified cache.
        /// </summary>
        /// <param name="invocation"></param>
        /// <param name="cacheClient"></param>
        /// <param name="cacheKey"></param>
        /// <param name="region"></param>
        /// <param name="directive"></param>
        protected static void PutResponseInCache(IInvocation invocation, ICacheClient cacheClient, string cacheKey, string region, ResponseCachingDirective directive)
        {
            // bail if the directive does not tell us to cache anything
            if (directive == null || !directive.EnableCaching || directive.TimeToLive == TimeSpan.Zero)
            {
                return;
            }

            // if we don't have a cache key, this is an error
            if (cacheKey == null)
            {
                throw new InvalidOperationException(
                          string.Format("{0} is cacheable but the request class does not implement IDefinesCacheKey.", invocation.GetType().FullName));
            }

            // put response in cache
            cacheClient.Put(cacheKey, invocation.ReturnValue, new CachePutOptions(region, directive.TimeToLive, false));
        }
Example #9
0
        private static Type GetTypeWithGenericArgumentsForMethodParameters(IInvocation invocation)
        {
            Type genericType = invocation.GetType();
            if (genericType.IsGenericType) //generic method
                return genericType;
            //Generic class:

            Type type = MockRepository.GetMockedObject(invocation.Proxy).GetDeclaringType(invocation.Method);
            if (type == null)
                throw new InvalidOperationException("BUG: Could not find a declaring type for method " + invocation.Method);
            return type;
        }
		/// <summary>
		/// Puts the invocation response in the specified cache.
		/// </summary>
		/// <param name="invocation"></param>
		/// <param name="cacheClient"></param>
		/// <param name="cacheKey"></param>
		/// <param name="region"></param>
		/// <param name="directive"></param>
		protected static void PutResponseInCache(IInvocation invocation, ICacheClient cacheClient, string cacheKey, string region, ResponseCachingDirective directive)
		{
			// bail if the directive does not tell us to cache anything
			if (directive == null || !directive.EnableCaching || directive.TimeToLive == TimeSpan.Zero)
				return;

			// if we don't have a cache key, this is an error
			if (cacheKey == null)
				throw new InvalidOperationException(
					string.Format("{0} is cacheable but the request class does not implement IDefinesCacheKey.", invocation.GetType().FullName));

			// put response in cache
			cacheClient.Put(cacheKey, invocation.ReturnValue, new CachePutOptions(region, directive.TimeToLive, false));
		}
    	/// <summary>
    	/// Puts the invocation response in the specified cache.
    	/// </summary>
    	/// <param name="invocation"></param>
    	/// <param name="cacheClient"></param>
    	/// <param name="request"> </param>
    	/// <param name="region"></param>
    	/// <param name="directive"></param>
    	protected static void PutResponseInCache(IInvocation invocation, object request, ICacheClient cacheClient, string region, ResponseCachingDirective directive)
		{
			// bail if the directive does not tell us to cache anything
			if (directive == null || !directive.EnableCaching || directive.TimeToLive == TimeSpan.Zero)
				return;

			var strategy = ResponseDataCachingStrategy.Get(invocation.Method);
			var data = strategy.GetCacheDataToPut(request, invocation.ReturnValue);
			if (data == null || data.Length == 0)
			{
				throw new InvalidOperationException(
					string.Format("{0} is cacheable but the caching strategy didn't return any data to put in the cache.", invocation.GetType().FullName));
			}

    		foreach (var item in data)
				cacheClient.Put(item.CacheKey, item.Data, new CachePutOptions(region, directive.TimeToLive, false));
		}
Example #12
0
 public void Intercept(IInvocation invocation)
 {
     InvocationType = invocation.GetType();
 }
        /// <summary>
        /// Puts the invocation response in the specified cache.
        /// </summary>
        /// <param name="invocation"></param>
        /// <param name="cacheClient"></param>
        /// <param name="request"> </param>
        /// <param name="region"></param>
        /// <param name="directive"></param>
        protected static void PutResponseInCache(IInvocation invocation, object request, ICacheClient cacheClient, string region, ResponseCachingDirective directive)
        {
            // bail if the directive does not tell us to cache anything
            if (directive == null || !directive.EnableCaching || directive.TimeToLive == TimeSpan.Zero)
            {
                return;
            }

            var strategy = ResponseDataCachingStrategy.Get(invocation.Method);
            var data     = strategy.GetCacheDataToPut(request, invocation.ReturnValue);

            if (data == null || data.Length == 0)
            {
                throw new InvalidOperationException(
                          string.Format("{0} is cacheable but the caching strategy didn't return any data to put in the cache.", invocation.GetType().FullName));
            }

            foreach (var item in data)
            {
                cacheClient.Put(item.CacheKey, item.Data, new CachePutOptions(region, directive.TimeToLive, false));
            }
        }