private static IEnumerable <StackFrameInfo> getCurrentStackFrames(Predicate <Type> skipFrame) { var enhancedStackTrace = EnhancedStackTrace.Current(); var stackFrames = enhancedStackTrace.GetFrames(); if (stackFrames == null) { yield break; } foreach (var stackFrame in stackFrames) { if (!stackFrame.HasMethod()) { continue; } var methodBase = stackFrame.GetMethod(); if (methodBase == null) { continue; } var resolvedMethod = EnhancedStackTrace.GetMethodDisplayString(methodBase); if (resolvedMethod == null) { continue; } var declaringType = methodBase.DeclaringType; if (declaringType == null) { continue; } if (declaringType == typeof(EnhancedStackTraceService)) { continue; } if (skipFrame(declaringType)) { continue; } yield return(new StackFrameInfo { Method = resolvedMethod.ToString(), File = stackFrame.GetFileName(), Line = stackFrame.GetFileLineNumber(), Column = stackFrame.GetFileColumnNumber() }); } }
/// <summary> /// Gets the stack trace scoped to the given invocation. /// </summary> public static string GetStackTrace(this IMethodInvocation invocation) { var allFrames = EnhancedStackTrace.Current(); var invocationFrame = allFrames.FirstOrDefault(x => x.GetMethod() == invocation.MethodBase); //if (invocationFrame == null) // We know that the generated proxies live in the same assembly as the tests, so we use that // to scope the stack trace from the current invocation method up to the top call (test method) var testFrame = allFrames.LastOrDefault(x => x.GetMethod().DeclaringType?.Assembly == invocation.MethodBase.DeclaringType.Assembly); var sb = new StringBuilder(); // Always append if we didn't find the tip invocation frame var appendLine = invocationFrame == null; foreach (var frame in allFrames) { if (!appendLine && frame == invocationFrame) { appendLine = true; } if (appendLine) { sb.Append("\t"); var filePath = frame.GetFileName(); if (!string.IsNullOrEmpty(filePath)) { sb.Append(EnhancedStackTrace.TryGetFullPath(filePath).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); var lineNo = frame.GetFileLineNumber(); var colNo = frame.GetFileColumnNumber(); if (lineNo != 0 && colNo != 0) { sb.Append("(").Append(lineNo).Append(",").Append(colNo).Append("): "); } } sb.Append("at "); sb.AppendLine(frame.ToString()); if (frame == testFrame) { break; } } } return(sb.ToString()); }
private static string PrepareStackTrace() { var frames = EnhancedStackTrace.Current().ToList(); var sb = new StringBuilder(); var done = false; for (var fi = 0; !(sb.Length > 0 && done); fi++) { var frame = frames[fi]; var methodTypeName = frame.MethodInfo.DeclaringType.FullName; if (IgnoreNamespaces.All(x => !methodTypeName.StartsWith(x))) { if (sb.Length > 0) { sb.Append(Environment.NewLine); } sb.Append(" at "); MethodInfoAppend.Invoke(frame.MethodInfo, new[] { (object)sb }); var filePath = frame.GetFileName(); if (!string.IsNullOrEmpty(filePath)) { sb.Append(" in "); sb.Append(EnhancedStackTrace.TryGetFullPath(filePath)); } var lineNo = frame.GetFileLineNumber(); if (lineNo != 0) { sb.Append(":line "); sb.Append(lineNo); } continue; } done = sb.Length > 0; } return(sb.ToString()); }
public async Task Current() { // Arrange EnhancedStackTrace est = null; // Act await Task.Run(() => est = EnhancedStackTrace.Current()).ConfigureAwait(false); // Assert var stackTrace = est.ToString(); stackTrace = ReplaceLineEndings.Replace(stackTrace, ""); var trace = stackTrace.Split(Environment.NewLine); Assert.Equal( new[] { " at void System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, object state)", " at bool System.Threading.ThreadPoolWorkQueue.Dispatch()" }, trace); }
public async Task Current() { // Arrange EnhancedStackTrace est = null; // Act await Task.Run(() => est = EnhancedStackTrace.Current()).ConfigureAwait(false); // Assert var stackTrace = est.ToString(); stackTrace = ReplaceLineEndings.Replace(stackTrace, ""); var trace = stackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.None) // Remove Full framework entries .Where(s => !s.StartsWith(" at bool System.Threading._ThreadPoolWaitCallbac") && !s.StartsWith(" at void System.Threading.Tasks.Task.System.Thre")); Assert.Equal( new[] { " at bool System.Threading.ThreadPoolWorkQueue.Dispatch()" }, trace); }
/// <summary> /// 监听全局异常 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { var exception = (Exception)e.ExceptionObject; if (exception is AppFriendlyException) { return; } // 获取调用堆栈信息 var stackTrace = EnhancedStackTrace.Current(); // 获取堆栈第一个全局 [IfException] 特性 var ifExceptionAttribute = stackTrace .Where(u => u.MethodInfo.MethodBase != null && u.MethodInfo.MethodBase.IsDefined(typeof(IfExceptionAttribute), true)) .SelectMany(u => u.MethodInfo.MethodBase.GetCustomAttributes <IfExceptionAttribute>(true)) .FirstOrDefault(u => u.ErrorCode == null && !string.IsNullOrWhiteSpace(u.ErrorMessage)); // 打印全局消息 if (ifExceptionAttribute != null) { Console.WriteLine(ifExceptionAttribute.ErrorMessage); } }
public ContainerBuilder InitContainer() { var assemblies = AssemblyUtils.GetAppAssemblies(); PrintHeader(); EnhancedStackTrace.Current(); InitPolly(); ServicesInfo = new ObservableCollection <ServiceInfo>(); ContainerBuilder = new ContainerBuilder(); ContainerBuilder.RegisterModule(new LogRequestModule()); ContainerBuilder.RegisterInstance(_neonConfig); ContainerBuilder.RegisterInstance <IServicesManager>(this); InitManagers(); ContainerBuilder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces(); AssemblyUtils.GetAppAssemblies().ForEach(a => { ContainerBuilder .RegisterAssemblyTypes(a) .AsClosedTypesOf(typeof(IRequestHandler <,>)) .AsImplementedInterfaces().SingleInstance();; ContainerBuilder .RegisterAssemblyTypes(a) .AsClosedTypesOf(typeof(INotificationHandler <>)) .AsImplementedInterfaces().SingleInstance(); }); // It appears Autofac returns the last registered types first ContainerBuilder.RegisterGeneric(typeof(RequestPostProcessorBehavior <,>)).As(typeof(IPipelineBehavior <,>)); ContainerBuilder.RegisterGeneric(typeof(RequestPreProcessorBehavior <,>)).As(typeof(IPipelineBehavior <,>)); ContainerBuilder.Register <ServiceFactory>(ctx => { var c = ctx.Resolve <IComponentContext>(); return(t => c.Resolve(t)); }); var singletonServices = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(SingletonAttribute)); var transientServices = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(TransientAttribute)); var scopedServices = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ScopedAttribute)); var dataAccess = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(DataAccessAttribute)); var luaObjects = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ScriptObjectAttribute)); var jobObjects = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(SchedulerJobTaskAttribute)); var dbSeedsObject = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(DatabaseSeedAttribute)); var componentsObject = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ComponentAttribute)); var noSqlConnectors = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(NoSqlConnectorAttribute)); var scriptEngines = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ScriptEngineAttribute)); _availableServices = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(ServiceAttribute)); _logger.LogDebug($"Services {_availableServices.Count}"); _logger.LogDebug($"Singleton services {singletonServices.Count}"); _logger.LogDebug($"Transient services {transientServices.Count}"); _logger.LogDebug($"Scoped services {scopedServices.Count}"); _logger.LogDebug($"DataAccesses {dataAccess.Count}"); luaObjects.ForEach(l => { ContainerBuilder.RegisterType(l).AsSelf().SingleInstance(); }); singletonServices.ForEach(t => RegisterService(LifeScopeTypeEnum.SINGLETON, t)); componentsObject.ForEach(t => RegisterService(LifeScopeTypeEnum.SINGLETON, t)); scriptEngines.ForEach(s => RegisterService(LifeScopeTypeEnum.SINGLETON, s)); ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray()) .Where(t => t == typeof(IDatabaseSeed)) .AsImplementedInterfaces() .SingleInstance(); ContainerBuilder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()) .Where(t => t == typeof(IDataAccess <>)) .AsImplementedInterfaces() .SingleInstance(); ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray()) .AsClosedTypesOf(typeof(IDataAccess <>)).AsImplementedInterfaces(); ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray()) .AsClosedTypesOf(typeof(AbstractDataAccess <>)).AsImplementedInterfaces(); ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray()) .AsClosedTypesOf(typeof(IDtoMapper <,>)).AsImplementedInterfaces(); ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray()) .AsClosedTypesOf(typeof(AbstractDtoMapper <,>)).AsImplementedInterfaces(); dataAccess.ForEach(d => { ContainerBuilder.RegisterType(d).As(AssemblyUtils.GetInterfaceOfType(d)).InstancePerLifetimeScope(); }); noSqlConnectors.ForEach(t => { ContainerBuilder.RegisterType(t).InstancePerDependency(); }); transientServices.ForEach(t => RegisterService(LifeScopeTypeEnum.TRANSIENT, t)); dbSeedsObject.ForEach(t => { ContainerBuilder.RegisterType(t).AsSelf().InstancePerLifetimeScope(); }); scopedServices.ForEach(t => RegisterService(LifeScopeTypeEnum.SCOPED, t)); jobObjects.ForEach(t => RegisterService(LifeScopeTypeEnum.SCOPED, t)); ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray()) .Where(t => t.Name.ToLower().EndsWith("service")) .AsImplementedInterfaces().SingleInstance(); //ContainerBuilder.RegisterAssemblyTypes(AssemblyUtils.GetAppAssemblies().ToArray()) // .Where(t => t.Name.ToLower().EndsWith("component")) // .AsImplementedInterfaces().SingleInstance(); return(ContainerBuilder); }
/// <summary> /// 抛出异常. /// </summary> /// <param name="code">Code.</param> /// <param name="title">Title.</param> /// <param name="messages">Messages.</param> /// <returns>Friendly Exception.</returns> public static FriendlyException ThrowException(int code, string title, params string[] messages) { return(new FriendlyException(code, EnhancedStackTrace.Current(), title, messages)); }
protected override StackTrace CreateStackTrace(Exception exception) => exception == null ? EnhancedStackTrace.Current() : new EnhancedStackTrace(exception);