예제 #1
0
        public void StackTraceHelper_ProducesReadableOutput()
        {
            // Arrange
            var expectedCallStack = new List <string>()
            {
                "Microsoft.Extensions.Internal.StackTraceHelperTest.Iterator()+MoveNext()",
                "string.Join(string separator, IEnumerable<string> values)",
                "Microsoft.Extensions.Internal.StackTraceHelperTest+GenericClass<T>.GenericMethod<V>(ref V value)",
                "Microsoft.Extensions.Internal.StackTraceHelperTest.MethodAsync(int value)",
                "Microsoft.Extensions.Internal.StackTraceHelperTest.MethodAsync<TValue>(TValue value)",
                "Microsoft.Extensions.Internal.StackTraceHelperTest.Method(string value)",
                "Microsoft.Extensions.Internal.StackTraceHelperTest.StackTraceHelper_ProducesReadableOutput()",
            };

            Exception exception = null;

            try
            {
                Method("test");
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            // Act
            var stackFrames = StackTraceHelper.GetFrames(exception, out _);
            var methodNames = stackFrames.Select(stackFrame => stackFrame.MethodDisplayInfo.ToString()).ToArray();

            // Assert
            Assert.Equal(expectedCallStack, methodNames);
        }
예제 #2
0
 public static bool BeforeDo(ProxyBase __instance)
 {
     try
     {
         if (__instance == null)
         {
             return(true);
         }
         Type type = __instance.GetType();
         Logger.Error(type.FullName + "-BeforeDo-SessionID:" + ServiceSession.SessionID);
         ProxyType proxyType = null;
         if (!string.IsNullOrEmpty(type.FullName))
         {
             ProxyTypeDict.TryGetValue(type.FullName, out proxyType);
         }
         Logger.Error("PostData:" + (proxyType == null
             ? ProxyJsonHelper.ProxyObjectToJsonString(__instance)
             : ProxyJsonHelper.ProxyObjectToJsonString(__instance, false, proxyType.UseDataMemberTransData,
                                                       proxyType.InMaxExpandDepth)));
         //输出调用堆栈
         Logger.Error("StackTrace:\r\n" + StackTraceHelper.GetCurrentStackTraceString(3));
     }
     catch (Exception ex)
     {
         Logger.Error(ex);
     }
     return(true);
 }
            public override void Eval(MockDirectoryWrapper dir)
            {
                // Since we throw exc during abort, eg when IW is
                // attempting to delete files, we will leave
                // leftovers:
                dir.AssertNoUnrefencedFilesOnClose = false;

                if (DoFail)
                {
                    bool sawAbortOrFlushDoc = StackTraceHelper.DoesStackTraceContainMethod("Abort") ||
                                              StackTraceHelper.DoesStackTraceContainMethod("FinishDocument");
                    bool sawClose = StackTraceHelper.DoesStackTraceContainMethod("Close") ||
                                    StackTraceHelper.DoesStackTraceContainMethod("Dispose");
                    bool sawMerge = StackTraceHelper.DoesStackTraceContainMethod("Merge");

                    if (sawAbortOrFlushDoc && !sawClose && !sawMerge)
                    {
                        if (OnlyOnce)
                        {
                            DoFail = false;
                        }
                        //System.out.println(Thread.currentThread().getName() + ": now fail");
                        //new Throwable(Console.WriteLine().StackTrace);
                        throw new IOException("now failing on purpose");
                    }
                }
            }
예제 #4
0
        public void GetCallerInformation()
        {
            // Arrange
            string projectDirectory = Directory.GetParent(Directory.GetCurrentDirectory())?.Parent?.FullName;

            if (string.IsNullOrEmpty(projectDirectory))
            {
                throw new NotImplementedException();
            }
            const int callerLineNumber = 68;
            string    callerFilePath   = projectDirectory + @"\StackTraceTest.cs";
            string    callerMemberName = MethodBase.GetCurrentMethod().Name;
            var       expectedValue    = new Dictionary <string, string>
            {
                {
                    nameof(callerLineNumber), callerLineNumber.ToString()
                },
                {
                    nameof(callerFilePath), callerFilePath
                },
                {
                    nameof(callerMemberName), callerMemberName
                }
            };

            // Act
            Dictionary <string, string> actualValue = StackTraceHelper.GetCallerInformation();

            // Assert
            CollectionAssert.AreEquivalent(expectedValue, actualValue);
        }
예제 #5
0
 public IActionResult Delay(int seconds)
 {
     ViewBag.StackTrace = StackTraceHelper.GetUsefulStack();
     Thread.Sleep(TimeSpan.FromSeconds(seconds));
     AddCorrelationIdentifierToResponse();
     return(View(seconds));
 }
 public override void Eval(MockDirectoryWrapper dir)
 {
     if (StackTraceHelper.DoesStackTraceContainMethod("DoMerge"))
     {
         throw new IOException("now failing during merge");
     }
 }
예제 #7
0
        private void button4_Click(object sender, EventArgs e)
        {
            StackFrame stackFrame;
            string     stackTrace = StackTraceHelper.Get(out stackFrame);

            SetTextBoxesValues(stackTrace, stackFrame);
        }
        public async Task <IActionResult> DelayAsync(int seconds)
        {
            ViewBag.StackTrace = StackTraceHelper.GetUsefulStack();
            await Task.Delay(TimeSpan.FromSeconds(seconds));

            return(View("Delay", seconds));
        }
        public void StackTraceHelper_IncludesLineNumbersForFiles()
        {
            // Arrange
            Exception exception = null;

            try
            {
                // Throwing an exception in the current assembly always seems to populate the full stack
                // trace regardless of symbol type. Crossing assembly boundaries ensures PortablePdbReader gets used
                // on desktop.
                Thrower.Throw();
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            // Act
            var stackFrames = StackTraceHelper.GetFrames(exception);

            // Assert
            Assert.Collection(stackFrames,
                              frame =>
            {
                Assert.Contains("Thrower.cs", frame.FilePath);
                Assert.Equal(17, frame.LineNumber);
            },
                              frame =>
            {
                Assert.Contains("StackTraceHelperTest.cs", frame.FilePath);
            });
        }
예제 #10
0
            public override void Eval(MockDirectoryWrapper dir)
            {
                // Since we throw exc during abort, eg when IW is
                // attempting to delete files, we will leave
                // leftovers:
                dir.AssertNoUnreferencedFilesOnClose = false;

                if (m_doFail)
                {
                    // LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)]
                    // to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods.
                    bool sawAbortOrFlushDoc = StackTraceHelper.DoesStackTraceContainMethod("Abort") ||
                                              StackTraceHelper.DoesStackTraceContainMethod("FinishDocument");
                    bool sawClose = StackTraceHelper.DoesStackTraceContainMethod("Close") ||
                                    StackTraceHelper.DoesStackTraceContainMethod("Dispose");
                    bool sawMerge = StackTraceHelper.DoesStackTraceContainMethod("Merge");

                    if (sawAbortOrFlushDoc && !sawClose && !sawMerge)
                    {
                        if (OnlyOnce)
                        {
                            m_doFail = false;
                        }
                        //System.out.println(Thread.currentThread().getName() + ": now fail");
                        //new Throwable(Console.WriteLine().StackTrace);
                        throw new IOException("now failing on purpose");
                    }
                }
            }
 public override void Eval(MockDirectoryWrapper dir)
 {
     /*typeof(PersistentSnapshotDeletionPolicy).Name.Equals(frame.GetType().Name) && */
     if (StackTraceHelper.DoesStackTraceContainMethod("Persist"))
     {
         throw new IOException("now fail on purpose");
     }
 }
예제 #12
0
        public void GetMethodDisplayString_ReturnsTypeNameQualifiedMethods(MethodBase method, string expected)
        {
            // Act
            var actual = StackTraceHelper.GetMethodDisplayString(method);

            // Assert
            Assert.Equal(expected, actual.ToString());
        }
예제 #13
0
            private string GetMethodFullName(MethodBase m)
            {
                StringBuilder sb = new StringBuilder();

                StackTraceHelper.GetFullNameForStackTrace(sb, m);

                return(sb.ToString());
            }
예제 #14
0
        private static IEnumerable <string> EnumerateFiles(string path, string searchPattern, bool useSearchOption, SearchOption searchOption)
        {
            string methodName       = StackTraceHelper.GetMethod(StackTraceCaller.This).Name;
            bool   logicalOperation = TraceHelper.StartLogicalOperation(methodName);

            IEnumerable <string> output = new List <string>();

            if (Directory.Exists(path))
            {
                try
                {
                    if (!string.IsNullOrEmpty(searchPattern))
                    {
                        output = useSearchOption
                                     ? Directory.EnumerateFiles(path, searchPattern, searchOption)
                                     : Directory.EnumerateFiles(path, searchPattern);
                    }
                    else
                    {
                        output = Directory.EnumerateFiles(path);
                    }

                    // HARD-CODED constant
                    Tracer.Instance.TraceEvent(TraceEventType.Verbose, 0, "List retrieved succesfully.");
                }
                catch (ArgumentNullException argumentNullException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, argumentNullException.Message);
                }
                catch (ArgumentException argumentException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, argumentException.Message);
                }
                catch (UnauthorizedAccessException unauthorizedAccessException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, unauthorizedAccessException.Message);
                }
                catch (DirectoryNotFoundException directoryNotFoundException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, directoryNotFoundException.Message);
                }
                catch (IOException ioException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, ioException.Message);
                }
                catch (SecurityException securityException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, securityException.Message);
                }
            }

            if (logicalOperation)
            {
                TraceHelper.StopLogicalOperation();
            }

            return(output);
        }
