public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var trace = context.ServiceProvider.GetService <IDataAccessTrace>();

            if (trace != null && context.Implementation is IDataCommand command)
            {
                var       startDateTime = DateTime.Now;
                Exception err           = null;
                try
                {
                    await context.Invoke(next);
                }
                catch (Exception ex)
                {
                    err = ex;
                    throw ex;
                }
                finally
                {
                    trace.Record(startDateTime, DateTime.Now, context, err);
                }
            }
            else
            {
                await context.Invoke(next);
            }
        }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var profilers = context.ServiceProvider.ResolveMany <IProfiler <RedisProfilingContext> >();

            if (profilers.Any())
            {
                var connectionMultiplexer = context.ServiceProvider.ResolveRequired <IConnectionMultiplexer>();
                var profilerContext       = new object();
                AspectRedisDatabaseProfilerContext.Context = profilerContext;
                connectionMultiplexer.BeginProfiling(profilerContext);
                await context.Invoke(next);

                var profiledResult        = connectionMultiplexer.FinishProfiling(profilerContext);
                var redisProfiledCommands = profiledResult.Select(x =>
                                                                  RedisProfilingCommand.Create(
                                                                      x.Command, x.EndPoint, x.Db, x.CommandCreated, x.CreationToEnqueued,
                                                                      x.EnqueuedToSending, x.SentToResponse, x.ResponseToCompletion, x.ElapsedTime,
                                                                      connectionMultiplexer.ClientName, connectionMultiplexer.OperationCount)).ToArray();
                foreach (var profiler in profilers)
                {
                    profiler.Invoke(new RedisProfilingContext(redisProfiledCommands));
                }
                AspectRedisDatabaseProfilerContext.Context = null;
            }
            else
            {
                await context.Invoke(next);
            }
        }
示例#3
0
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            if (!Enable)
            {
                return(context.Invoke(next));
            }
            string className  = context.Implementation.GetType().Name;
            string methodName = context.ImplementationMethod.Name;
            string cnt;

            try
            {
                cnt = Newtonsoft.Json.JsonConvert.SerializeObject(context.Parameters);
            }
            catch { cnt = "没有获取到方法参数值。"; }
            Listener.Write(LogTypeEnum.MethodEntry, className, methodName, cnt);
            var t = context.Invoke(next);

            if (t.Exception != null)
            {
                string cont;
                try
                {
                    cont = Newtonsoft.Json.JsonConvert.SerializeObject(t.Exception);
                }
                catch { cont = t.Exception.Message + "\r\nStackTrace:\r\n" + t.Exception.StackTrace; }
                Listener.Write(LogTypeEnum.MethodException, className, methodName, cont);
            }
            else
            {
                try
                {
                    bool   isTask = context.ImplementationMethod.ReturnType.IsGenericType && context.ImplementationMethod.ReturnType.GetGenericTypeDefinition() == typeof(Task <>);
                    object realResult;
                    if (isTask)
                    {
                        realResult = context.ImplementationMethod.ReturnType.GetProperty("Result", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).GetValue(context.ReturnValue);
                    }
                    else
                    {
                        realResult = context.ReturnValue;
                    }
                    Listener.Write(LogTypeEnum.MethodLeave, className, methodName, Newtonsoft.Json.JsonConvert.SerializeObject(realResult));
                }
                catch
                {
                    Listener.Write(LogTypeEnum.MethodLeave, className, methodName, "没有获取到方法返回值。");
                }
            }
            return(t);
        }
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            await context.Invoke(next);

            var para = context.Parameters?.FirstOrDefault();

            if (para is int num)
            {
                for (var i = 0; i < num - 1; i++)
                {
                    await context.Invoke(next);
                }
            }
        }
