Example #1
0
        private void ExcuteExHandle(IInvocation invocation, Exception ex)
        {
            ExHandleAttribute attribute = AttributeHelper.GetAttribute <ExHandleAttribute>(invocation) as ExHandleAttribute;

            if (attribute == null)
            {
                if (ex != null)
                {
                    throw ex;
                }
                else
                {
                    return;
                }
            }
            if (attribute.IsLog)
            {
                if (LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("{0} {1} -----EXHandle ", "Exception", InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel, ex);
                }
            }
            if (attribute.IsThrow)
            {
                throw ex;
            }
            //若忽略则什么都不做
            if (attribute.IsIgnore)
            {
                return;
            }
        }
Example #2
0
 private void ComponentRegistered(string key, IHandler handler)
 {
     if (InterceptorHelper.HasInterceptor(handler.ComponentModel.Implementation))
     {
         handler.ComponentModel.Interceptors.AddIfNotInCollection(new InterceptorReference(typeof(InterceptorProxy)));
     }
 }
        public void Intercept(IInvocation invocation)
        {
            if (!InterceptorHelper.DecideToIntercept(invocation, out attribute) ||
                invocation.Method.ReturnType == typeof(void) ||
                invocation.Method.ReturnType == typeof(Task))
            {
                invocation.Proceed();
                return;
            }

            cacheKey = string.Concat(invocation.TargetType.FullName, ".", invocation.Method.Name, "(", JsonConvert.SerializeObject(invocation.Arguments), ")");

            var delegateType = InterceptorHelper.GetDelegateType(invocation);

            if (delegateType == MethodType.Synchronous)
            {
                InterceptSynchronous(invocation);
            }
            if (delegateType == MethodType.AsyncAction)
            {
                throw new NotSupportedException($"A method with a return type Task cannot be cached.");
            }
            if (delegateType == MethodType.AsyncFunction)
            {
                InterceptAsynchronousWithResultUsingReflection(invocation);
            }
        }
Example #4
0
 private string getKey(IInvocation invocation, CacheAttribute attribute)
 {
     if (attribute.IsKey)
     {
         if (attribute.IsResolve)
         {
             throw new NotSupportedException();
         }
         else
         {
             return(attribute.Key);
         }
     }
     else//if (attribute.IsArg)
     {
         if (attribute.IsResolve)
         {
             throw new NotSupportedException();
         }
         else
         {
             object[] args = InterceptorHelper.GetInvocationMethodArgs(invocation);
             if (attribute.Arg <= args.Length)
             {
                 return(args[attribute.Arg].ToString());
             }
             else
             {
                 throw new IndexOutOfRangeException();
             }
         }
     }
 }
        public void Intercept(IInvocation invocation)
        {
            if (!InterceptorHelper.DecideToIntercept(invocation, out attribute))
            {
                invocation.Proceed();
                return;
            }

            var validator  = (IValidator)Activator.CreateInstance(attribute.ValidatorType);
            var entityType = attribute.ValidatorType.BaseType.GetGenericArguments()[0];

            var entities = invocation.Arguments.Where(t => t != null && t.GetType() == entityType).ToList();

            foreach (var entity in entities)
            {
                var result = validator.Validate(entity);
                if (result.Errors.Count > 0)
                {
                    _logger.Info(() =>
                    {
                        return(JsonConvert.SerializeObject(result.Errors.ToList().Select(e => $"{e.ErrorCode} - {e.ErrorMessage}").ToList(), Formatting.None));
                    });
                    throw new ValidationException(result.Errors);
                }
            }

            invocation.Proceed();
        }