예제 #15
0
        public static byte[] ReadFileAllBytes(string path, Encoding encoding)
        {
            string methodName = StackTraceHelper.GetMethod(StackTraceCaller.This)
                                .Name;
            bool logicalOperation = TraceHelper.StartLogicalOperation(methodName);

            byte[] output  = null;
            bool   isExist = File.Exists(path);

            if (isExist)
            {
                try
                {
                    output = File.ReadAllBytes(path);
                    // HARD-CODED constant
                    Tracer.Instance.TraceEvent(TraceEventType.Verbose, 0, string.Format(CultureInfo.InvariantCulture, "Read complete {0}", path));
                }
                catch (ArgumentNullException argumentNullException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, argumentNullException.Message);
                }
                catch (ArgumentException argumentException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, argumentException.Message);
                }
                catch (UnauthorizedAccessException unauthorizedAccessException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, unauthorizedAccessException.Message);
                }
                catch (SecurityException securityException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, securityException.Message);
                }
                catch (DirectoryNotFoundException directoryNotFoundException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, directoryNotFoundException.Message);
                }
                catch (FileNotFoundException fileNotFoundException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, fileNotFoundException.Message);
                }
                catch (IOException ioException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, ioException.Message);
                }
                catch (NotSupportedException notSupportedException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, notSupportedException.Message);
                }
            }

            if (logicalOperation)
            {
                TraceHelper.StopLogicalOperation();
            }

            return(output);
        }