示例#5
0
            public override async Task Invoke(AspectContext context, AspectDelegate next)
            {
                if (context.Proxy is Service service)
                {
                    service.CurrentValue = null;
                    await context.Invoke(next);

                    var value = await context.UnwrapAsyncReturnValue();

                    service.CurrentValue = value;
                }
                else
                {
                    await context.Invoke(next);
                }
            }
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var dataValidator = context.ServiceProvider.GetService(typeof(IDataValidator)) as IDataValidator;

            CheckResolved(dataValidator);
            var dataStateFactory = context.ServiceProvider.GetService(typeof(IDataStateFactory)) as IDataStateFactory;

            CheckResolved(dataStateFactory);
            var dataValidationContext = new DataValidationContext(context);

            dataValidator.Validate(dataValidationContext);
            context.SetDataValidationContext(dataValidationContext);
            var dataState = dataStateFactory.CreateDataState(dataValidationContext);

            if (context.Implementation is IDataStateProvider dataStateProvider)
            {
                dataStateProvider.DataState = dataState;
            }
            else
            {
                var implementationTypeInfo = context.Implementation.GetType().GetTypeInfo();
                var dataStateProperty      = implementationTypeInfo.GetProperty("DataState");
                if (dataStateProperty != null && dataStateProperty.CanWrite)
                {
                    dataStateProperty.GetReflector().SetValue(context.Implementation, dataState);
                }
            }
            return(context.Invoke(next));
        }
示例#7
0
        /// <summary>
        /// 动态拦截的方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var Key = new Cachekey(context.ServiceMethod, context.Parameters).GetHashCode();

            if (memoryCache.TryGetValue(Key, out object value))
            {
                context.ReturnValue = ((MemoryCacheEntity)value).ReturnValue;
                var Parameters = ((MemoryCacheEntity)value).Parameters;
                if (context.Parameters != null && Parameters != null && Parameters.Length == context.Parameters.Length)
                {
                    for (int i = 0; i < context.Parameters.Length; i++)
                    {
                        context.Parameters[i] = Parameters[i];
                    }
                }
            }
            else
            {
                await context.Invoke(next);

                if (CachingTime <= 0)
                {
                    //不过期
                    memoryCache.Set(Key, new MemoryCacheEntity(context.ReturnValue, context.Parameters));
                }
                else
                {
                    memoryCache.Set(Key, new MemoryCacheEntity(context.ReturnValue, context.Parameters), new TimeSpan(0, 0, CachingTime));
                }
            }
        }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var Parameters = context.Parameters;
            await context.Invoke(next);

            var result = context.IsAsync() ? await context.UnwrapAsyncReturnValue(): context.ReturnValue;
        }
示例#9
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var parameters = context.ServiceMethod.GetParameters();

            //判断Method是否包含ref / out参数
            if (parameters.Any(it => it.IsIn || it.IsOut))
            {
                await next(context);
            }
            else
            {
                var key = string.IsNullOrEmpty(CacheKey)
                    ? new CacheKey(context.ServiceMethod, parameters).GetHashCode().ToString()
                    : CacheKey;
                if (_cache.TryGetValue(key, out object value))
                {
                    context.ReturnValue = value;
                }
                else
                {
                    await context.Invoke(next);

                    _cache.Set(key, context.ReturnValue, new MemoryCacheEntryOptions()
                    {
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(Expiration)
                    });
                    await next(context);
                }
            }
        }
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var parameters = context.ServiceMethod.GetParameters();

            //判断Method是否包含ref / out参数
            if (parameters.Any(it => it.IsIn || it.IsOut))
            {
                await next(context);
            }
            else
            {
                var key = string.IsNullOrEmpty(CacheKey)
                    ? new CacheKey(context.ServiceMethod, parameters).GetHashCode().ToString()
                    : CacheKey;
                var value = await DistributedCacheManager.GetAsync(key);

                if (value != null)
                {
                    context.ReturnValue = value;
                }
                else
                {
                    await context.Invoke(next);

                    await DistributedCacheManager.SetAsync(key, context.ReturnValue, Expiration);
                    await next(context);
                }
            }
        }
