public void Invoke(AspectContext container, AspectIntercept intercept)
        {
            if (intercept == AspectIntercept.Prolog)
            {
                var builder = new StringBuilder();

                builder.Append(string.Format("{0} with Parameters: ", container.Name));

                foreach (var param in container)
                {
                    builder.Append(string.Format("{0} : {1} | ", param.Name, param.Value));
                }

                Console.WriteLine(builder.ToString());
            }

            if (intercept == AspectIntercept.Epilog)
            {
                Console.WriteLine(container.HasReturnValue
                                          ? string.Format("{0} returned with value {1}", container.Name, container.ReturnValue)
                                          : string.Format("{0} returned", container.Name));
            }

            if (intercept == AspectIntercept.Exception)
            {
                Console.WriteLine(string.Format("EXCPETION in {0} with message: {1}", container.Name, container.Exception.Message));
                container.IsHandeled = true;
            }
        }
        public int LogChangedValue(AspectContext context)
        {
            var entity = (BaseEntity)context.Method.Args[0];
            Dictionary<string, EntityColumn> changedColumns = entity.GetChangedColumns();
            if (changedColumns.Count == 0)
                return 0;

            var logContext = new LogContext {EntityName = entity.EntityName, TableName = entity.TableName};

            foreach (var c in changedColumns)
            {
                logContext.Values.Add(c.Key, new ChangedEntityColumn(c.Value.OldValue, c.Value.CurrentValue));
            }

            try
            {
                LogManager.Instance.Write(logContext, true);
            }
            catch (Exception exp)
            {
                throw exp;
            }

            return changedColumns.Count;
        }
Beispiel #3
0
 public async override Task Invoke(AspectContext context, AspectDelegate next)
 {
     try
     {
         Console.WriteLine("Before service call");
         await next(context);//执行被拦截的方法
     }
     catch (Exception)
     {
         Console.WriteLine("Service threw an exception!");
         throw;
     }
     finally
     {
         Console.WriteLine("After service call");
     }
 }
Beispiel #4
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var transaction = SmartSqlContainer.Instance.GetSmartSql(Alias).SqlMapper;

            try
            {
                transaction.BeginTransaction();
                await next.Invoke(context);

                transaction.CommitTransaction();
            }
            catch (Exception ex)
            {
                transaction.RollbackTransaction();
                throw ex;
            }
        }
        /// <summary>
        /// 方法参数放进字典
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Dictionary <string, object> GetParameterDictoryFromContext(AspectContext context)
        {
            var parameterDic   = new Dictionary <string, object>();
            var parameterInfos = context.ProxyMethod.GetParameters();

            if (!parameterInfos.Any())
            {
                return(parameterDic);
            }

            for (var i = 0; i < parameterInfos.Length; i++)
            {
                parameterDic.Add(parameterInfos[i].Name, context.Parameters[i]);
            }

            return(parameterDic);
        }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            await next.Invoke(context);

            //Console.WriteLine($"______before->{context.ServiceMethod.Name}:Completed;DothingAfterExecuting");
            if (context.ProxyMethod.Name.Contains("GetAsync"))
            {
                if (context.ReturnValue is Task <System.Collections.Generic.List <DBModel.Entity.TbUser> > )
                {
                    var rtnVal = context.ReturnValue as Task <System.Collections.Generic.List <DBModel.Entity.TbUser> >;
                    rtnVal.Result.Add(new DBModel.Entity.TbUser()
                    {
                        Name = "Test"
                    });
                }
            }
        }
        /// <summary>
        /// 执行后
        /// </summary>
        /// <param name="log">日志操作</param>
        /// <param name="context">Aspect上下文</param>
        /// <param name="methodName">方法名</param>
        private async Task ExecuteAfter(ILog log, AspectContext context, string methodName)
        {
            if (context.ServiceMethod.ReturnType == typeof(Task) ||
                context.ServiceMethod.ReturnType == typeof(void) ||
                context.ServiceMethod.ReturnType == typeof(ValueTask))
            {
                return;
            }
            var returnValue = context.IsAsync() ? await context.UnwrapAsyncReturnValue() : context.ReturnValue;

            var returnType = returnValue.GetType().FullName;

            log.Caption($"{context.ServiceMethod.Name}方法执行后")
            .Method(methodName)
            .Content($"返回类型: {returnType}, 返回值: {returnValue.SafeString()}");
            WriteLog(log);
        }
        /// <summary>
        /// 执行
        /// </summary>
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            await next(context);

            var manager = context.ServiceProvider.GetService <IUnitOfWorkManager>();

            if (manager == null)
            {
                return;
            }
            await manager.CommitAsync();

            if (context.Implementation is ICommitAfter service)
            {
                service.CommitAfter();
            }
        }
