Пример #1
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)
            {
                if (Level.HasValue)
                {
                    await sessionStore.Open().TransactionWrapAsync(Level.Value, async() =>
                    {
                        await next.Invoke(context);
                    });
                }
                else
                {
                    await sessionStore.Open().TransactionWrapAsync(async() =>
                    {
                        await next.Invoke(context);
                    });
                }
            }
        }
Пример #2
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            _ = context ?? throw new ArgumentNullException(nameof(context));
            _ = next ?? throw new ArgumentNullException(nameof(next));
            var dbContext = GetCurrentDbContext(context);

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

                return;
            }

            bool started = false;

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

                await dbContext.SaveChangesAsync();

                if (started)
                {
                    CommitTransaction(dbContext);
                }
            }
            catch
            {
                if (started)
                {
                    RollbackTransaction(dbContext);
                }

                throw;
            }
            finally
            {
                if (started)
                {
                    ResetTransaction(dbContext);
                }
            }
        }
        public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next)
        {
            await next.Invoke(aspectContext);


            //执行异常了不执行after 去执行Throw
            if (aspectContext.Exception != null)
            {
                return;
            }


            if (_afterAttribute != null)
            {
                await this._afterAttribute.AfterReturn(aspectContext, aspectContext.ReturnValue);
            }
            else
            {
                var rt = AutoConfigurationHelper.InvokeInstanceMethod(
                    _pointCutMethod.Instance,
                    _pointCutMethod.MethodInfo,
                    _pointCutMethod.MethodParameters,
                    aspectContext.ComponentContext,
                    aspectContext,
                    returnValue: aspectContext.ReturnValue,
                    returnParam: _pointCutMethod.PointcutBasicAttribute.Returing,
                    injectAnotation: _pointCutMethod.PointcutInjectAnotation);

                if (typeof(Task).IsAssignableFrom(_pointCutMethod.MethodReturnType))
                {
                    await((Task)rt).ConfigureAwait(false);
                }
            }
        }
        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 publisher = context.ServiceProvider.GetService <ICapPublisher>();

            if (publisher == null)
            {
                throw new SmartSqlException($"Unable to resolve service for type {typeof(ICapPublisher).FullName}.");
            }

            var transcation = sessionStore.LocalSession?.Transaction;

            if (transcation != null)
            {
                throw new SmartSqlException(
                          "SmartSqlMapper could not invoke BeginCapTransaction(). A CapTransaction is already existed.");
            }

            using (sessionStore)
            {
                await sessionStore.Open().CapTransactionWrapAsync(Level, publisher, async() =>
                {
                    await next.Invoke(context);
                }, AutoCommit);
            }
        }
Пример #5
0
        public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next)
        {
            try
            {
                if (!_isAfterAround)
                {
                    await next.Invoke(aspectContext);
                }
            }
            finally
            {
                //不管成功还是失败都会执行的
                if (_afterAttribute != null)
                {
                    await this._afterAttribute.After(aspectContext, aspectContext.Exception ?? aspectContext.ReturnValue);
                }
                else
                {
                    var rt = AutoConfigurationHelper.InvokeInstanceMethod(
                        _pointCutMethod.Instance,
                        _pointCutMethod.MethodInfo,
                        _pointCutMethod.MethodParameters,
                        aspectContext.ComponentContext,
                        aspectContext,
                        returnValue: aspectContext.Exception ?? aspectContext.ReturnValue,
                        returnParam: _pointCutMethod.PointcutBasicAttribute.Returing,
                        injectAnotation: _pointCutMethod.PointcutInjectAnotation);

                    if (typeof(Task).IsAssignableFrom(_pointCutMethod.MethodReturnType))
                    {
                        await((Task)rt).ConfigureAwait(false);
                    }
                }
            }
        }
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            _ = context ?? throw new ArgumentNullException(nameof(context));
            _ = next ?? throw new ArgumentNullException(nameof(next));
            var implParameters    = context.ImplementationMethod.GetParameters();
            var serviceParameters = context.ServiceMethod.GetParameters();

            for (int i = 0; i < implParameters.Length; i++)
            {
                var    implParameterInfo    = implParameters[i];
                var    serviceParameterInfo = serviceParameters[i];
                object value = context.Parameters[i];
                var    validationAttributes = validationAttributeCache.GetValidationAttributes(implParameterInfo, serviceParameterInfo);
                if (value is null)
                {
                    var nullValueContext = new ValidationContext(new object(), context.ServiceProvider, null)
                    {
                        MemberName = implParameterInfo.Name
                    };
                    Validator.ValidateValue(value, nullValueContext, validationAttributes);
                }
                else
                {
                    var objectContext = new ValidationContext(value, context.ServiceProvider, null)
                    {
                        MemberName = implParameterInfo.Name
                    };
                    Validator.ValidateValue(value, objectContext, validationAttributes);
                    Validator.ValidateObject(value, objectContext, true);
                }
            }
            return(next.Invoke(context));
        }