示例#11
0
        /// <summary>
        /// 执行被拦截方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        private async Task <object> RunAndGetReturn(AspectContext context, AspectDelegate next)
        {
            await context.Invoke(next);

            return(context.IsAsync()
            ? await context.UnwrapAsyncReturnValue()
            : context.ReturnValue);
        }
            public override async Task Invoke(AspectContext context, AspectDelegate next)
            {
                await context.Invoke(next);

                var result = (int)context.ReturnValue;

                context.ReturnValue = result + 2;
            }
示例#13
0
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            IAsyncPolicy policy = null;

            if (MaxRetryTimes > 0)
            {
                policy = Policy.Handle <Exception>().RetryAsync(MaxRetryTimes);
            }
            if (policy == null)
            {
                return(context.Invoke(next));
            }
            else
            {
                return(policy.ExecuteAsync(() => context.Invoke(next)));
            }
        }
示例#14
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var sw = Stopwatch.StartNew();

            if (Env.IsDevelopment)
            {
                for (int i = 0; i < ExecuteCount; i++)
                {
                    await context.Invoke(next);
                }
            }
            else
            {
                await context.Invoke(next);
            }
            sw.Stop();
            Logger.LogWarning($"【{context.Implementation}.{context.ServiceMethod.Name}】【params:{string.Join(",", context.Parameters)}】:{sw.ElapsedMilliseconds}ms");
        }
示例#15
0
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            Assert.True(context.IsAsync());
            await context.Invoke(next);

            var result = context.UnwrapAsyncReturnValue();

            Assert.Equal(100, result);
        }
示例#16
0
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var serviceType = context.ServiceMethod.DeclaringType;

            if (excepts.Any(x => serviceType.Name.Matches(x)) || excepts.Any(x => serviceType.Namespace.Matches(x)) || context.Implementation is IServiceTracer)
            {
                await context.Invoke(next);

                return;
            }
            await ServiceTracer?.ChildTraceAsync(context.ServiceMethod.GetReflector().DisplayName, DateTimeOffset.UtcNow, async span =>
            {
                span.Log(LogField.CreateNew().MethodExecuting());
                span.Tags.Set("ServiceType", context.ServiceMethod.DeclaringType.GetReflector().FullDisplayName);
                span.Tags.Set("ImplementationType", context.ImplementationMethod.DeclaringType.GetReflector().FullDisplayName);
                await context.Invoke(next);
                span.Log(LogField.CreateNew().MethodExecuted());
            });
        }
示例#17
0
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            Task      t  = null;
            Exception ex = null;

            try
            {
                t = context.Invoke(next);
            }
            catch (Exception e) { ex = e; }
            if (t != null && t.Exception != null)
            {
                ex = t.Exception;
            }
            if (ex != null && context.ProxyMethod.ReturnType == typeof(IApiResultModel))
            {
                Exception exception = ex.GetInnerException();
                if (exception is ServiceException)
                {
                    context.ReturnValue = new ApiResultModelNoData()
                    {
                        code        = 1001,
                        enumMsgType = null,
                        message     = exception.Message,
                        result      = false,
                        time        = DateTime.Now.ToTimeStamp(true).ToString()
                    };
                }
                else if (exception is System.Threading.Tasks.TaskCanceledException)
                {
                    context.ReturnValue = ApiResultModel.FromError("第三方服务暂时不可用,请稍候再试。");
                }
                else if (exception is SqlException)
                {
                    if (exception.Message.StartsWith("timeout", StringComparison.OrdinalIgnoreCase))
                    {
                        context.ReturnValue = ApiResultModel.FromError("数据库连接超时,请稍候再试。");
                    }
                    else
                    {
                        context.ReturnValue = ApiResultModel.FromError("数据库执行错误,请稍候再试。");
                    }
                }
                else
                {
                    context.ReturnValue = ApiResultModel.FromError(exception.Message);
                }
                return(Task.CompletedTask);
            }
            else
            {
                return(t);
            }
        }