Beispiel #9
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var sessionStore = context.ServiceProvider.GetSessionStore(Alias);

            if (sessionStore == null)
            {
                throw new SmartSqlException($"can not find SmartSql instance by Alias:{Alias}.");
            }
            var inTransaction = sessionStore.LocalSession?.Transaction != null;

            if (inTransaction)
            {
                await next.Invoke(context); return;
            }

            using (sessionStore)
                using (var dbSession = sessionStore.Open())
                {
                    try
                    {
                        dbSession.BeginTransaction(Level);
                        await next.Invoke(context);

                        var canCommit = true;
                        if (CommitWhenReturnTrue)
                        {
                            canCommit = context.ServiceMethod.ReturnType == typeof(bool) && true == (bool)context.ReturnValue;
                        }

                        if (canCommit)
                        {
                            dbSession.CommitTransaction();
                        }
                        else
                        {
                            dbSession.RollbackTransaction();
                        }
                    }
                    catch (Exception ex)
                    {
                        dbSession.RollbackTransaction();
                        throw ex;
                    }
                }
        }
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            _ = context ?? throw new ArgumentNullException(nameof(context));
            _ = next ?? throw new ArgumentNullException(nameof(next));
            var mongoContext = GetCurrentMongoContext(context);

            if (mongoContext == null)
            {
                var logger =
                    context.ServiceProvider.GetService(
                        typeof(ILogger <>).MakeGenericType(context.ImplementationMethod.DeclaringType)) as ILogger;
                logger.LogWarning($"Can not find mongo context in current type '{context.ImplementationMethod.DeclaringType}', {nameof(TransactionAttribute)} will be ignored.");
                await next?.Invoke(context);

                return;
            }

            bool started = false;

            try
            {
                started = StartTransaction(mongoContext);
                await next?.Invoke(context);

                if (started)
                {
                    CommitTransaction(mongoContext);
                }
            }
            catch
            {
                if (started)
                {
                    RollbackTransaction(mongoContext);
                }
                throw;
            }
            finally
            {
                if (started)
                {
                    ResetTransaction(mongoContext);
                }
            }
        }
Beispiel #11
0
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var cachedConfigurationProvider = context.ServiceProvider.GetService <IOptionsMonitor <FilterCachedConfiguration> >();
            var configCache = context.GetCacheConfigurationByMethodName(cachedConfigurationProvider.CurrentValue);

            var methodReturnType = context.ProxyMethod.ReturnType;

            if (
                configCache == null ||
                methodReturnType == typeof(void) ||
                methodReturnType == typeof(Task) ||
                methodReturnType == typeof(ValueTask)
                )
            {
                await next(context);

                return;
            }

            if (string.IsNullOrWhiteSpace(CacheName))
            {
                CacheName = context.GetGenerateKeyByMethodNameAndValues();
            }

            ResponseCacheService = context.ServiceProvider.GetService <IResponseCacheService>();

            var returnType = context.IsAsync() ? methodReturnType.GenericTypeArguments.FirstOrDefault() : methodReturnType;

            var cachedValue = await ResponseCacheService.GetCachedResponseAsync(CacheName, returnType);

            if (cachedValue != null)
            {
                context.SetReturnType(methodReturnType, cachedValue);
                return;
            }

            await next(context);

            await ResponseCacheService
            .SetCacheResponseAsync(
                CacheName,
                await context.GetReturnValueAsync(),
                TimeSpan.FromSeconds(configCache.TimeToLiveSeconds ?? TimeToLiveSeconds)
                );
        }