Пример #7
0
 public override Task Invoke(AspectContext context, AspectDelegate next)
 {
     using (SmartSqlContainer.Instance.GetSmartSql(Alias).SmartSqlConfig.SessionStore.Open())
     {
         return(next.Invoke(context));
     }
 }
Пример #8
0
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            Console.WriteLine("开始记录日志");
            await next.Invoke(context);

            Console.WriteLine("结束记录日志");
        }
Пример #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 Task Invoke(AspectContext context, AspectDelegate next)
        {
            // Buraya yazılan kodlar before

            return(next.Invoke(context).ContinueWith(task =>
            {
                // buraya yazılan kodlar after
            }));
        }
        public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next)
        {
            try
            {
                if (!_isFromAround)
                {
                    await next.Invoke(aspectContext);
                }
            }
            finally
            {
                //只有目标方法出现异常才会走 增强的方法出异常不要走
                if (aspectContext.Exception != null)
                {
                    Exception ex = aspectContext.Exception;
                    if (aspectContext.Exception is TargetInvocationException targetInvocationException)
                    {
                        ex = targetInvocationException.InnerException;
                    }

                    if (ex == null)
                    {
                        ex = aspectContext.Exception;
                    }

                    var currentExType = ex.GetType();

                    if (_pointcutThrowin != null)
                    {
                        if (_pointcutThrowin.PointcutBasicAttribute.ExceptionType == null || _pointcutThrowin.PointcutBasicAttribute.ExceptionType == currentExType)
                        {
                            var rt = AutoConfigurationHelper.InvokeInstanceMethod(
                                _pointcutThrowin.Instance,
                                _pointcutThrowin.MethodInfo,
                                _pointcutThrowin.MethodParameters,
                                aspectContext.ComponentContext,
                                aspectContext,
                                returnValue: ex,
                                returnParam: _pointcutThrowin.PointcutBasicAttribute.Throwing,
                                injectAnotation: _pointcutThrowin.PointcutInjectAnotation);
                            if (typeof(Task).IsAssignableFrom(_pointcutThrowin.MethodReturnType))
                            {
                                await((Task)rt).ConfigureAwait(false);
                            }
                        }
                    }
                    else
                    {
                        if (_aspectThrowing.ExceptionType == null || _aspectThrowing.ExceptionType == currentExType)
                        {
                            await _aspectThrowing.AfterThrows(aspectContext, aspectContext.Exception);
                        }
                    }
                }
            }
        }
Пример #12
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}.");
            }
            if (sessionStore.LocalSession != null)
            {
                await next.Invoke(context); return;
            }

            using (sessionStore)
            {
                sessionStore.Open();
                await next.Invoke(context);
            }
        }
Пример #13
0
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var dbSession = MapperContainer.Instance.GetSqlMapperByAlias(Alias);

            try
            {
                dbSession.BeginSession();
                return(next.Invoke(context));
            }
            finally
            {
                dbSession.EndSession();
            }
        }
Пример #14
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var apm_actived = context.ServiceProvider?.IsApmAgentConfigured() ?? false;

            if (apm_actived && this.__current_trans__(out var transaction))
            {
                var m           = context.ImplementationMethod;
                var type_name   = m.DeclaringType.FullName;
                var method_name = m.Name;

                var full_name = $"{type_name}.{method_name}";

                var span = transaction.StartSpan(full_name, type_name);

                var params_data = string.Join(",", m.GetParameters().Select(x => $"{x.ParameterType.Name} {x.Name}"));
                span.Labels["function"] = $"{m.ReturnType.FullName} {method_name}({params_data});";

                try
                {
                    await next.Invoke(context);
                }
                catch (Exception e)
                {
                    span.CaptureException(e);
                    throw;
                }
                finally
                {
                    span.End();
                }
            }
            else
            {
                //如果没有开启apm
                await next.Invoke(context);
            }
        }