示例#18
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            await Task.Delay(100);

            if (context.Proxy is AwaitBeforeInvokeTester tester &&
                tester.Cts.IsCancellationRequested)
            {
                context.ReturnValue = Task.FromResult(-1);
                return;
            }
            await context.Invoke(next);
        }
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            IList <Tuple <string, string> > values = new List <Tuple <string, string> >
            {
                new Tuple <string, string>("key1", "value1"),
                new Tuple <string, string>("key2", "value2"),
                new Tuple <string, string>("key3", "value3")
            };

            //bool added = await _redisCacheClient.Db15.AddAllAsync(values);
            await context.Invoke(next);
        }
示例#20
0
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            Console.WriteLine("Permission Interceptor...");

            if (PermissionStore.HasPermission(Context.GetRole(), _module, _function))
            {
                return(context.Invoke(next));
            }

            Console.WriteLine($"Has no permission to call : module --> {_module}, function --> {_function} ");
            return(Task.CompletedTask);
        }
 public override async Task Invoke(AspectContext context, AspectDelegate next)
 {
     try
     {
         await context.Invoke(next);
     }
     catch (Exception ex)
     {
         if (!ex.Message.EndsWith($"-{ReturnedStatus.AbnormalCode}."))
         {
             var logService = FrameWorkService.ServiceProvider.GetService <ISysAbnormalLogService>();
             var log        = new Sys_AbnormalLog();
             log.Body         = context.Parameters.ObjectToJson();
             log.ErrorMessage = ex.ToString();
             log.RequestUrl   = context.ImplementationMethod.ReflectedType.FullName + "." + context.ImplementationMethod.Name;
             log.ClientIp     = FrameWorkService.ServiceProvider.GetService <IHttpContextAccessor>().HttpContext.Connection.RemoteIpAddress.ToString();
             log.SetUserToModelCreate();
             var id           = logService.InsertReturnIdentity(log);
             var returnedData = new ReturnedDataResult()
             {
                 Status  = ReturnedStatus.AbnormalCode,
                 Message = $"请联系开发人员 logid:{id}!"
             };
             ////创建并返回继承自ReturnedResult的return对象
             if (context.ProxyMethod.ReturnType == typeof(ReturnedDataResult))
             {
                 context.ReturnValue = returnedData;
             }
             else
             {
                 throw new Exception($"@{returnedData.Message}-{ returnedData.Status }");
             }
         }
         else
         {
             if (context.ProxyMethod.ReturnType == typeof(ReturnedDataResult))
             {
                 context.ReturnValue = new ReturnedDataResult()
                 {
                     Status  = ReturnedStatus.AbnormalCode,
                     Message = ex.Message.Substring(ex.Message.IndexOf("@") + 1).Replace($"-{ReturnedStatus.AbnormalCode}.", string.Empty)
                 };
             }
             else
             {
                 throw new Exception(ex.Message);
             }
         }
     }
 }
示例#22
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var typeFullName = context.ServiceMethod.DeclaringType.FullName;
            var method       = context.ServiceMethod.Name;
            var args         = string.Join(",", context.Parameters);

            var cachingKey = $"{typeFullName}_{method}_{args}".Trim('_');

            if (_memoryCache.TryGetValue(cachingKey, out var cachingValue))
            {
                context.ReturnValue = cachingValue;
                return;
            }
            if (string.IsNullOrEmpty(cachingKey))
            {
                await context.Invoke(next);

                return;
            }
            await context.Invoke(next);

            _memoryCache.Set(cachingKey, context.ReturnValue, DateTimeOffset.Now.AddMilliseconds(ExpireMS));
        }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            await context.Invoke(next);

            if (context.Implementation is IConnectionMultiplexer connectionMultiplexer)
            {
                var database = (IDatabase)context.ReturnValue;
                if (!database.IsProxy())
                {
                    var proxyGenerator = (IProxyGenerator)context.ServiceProvider.GetService(typeof(IProxyGenerator));
                    context.ReturnValue = proxyGenerator.CreateInterfaceProxy <IDatabase>(database);
                }
            }
        }
