当前位置: 首页>>代码示例>>C#>>正文


C# StackTrace.GetFrames方法代码示例

本文整理汇总了C#中System.Diagnostics.StackTrace.GetFrames方法的典型用法代码示例。如果您正苦于以下问题:C# StackTrace.GetFrames方法的具体用法?C# StackTrace.GetFrames怎么用?C# StackTrace.GetFrames使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Diagnostics.StackTrace的用法示例。


在下文中一共展示了StackTrace.GetFrames方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OnException

        public void OnException(ExceptionContext context)
        {
            this._logger.LogError("MatterCenterExceptionFilter", context.Exception);
            var stackTrace = new StackTrace(context.Exception, true);
            StackFrame stackFrameInstance = null;

            if(stackTrace.GetFrames().Length>0)
            {
                for(int i=0; i< stackTrace.GetFrames().Length; i++)
                {
                    if(stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter"))
                    {
                        stackFrameInstance = stackTrace.GetFrames()[i];
                        break;
                    }
                }
            }

            var response = new ErrorResponse()
            {
                Message = context.Exception.Message,
                StackTrace = context.Exception.ToString(),
                Description = "Error occured in the system. Please contact the administrator",
                //Exception = context.Exception.ToString(),
                LineNumber = stackFrameInstance?.GetFileLineNumber(),
                MethodName = stackFrameInstance?.GetMethod().Name,
                ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name,
                ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString()
            };
            context.Result = new ObjectResult(response)
            {
                StatusCode = (int)HttpStatusCode.InternalServerError,
                DeclaredType = typeof(ErrorResponse)                
            };
        }
开发者ID:Microsoft,项目名称:mattercenter,代码行数:35,代码来源:MatterCenterExceptionFilter.cs

示例2: GenerateErrorResponse

        /// <summary>
        /// This method will generate error response that will be sent to the client
        /// </summary>
        /// <param name="ex">Exception object that occured </param>
        /// <returns></returns>
        public ErrorResponse GenerateErrorResponse(Exception ex)
        {
            var stackTrace = new StackTrace(ex, true);
            StackFrame stackFrameInstance = null;

            if (stackTrace.GetFrames().Length > 0)
            {
                for (int i = 0; i < stackTrace.GetFrames().Length; i++)
                {
                    if (stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter"))
                    {
                        stackFrameInstance = stackTrace.GetFrames()[i];
                        break;
                    }
                }
            }
            //Create custom exception response that needs to be send to client
            var response = new ErrorResponse()
            {
                Message = ex.Message,
                StackTrace = ex.StackTrace.ToString(),
                Description = "Error occured in the system. Please contact the administrator",
                Exception = ex,
                LineNumber = stackFrameInstance?.GetFileLineNumber(),
                MethodName = stackFrameInstance?.GetMethod().Name,
                ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name,
                ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString(),
                IsErrror = true
            };
            return response;
        }
开发者ID:Microsoft,项目名称:mattercenter,代码行数:36,代码来源:CustomLogger.cs

示例3: TraceCall

        public static void TraceCall()
        {
#if TRACE

            var st = new StackTrace();
            var caller_sf = st.GetFrames()[1];
            var caller_method = caller_sf.GetMethod();

            //if (caller_sf.ToString() == lastCall)
            //    return;
            //else
            //    lastCall = caller_sf.ToString();


            var caller_method_from_compiler_non_tainted = st.GetFrames().Skip(2).SkipWhile(x => x.GetMethod().DeclaringType.FullName.Contains("Microsoft.FSharp.Compiler.Tainted")).FirstOrDefault();

            // var caller_params = caller_method.GetParameters();
            Console.WriteLine("Called {0}.{1}.{2} [from {3}]", 
                                    caller_method.DeclaringType.Namespace, 
                                    caller_method.DeclaringType.Name, 
                                    caller_method.Name, 
                                    caller_method_from_compiler_non_tainted.GetMethod().Name);
#else
#endif
        }
开发者ID:xenocons,项目名称:visualfsharp,代码行数:25,代码来源:Helpers.cs

示例4: OnException

        /// <summary>
        /// Implement OnException method of IExceptionFilter which will be invoked
        /// for all unhandled exceptions
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            this._logger.LogError("MatterCenterExceptionFilter", context.Exception);
            var stackTrace = new StackTrace(context.Exception, true);
            StackFrame stackFrameInstance = null;

            if(stackTrace.GetFrames().Length>0)
            {
                for(int i=0; i< stackTrace.GetFrames().Length; i++)
                {
                    if(stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter"))
                    {
                        stackFrameInstance = stackTrace.GetFrames()[i];
                        break;
                    }
                }
            }
            //Create custom exception response that needs to be send to client
            var response = new ErrorResponse()
            {
                Message = context.Exception.Message,
                StackTrace = context.Exception.ToString(),
                Description = "Error occured in the system. Please contact the administrator",
                //Exception = context.Exception.ToString(),
                LineNumber = stackFrameInstance?.GetFileLineNumber(),
                MethodName = stackFrameInstance?.GetMethod().Name,
                ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name,
                ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString()
            };

            //Create properties that need to be added to application insights
            var properties = new Dictionary<string, string>();
            properties.Add("StackTrace", response.StackTrace);
            properties.Add("LineNumber", response.LineNumber.ToString());
            properties.Add("MethodName", response.MethodName.ToString());
            properties.Add("ClassName", response.ClassName.ToString());
            properties.Add("ErrorCode", response.ErrorCode.ToString());           

            //Create Telemetry object to add exception to the application insights
            var ai = new TelemetryClient();
            ai.InstrumentationKey = instrumentationKey;
            if(ai.IsEnabled())
            {
                //add exception to the Application Insights
                ai.TrackException(context.Exception, properties);
            }           
            
            //Send the exceptin object to the client
            context.Result = new ObjectResult(response)
            {
                StatusCode = (int)HttpStatusCode.InternalServerError,
                DeclaredType = typeof(ErrorResponse)                
            };
        }
开发者ID:Microsoft,项目名称:mattercenter,代码行数:59,代码来源:MatterCenterExceptionFilter.cs

示例5: Check

		// avoid replication of tests on all constructors (this is no 
		// problem because the stack is already set correctly). The 
		// goal is to call every property and methods to see if they
		// have any* security requirements (*except for LinkDemand and
		// InheritanceDemand).
		private void Check (StackTrace st)
		{
			if (st.FrameCount > 0)
				Assert.IsNotNull (st.GetFrame (0), "GetFrame");
			else
				Assert.IsNull (st.GetFrame (0), "GetFrame");
			if (st.FrameCount > 0)
				Assert.IsNotNull (st.GetFrames (), "GetFrames");
			else
				Assert.IsNull (st.GetFrames (), "GetFrames");
			Assert.IsNotNull (st.ToString (), "ToString");
		}
开发者ID:Profit0004,项目名称:mono,代码行数:17,代码来源:StackTraceCas.cs

示例6: SentryStacktrace

        public SentryStacktrace(Exception e)
        {
            StackTrace trace = new StackTrace(e, true);

            if (trace.GetFrames() != null)
            {
                int length = trace.GetFrames().Length;
                this.Frames = new ExceptionFrame[length];
                for (int i=0; i<length; i++) {
                    StackFrame frame = trace.GetFrame(length - i - 1);
                    this.Frames[i] = BuildExceptionFrame(frame);
                }
            }
        }
开发者ID:jalaziz,项目名称:raven-csharp,代码行数:14,代码来源:SentryStacktrace.cs

示例7: SentryStacktrace

        public SentryStacktrace(Exception e)
        {
            StackTrace trace = new StackTrace(e, true);

            Frames = (trace.GetFrames() ?? new StackFrame[0]).Reverse().Select(frame =>
            {
                int lineNo = frame.GetFileLineNumber();

                if (lineNo == 0)
                {
                    //The pdb files aren't currently available
                    lineNo = frame.GetILOffset();
                }

                var method = frame.GetMethod();
                return new ExceptionFrame()
                {
                    Filename = frame.GetFileName(),
                    Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null,
                    Function = method.Name,
                    Source = method.ToString(),
                    LineNumber = lineNo,
                    ColumnNumber = frame.GetFileColumnNumber()
                };
            }).ToList();
        }
开发者ID:kimsama,项目名称:Unity3D-Raven,代码行数:26,代码来源:SentryStacktrace.cs

示例8: GetCallStack

        /// <summary>
        /// Collects the call stack at a given moment in time.
        /// </summary>
        /// <returns>A string representing the call stack in the form Function1,Class1,FileInfo1\nFunction2,Class2,FileInfo2\n...</returns>
        protected string GetCallStack()
        {
            StackTrace stackTrace = new StackTrace(true);
            StackFrame[] stackFrames = stackTrace.GetFrames();
            string stack = string.Empty;

            foreach (StackFrame stackFrame in stackFrames)
            {
                MethodBase method = stackFrame.GetMethod();

                if (method != null && method.ReflectedType != null)
                {
                    string function = method.Name;
                    string className = method.ReflectedType.FullName;
                    string fileName = stackFrame.GetFileName();
                    string fileInfo = (fileName != null) ? string.Format(CultureInfo.InvariantCulture, "{0}:{1}", fileName.Split('\\').Last(), stackFrame.GetFileLineNumber()) : string.Empty;
                    bool isOwnCode = !(className.StartsWith("Microsoft.", StringComparison.Ordinal) || className.StartsWith("System.", StringComparison.Ordinal));

                    // This data gets stored in a custom property. The length of data stored in a custom property is limited.
                    // We save space by only sending the last part of the namespace (the class name).
                    className = className.Split('.').Last();

                    // We save even more space by only sending the "Just My Code" version of the call stack.
                    if (isOwnCode)
                    {
                        stack += string.Format(CultureInfo.InvariantCulture, "{0},{1},{2}\n", function, className, fileInfo);
                    }
                }
            }

            return stack;
        }
开发者ID:xornand,项目名称:ApplicationInsights-SDK-Labs,代码行数:36,代码来源:DependencyCallstacksTelemetryInitializer.cs

示例9: Log

		private Logger Log(Level Level, object Format, params object[] Params)
		{
			if (Enabled || OnGlobalLog != null)
			{
				StackTrace stackTrace = new StackTrace();
				StackFrame StackFrame = null;
				foreach (var Frame in stackTrace.GetFrames())
				{
					if (Frame.GetMethod().DeclaringType != typeof(Logger))
					{
						StackFrame = Frame;
						break;
					}
				}

				if (Enabled)
				{
					if (OnLog != null) OnLog(Level, String.Format(Format.ToString(), Params), StackFrame);
				}

				if (OnGlobalLog != null)
				{
					OnGlobalLog(Name, Level, String.Format(Format.ToString(), Params), StackFrame);
				}
			}

			return this;
		}
开发者ID:soywiz,项目名称:csharputils,代码行数:28,代码来源:Logger.cs

示例10: BeginLog

        public static void BeginLog(string message)
        {
            if (LoggerData._logging.Equals(true))
            {
                string callingmethod = string.Empty;
                int managedthreadid = Thread.CurrentThread.ManagedThreadId;

                StackTrace stackTrace = new StackTrace();
                if (stackTrace != null)
                {
                    StackFrame[] stackFrames = stackTrace.GetFrames();
                    if (stackFrames != null && (stackFrames.Count() >= 1))
                    {
                        callingmethod = ((System.Type)stackFrames[1].GetMethod().ReflectedType).Name + "." + stackFrames[1].GetMethod().Name;
            //						System.Diagnostics.Debug.WriteLine(callingmethod);
                    }
                }

                LoggerData loggerdata = new LoggerData(message, System.Environment.TickCount, callingmethod);
                if (_threadtotickcountqueue.ContainsKey(managedthreadid))
                    ((Stack<LoggerData>)_threadtotickcountqueue[managedthreadid]).Push(loggerdata);
                else
                {
                    Stack<LoggerData> queue = new Stack<LoggerData>();
                    queue.Push(loggerdata);
                    _threadtotickcountqueue[managedthreadid] = queue;
                }
            }
        }
开发者ID:kmrgithub,项目名称:KRSrcWorkflow,代码行数:29,代码来源:WFLogger.cs

示例11: UsePrefix

        public Boolean UsePrefix()
        {
            StackTrace stackTrace = new StackTrace();
            List<StackFrame> stackFramesNow = stackTrace.GetFrames().ToList();

            stackFramesNow.Reverse();

            Boolean foundAll = true;

            foreach (var stackFrame in stackFrames)
            {
                Boolean foundNow = false;

                foreach (var frameNow in stackFramesNow)
                {
                    string stackCompare = stackFrame.GetMethod().Module + "#" + stackFrame.GetMethod().Name;
                    string nowCompare = frameNow.GetMethod().Module + "#" + frameNow.GetMethod().Name;

                    if (stackCompare == nowCompare)
                    {
                        foundNow = true;
                        break;
                    }
                }

                foundAll = foundAll & foundNow;
            }

            return foundAll;
        }
开发者ID:Edi-28,项目名称:UtilInfolog,代码行数:30,代码来源:InfologPrefix.cs

示例12: LogError

 public static void LogError(string msg , LogType lt , Exception ex)
 {
     writeMutex.WaitOne();
     System.IO.StreamWriter file = new System.IO.StreamWriter(Env.ErrorFolderPath, true);
     file.WriteLine(lt.ToString() + ":");
     string[] lines = msg.Split('\n');
     foreach (var l in lines)
     {
         file.WriteLine(l);
     }
     file.WriteLine("_Time :"+ DateTime.Now.ToString(CultureInfo.InvariantCulture));
     if(ex != null)
     {
         var st = new StackTrace(ex, true);
         var stackFrames = st.GetFrames();
         if (stackFrames != null)
             foreach (var frame in stackFrames)
             {
                 file.WriteLine("_Frame : " + frame.ToString());
                 // Get the line number from the stack frame
                 var line = frame.GetFileLineNumber();
                 file.WriteLine("_Line : " + line.ToString());
             }
     }
     file.WriteLine("---------------------------------------------------------END----------------------------------------------------------");
     file.Close();
     writeMutex.ReleaseMutex();
 }
开发者ID:masoudrk,项目名称:Cad2D,代码行数:28,代码来源:Logger.cs

示例13: Perform

        public bool Perform()
        {
            Reset();

            StackTrace trace = new StackTrace(false);

            StackFrame[] frames= trace.GetFrames();
            for (int i=frames.Length-1; i>=0; i--)
            {
                StackFrame frame = frames[i];

                string typeName = frame.GetMethod().DeclaringType.FullName;

                mTrace.Append(Common.NewLine + typeName + " : " + frame.GetMethod());

                List<StackFrameBase> tests;
                if (mTests.TryGetValue("", out tests))
                {
                    if (Test(frame, trace, tests)) return true;
                }

                if (mTests.TryGetValue(typeName, out tests))
                {
                    if (Test(frame, trace, tests)) return true;
                }
            }

            return false;
        }
开发者ID:Robobeurre,项目名称:NRaas,代码行数:29,代码来源:StackTracer.cs

示例14: GetSource

        private static string GetSource()
        {
            // skip 2 frames: GetSource and its caller
            var trace = new StackTrace(2);
            var frames = trace.GetFrames();

            // might not need a foreach, but doing to to be sure
            foreach (var frame in frames)
            {
                var method = frame.GetMethod();
                var type = method.DeclaringType;

                var assembly = type.Assembly;

                // only remove System?
                if (assembly.GetName().Name == "System")
                {
                    continue;
                }

                // in case there are > 2 frames
                if (type.Name == "Log")
                {
                    continue;
                }

                // that sounds just about nice
                return string.Format("{0}::{1}", type.Name, method.Name);
            }

            return "";
        }
开发者ID:bobolo,项目名称:iw5m-scripts,代码行数:32,代码来源:Log.cs

示例15: ER

 public static void ER(Exception e, params string[] extras)
 {
     StackTrace st = new StackTrace();
     StackFrame[] frames = st.GetFrames();
     string methodName = "UnknownMethod";
     for(int i=0;i< frames.Length;i++)
     {
         if (frames[i].GetMethod().Name == System.Reflection.MethodInfo.GetCurrentMethod().Name)
         {
             if (i + 1 < frames.Length)
             {
                 methodName = frames[i + 1].GetMethod().Name;
                 break;
             }
         }
     }
     Console.WriteLine(String.Format("{1}[{4}:{5}][ERROR({2})]{0}:{3}", methodName, tab, Thread.CurrentThread.ManagedThreadId, e.Message, DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()));
     Console.WriteLine("==========StackTrace==========");
     if (e.StackTrace != null)
         Console.WriteLine(e.StackTrace.ToString());
     else
         Console.WriteLine(st.ToString());
     Console.WriteLine("=============END==============");
     foreach (string s in extras)
         Console.WriteLine(s);
 }
开发者ID:YoshiEnVerde,项目名称:OCTGN,代码行数:26,代码来源:Logger.cs


注:本文中的System.Diagnostics.StackTrace.GetFrames方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。