예제 #16
0
        /// <summary>
        /// Gets the <see cref="StackTraceInformation"/> for an exception.
        /// </summary>
        /// <param name="exception">An <see cref="Exception"/> instance.</param>
        /// <returns>StackTraceInformation for the exception</returns>
        internal static StackTraceInformation TryGetStackTraceInformation(this Exception exception)
        {
            if (!string.IsNullOrEmpty(exception?.StackTrace))
            {
                return(StackTraceHelper.CreateStackTraceInformation(exception, false, exception.StackTrace));
            }

            return(null);
        }
예제 #17
0
        public static bool WriteFileAllBytes(string path, byte[] bytes)
        {
            string methodName = StackTraceHelper.GetMethod(StackTraceCaller.This)
                                .Name;
            bool logicalOperation = TraceHelper.StartLogicalOperation(methodName);

            var output = false;

            try
            {
                File.WriteAllBytes(path, bytes);
                output = true;

                // HARD-CODED constant
                Tracer.Instance.TraceEvent(TraceEventType.Verbose, 0, string.Format(CultureInfo.InvariantCulture, "Write complete {0}", path));
            }
            catch (ArgumentNullException argumentNullException)
            {
                Tracer.Instance.TraceEvent(TraceEventType.Error, 0, argumentNullException.Message);
            }
            catch (ArgumentException argumentException)
            {
                Tracer.Instance.TraceEvent(TraceEventType.Error, 0, argumentException.Message);
            }
            catch (UnauthorizedAccessException unauthorizedAccessException)
            {
                Tracer.Instance.TraceEvent(TraceEventType.Error, 0, unauthorizedAccessException.Message);
            }
            catch (SecurityException securityException)
            {
                Tracer.Instance.TraceEvent(TraceEventType.Error, 0, securityException.Message);
            }
            catch (DirectoryNotFoundException directoryNotFoundException)
            {
                Tracer.Instance.TraceEvent(TraceEventType.Error, 0, directoryNotFoundException.Message);
            }
            catch (FileNotFoundException fileNotFoundException)
            {
                Tracer.Instance.TraceEvent(TraceEventType.Error, 0, fileNotFoundException.Message);
            }
            catch (IOException ioException)
            {
                Tracer.Instance.TraceEvent(TraceEventType.Error, 0, ioException.Message);
            }
            catch (NotSupportedException notSupportedException)
            {
                Tracer.Instance.TraceEvent(TraceEventType.Error, 0, notSupportedException.Message);
            }


            if (logicalOperation)
            {
                TraceHelper.StopLogicalOperation();
            }

            return(output);
        }