Beispiel #12
0
        public Task Invoke(AspectContext context, AspectDelegate next)
        {
            try
            {
                // Buraya yazılan kodlar before

                return(next.Invoke(context).ContinueWith(task =>
                {
                    // buraya yazılan kodlar finish
                }));
            }
            catch (Exception ex)
            {
                //log ex yazdır.

                throw;
            }
        }
 public override async Task Invoke(AspectContext context, AspectDelegate next)
 {
     try
     {
         await next(context);//执行被拦截的方法
     }
     catch (Exception ex)
     {
         //context.ServiceMethod被拦截的方法。context.ServiceMethod.DeclaringType被拦截方法所在的类
         //context.Implementation实际执行的对象p
         //context.Parameters方法参数值
         //如果执行失败,则执行FallBackMethod
         var    fallBackMethod = context.ServiceMethod.DeclaringType.GetMethod(this.FallBackMethod);
         Object fallBackResult = fallBackMethod.Invoke(context.Implementation, context.Parameters);
         context.ReturnValue = fallBackResult;
         await Task.FromResult(0);
     }
 }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var     logger   = context.ServiceProvider.GetService(typeof(ILogger <SystemLogsAttribute>)) as ILogger <SystemLogsAttribute>;
            dynamic paramObj = context.Parameters.FirstOrDefault();
            string  param    = JsonConvert.SerializeObject(paramObj);
            string  key      = "Param:" + param;

            logger.LogInformation(key);
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                throw;
            }
        }
Beispiel #15
0
        public async Task Process()
        {
            var data = await ActualWordsHandler.InstanceSimple.TextSplitter.Process(new ParseRequest("I like my school teacher.")).ConfigureAwait(false);

            var document = data.Construct(ActualWordsHandler.InstanceSimple.WordFactory);
            var review   = ActualWordsHandler.InstanceSimple.Container.Resolve <Func <Document, IParsedReviewManager> >()(document).Create();
            var context  = new AspectContext(true, review.ImportantWords.ToArray());

            context.Process();
            var attributes = context.GetAttributes().ToArray();
            var features   = context.GetFeatures().ToArray();

            Assert.AreEqual(1, attributes.Length);
            Assert.AreEqual("like", attributes[0].Text);
            Assert.AreEqual(2, features.Length);
            Assert.IsTrue(features.Any(item => item.Text == "school"));
            Assert.IsTrue(features.Any(item => item.Text == "teacher"));
        }
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            using (var trans = DbContext.Database.BeginTransaction())
            {
                try
                {
                    await next(context);

                    DbContext.SaveChanges();
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
        public IAspectBuilder Create(AspectContext context)
        {
            var aspectBuilder = new AspectBuilder(ctx => ctx.Complete(), null);

            foreach (var interceptor in _interceptorCollector.Collect(context.ServiceMethod, context.ImplementationMethod))
            {
                if (interceptor is IScopeInterceptor scopedInterceptor)
                {
                    if (!_aspectContextScheduler.TryRelate(context as ScopeAspectContext, scopedInterceptor))
                    {
                        continue;
                    }
                }
                aspectBuilder.AddAspectDelegate(interceptor.Invoke);
            }

            return(aspectBuilder);
        }
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var parameters = context.GetParameters();
            var param      = parameters.FirstOrDefault(x => x.ParameterInfo.GetCustomAttribute <FromCapAttribute>() != null);

            if (param == null)
            {
                await next(context);

                return;
            }

            if (param.Value is CapHeader capHeader)
            {
                InitTraceIdContext(capHeader);
                await next(context);
            }
        }
        /// <summary>
        /// 执行
        /// </summary>
        /// <returns></returns>
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var cacheKey   = GenerateCacheKey(context, ParamCount);
            var type       = context.ServiceMethod.ReturnType;
            var cacheValue = CacheProvider.Get(cacheKey, type);

            if (cacheValue.HasValue)
            {
                context.ReturnValue = cacheValue.Value;
                return;
            }
            await next(context);

            if (!string.IsNullOrWhiteSpace(cacheKey))
            {
                CacheProvider.Set(cacheKey, context.ReturnValue, TimeSpan.FromSeconds(Expiration));
            }
        }
 public async override Task Invoke(AspectContext context, AspectDelegate next)
 {
     try
     {
         Logger.LogInformation($"{context.Implementation}. { context.ProxyMethod.Name} 开始执行!");
         SetTokenValue(context);
         await next(context);
     }
     catch (Exception exc)
     {
         Logger.LogError($"异常发生:{exc.Message}");
         throw exc;
     }
     finally
     {
         Logger.LogInformation($"{context.Implementation}. { context.ProxyMethod.Name} 执行结束!");
     }
 }