Пример #15
0
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var transaction = MapperContainer.Instance.GetSqlMapperByAlias(Alias);

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

                transaction.CommitTransaction();
            }
            catch (Exception ex)
            {
                transaction.RollbackTransaction();
                throw ex;
            }
        }
        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"
                    });
                }
            }
        }
Пример #17
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;
            }
        }
Пример #18
0
        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            _ = context ?? throw new ArgumentNullException(nameof(context));
            _ = next ?? throw new ArgumentNullException(nameof(next));
            IAuditLogService auditLogService = context.ServiceProvider.GetRequiredService <IAuditLogService>();
            ITimeService     timeService     = context.ServiceProvider.GetRequiredService <ITimeService>();

            var record = new AuditLogRecord
            {
                ApplicationName =
                    this.ApplicationName ?? context.ServiceProvider.GetRequiredService <IHostEnvironment>().ApplicationName,
                FunctionName  = this.FunctionName ?? context.ImplementationMethod.DeclaringType.FullName,
                OperationName = this.OperationName ?? context.ServiceMethod.Name,
                StartTime     = await timeService.Current(),
                Operator      = Thread.CurrentPrincipal?.Identity?.Name,
                RequestIp     = "127.0.0.1",
                Arguments     = buildInputArguments(context)
            };

            try
            {
                await next.Invoke(context);

                record.Success = true;
                record.Message = this.BuildMessage(context);
                record.EndTime = await timeService.Current();

                record.Result = buildResult(context);
                await auditLogService.LogRecord(record);
            }
            catch (Exception e)
            {
                record.Message = e.Message;
                record.Success = false;
                record.EndTime = await timeService.Current();

                record.Result = ExceptionInfo.FromException(e);
                await auditLogService.LogRecord(record);

                throw;
            }
        }
        public async Task OnInvocation(AspectContext aspectContext, AspectDelegate next)
        {
            if (_beforeAttribute != null)
            {
                await this._beforeAttribute.Before(aspectContext);
            }
            else
            {
                var rt = AutoConfigurationHelper.InvokeInstanceMethod(
                    _pointCutMethod.Instance,
                    _pointCutMethod.MethodInfo,
                    _pointCutMethod.MethodParameters,
                    aspectContext.ComponentContext, aspectContext, injectAnotation: _pointCutMethod.PointcutInjectAnotation);
                if (typeof(Task).IsAssignableFrom(_pointCutMethod.MethodReturnType))
                {
                    await((Task)rt).ConfigureAwait(false);
                }
            }

            await next.Invoke(aspectContext);
        }
Пример #20
0
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            using (var transaction = Context.Database.BeginTransaction())
            {
                Logger.LogInformation("begin transaction");
                try
                {
                    await next.Invoke(context);

                    transaction.Commit();
                    Logger.LogInformation("commit transaction");
                }
                catch
                {
                    transaction.Rollback();
                    Logger.LogInformation("transaction rollback");

                    throw;
                }
            }
        }
Пример #21
0
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            string      functionCode = context.ImplementationMethod.GetFunctionCode();
            IAppContext appContext   = context.ServiceProvider.GetRequiredService <IAppContext>();
            string      contextValue = appContext.GetValue(ContextKey)?.ToString();
            var         throttleCode = new ThrottleCode
            {
                ContextKind  = ContextKey,
                FunctionCode = functionCode,
                ContextValue = contextValue
            };
            var throttleValue = new ThrottleValue();

            var throttleService = context.ServiceProvider.GetRequiredService <IThrottleService>();

            if (await throttleService.ShouldPass(throttleCode, throttleValue))
            {
                await next.Invoke(context);
            }
            else
            {
                throw new ApplicationException("Throttle limited.");
            }
        }
Пример #22
0
 /// <summary>
 /// Invokes the.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="next">The next.</param>
 /// <returns>A Task.</returns>
 public override async Task Invoke(AspectContext context, AspectDelegate next)
 {
     var policy = Policy.Handle <Exception>().RetryAsync(this.option.RetryCount);
     await policy.ExecuteAsync(() => next?.Invoke(context));
 }
 public async override Task Invoke(AspectContext context, AspectDelegate next)
 {
     //Console.WriteLine($"______DothingBeforeExecuting;next->{context.ServiceMethod.Name}");
     await next.Invoke(context);
 }