Example #6
0
        private bool tryAccess(IInvocation invocation)
        {
            PermissionPointAttribute attribute = AttributeHelper.GetAttribute <PermissionPointAttribute>(invocation) as PermissionPointAttribute;

            if (attribute == null)
            {
                return(true);
            }
            string strLogHeader = "Access accepted";

            try
            {
                IPermissionPointResolve resolve = IocCoreFactory.Get <IPermissionPointResolve>(attribute.ResolveType);
                PermissionPoint         point   = new DefaultPermissionPoint(attribute,
                                                                             InterceptorHelper.GetInvocationTarget(invocation),
                                                                             InterceptorHelper.GetInvocationMethod(invocation) as MemberInfo,
                                                                             InterceptorHelper.GetInvocationMethodArgs(invocation)) as PermissionPoint;
                PermissionInfo info = resolve.Resolve(point);
                info++;
                if (attribute.IsAcceptLog && LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("{0} {1} {2} {3}-----Access Log ", strLogHeader, PrincipalTokenHolder.CurrentPrincipal.ToString(), attribute.ToString(), InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel);
                }
            }
            catch (AccessException ex)
            {
                strLogHeader = "Access Denied";
                if (attribute.IsAcceptLog && LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("{0} {1} {2} {3}-----Access Log ", strLogHeader, PrincipalTokenHolder.CurrentPrincipal.ToString(), attribute.ToString(), InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel, ex);
                }
                if (attribute.IsAlert)
                {
                    Console.WriteLine("Access diny alert!");
                }
                if (attribute.IsThrow)
                {
                    throw ex;
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
Example #7
0
        private IDependencyWrapper getDependency(IInvocation invocation, CacheAttribute attribute)
        {
            Type               targetType         = invocation.TargetType;
            MethodInfo         dependencyCallback = targetType.GetMethod(attribute.DependencyCallback);
            IDependencyWrapper dependency         = (IDependencyWrapper)dependencyCallback.Invoke(
                null,
                new object[] {
                InterceptorHelper.GetInvocationTarget(invocation),
                InterceptorHelper.GetInvocationMethodArgs(invocation)
            }
                );

            return(dependency);
        }
Example #8
0
        private void PostProceed(IInvocation invocation)
        {
            LogAttribute attribute = AttributeHelper.GetAttribute <LogAttribute>(invocation) as LogAttribute;

            if (attribute != null && attribute.IsPostLog)
            {
                //拦截器log屏蔽
                if (LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("{0} -----Post log", InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel);
                }
            }
        }
Example #9
0
        public override void Activate(IContext context, InstanceReference reference)
        {
            if (reference.Instance is IInterceptorProxy)
            {
                return;
            }

            if (reference.Instance is IInterceptor)
            {
                return;
            }

            if (InterceptorHelper.HasInterceptor(reference.Instance.GetType()))
            {
                var proxy = context.Kernel.Get <IInterceptorProxy>();
                reference.Instance = _proxyFactory.CreateProxy(reference.Instance, proxy);
            }

            base.Activate(context, reference);
        }
        public void PostProcess(IServiceRequestResult result)
        {
            var instance = result.ActualResult;

            if (instance == null)
            {
                return;
            }

            // inteceptors could not be intercepted too, thus skip the code below
            if (instance is IInterceptor)
            {
                return;
            }

            if (InterceptorHelper.HasInterceptor(instance.GetType()))
            {
                var proxy = result.Container.GetService(typeof(IInterceptorProxy)) as IInterceptorProxy;
                result.ActualResult = _proxyFactory.CreateProxy(instance, proxy);
            }
        }
Example #11
0
        private void RegistrationActivating(object sender, ActivatingEventArgs <object> e)
        {
            var interceptorProxy = e.Instance as IInterceptorProxy;

            if (interceptorProxy != null)
            {
                interceptorProxy.Container = new ServiceLocatorAdapter(e.Context.Resolve <IComponentContext>());
                return;
            }

            if (e.Instance is IInterceptor)
            {
                return;
            }

            if (InterceptorHelper.HasInterceptor(e.Instance.GetType()))
            {
                var proxy = e.Context.Resolve <IInterceptorProxy>();
                e.Instance = _proxyFactory.CreateProxy(e.Instance, proxy);
            }
        }
        public void Intercept(IInvocation invocation)
        {
            if (!InterceptorHelper.DecideToIntercept(invocation, out attribute))
            {
                invocation.Proceed();
                return;
            }

            var delegateType = InterceptorHelper.GetDelegateType(invocation);

            if (delegateType == MethodType.Synchronous)
            {
                InterceptSynchronous(invocation);
            }
            if (delegateType == MethodType.AsyncAction)
            {
                InterceptAsynchronous(invocation);
            }
            if (delegateType == MethodType.AsyncFunction)
            {
                InterceptAsynchronousWithResultUsingReflection(invocation);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="services"></param>
 /// <returns></returns>
 internal static IServiceCollection RegisterConventionalInterceptor(this IServiceCollection services)
 {
     InterceptorHelper.RegisterConventionalInterceptor(services);
     return(services);
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="services"></param>
 /// <param name="registrar"></param>
 /// <returns></returns>
 public static IServiceCollection AddConventionalRegistrar(this IServiceCollection services, IConventionaInterceptorRegistrar registrar)
 {
     InterceptorHelper.AddConventionalRegistrar(services, registrar);
     return(services);
 }
 /// <summary />
 /// <param name="type"></param>
 /// <returns></returns>
 public bool MatchesType(Type type)
 {
     return(InterceptorHelper.HasInterceptor(type));
 }
Example #16
0
        public override void Intercept(IInvocation invocation)
        {
            CacheAttribute attribute = AttributeHelper.GetAttribute <CacheAttribute>(invocation) as CacheAttribute;

            attribute.Key = getKey(invocation, attribute);
            ICache cache     = IocCoreFactory.Get <ICache>();
            object cacheData = cache.Get(attribute.Key);

            if (cacheData != null)
            {
                invocation.ReturnValue = cacheData;
                if (LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("Cache Hit! Key:\"{0}\" Caller:{1}", attribute.Key, InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel);
                }
                return;
            }
            IDependencyWrapper dependency;

            if (!String.IsNullOrWhiteSpace(attribute.DependencyCallback))
            {
                dependency = getDependency(invocation, attribute);
            }
            else
            {
                dependency = null;
            }
            invocation.Proceed();
            if (dependency != null)
            {
                object     returnValue       = invocation.ReturnValue;
                MethodInfo onRemovedCallback = invocation.TargetType.GetMethod(attribute.OnRemovedCallback);
                cache.Insert(
                    attribute.Key,
                    returnValue,
                    dependency.Instance,
                    attribute.Absolute,
                    attribute.Sliding,
                    (int)attribute.Priority,
                    onRemovedCallback);
                if (LogLevel <= attribute.LogLevel)
                {
                    StringBuilder logstr = new StringBuilder();
                    logstr.AppendFormat("Cache Insert! Key:\"{0}\" Caller:{1}", attribute.Key, InterceptorHelper.GetMethodInfo(invocation));
                    Log.Log(logstr.ToString(), attribute.LogLevel);
                }
            }
        }