Beispiel #21
0
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            if (string.IsNullOrEmpty(Sql))
            {
                throw new ArgumentNullException(nameof(Sql));
            }

            var paramters   = context.GetParameters();
            var queryParams = ToParamterDict(paramters);

            using (var conn = ConnectionFactory.CreateConnection(ConnectionName))
            {
                var result = QueryHelper.RunGenericCount(context.ServiceMethod.ReturnType, conn, Sql, queryParams);
                context.ReturnValue = result;
            }

            return(context.Break());
        }
Beispiel #22
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");
        }
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            await using var tran =
                            EfNestedTransactionContext.BeginNestedTransaction(DbContextType, context.ServiceProvider, IsolationLevel);

            try
            {
                await next(context);

                await tran.CommitAsync();
            }
            catch
            {
                await tran.RollbackAsync();

                throw;
            }
        }
Beispiel #24
0
 public override async Task Invoke(AspectContext context, AspectDelegate next)
 {
     try
     {
         var unitOfWork = (IUnitOfWork)context.ServiceProvider.GetService(typeof(IUnitOfWork));
         if (unitOfWork.IsNotNull())
         {
             await unitOfWork.UseTransactionAsync(async() =>
             {
                 await next(context);
             });
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Beispiel #25
0
        public async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var _uowHelper = context.ServiceProvider.Resolve <IUowHelper>();

            if (_uowHelper.IsExistUow)
            {
                await next(context);
            }
            else
            {
                using (var uow = _uowHelper.Create())
                {
                    await next(context);

                    uow.Commit();
                }
            }
        }
        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(FromDbOptionAttribute))).ToList();

            if (properties.Any())
            {
                var options = context.ServiceProvider.GetServices <IOptions <DbContextOption> >().ToList();
                foreach (var property in properties)
                {
                    var attribute = property.GetCustomAttribute <FromDbOptionAttribute>();
                    var option    = options.FirstOrDefault(m => m.Value.TagName == attribute.TagName);
                    property.SetValue(context.Implementation, option);
                }
            }
            return(context.Invoke(next));
        }
        /// <summary>
        /// 执行
        /// </summary>
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var methodName = GetMethodName(context);
            var log        = Log.GetLog(methodName);

            try {
                await next(context);
            }
            catch (Exception ex) {
                log.Class(context.ServiceMethod.DeclaringType.FullName).Method(methodName).Exception(ex);
                foreach (var parameter in context.GetParameters())
                {
                    parameter.AppendTo(log);
                }
                log.Error();
                throw;
            }
        }
        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, context.Parameters).GetRedisCacheKey()
                    : CacheKey;
                var value = await DistributedCacheManager.GetAsync(key);

                if (value != null)
                {
                    if (context.ServiceMethod.IsReturnTask())
                    {
                        dynamic result = JsonConvert.DeserializeObject(value,
                                                                       context.ServiceMethod.ReturnType.GenericTypeArguments[0]);
                        context.ReturnValue = Task.FromResult(result);
                    }
                    else
                    {
                        context.ReturnValue = JsonConvert.DeserializeObject(value, context.ServiceMethod.ReturnType);
                    }
                }
                else
                {
                    await context.Invoke(next);

                    dynamic returnValue = context.ReturnValue;
                    if (context.ServiceMethod.IsReturnTask())
                    {
                        returnValue = returnValue.Result;
                    }
                    await DistributedCacheManager.SetAsync(key, returnValue, Expiration);

                    //await next(context);
                }
            }
        }
        private AsyncPolicy BuildPolicy(AspectContext context, AsyncPolicy policy)
        {
            if (policy != null)
            {
                return(policy);
            }

            policy = Policy.NoOpAsync();
            if (IsEnableCircuitBreaker)
            {
                policy = policy.WrapAsync(Policy.Handle <Exception>().CircuitBreakerAsync(
                                              ExceptionsAllowedBeforeBreaking,
                                              TimeSpan.FromMilliseconds(MillisecondsOfBreak)));
            }

            if (TimeOutMilliseconds > 0)
            {
                policy = policy.WrapAsync(Policy.TimeoutAsync(() => TimeSpan.FromMilliseconds(TimeOutMilliseconds),
                                                              Polly.Timeout.TimeoutStrategy.Pessimistic));
            }

            if (MaxRetryTimes > 0)
            {
                policy = policy.WrapAsync(Policy.Handle <Exception>().WaitAndRetryAsync(MaxRetryTimes,
                                                                                        i => TimeSpan.FromMilliseconds(RetryIntervalMilliseconds)));
            }

            var policyFallBack = Policy
                                 .Handle <Exception>()
                                 .FallbackAsync((ctx, t) =>
            {
                var aspectContext         = (AspectContext)ctx["aspectContext"];
                var fallBackMethod        = context.ServiceMethod?.DeclaringType?.GetMethod(FallBackMethod);
                var fallBackResult        = fallBackMethod?.Invoke(context.Implementation, context.Parameters);
                aspectContext.ReturnValue = fallBackResult;

                return(Task.FromResult(fallBackResult));
            }, async(ex, t) => throw ex);

            policy = policyFallBack.WrapAsync(policy);
            policies.TryAdd(context.ServiceMethod, policy);

            return(policy);
        }