예제 #18
0
 public override void Eval(MockDirectoryWrapper dir)
 {
     // LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)]
     // to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods.
     if (StackTraceHelper.DoesStackTraceContainMethod("DoMerge"))
     {
         throw new IOException("now failing during merge");
     }
 }
 public override void Eval(MockDirectoryWrapper dir)
 {
     // LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)]
     // to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods.
     if (StackTraceHelper.DoesStackTraceContainMethod(typeof(PersistentSnapshotDeletionPolicy).Name, "Persist"))
     {
         throw new IOException("now fail on purpose");
     }
 }
예제 #20
0
        /// <summary>
        /// 获取当前运行的代码信息作为日志的Tag
        /// 格式为 文件名-方法名-代码所在行数
        /// </summary>
        /// <param name="skipFrames"></param>
        /// <returns></returns>
        public static string GetTag(int skipFrames = 2)
        {
            StackFrame frame      = new StackFrame(skipFrames, true);
            var        lineNumber = StackTraceHelper.GetLineNumber(frame);
            var        method     = StackTraceHelper.GetMethod(frame);
            var        fileName   = StackTraceHelper.GetFileNameWithoutPath(frame);

            return(string.Format("{0}-{1}-{2}", fileName, method, lineNumber));
        }
예제 #21
0
        /// <summary>
        /// Инициализирует новый экземпляр <see cref="Element"/>.
        /// </summary>
        /// <param name="context">Экземпляр контекста <see cref="BotContext"/>.</param>
        protected Element(BotContext context)
        {
            Context = Check.NotNull(context, nameof(context));
            _logger = Check.NotNull(context.Logger, nameof(context.Logger));

            var info = StackTraceHelper.GetInfo();

            ((IInterceptable)this).Info = info;
            LogName = info.FullName;
        }
예제 #22
0
    public void StackIsSimplified()
    {
        Func <Task> call = OuterMethodAsync;
        Exception   ex   = call.Should().Throw <InvalidOperationException>().Which;

        var originalStack   = new StackTrace(ex).GetFrames();
        var simplifiedStack = StackTraceHelper.SimplifyStackTrace(ex);

        simplifiedStack.Count().Should().BeLessThan(originalStack.Length);
    }
예제 #23
0
        public IActionResult Index()
        {
            ViewBag.ProfilerAttached       = SampleHelpers.IsProfilerAttached();
            ViewBag.TracerAssemblyLocation = SampleHelpers.GetTracerAssemblyLocation();
            ViewBag.StackTrace             = StackTraceHelper.GetUsefulStack();

            var envVars = SampleHelpers.GetDatadogEnvironmentVariables();

            AddCorrelationIdentifierToResponse();
            return(View(envVars.ToList()));
        }
 private void ShowOrThrowError(string title, JArray details, int exceptionId)
 {
     if (_devSupportManager.IsEnabled)
     {
         _devSupportManager.ShowNewJavaScriptError(title, details, exceptionId);
     }
     else
     {
         var stackTrace = StackTraceHelper.ConvertJavaScriptStackTrace(details);
         throw new JavaScriptException(title, stackTrace.PrettyPrint());
     }
 }
예제 #25
0
        public static bool CopyFile(string sourceFile, string destinationFile, bool overwrite)
        {
            string methodName = StackTraceHelper.GetMethod(StackTraceCaller.This)
                                .Name;
            bool logicalOperation = TraceHelper.StartLogicalOperation(methodName);

            var  output  = false;
            bool isExist = File.Exists(sourceFile);

            if (isExist)
            {
                try
                {
                    File.Copy(sourceFile, destinationFile, overwrite);
                    output = true;

                    // HARD-CODED constant
                    Tracer.Instance.TraceEvent(TraceEventType.Verbose, 0, string.Format(CultureInfo.InvariantCulture, "Copied from {0} to {1}, overwrite {2}", sourceFile, destinationFile, overwrite));
                }
                catch (ArgumentNullException argumentNullException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, argumentNullException.Message);
                }
                catch (ArgumentException argumentException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, argumentException.Message);
                }
                catch (UnauthorizedAccessException unauthorizedAccessException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, unauthorizedAccessException.Message);
                }
                catch (DirectoryNotFoundException directoryNotFoundException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, directoryNotFoundException.Message);
                }
                catch (IOException ioException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, ioException.Message);
                }
                catch (NotSupportedException notSupportedException)
                {
                    Tracer.Instance.TraceEvent(TraceEventType.Error, 0, notSupportedException.Message);
                }
            }

            if (logicalOperation)
            {
                TraceHelper.StopLogicalOperation();
            }

            return(output);
        }
