public void Advise(MethodAdviceContext context) { SnapshotProfile profile = Profile.Value; if (profile == null) { context.Proceed(); return; } if (!context.HasReturnValue) { return; } string folderPath = Path.Combine( profile.FolderPath, context.TargetType.FullName, context.TargetMethod.Name); string filePath = GetFilePath(context.TargetMethod, context.Arguments, folderPath); if (profile.Mode == SnapshotMode.Read) { context.ReturnValue = ReadReturnValue(context.TargetMethod, filePath); } else if (profile.Mode == SnapshotMode.Write) { context.Proceed(); WriteReturnValue(context.ReturnValue, context.TargetMethod, folderPath, filePath); } }
public void Advise(MethodAdviceContext context) { dynamic o = context.Target; o.Access++; context.Proceed(); }
public void Advise(MethodAdviceContext context) { var sp = new Stopwatch(); sp.Start(); var methodinfo = context.TargetType + "-" + context.TargetMethod.Name; var parameters = context.TargetMethod.GetParameters(); var sb = new StringBuilder(); for (var i = 0; i < parameters.Length; i++) { sb.Append($"参数名{parameters[i].Name}-值{JsonHelper.Serialize(context.Arguments[i])} "); } LogHelper.Info($"执行{methodinfo}方法,入参信息:{sb.ToString()}"); context.Proceed(); sp.Stop(); LogHelper.Info(context.HasReturnValue ? $"执行{methodinfo}完毕,耗时{sp.ElapsedMilliseconds}毫秒,返回值{JsonHelper.Serialize(context.ReturnValue)}。" : $"执行{methodinfo}完毕,耗时{sp.ElapsedMilliseconds}毫秒,本方法无返回值。"); }
public void Advise(MethodAdviceContext context) { Enabled = true; if (!Enabled) { return; } var stopwatch = new Stopwatch(); stopwatch.Start(); context.Proceed(); stopwatch.Stop(); var ms = stopwatch.Elapsed.Milliseconds; //if (ContainsInSet(context.TargetType?.Namespace)) foreach (var tt in TargetTypesSet) { if (context.TargetType.Namespace == null) { continue; } if (context.TargetType.Namespace.StartsWith(tt)) { foreach (var a in context.Arguments) { _logger.Trace(a.ToString()); } _logger.Trace($@" {context?.Target?.ToString()} {context?.TargetMethod} {ms}"); } } }
public void Advise(MethodAdviceContext context) { using (var transactionScope = new TransactionScope()) { if (context.Parameters[0] == null) { context.Parameters[0] = new SqlConntection(); } context.Proceed(); if (context.HasReturnValue) { bool success = (bool)context.ReturnValue; if (success) { transactionScope.Complete(); } } else { transactionScope.Complete(); } } }
/// <summary> /// 拦截方法 /// </summary> /// <param name="context">方法元数据</param> public void Advise(MethodAdviceContext context) { if (context.TargetMethod.IsDefined(typeof(RequireAuthorizationAttribute))) { //获取正在执行的方法路径 string methodPath = context.TargetMethod.GetMethodPath(); //验证登录信息是否为null if (Membership.LoginInfo == null) { throw new ApplicationException("当前登录信息为空,请重新登录!"); } //从登录信息中取出权限集 IEnumerable <string> currentAuthorityPaths = Membership.LoginInfo.LoginAuthorityInfos.Values.SelectMany(x => x).Select(x => x.AuthorityPath); //验证权限 if (currentAuthorityPaths.All(path => path != methodPath)) { throw new NoPermissionException("您没有权限,请联系系统管理员!"); } } context.Proceed(); }
public void Advise(MethodAdviceContext context) { try { //Method ya da class a gönderilen değerler alındı IList <object> arguments = context.Arguments; Console.WriteLine(context.TargetName + " Method'a girdi"); if (arguments != null && arguments.Count > 0) { foreach (var arg in arguments) { //değerler ekrana yazdırıldı Console.WriteLine("Parametre : " + arg); } } //Method işlemi yürütüldü context.Proceed(); Console.WriteLine(context.TargetName + " Methodan çıktı"); } catch (Exception ex) { Console.WriteLine("hata oluştu"); Debug.WriteLine(ex); } }
internal static async Task <object> ProceedAsync1(this MethodAdviceContext ctx) { ctx.Proceed(); if (!ctx.HasReturnValue) { return(null); } var task = ctx.ReturnValue as Task; if (task != null) { await task; // improve logic here we use MethodInfo.ReturnType (declared type) instead of task.GetType() which caused VoidTaskResult problem. var methodInfo = ctx.TargetMethod as MethodInfo; if (methodInfo != null && methodInfo.ReturnType.IsGenericType) { return(((dynamic)task).Result); } return(null); } return(ctx.ReturnValue); }
public void Advise(MethodAdviceContext context) { var target = (AsyncTest)context.Target; context.Proceed(); Assert.AreEqual(AsyncTest.FinalStep, target.AwaitStep); }
public void Advise(MethodAdviceContext context) { List <ValidationError> errors = new List <ValidationError>(); if (ArgumentNames) { ParameterInfo[] parameters = context.TargetMethod.GetParameters(); int i = 0; foreach (object argument in context.Arguments) { errors.AddRange(argument.ValidateAnnotations(parameters[i++].Name)); } } else { foreach (object argument in context.Arguments) { errors.AddRange(argument.ValidateAnnotations()); } } if (errors.Count > 0) { throw new ValidationException(errors.ToArray()); } context.Proceed(); }
public void Advise(MethodAdviceContext context) { var enter = JObject.FromObject(new { MethodName = context.TargetName, TargetType = context.TargetType.FullName, Arguments = new JArray(context.Arguments) }); // do things you want here this.Log().Info(enter.ToString()); context.Proceed(); // this calls the original method // do other things here if (context.HasReturnValue) { var retrn = JObject.FromObject(new { MethodName = context.TargetName, context.ReturnValue, }); this.Log().Info(retrn.ToString()); } }
public void Advise(MethodAdviceContext context) { Console.WriteLine("Before Run Method"); // do things you want here context.Proceed(); // this calls the original method // do other things here }
public void Advise(MethodAdviceContext context) { try { var tname = context.TargetName; var fname = context.TargetType.FullName; System.Diagnostics.Debug.WriteLine($"ASPECT INFO: {fname + tname}"); context.Proceed(); if (tname == "Get") { long totalsize = PrintPropertiesSizeof(context); Debug.WriteLine($"total size = {totalsize}"); if (totalsize > MemThreshold) { Debug.Write(fname + tname + context.Target.ToString()); Debug.WriteLine(totalsize + "is more than threshold, that's " + MemThreshold); Debug.WriteLine("INFO:"); PrintPropertiesSizeof(context); Debugger.Break(); } var result = context.ReturnValue; } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
public void Advise(MethodAdviceContext context) { Type returnType = (context.TargetMethod as MethodInfo).ReturnType; if (!IsSubclassOfRawGeneric(typeof(ServiceResult <>), returnType)) { throw new Exception("ValidationAdvice should only use at service methods with subclass of ResponseBase return type."); } if (context.Arguments.Count != 1) { throw new Exception("Service methods should have one and only one argument as subclass of RequestBase"); } object requestObject = context.Arguments[0]; //if (!requestObject.GetType().GetInterfaces().Contains(typeof(IRequest))) // throw new Exception("Service methods should have one and only one argument as subclass of RequestBase"); //IList<ValidationResult> invalidItems = new List<ValidationResult>(); //bool objectIsvalid = Validator.TryValidateObject(requestObject, new ValidationContext(requestObject, null, null), invalidItems, validateAllProperties); //if (!objectIsvalid) //{ // object instance = Activator.CreateInstance(returnType); // (instance as BaseServiceResult).StatusCode = StatusCode.BadRequest; // (instance as BaseServiceResult).ModelValidationErrors = invalidItems.ToList().Select(P => new ValidationError(P.ErrorMessage)).ToList(); // context.ReturnValue = instance; //} //else context.Proceed(); }
public void Advise(MethodAdviceContext context) { context.Proceed(); if (((MethodInfo)context.TargetMethod).ReturnType == typeof(int)) { context.ReturnValue = (int)context.ReturnValue + 1; } }
/// <summary> /// 拦截方法 /// </summary> /// <param name="context">方法元数据</param> public void Advise(MethodAdviceContext context) { TransactionScopeAsyncFlowOption asyncFlowOption = TransactionScopeAsyncFlowOption.Enabled; using (TransactionScope scope = new TransactionScope(this._scopeOption, asyncFlowOption)) { context.Proceed(); scope.Complete(); } }
//Public #region # 拦截方法 —— void Advise(MethodAdviceContext context) /// <summary> /// 拦截方法 /// </summary> /// <param name="context">方法元数据</param> public void Advise(MethodAdviceContext context) { bool hasCache = this.OnEntry(context); if (!hasCache) { context.Proceed(); this.OnExit(context); } }
public void Advise(MethodAdviceContext context) { if (ALists[context] == null) { ALists[context] = new List <ExternalClass>(); } ALists[context].Add(new ExternalClass()); var c = ALists[context].Count; context.Proceed(); }
public void Advise(MethodAdviceContext context) { OnEntry(context); if (context.ReturnValue != null) { return; } context.Proceed(); OnSuccess(context); }
/// <summary> /// 拦截方法 /// </summary> /// <param name="context">方法元数据</param> public void Advise(MethodAdviceContext context) { try { context.Proceed(); } catch (Exception exception) { this.OnException(context, exception); } }
/// <summary> /// Method invoked upon failure of the method to which the current /// aspect is applied. /// </summary> /// <param name="args">Information about the method being executed.</param> public void Advise(MethodAdviceContext context) { try { context.Proceed(); } catch (Exception e) { this.Log().Error(e, $"Error from {nameof(ExceptionAdvice)}"); } }
/// <summary> /// Implements advice logic. /// Usually, advice must invoke context.Proceed() /// </summary> /// <param name="context">The method advice context.</param> public void Advise(MethodAdviceContext context) { var paramIn = GetInParam(context); // 跳过构造函数和属性(仅记录异常日志,运行日志不记录) if (context.TargetMethod.MemberType == MemberTypes.Constructor || context.TargetMethod.MemberType == MemberTypes.Property || context.TargetMethod.Name.StartsWith("set_") || context.TargetMethod.Name.StartsWith("get_")) { try { _logSpan = LogSpan.GetCurrentLogSpan(); _logSpan.FunctionName = $"{context.TargetMethod.Name}---(Constructor|Property)"; _logSpan.ParamIn = paramIn; context.Proceed(); } catch (Exception e) { // 构造函数中,如果不出现异常,则调用链不用延长,出现异常后才延长调用链 var logTmp = LogSpan.Extend(LogContext.Current); _logSpan.SpanChain = logTmp.SpanChain; _logSpan.ParamOut = $"Exception:{e}"; _logSpan.SpendTime = (DateTime.Now - _logSpan.CreateTime).TotalMilliseconds; LogManager.InnerException(e, "构造函数、属性初始化异常", _logSpan); throw; } return; } // 普通函数,运行日志和异常日志都会记录 _logSpan = LogSpan.Extend(LogContext.Current); _logSpan.FunctionName = $"{context.TargetMethod.Name}"; _logSpan.ParamIn = paramIn; context.Proceed(); _logSpan.ParamOut = GetOutParam(context); _logSpan.SpendTime = (DateTime.Now - _logSpan.CreateTime).TotalMilliseconds; LogManager.InnerRunningLog(_logSpan); }
public void Advise(MethodAdviceContext context) { // do things you want here Console.WriteLine("##### AOP: 业务逻辑处理之前,所做的处理!"); context.Proceed(); // this calls the original method // do other things here Console.WriteLine("##### AOP: 业务逻辑处理之后,所做的处理!"); }
public void Advise(MethodAdviceContext call) { if (_newParameter.HasValue && call.Arguments.Count > 0) { call.Arguments[0] = _newParameter.Value; } call.Proceed(); if (_newReturnValue.HasValue) { call.ReturnValue = _newReturnValue.Value; } }
public void Advise(MethodAdviceContext call) { if (_newParameter.HasValue) { call.Parameters[0] = _newParameter.Value; } call.Proceed(); if (_newReturnValue.HasValue) { call.ReturnValue = _newReturnValue.Value; } }
/// <summary> /// 拦截方法 /// </summary> /// <param name="context">方法元数据</param> public void Advise(MethodAdviceContext context) { #if NET40 || NET45 using (TransactionScope scope = new TransactionScope(this._scopeOption)) #endif #if NET451_OR_GREATER || NETSTANDARD2_0_OR_GREATER using (TransactionScope scope = new TransactionScope(this._scopeOption, TransactionScopeAsyncFlowOption.Enabled)) #endif { context.Proceed(); scope.Complete(); } }
public void Advise(MethodAdviceContext context) { LastAdvicesCount = ++AdvicesCount[context]; if (RandomString[context] == null) { RandomString[context] = "1"; } else { RandomString[context] += "0"; } LastRandomString = RandomString[context]; context.Proceed(); }
/// <summary> /// 拦截方法 /// </summary> /// <param name="context">方法元数据</param> public void Advise(MethodAdviceContext context) { Type executorType = context.TargetMethod.DeclaringType; FieldInfo logAppenderfField = executorType.GetField("_logAppender", BindingFlags.NonPublic | BindingFlags.Instance); string crontabName = executorType.GenericTypeArguments.Single().Name; Stopwatch watch = new Stopwatch(); try { DateTime startTime = DateTime.Now; watch.Start(); context.Proceed(); watch.Stop(); DateTime endTime = DateTime.Now; StringBuilder logAppender = (StringBuilder)logAppenderfField.GetValue(context.Target); Task.Run(() => { this.WriteFile(string.Format(_RunningLogPath, DateTime.Today), "===================================运行正常, 详细信息如下===================================" + Environment.NewLine + "[当前任务]" + crontabName + Environment.NewLine + "[开始时间]" + startTime + Environment.NewLine + "[结束时间]" + endTime + Environment.NewLine + "[运行耗时]" + watch.Elapsed + Environment.NewLine + logAppender + Environment.NewLine + Environment.NewLine); }); } catch (Exception exception) { StringBuilder logAppender = (StringBuilder)logAppenderfField.GetValue(context.Target); Task.Run(() => { this.WriteFile(string.Format(_ExceptionLogPath, DateTime.Today), "===================================运行异常, 详细信息如下===================================" + Environment.NewLine + "[当前任务]" + crontabName + Environment.NewLine + "[异常时间]" + DateTime.Now + Environment.NewLine + "[异常消息]" + exception.Message + Environment.NewLine + "[异常明细]" + exception + Environment.NewLine + "[内部异常]" + exception.InnerException + Environment.NewLine + "[堆栈信息]" + exception.StackTrace + Environment.NewLine + logAppender + Environment.NewLine + Environment.NewLine); }); } }
public void Advise(MethodAdviceContext context) { MethodInfo methodInfo = (MethodInfo)context.TargetMethod; Type returnType = methodInfo.ReturnType; IApiResponse response; try { context.Proceed(); return; } catch (ValidationException exception) { response = (IApiResponse)Activator.CreateInstance(returnType); response.ValidationErrors = exception.Errors; } catch (BusinessException exception) { response = (IApiResponse)Activator.CreateInstance(returnType); response.ErrorMessage = exception.Message; IApiError error = response as IApiError; if (error != null) { error.ErrorCode = exception.Code; } } catch (Exception exception) { response = (IApiResponse)Activator.CreateInstance(returnType); response.ErrorMessage = exception.Message; IBusinessException businessException = exception as IBusinessException; if (businessException != null) { IApiError error = response as IApiError; if (error != null) { error.ErrorCode = businessException.Code; } } } response.IsSuccess = false; context.ReturnValue = response; }
public void Advise(MethodAdviceContext context) { var originalColor = Console.ForegroundColor; Stopwatch sw = new Stopwatch(); sw.Start(); try { Console.WriteLine("Before"); context.Proceed(); Console.WriteLine("After"); if (context.HasReturnValue) { var generalResult = context.ReturnValue as GeneralResult; if (generalResult != null && generalResult.IsSuccess == false) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Method: {context.TargetMethod.Name} failed: {generalResult.Message}, \n Params: [{String.Join(",", context.Parameters)}]"); Console.ForegroundColor = originalColor; } } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Method: {context.TargetMethod.Name} throws exception. \n Params: [{String.Join(",", context.Parameters)}] \n Exception: \n {e}"); Console.ForegroundColor = originalColor; context.ReturnValue = new GeneralResult { IsSuccess = false, Message = "Exception occured" }; } sw.Stop(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Method {context.TargetMethod.Name} execution time: {sw.Elapsed}"); Console.ForegroundColor = originalColor; }