Beispiel #30
0
        /// <summary>执行拦截业务,并根据返回结果决定提交事务还是回滚</summary>
        /// <param name="context">切面上下文</param>
        /// <param name="next">被拦截并包装的操作</param>
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            IServiceProvider   provider          = context.ServiceProvider;
            IUnitOfWorkManager unitOfWorkManager = provider.GetService <IUnitOfWorkManager>();

            try
            {
                await next(context);

                if (!RequiredCheckReturnValue)
                {
#if NET5_0
                    await unitOfWorkManager.CommitAsync();
#else
                    unitOfWorkManager.Commit();
#endif
                    return;
                }
                Type returnType = context.ProxyMethod.ReturnType;
                ITransactionDecision decision = provider.GetServices <ITransactionDecision>()
                                                .FirstOrDefault(m => m.IsFit(returnType));
                if (decision == null)
                {
                    throw new OsharpException($"无法找到与结果类型 {returnType} 匹配的 {typeof(ITransactionDecision)} 事务裁决器,请继承接口实现一个");
                }
                if (decision.CanCommit(context.ReturnValue))
                {
#if NET5_0
                    await unitOfWorkManager.CommitAsync();
#else
                    unitOfWorkManager.Commit();
#endif
                }
            }
            catch (Exception)
            {
#if NET5_0
                await unitOfWorkManager.CommitAsync();
#else
                unitOfWorkManager.Commit();
#endif
                throw;
            }
        }
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            if (!IsOpen || Seconds <= 0)
            {
                await next(context);

                return;
            }

            try
            {
                var cacheService = context.ServiceProvider.GetService <ICacheService>();

                Type returnType = context.GetReturnType();

                string key = Utils.GetParamterKey(Prefix, Key, ParamterKey, context.Parameters);

                var result = cacheService.Get(key, returnType);

                if (result == null)
                {
                    await next(context);

                    var value = await context.GetReturnValue();

                    if (value != null)
                    {
                        cacheService.Set(key, TimeSpan.FromSeconds(Seconds), value);
                    }
                }
                else
                {
                    context.ReturnValue = context.ResultFactory(result, returnType, context.IsAsync());
                }
            }
            catch (Exception ex)
            {
                var logger = context.ServiceProvider.GetService <ILogger <CacheMethodAttribute> >();

                logger.LogError($"CacheMethod:Key:{Key},ParamterKey:{ParamterKey} {ex.FormatMessage()}");

                await next(context);
            }
        }
Beispiel #32
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var logger = context.ServiceProvider.GetService <ILogger <CustomInterceptorAttribute> >();

            try
            {
                logger.LogDebug("Before invoke");
                await next(context);
            }
            catch (Exception ex)
            {
                logger.LogError($"Exception is {ex}");
                throw;
            }
            finally
            {
                logger.LogDebug("After inovke");
            }
        }
Beispiel #33
0
 public void Invoke(AspectContext container, AspectIntercept intercept)
 {
     this.InvokeInternal(container, intercept);
 }
Beispiel #34
0
 public object Manipulate(AspectContext container, AspectIntercept intercept)
 {
     var ret = this.ManipulateInternal(container, intercept);
     container.IsManipulated = true;
     return ret;
 }
Beispiel #35
0
 protected abstract void InvokeInternal(AspectContext container, AspectIntercept intercept);
Beispiel #36
0
 protected abstract object ManipulateInternal(AspectContext container, AspectIntercept intercept);
 public void Invoke(AspectContext container, AspectIntercept intercept)
 {
     container.Implementation();
 }