예제 #26
0
        public void StackTraceHelper_PrettyPrintsStackTraceForMethodsOnGenericTypes()
        {
            // Arrange
            var exception = Record.Exception(() => new GenericClass <int>().Throw(0));

            // Act
            var stackFrames = StackTraceHelper.GetFrames(exception, out _);

            // Assert
            var methods = stackFrames.Select(frame => frame.MethodDisplayInfo.ToString()).ToArray();

            Assert.Equal("Microsoft.Extensions.Internal.StackTraceHelperTest+GenericClass<T>.Throw(T parameter)", methods[0]);
        }
예제 #27
0
        public void StackTraceHelper_PrettyPrintsStackTraceForMethodsWithGenericOutParameters()
        {
            // Arrange
            var exception = Record.Exception(() => MethodWithGenericOutParameter("Test", out int value));

            // Act
            var stackFrames = StackTraceHelper.GetFrames(exception, out _);

            // Assert
            var methods = stackFrames.Select(frame => frame.MethodDisplayInfo.ToString()).ToArray();

            Assert.Equal("Microsoft.Extensions.Internal.StackTraceHelperTest.MethodWithGenericOutParameter<TVal>(string a, out TVal value)", methods[0]);
        }
예제 #28
0
        public void StackTraceHelper_PrettyPrintsStackTraceForGenericMethods()
        {
            // Arrange
            var exception = Record.Exception(() => GenericMethod <string>(null));

            // Act
            var stackFrames = StackTraceHelper.GetFrames(exception, out _);

            // Assert
            var methods = stackFrames.Select(frame => frame.MethodDisplayInfo.ToString()).ToArray();

            Assert.Equal("Microsoft.Extensions.Internal.StackTraceHelperTest.GenericMethod<T>(T val)", methods[0]);
        }
예제 #29
0
        public void GetMethodFromStack_UsingStackTraceCaller()
        {
            // Arrange
            string expectedValue = MethodBase.GetCurrentMethod()
                                   .Name;

            // Act
            MethodBase value       = StackTraceHelper.GetMethod(StackTraceCaller.This);
            string     actualValue = value.Name;

            // Assert
            Assert.AreEqual(expectedValue, actualValue);
        }
예제 #30
0
        public static void PostfixTransactionAttributeProcess(TransactionAttribute __instance, object obj)
        {
            if (_debugConfig == null)
            {
                return;
            }
            string enterpriseID = PlatformContext.Current.EnterpriseID;
            string orgCode      = PlatformContext.Current.OrgCode;
            string userCode     = PlatformContext.Current.UserCode;

            if (!IsLog(enterpriseID, orgCode, userCode))
            {
                return;
            }
            StringBuilder sb         = new StringBuilder();
            StackTrace    stackTrace = new StackTrace(true);

            for (int i = 0; i < stackTrace.FrameCount; i++)
            {
                StackFrame frame  = stackTrace.GetFrame(i);
                MethodBase method = frame.GetMethod();
                if (method.DeclaringType == null)
                {
                    continue;
                }
                var transactionAttribute = Attribute.GetCustomAttribute(method, typeof(TransactionAttribute));
                if (transactionAttribute == null)
                {
                    continue;
                }
                string assemblyFullName = method.DeclaringType.Assembly.FullName;
                sb.AppendFormat("BPSV事务:");
                if (!string.IsNullOrEmpty(assemblyFullName))
                {
                    sb.Append(assemblyFullName.Split(',')[0]);
                    sb.Append("!");
                }
                sb.AppendFormat("{0}.{1} 事务类型:{2} 事务ID:{3}",
                                method.DeclaringType.FullName,
                                method.Name, __instance.TransactionOption, Transaction.Current == null
                        ? string.Empty
                        : Transaction.Current.TransactionInformation.LocalIdentifier);
                break;
            }
            if (_debugConfig.IsOutputTransactionStack)
            {
                sb.AppendLine();
                sb.Append(StackTraceHelper.GetCurrentStackTraceString(4));
            }
            Logger.Debug(sb.ToString());
        }