/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="next"></param> /// <returns></returns> public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (!ShouldSaveAudit(context, out var auditLog, out var auditLogAction)) { await next(); return; } using (CrossCuttingConcerns.Applying(context.Controller, AuditingInterceptor.Concerns)) { var stopwatch = Stopwatch.StartNew(); try { var result = await next(); if (result.Exception != null && !result.ExceptionHandled) { auditLog.Exceptions.Add(result.Exception); } } catch (Exception ex) { auditLog.Exceptions.Add(ex); throw; } finally { stopwatch.Stop(); auditLogAction.ExecutionDuration = stopwatch.Elapsed; auditLog.Actions.Add(auditLogAction); } } }
public void SimpleTest() { var preInvokeInfo = string.Empty; var postInvokeInfo = string.Empty; var exceptionHandlerInfo = string.Empty; var cc = new CrossCuttingConcerns(); cc.PreInvoke = (instanceId, methodName, parameters) => { preInvokeInfo = methodName + "_preInvokeInfo"; }; cc.PostInvoke = (instanceId, methodName, parameters) => { postInvokeInfo = methodName + "_postInvokeInfo"; }; cc.ExceptionHandler = (instanceId, methodName, parameters, exception) => { exceptionHandlerInfo = methodName + "_exceptionHandlerInfo"; return(false); //do not throw }; var t = Interceptor.Intercept <ISimpleMath>(new SimpleMath(), cc); var a = t.Add(1, 2); Assert.IsFalse(string.IsNullOrEmpty(preInvokeInfo)); Assert.IsFalse(string.IsNullOrEmpty(postInvokeInfo)); Assert.IsTrue(string.IsNullOrEmpty(exceptionHandlerInfo)); var b = t.Divide(4, 0); Assert.IsFalse(string.IsNullOrEmpty(preInvokeInfo)); Assert.IsFalse(string.IsNullOrEmpty(postInvokeInfo)); Assert.IsFalse(string.IsNullOrEmpty(exceptionHandlerInfo)); }
/// <summary> /// Shoulds the intercept. /// </summary> /// <param name="invocation">The invocation.</param> /// <param name="auditLog">The audit log.</param> /// <param name="auditLogAction">The audit log action.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> protected virtual bool ShouldIntercept( IMethodInvocation invocation, out AuditLogInfo auditLog, out AuditLogActionInfo auditLogAction) { auditLog = null; auditLogAction = null; if (CrossCuttingConcerns.IsApplied(invocation.TargetObject, CrossCuttingConcerns.Auditing)) { return(false); } // 如果没有获取到 Scop,则返回 false。 var auditLogScope = _auditingManager.Current; if (auditLogScope == null) { return(false); } // 进行二次判断是否需要存储审计日志。 if (!_auditingHelper.ShouldSaveAudit(invocation.Method)) { return(false); } // 构建审计日志信息。 auditLog = auditLogScope.Log; auditLogAction = _auditingHelper.CreateAuditLogAction( auditLog, invocation.TargetObject.GetType(), invocation.Method, invocation.Arguments ); return(true); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="audit"></param> /// <param name="auditAction"></param> /// <returns></returns> protected virtual bool ShouldIntercept(AspectContext context, out AuditInfo audit, out AuditActionInfo auditAction) { audit = null; auditAction = null; if (CrossCuttingConcerns.IsApplied(context.Implementation, Concerns)) { return(false); } if (context.ServiceMethod.AttributeExists <DisableAuditingAttribute>() || context.ImplementationMethod.AttributeExists <DisableAuditingAttribute>()) { return(false); } var auditScope = _auditingManager.Current; if (auditScope == null) { return(false); } if (!_auditingHelper.ShouldSaveAudit(context.ImplementationMethod, true) && !_auditingHelper.ShouldSaveAudit(context.ServiceMethod, true)) { return(false); } audit = auditScope.Info; auditAction = _auditingHelper.CreateAuditAction( context.Implementation.GetType(), context.ImplementationMethod, context.Parameters ); return(true); }
public void Intercept(IInvocation invocation) { if (CrossCuttingConcerns.IsApplied(invocation.InvocationTarget, CrossCuttingConcerns.Auditing)) { invocation.Proceed(); return; } if (!_auditingHelper.ShouldSaveAudit(invocation.MethodInvocationTarget)) { invocation.Proceed(); return; } var auditInfo = _auditingHelper.CreateAuditInfo(invocation.TargetType, invocation.MethodInvocationTarget, invocation.Arguments); if (invocation.Method.IsAsync()) { PerformAsyncAuditing(invocation, auditInfo); } else { PerformSyncAuditing(invocation, auditInfo); } }
public void Intercept(IInvocation invocation) { if (CrossCuttingConcerns.IsApplied(invocation.InvocationTarget, CrossCuttingConcerns.Validation)) { invocation.Proceed(); return; } using (var validator = _iocResolver.ResolveAsDisposable <MethodInvocationValidator>()) { validator.Object.Initialize(invocation.Method, invocation.Arguments); validator.Object.Validate(); } invocation.Proceed(); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="audit"></param> /// <param name="auditAction"></param> /// <returns></returns> protected virtual bool ShouldIntercept(IMethodInvocation context, out AuditInfo audit, out AuditActionInfo auditAction) { audit = null; auditAction = null; if (!_options.IsEnabled) { return(false); } if (!(_options.IsEnabledForAnonymousUsers || (_principalAccessor.Principal?.Identity?.IsAuthenticated ?? false))) { return(false); } if (CrossCuttingConcerns.IsApplied(context.TargetObject, Concerns)) { return(false); } if (context.Method.AttributeExists <AuditedAttribute>()) { return(true); } if (context.Method.AttributeExists <DisableAuditingAttribute>()) { return(false); } var auditScope = _auditingManager.Current; if (auditScope == null) { return(false); } if (!_auditingHelper.ShouldSaveAudit(context.Method, true)) { return(false); } audit = auditScope.Info; auditAction = _auditingHelper.CreateAuditAction( context.TargetObject.GetType(), context.Method, context.Arguments ); return(true); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="audit"></param> /// <param name="auditAction"></param> /// <returns></returns> protected virtual bool ShouldIntercept(AspectContext context, out AuditInfo audit, out AuditActionInfo auditAction) { audit = null; auditAction = null; if (_options.IsEnabled == false) { return(false); } if (!(_options.IsEnabledForAnonymousUsers || (_principalAccessor.Principal?.Identity?.IsAuthenticated ?? false))) { return(false); } if (CrossCuttingConcerns.IsApplied(context.Implementation, Concerns)) { return(false); } if (context.ServiceMethod.AttributeExists <DisableAuditingAttribute>() || context.ImplementationMethod.AttributeExists <DisableAuditingAttribute>()) { return(false); } var auditScope = _auditingManager.Current; if (auditScope == null) { return(false); } if (!_auditingHelper.ShouldSaveAudit(context.ImplementationMethod, true) && !_auditingHelper.ShouldSaveAudit(context.ServiceMethod, true)) { return(false); } audit = auditScope.Info; auditAction = _auditingHelper.CreateAuditAction( context.Implementation.GetType(), context.ImplementationMethod, context.Parameters ); return(true); }
public void SimpleTimingTest() { var preInvokeInfo = string.Empty; var postInvokeInfo = string.Empty; var exceptionHandlerInfo = string.Empty; var cc = new CrossCuttingConcerns(); cc.PreInvoke = (instanceId, methodName, parameters) => { preInvokeInfo = methodName + "_preInvokeInfo"; }; cc.PostInvoke = (instanceId, methodName, parameters) => { postInvokeInfo = methodName + "_postInvokeInfo"; }; cc.ExceptionHandler = (instanceId, methodName, parameters, exception) => { exceptionHandlerInfo = methodName + "_exceptionHandlerInfo"; return(false); //do not throw }; var t = Interceptor.Intercept <ISimpleMath>(new SimpleMath(), cc); var a = t.Add(1, 2); Assert.IsFalse(string.IsNullOrEmpty(preInvokeInfo)); Assert.IsFalse(string.IsNullOrEmpty(postInvokeInfo)); Assert.IsTrue(string.IsNullOrEmpty(exceptionHandlerInfo)); var sw = Stopwatch.StartNew(); var t2 = Interceptor.Intercept <ISimpleMath2>(new SimpleMath2(), cc); sw.Stop(); var interceptCtorTicks = sw.ElapsedTicks; var interceptCtorTs = sw.Elapsed; sw.Reset(); var c = t2.Add(2, 3); sw.Stop(); var interceptAddTicks = sw.ElapsedTicks; var interceptAddTs = sw.Elapsed; sw.Reset(); var t3 = Interceptor.Intercept <ISimpleMath2>(new SimpleMath2(), cc); sw.Stop(); var interceptCtorTicks2 = sw.ElapsedTicks; var interceptCtorTs2 = sw.Elapsed; sw.Reset(); var c2 = t3.Add(2, 3); sw.Stop(); var interceptAddTicks2 = sw.ElapsedTicks; var interceptAddTs2 = sw.Elapsed; sw.Reset(); var t4 = new SimpleMath2(); sw.Stop(); var plainCtorTicks = sw.ElapsedTicks; var plainCtorTs = sw.Elapsed; sw.Reset(); var c3 = t4.Add(2, 3); sw.Stop(); var plainAddTicks = sw.ElapsedTicks; var plainAddTs = sw.Elapsed; Assert.IsTrue(plainCtorTicks <= interceptCtorTicks); Assert.IsTrue(plainAddTicks <= interceptAddTicks); Assert.IsTrue(plainCtorTicks <= interceptCtorTicks2); Assert.IsTrue(plainAddTicks <= interceptAddTicks2); Assert.IsTrue(plainCtorTs <= interceptCtorTs); Assert.IsTrue(plainAddTs <= interceptAddTs); Assert.IsTrue(plainCtorTs <= interceptCtorTs2); Assert.IsTrue(plainAddTs <= interceptAddTs2); }
// Only the Distribuor class is allowed to create a client. internal DistributedClient(IPEndPoint[] servers, DistributedSessionNode[] nodes, IPEndPoint[] failedNodes, Exception[] failedNodeExceptionss, float subscriptionRate, int logPollingInterval) { _servers = servers; _nodes = nodes; _failedNodes = failedNodes; _failedNodeExceptions = failedNodeExceptionss; _subscriptionRate = subscriptionRate; _logPollingInterval = logPollingInterval; if (_logPollingInterval == 0) { _continuePollingLogs = false; } //create proxies for each node in _nodes, based on sub rate var allEndPoints = new List <IPEndPoint>(); var allProxies = new List <TInterface>(); var proxiesOnePerNode = new List <TInterface>(); _nodeJobCounts = new ushort[_nodes.Length]; for (int index = 0; index < _nodes.Length; index++) { var node = _nodes[index]; //initialize job count for node _nodeJobCounts[index] = 0; //add proxy to each subscription int subRate = Convert.ToInt32(node.LogicProcessorCount * _subscriptionRate); if (subRate < 1) { subRate = 1; } for (int i = 0; i < subRate; i++) { var proxy = DistributedProxy.CreateProxy <TInterface>(new DistributedEndPoint() { EndPoint = node.EndPoint, SessionId = node.SessionId }); allProxies.Add(proxy); allEndPoints.Add(node.EndPoint); if (i == 0) { proxiesOnePerNode.Add(proxy); } } } _proxiesOnePerNode = proxiesOnePerNode.ToArray(); var proxies = allProxies.ToArray(); _interceptEndPoints = allEndPoints.ToArray(); _interceptStatuses = new byte[proxies.Length]; //shuffle these arrays randomly but assure their indexes are in sync var count = proxies.Length; var rand = new Random(DateTime.Now.Millisecond); for (int i = 0; i < count; i++) //O(n) shuffle { int index = rand.Next(i, count); var tmpProxy = proxies[i]; proxies[i] = proxies[index]; proxies[index] = tmpProxy; var tmpEndPoint = _interceptEndPoints[i]; _interceptEndPoints[i] = _interceptEndPoints[index]; _interceptEndPoints[index] = tmpEndPoint; _interceptStatuses[i] = 0; //initialization only } //create interception points to track usage var crossCuttingConcerns = new CrossCuttingConcerns() { PreInvoke = OnProxyInvoke, PostInvoke = OnProxyInvokeComplete }; _intercepts = new TInterface[proxies.Length]; for (int index = 0; index < proxies.Length; index++) { var proxy = proxies[index]; _intercepts[index] = Interceptor.Intercept(index, proxy, crossCuttingConcerns); } _pollTimer = new Timer(PollLogs, null, new TimeSpan(0, 0, _logPollingInterval), new TimeSpan(0, 0, _logPollingInterval)); }
public CustomerManager() { _concerns = new CrossCuttingConcerns(); }
public static void RunPerfTest() { var preInvokeInfo = string.Empty; var postInvokeInfo = string.Empty; var exceptionHandlerInfo = string.Empty; var cc = new CrossCuttingConcerns(); cc.PreInvoke = (instanceId, methodName, parameters) => { preInvokeInfo = methodName + "_preInvokeInfo"; }; cc.PostInvoke = (instanceId, methodName, parameters) => { postInvokeInfo = methodName + "_postInvokeInfo"; }; cc.ExceptionHandler = (instanceId, methodName, parameters, exception) => { exceptionHandlerInfo = methodName + "_exceptionHandlerInfo"; return false; //do not throw }; var t = Interceptor.Intercept<ISimpleMath>(new SimpleMath(), cc); var a = t.Add(1, 2); var sw = Stopwatch.StartNew(); var t2 = Interceptor.Intercept<ISimpleMath2>(new SimpleMath2(), cc); sw.Stop(); var interceptCtorTicks = sw.ElapsedTicks; var interceptCtorTs = sw.Elapsed; sw.Restart(); var c = t2.Add(2, 3); sw.Stop(); var interceptAddTicks = sw.ElapsedTicks; var interceptAddTs = sw.Elapsed; sw.Restart(); var t3 = Interceptor.Intercept<ISimpleMath2>(new SimpleMath2(), cc); sw.Stop(); var interceptCtorTicks2 = sw.ElapsedTicks; var interceptCtorTs2 = sw.Elapsed; sw.Restart(); var c2 = t3.Add(2, 3); sw.Stop(); var interceptAddTicks2 = sw.ElapsedTicks; var interceptAddTs2 = sw.Elapsed; sw.Restart(); var t4 = new SimpleMath2(); sw.Stop(); var plainCtorTicks = sw.ElapsedTicks; var plainCtorTs = sw.Elapsed; sw.Restart(); var c3 = t4.Add(2, 3); sw.Stop(); var plainAddTicks = sw.ElapsedTicks; var plainAddTs = sw.Elapsed; Console.WriteLine("Ticks plain vs intercepted first ctr: {0}, {1}", plainCtorTicks, interceptCtorTicks); Console.WriteLine("Ticks plain vs intercepted first add: {0}, {1}", plainAddTicks, interceptAddTicks); Console.WriteLine("Ticks plain vs intercepted second ctr: {0}, {1}", plainCtorTicks, interceptCtorTicks2); Console.WriteLine("Ticks plain vs intercepted second add: {0}, {1}", plainAddTicks, interceptAddTicks2); Console.WriteLine("TS plain vs intercepted first ctr: {0}, {1}", plainCtorTs, interceptCtorTs); Console.WriteLine("TS plain vs intercepted first add: {0}, {1}", plainAddTs, interceptAddTs); Console.WriteLine("TS plain vs intercepted second ctr: {0}, {1}", plainCtorTs, interceptCtorTs2); Console.WriteLine("TS plain vs intercepted second add: {0}, {1}", plainAddTs, interceptAddTs2); }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { IAuditingConfiguration configuration = _provider.GetRequiredService <IAuditingConfiguration>(); if (!ShouldSaveAudit(context, configuration)) { await next(); return; } using (CrossCuttingConcerns.Applying(context.Controller, CrossCuttingConcerns.Auditing)) { IAuditStore store = _provider.GetService <IAuditStore>(); IFunction function = context.GetExecuteFunction(); //var auditInfo = store.CreateAuditInfo( // context.ActionDescriptor.AsControllerActionDescriptor().ControllerTypeInfo.AsType(), // context.ActionDescriptor.AsControllerActionDescriptor().MethodInfo, // context.ActionArguments //); Type type = context.ActionDescriptor.AsControllerActionDescriptor().ControllerTypeInfo.AsType(); List <Type> ignoredTypes = configuration.IgnoredTypes; AuditOperationEntry operation = new AuditOperationEntry { FunctionName = function.Name, ClientIpAddress = context.HttpContext.GetClientIp(), UserAgent = context.HttpContext.Request.Headers["User-Agent"].FirstOrDefault(), CreatedTime = DateTime.Now, ServiceName = type != null ? type.FullName : "", Parameters = ConvertArgumentsToJson(context.ActionArguments, ignoredTypes), }; if (context.HttpContext.User.Identity.IsAuthenticated && context.HttpContext.User.Identity is ClaimsIdentity identity) { operation.UserId = identity.GetUserId(); operation.UserName = identity.GetUserName(); } var stopwatch = Stopwatch.StartNew(); ActionExecutedContext result = null; try { result = await next(); if (result.Exception != null && !result.ExceptionHandled) { operation.Exception = result.Exception; } } catch (Exception ex) { operation.Exception = ex; throw; } finally { stopwatch.Stop(); operation.Elapsed = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds); if (configuration.SaveReturnValues && result != null) { switch (result.Result) { case ObjectResult objectResult: operation.ReturnValue = AuditingHelper.Serialize(objectResult.Value, ignoredTypes); break; case JsonResult jsonResult: operation.ReturnValue = AuditingHelper.Serialize(jsonResult.Value, ignoredTypes); break; case ContentResult contentResult: operation.ReturnValue = contentResult.Content; break; case AjaxResult ajaxResult: operation.ReturnValue = ajaxResult.Content; break; } } await store.SaveAsync(operation); } } }
public static void RunPerfTest() { var preInvokeInfo = string.Empty; var postInvokeInfo = string.Empty; var exceptionHandlerInfo = string.Empty; var cc = new CrossCuttingConcerns(); cc.PreInvoke = (instanceId, methodName, parameters) => { preInvokeInfo = methodName + "_preInvokeInfo"; }; cc.PostInvoke = (instanceId, methodName, parameters) => { postInvokeInfo = methodName + "_postInvokeInfo"; }; cc.ExceptionHandler = (instanceId, methodName, parameters, exception) => { exceptionHandlerInfo = methodName + "_exceptionHandlerInfo"; return(false); //do not throw }; var t = Interceptor.Intercept <ISimpleMath>(new SimpleMath(), cc); var a = t.Add(1, 2); var sw = Stopwatch.StartNew(); var t2 = Interceptor.Intercept <ISimpleMath2>(new SimpleMath2(), cc); sw.Stop(); var interceptCtorTicks = sw.ElapsedTicks; var interceptCtorTs = sw.Elapsed; sw.Restart(); var c = t2.Add(2, 3); sw.Stop(); var interceptAddTicks = sw.ElapsedTicks; var interceptAddTs = sw.Elapsed; sw.Restart(); var t3 = Interceptor.Intercept <ISimpleMath2>(new SimpleMath2(), cc); sw.Stop(); var interceptCtorTicks2 = sw.ElapsedTicks; var interceptCtorTs2 = sw.Elapsed; sw.Restart(); var c2 = t3.Add(2, 3); sw.Stop(); var interceptAddTicks2 = sw.ElapsedTicks; var interceptAddTs2 = sw.Elapsed; sw.Restart(); var t4 = new SimpleMath2(); sw.Stop(); var plainCtorTicks = sw.ElapsedTicks; var plainCtorTs = sw.Elapsed; sw.Restart(); var c3 = t4.Add(2, 3); sw.Stop(); var plainAddTicks = sw.ElapsedTicks; var plainAddTs = sw.Elapsed; Console.WriteLine("Ticks plain vs intercepted first ctr: {0}, {1}", plainCtorTicks, interceptCtorTicks); Console.WriteLine("Ticks plain vs intercepted first add: {0}, {1}", plainAddTicks, interceptAddTicks); Console.WriteLine("Ticks plain vs intercepted second ctr: {0}, {1}", plainCtorTicks, interceptCtorTicks2); Console.WriteLine("Ticks plain vs intercepted second add: {0}, {1}", plainAddTicks, interceptAddTicks2); Console.WriteLine("TS plain vs intercepted first ctr: {0}, {1}", plainCtorTs, interceptCtorTs); Console.WriteLine("TS plain vs intercepted first add: {0}, {1}", plainAddTs, interceptAddTs); Console.WriteLine("TS plain vs intercepted second ctr: {0}, {1}", plainCtorTs, interceptCtorTs2); Console.WriteLine("TS plain vs intercepted second add: {0}, {1}", plainAddTs, interceptAddTs2); }