示例#24
0
 public async override Task Invoke(AspectContext context, AspectDelegate next)
 {
     try
     {
         await context.Invoke(next);
     }
     catch (Exception ex)
     {
         var    fallBackMethod = context.ServiceMethod.DeclaringType.GetMethod(FallBackMethodName);
         object fallBackResult = fallBackMethod.Invoke(context.Implementation, context.Parameters);
         context.ReturnValue = fallBackResult;
         await Task.FromResult(0);
     }
 }
示例#25
0
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            List <string> errors = new List <string>();

            var param = context.Parameters[0];
            var tem   = validateErrors(param);

            errors.AddRange(tem);
            if (errors.Count > 0)
            {
                throw new ParameterValidateException(Newtonsoft.Json.JsonConvert.SerializeObject(errors));
            }
            return(context.Invoke(next));
        }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            await context.Invoke(next);

            if (context.Implementation is IConnectionMultiplexer connectionMultiplexer)
            {
                var subscriber = (ISubscriber)context.ReturnValue;
                if (!subscriber.IsProxy())
                {
                    var proxyGenerator = context.ServiceProvider.Resolve <IProxyGenerator>();
                    context.ReturnValue = proxyGenerator.CreateInterfaceProxy <ISubscriber>(subscriber);
                }
            }
        }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var serviceType = context.ServiceMethod.DeclaringType;

            if (excepts.Contains(serviceType.Name) || excepts.Contains(serviceType.Namespace) || context.Implementation is ILogger)
            {
                await context.Invoke(next);

                return;
            }
            var       logger    = (ILogger <MethodExecuteLoggerInterceptor>)context.ServiceProvider.GetService(typeof(ILogger <MethodExecuteLoggerInterceptor>));
            Stopwatch stopwatch = Stopwatch.StartNew();
            await context.Invoke(next);

            stopwatch.Stop();
            logger?.LogInformation("Executed method {0}.{1}.{2} ({3}) in {4}",
                                   context.ServiceMethod.DeclaringType.Namespace,
                                   context.ServiceMethod.DeclaringType.GetReflector().DisplayName,
                                   context.ServiceMethod.Name,
                                   context.ServiceMethod.DeclaringType.Assembly.GetName().Name,
                                   stopwatch.Elapsed
                                   );
        }
示例#28
0
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            ISyncPolicy policy = null;

            if (MaxRetryTimes > 0)
            {
                if (HandleTimeoutOnly)
                {
                    policy = Policy.Handle <TimeoutRejectedException>().Retry(MaxRetryTimes);
                }
                else
                {
                    policy = Policy.Handle <Exception>().Retry(MaxRetryTimes);
                }
            }
            if (TimeoutByMillisecond > 0)
            {
                var timeoutPolicy = Policy.Timeout(TimeSpan.FromMilliseconds(TimeoutByMillisecond), Polly.Timeout.TimeoutStrategy.Pessimistic);
                if (policy == null)
                {
                    policy = timeoutPolicy;
                }
                else
                {
                    policy = policy.Wrap(timeoutPolicy);
                }
            }
            if (policy == null)
            {
                return(context.Invoke(next));
            }
            else
            {
                return(policy.Execute(() => context.Invoke(next)));
            }
        }
 public override async Task Invoke(AspectContext context, AspectDelegate next)
 {
     try
     {
         await context.Invoke(next);
     }
     catch (AccessViolationException ex)
     {
         context.ReturnValue = "404";
     }
     catch (Exception ex)
     {
         context.ReturnValue = "404";
     }
 }
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var impType    = context.Implementation.GetType();
            var properties = impType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                             .Where(p => p.IsDefined(typeof(FromDbContextFactoryAttribute))).ToList();

            if (properties.Any())
            {
                foreach (var property in properties)
                {
                    var attribute = property.GetCustomAttribute <FromDbContextFactoryAttribute>();
                    var dbContext = context.ServiceProvider.GetDbContext(attribute.DbContextTagName);
                    property.SetValue(context.Implementation, dbContext);
                }
            }
            return(context.Invoke(next));
        }