GetFileLineNumber() public method

public GetFileLineNumber ( ) : int
return int
        private void PrintException(Exception ex, List <GeneratedCode> generatedCodes)
        {
            var frames = new List <Interface.StackFrame>();

            var stackTrace = new StackTrace(ex, true);

            for (int i = 0; i < stackTrace.FrameCount; ++i)
            {
                System.Diagnostics.StackFrame diagnosticFrame = stackTrace.GetFrame(i);

                // Extract method name
                MethodBase method = diagnosticFrame.GetMethod();
                // Note(Maik): Skip internal render methods in case of a stack trace.
                if (Attribute.IsDefined(method, typeof(HideStackTraceAttribute)))
                {
                    continue;
                }
                Type declaringType = method.DeclaringType;
                var  methodSb      = new StringBuilder();
                if (declaringType != null)
                {
                    methodSb.Append(declaringType.FullName).Append(".");
                }
                methodSb.Append(method.Name);

                // Extract original filename, line and column
                int?line = null;
                if (diagnosticFrame.GetFileLineNumber() != 0)
                {
                    line = diagnosticFrame.GetFileLineNumber();
                }

                int?column = null;
                if (diagnosticFrame.GetFileColumnNumber() != 0)
                {
                    column = diagnosticFrame.GetFileColumnNumber();
                }

                string        filename      = diagnosticFrame.GetFileName();
                GeneratedCode generatedCode = generatedCodes.FirstOrDefault(gcode => string.Compare(gcode.TemplatePath, filename, StringComparison.OrdinalIgnoreCase) == 0);
                if ((generatedCode != null) && (line != null))
                {
                    var position = new TextPosition(line.Value, column ?? 1);
                    TextFilePosition original = generatedCode.SourceMap.FindSourceByGenerated(position);
                    if (original.IsValid)
                    {
                        filename = original.Name;
                        line     = original.Line;
                        column   = original.Column;
                    }
                }

                var msgFrame = new Interface.StackFrame(methodSb.ToString(), filename, line, column);
                frames.Add(msgFrame);
            } // for

            this.MessageHandler.Message(TraceLevel.Error, $"{ex.GetType().FullName}: {ex.Message}", string.Empty, new TextPosition());
            this.MessageHandler.StackTrace(frames);
        }
        // private static readonly Log log = Log.getLog(typeof(FaultSerializer));

        private static String toString(StackFrame frame)
        {
            String answer = "";
            MethodBase method = frame.GetMethod();

            if( null != method ) 
            {
                answer += "[";
                Type declaringType = method.DeclaringType;
                if (null != declaringType) 
                {
                    String moduleName = declaringType.Name;
                    if (null != moduleName)
                    {
                        answer += moduleName;
                    }
                }
                String methodName = method.Name;
                if (null != methodName)
                {
                    answer += " ";
                    answer += methodName;
                }
                answer += "]";
            }


            if( 0 != answer.Length ) {
                answer += " ";
            }

            String fileName = frame.GetFileName();
            if (null == fileName || 0 == fileName.Length)
            {
                fileName = "?";
            }
            else
            {
                int lastSlash = fileName.LastIndexOf('\\');
                if (-1 != lastSlash)
                {
                    fileName = fileName.Substring(lastSlash+1); // +1 to skip over the '\'
                }
            }


            String lineNumber = "?";
            if (0 != frame.GetFileLineNumber())
            {
                lineNumber = String.Format("{0}", frame.GetFileLineNumber());
            }

            answer += String.Format("({0}:{1})", fileName, lineNumber);

            return answer;

        }
Beispiel #3
0
        /// <summary>
        /// Raises an internal error. The reason why this is private is so that only
        /// the other InternalError functions can call it. This ensures that the
        /// function can always backtrack exactly 2 stack frames to get to the place
        /// which invoked InternalError.
        /// </summary>
        private static void InternalErrorPrivate(string errorMsg)
        {
            string str = "Internal application error has occurred. Please inform the developer.\n";
            if (errorMsg != null) str += "\nError message: " + errorMsg;
            StackFrame sf = new StackFrame(2, true);
            str += "\nMethod: " + sf.GetMethod();
            if (sf.GetFileLineNumber() != 0)
                // The line number is zero if there is no program database in the
                // application directory (which is the case when a normal user runs it)
                str += "\nFile: " + sf.GetFileName() + "\nLine: " + sf.GetFileLineNumber();

            DlgMessage.Show(str, "Internal error", DlgType.Error, "OK");
        }
Beispiel #4
0
 private static LogInfo Format(string msg, Exception ex = null)
 {
     var f = new StackFrame(6, true);
     var method = f.GetMethod();
     var fileInfo = string.Format("{0}[{1}]", f.GetFileName(), f.GetFileLineNumber());
     if (ex != null)
     {
         method = ex.TargetSite;
     }
     var result = new LogInfo
     {
         Method = string.Format("{0} {1}",
             method.DeclaringType,
             method.Name),
         Message = msg,
         File = string.Empty,
         Detail = string.Empty
     };
     result.File = fileInfo;
     if (ex != null)
     {
         result.Detail = ex.Format();
     }
     return result;
 }
Beispiel #5
0
    /// <summary>
    /// <para>警告!!!!!!!!!!!!!!!!!!!!</para>
    /// <para>这个函数请谨慎使用,会实时打印出函数调用栈信息,类似 print( Exception.stackTrace ),</para>
    /// <para>调用栈目前只打印了,从调用这个函数开始的函数往下10层,并不是全部的栈信息。</para>
    /// <para>本函数只在windows pc下才可以被正确执行,其余平台等于普通log</para>
    /// </summary>
    /// <param name="fmt"></param>
    /// <param name="args"></param>
    public static void LogStackTrace(string fmt, params object[] args)
    {
        string str = "";

        if (args.Length == 0)
        {
            str = fmt;
        }
        else
        {
            str = string.Format(fmt, args);
        }
#if UNITY_STANDALONE_WIN
        str += "\n";
        System.Diagnostics.StackTrace st    = new System.Diagnostics.StackTrace(true);
        System.Diagnostics.StackFrame frame = null;
        for (int i = 1; i < 11; i++)
        {
            frame = st.GetFrame(i);
            str  += frame.GetFileName() + " - ( " + frame.GetFileLineNumber() + " , " + frame.GetFileColumnNumber() + " ) : " + frame.GetMethod().Name + " \n";
        }

        Debug(str);
#else
        Debug(str);
#endif
    }
        private static void ShowVsAssert(string stackTrace, StackFrame frame, string message, string detailMessage) {
            int[] disable = new int[1];
            try {
                string detailMessage2;
                
                if (detailMessage == null)
                    detailMessage2 = stackTrace; 
                else
                    detailMessage2 = detailMessage + Environment.NewLine + stackTrace;                
                string fileName = (frame == null) ? string.Empty : frame.GetFileName();
                if (fileName == null) {
                    fileName = string.Empty;
                }

                int lineNumber = (frame == null) ? 0 : frame.GetFileLineNumber();
                int returnCode = VsAssert(detailMessage2, message, fileName, lineNumber, disable);
                if (returnCode != 0) {
                    if (!System.Diagnostics.Debugger.IsAttached) {
                        System.Diagnostics.Debugger.Launch();
                    }
                    System.Diagnostics.Debugger.Break();
                }
                if (disable[0] != 0)
                    ignoredAsserts[MakeAssertKey(fileName, lineNumber)] = null;
            }
            catch (Exception) {
                vsassertPresent = false;
            }
        }
Beispiel #7
0
    public void TraceStack(System.Diagnostics.StackFrame stackFrame)
    {
        var    method     = stackFrame.GetMethod();
        string className  = method.DeclaringType.Name;
        string methodName = method.Name;
        Regex  regEx      = new Regex(@"(.+)\+\<(.+)\>");
        var    match      = regEx.Match(method.DeclaringType.ToString());

        if (match.Success)
        {
            className  = match.Groups[1].Value;
            methodName = match.Groups[2].Value;
        }

        mCallStackBuilder.Length = 0;
        mCallStackBuilder.AppendFormat
        (
            "at {0}.{1} () [0x0000] in {2}:{3}",
            className,
            methodName,
            stackFrame.GetFileName(),
            stackFrame.GetFileLineNumber()
        );

        mCallStackFrames.Push(mCallStackBuilder.ToString());
    }
Beispiel #8
0
        /// <summary>
        ///     Trace game action.
        /// </summary>
        /// <param name="family">The monitored Family to use to build trace.</param>
        /// <param name="actionName">Action name you want to trace, this name has to match with a transition defined into associated Petri Net of the "family" parameter <see cref="ComponentMonitoring.PnmlFile"/>.</param>
        /// <param name="performedBy">Specify who perform this action, the player or the system. <see cref="MonitoringManager.Source"/></param>
        /// <param name="processLinks">Set to false if the logic expression associated to the action include "+" operators AND the action performed by the player is not allowed by the system. In this case fourth parameters will not be processed. True (default) means fourth parameter will be analysed.</param>
        /// <param name="linksConcerned">links label concerned by this action. You can leave empty if only "*" operators are used in logic expression. Must be defined if logic expression associated to the action include "+" operators. For instance, if logic expression is "(l0+l1)*l3" you have to indicate which links to use to build the trace: l0 and l3 OR l1 and l3 => <code>MonitoringManager.trace(..., "l0", "l3");</code> OR <code>MonitoringManager.trace(..., "l1", "l3");</code></param>
        /// <returns> labels found for this game action if in game analysis is enabled (see: MonitoringManager). return empty Array else </returns>
        public static string[] trace(Family family, string actionName, string performedBy, bool processLinks = true, params string[] linksConcerned)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1, true);                                                      // get caller stackFrame with informations
            string exceptionStackTrace = "(at " + stackFrame.GetFileName() + ":" + stackFrame.GetFileLineNumber().ToString() + ")";                     // to point where this function was called

            if (MonitoringManager.Instance == null)
            {
                throw new TraceAborted("No MonitoringManager found. You must add MonitoringManager component to one of your GameObject first (the Main_Loop for instance).", null);
            }

            FamilyMonitoring fm = MonitoringManager.Instance.getFamilyMonitoring(family);

            if (fm == null)
            {
                throw new TraceAborted("No monitor found for this family.", null);
            }

            string internalName = fm.getInternalName(actionName, exceptionStackTrace, processLinks, linksConcerned);

            if (fm.fullPnSelected >= MonitoringManager.Instance.PetriNetsName.Count)
            {
                fm.fullPnSelected = 1;
            }
            string pnName = MonitoringManager.Instance.PetriNetsName[fm.fullPnSelected];

            return(MonitoringManager.processTrace(pnName, internalName, performedBy));
        }
Beispiel #9
0
        private static void Log(LogLevel logLevel, string msg)
        {
            if (logLevel < LogLevel) return;

            StackFrame frame = new StackFrame(2, true);
            var method = frame.GetMethod();
            var lineNumber = frame.GetFileLineNumber();

            var color = Console.ForegroundColor;
            switch (logLevel)
            {
                case LogLevel.None:
                    break;
                case LogLevel.Debug:
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    break;
                case LogLevel.Info:
                    Console.ForegroundColor = ConsoleColor.Gray;
                    break;
                case LogLevel.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                case LogLevel.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
            }

            Console.WriteLine("{0}.{1}:{2} - {3}", method.DeclaringType.FullName, method.Name, lineNumber, msg);
            Console.ForegroundColor = color;
        }
Beispiel #10
0
        // сформировать данные о фрейме стека
        private static StackItem GetStackItem(StackFrame sf)
        {
            if( sf == null )
                        return null;
                MethodBase method = sf.GetMethod();
                if( method == null || method.ReflectedType == null )
                        return null;

                // получить информацию о данном фрейме стека
                StackItem item  = new StackItem();
                item.Module     = method.Module.Assembly.FullName;
                item.ClassName  = method.ReflectedType.Name;
                item.MethodName = method.Name;
                item.FileName   = sf.GetFileName();
                item.Line       = sf.GetFileLineNumber();

                // получить параметры данного метода
                StringBuilder parameters = new StringBuilder();
                ParameterInfo[] paramsInfo = method.GetParameters();
                for( Int32 i = 0; i < paramsInfo.Length; i++ )
                {
                        ParameterInfo currParam = paramsInfo[ i ];
                        parameters.Append( currParam.ParameterType.Name );
                        parameters.Append( " " );
                        parameters.Append( currParam.Name );
                        if( i != paramsInfo.Length - 1 )
                                parameters.Append( ", " );
                }

                item.Params = parameters.ToString();

                return item;
        }
Beispiel #11
0
    private void DebugLog(string msg, object listenerObject, System.Diagnostics.StackFrame stack)
    {
        var path      = stack.GetFileName();
        var lastIndex = path.LastIndexOf(System.IO.Path.DirectorySeparatorChar);

        path = path.Substring(lastIndex + 1, path.Length - lastIndex - 1);

        int line = stack.GetFileLineNumber();

        string listenerTypeName = "";

        UnityEngine.Object unityContext = null;

        if (listenerObject != null)
        {
            unityContext = listenerObject as UnityEngine.Object;

            if (!unityContext)
            {
                listenerTypeName = listenerObject.GetType().Name;
            }
            else
            {
                listenerTypeName = unityContext.name;
            }
        }

        Debug.Log((msg + " from '" + listenerTypeName + "' at " + path + ", line: " + line), unityContext);
    }
Beispiel #12
0
        /// <summary>
        /// Converts a System.Diagnostics.StackFrame to a Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryTypes.StackFrame.
        /// </summary>
        internal static IStackFrame GetStackFrame(System.Diagnostics.StackFrame stackFrame, int frameId)
        {
            var convertedStackFrame = new Telemetry.DataContract.StackFrame()
            {
                level = frameId
            };

            var    methodInfo = stackFrame.GetMethod();
            string fullName;

            if (methodInfo.DeclaringType != null)
            {
                fullName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name;
            }
            else
            {
                fullName = methodInfo.Name;
            }

            convertedStackFrame.method   = fullName;
            convertedStackFrame.assembly = methodInfo.Module.Assembly.FullName;
            convertedStackFrame.fileName = stackFrame.GetFileName();

            // 0 means it is unavailable
            int line = stackFrame.GetFileLineNumber();

            if (line != 0)
            {
                convertedStackFrame.line = line;
            }

            return(convertedStackFrame);
        }
Beispiel #13
0
    /// <summary>s
    /// 写入带 堆栈执行 的Info 日志
    /// </summary>
    /// <param name="logName">日志名称</param>
    /// <param name="developer">开发记录者</param>
    /// <param name="Info_objs">日志内容</param>
    public static void LogWrite(string logName, Developer developer, params object[] Info_objs)
    {
        lock (locker)
        {
            List <string> lstDetails            = new List <string>();
            System.Diagnostics.StackTrace stack = new System.Diagnostics.StackTrace(1, true);
            System.Diagnostics.StackFrame frame = stack.GetFrame(0);
            string execFile   = frame.GetFileName();
            string fullName   = frame.GetMethod().DeclaringType.FullName;
            string methodName = frame.GetMethod().Name;
            int    execLine   = frame.GetFileLineNumber();
            lstDetails.Add("文件路径:" + execFile + "\r\n");
            lstDetails.Add("类全命名:" + fullName + "\r\n");
            lstDetails.Add("执行方法:" + methodName + "\r\n");
            lstDetails.Add("当前行号:" + execLine + "\r\n");

            if (Info_objs != null && Info_objs.Length > 0)
            {
                List <string> lstInfo = new List <string>();
                foreach (var item in Info_objs)
                {
                    lstInfo.Add(Log.GetModelData(item));
                }
                lstDetails.Add("标记信息:" + string.Join(";", lstInfo.ToArray()));
            }
            Write(logName, developer, LogLevel.Info, string.Join("\r\n", lstDetails.ToArray()), DateTime.Now);
        }
    }
Beispiel #14
0
    public static string GetStackTrace(int skipFrames = 1)
    {
        StringBuilder sb = new StringBuilder();

        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true);

        // maybe count-skipframes;
        string stackIndent = "|";
        string filename    = "";

        for (int i = skipFrames; i < st.FrameCount; i++)
        {
            stackIndent += " ";
            System.Diagnostics.StackFrame sf = st.GetFrame(i);
            sb.Append(stackIndent);
            filename = sf.GetFileName();
            if (filename != null)
            {
                int lastIndex = filename.LastIndexOf("\\");
                if (lastIndex > 0)
                {
                    sb.Append(filename.Substring(lastIndex));
                }
                else
                {
                    sb.Append(filename);
                }
            }

            sb.Append(sf.GetFileLineNumber());
        }
        return(sb.ToString());
    }
        /// <summary>
        /// returns a stack frame item from a stack frame. This 
        /// </summary>
        /// <param name="frame"></param>
        /// <returns></returns>
        public StackFrameItem(StackFrame frame)
        {
            // set default values
            m_lineNumber = NA;
            m_fileName = NA;
            m_method = new MethodItem();
            m_className = NA;

			try
			{
				// get frame values
				m_lineNumber = frame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
				m_fileName = frame.GetFileName();
				// get method values
				MethodBase method = frame.GetMethod();
				if (method != null)
				{
					if(method.DeclaringType != null)
						m_className = method.DeclaringType.FullName;
					m_method = new MethodItem(method);
				}
			}
			catch (Exception ex)
			{
				LogLog.Error(declaringType, "An exception ocurred while retreiving stack frame information.", ex);
			}

            // set full info
            m_fullInfo = m_className + '.' + m_method.Name + '(' + m_fileName + ':' + m_lineNumber + ')';
        }
Beispiel #16
0
    static public void Assert(bool expression)
    {
        if (!expression)
        {
#if UNITY_EDITOR
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(1);

            string fileName   = stackFrame.GetFileName();
            int    lineNumber = stackFrame.GetFileLineNumber();

            string message = "Assertion failed: file " + fileName + ", line " + lineNumber;

            Debug.LogError(message);

            if (UnityEditor.EditorUtility.DisplayDialog("Assertion failed", message, "Break", "Ignore"))
            {
                Debug.Break();
                UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(fileName, lineNumber);
            }
#else
            Debug.LogError("Assertion failed");
#endif
        }
    }
Beispiel #17
0
        /// <summary>
        ///     Get next actions to perform in order to reach targeted game action.
        /// </summary>
        /// <param name="family">The monitored Family on which you want reach action.</param>
        /// <param name="targetedActionName">Action name you want to reach, this name has to match with a transition defined into associated Petri Net  of the "family" parameter <see cref="ComponentMonitoring.PnmlFile"/> The special key word "##playerObjectives##" enable to target all player objective actions defined inside full Petri Net from which the monitor is part of (in this special case, "linksConcerned" parameter will be ignore).</param>
        /// <param name="maxActions">Maximum number of actions returned.</param>
        /// <param name="linksConcerned">links label concerned by this action. You can leave empty if only "*" operators are used in logic expression. Must be defined if logic expression associated to the action include "+" operators. For instance, if logic expression is "(l0+l1)*l3" you have to indicate which links to use to look for the trace: l0 and l3 OR l1 and l3 => <code>MonitoringManager.getNextActionToReach(..., "l0", "l3");</code> OR <code>MonitoringManager.getNextActionToReach(..., "l1", "l3");</code></param>
        /// <returns>List of Pairs including a ComponentMonitoring and its associated game action useful to reach the targeted action, the number of actions returned is less or equal to maxActions parameters.</returns>
        public static List <KeyValuePair <ComponentMonitoring, string> > getNextActionsToReach(Family family, string targetedActionName, int maxActions, params string[] linksConcerned)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1, true);                                                      // get caller stackFrame with informations
            string exceptionStackTrace = "(at " + stackFrame.GetFileName() + ":" + stackFrame.GetFileLineNumber().ToString() + ")";                     // to point where this function was called

            if (MonitoringManager.Instance == null)
            {
                throw new TraceAborted("No MonitoringManager found. You must add MonitoringManager component to one of your GameObject first (the Main_Loop for instance).", null);
            }

            FamilyMonitoring fm = MonitoringManager.Instance.getFamilyMonitoring(family);

            if (fm == null)
            {
                throw new TraceAborted("No monitor found for this family", null);
            }

            string internalName = targetedActionName;

            if (!targetedActionName.Equals("##playerObjectives##"))
            {
                internalName = fm.getInternalName(targetedActionName, exceptionStackTrace, true, linksConcerned);
            }
            if (fm.fullPnSelected >= MonitoringManager.Instance.PetriNetsName.Count)
            {
                fm.fullPnSelected = 1;
            }
            string pnName = MonitoringManager.Instance.PetriNetsName[fm.fullPnSelected];

            return(MonitoringManager.getNextActionsToReach(pnName, internalName, maxActions));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionFrame"/> class.
        /// </summary>
        /// <param name="frame">The <see cref="StackFrame"/>.</param>
        public ExceptionFrame(StackFrame frame)
        {
            if (frame == null)
                return;

            int lineNo = frame.GetFileLineNumber();

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

            var method = frame.GetMethod();
            if (method != null)
            {
                Module = (method.DeclaringType != null) ? method.DeclaringType.FullName : null;
                Function = method.Name;
                Source = method.ToString();
            }
            else
            {
                // on some platforms (e.g. on mono), StackFrame.GetMethod() may return null
                // e.g. for this stack frame:
                //   at (wrapper dynamic-method) System.Object:lambda_method (System.Runtime.CompilerServices.Closure,object,object))

                Module = "(unknown)";
                Function = "(unknown)";
                Source = "(unknown)";
            }

            Filename = frame.GetFileName();
            LineNumber = lineNo;
            ColumnNumber = frame.GetFileColumnNumber();
        }
Beispiel #19
0
 public ConeStackFrame(StackFrame frame)
 {
     Method = frame.GetMethod();
     File = frame.GetFileName();
     Line = frame.GetFileLineNumber();
     Column = frame.GetFileColumnNumber();
 }
Beispiel #20
0
    /// bulk of code written by: Alex Marcum - 11/20/2012
    public static void logError(Exception ex)
    {
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1, true);

        //System.IO.FileInfo temp = new System.IO.FileInfo(fileName);
        //fileName = temp.Name;

        //Class Name is the Whole path to the Filename
        string fileName = stackFrame.GetFileName();
        string functionName = stackFrame.GetMethod().Name.ToString();
        int line = stackFrame.GetFileLineNumber();

        try
        {
            using (CCSEntities db = new CCSEntities())
            {
                ErrorLog el = new ErrorLog();

                el.TimeStamp = DateTime.Now;
                el.FileName = fileName;
                el.FunctionName = functionName;
                el.LineNumber = line.ToString();
                el.ErrorText = ex.Message;

                db.ErrorLogs.Add(el);
                db.SaveChanges();
            }
        }
        catch (Exception /*ex*/)
        {
        }
    }
        private void AddToLog(string msg, bool isAnError, UnityEngine.Object obj)
        {
            StackTrace stackTrace = new StackTrace(2, true);

            System.Diagnostics.StackFrame frame = stackTrace.GetFrame(0);
            this.LogMessage(msg, frame.GetFileName(), frame.GetFileLineNumber(), obj, isAnError);
        }
Beispiel #22
0
    private static void LogMessage(string tag, int stackIndex, string arguments, string message)
    {
#if DEBUG
        var frame = new System.Diagnostics.StackFrame(stackIndex, true);

        var thread     = System.Threading.Thread.CurrentThread;
        var threadInfo = "<" + thread.ManagedThreadId.ToString("000") + (string.IsNullOrEmpty(thread.Name) ? "" : ("=" + thread.Name)) + ">";
#if GG_PLATFORM_IOS
        var dateInfo = "";
#else
        var dateInfo = "[" + DateTime.Now.ToString("HH:mm:ss,fff") + "]";
#endif
        var backrefInfo = new string(' ', 32) + " in " + frame.GetFileName() + ":" + frame.GetFileLineNumber();
        var methodInfo  = frame.GetMethod().ReflectedType.Name + "." + frame.GetMethod().Name + "(" + arguments + ")";

        var msg = threadInfo + " " + dateInfo + " " + methodInfo + " " + message + " " + backrefInfo;

#if GG_PLATFORM_ANDROID
        Android.Util.Log.Debug(tag, msg);
#elif GG_PLATFORM_IOS
        Console.WriteLine(tag + " " + msg);
#else
        Debug.WriteLine(tag + " " + msg);
#endif
#endif // DEBUG
    }
Beispiel #23
0
 static void Log(object message)
 {
     StackFrame frame = new StackFrame(1, true);
     var method = frame.GetMethod();
     var fileName = frame.GetFileName();
     var lineNumber = frame.GetFileLineNumber();
     Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, method.Name, message);
 }
Beispiel #24
0
		public void Default ()
		{
			StackFrame sf = new StackFrame ();
			Assert.AreEqual (0, sf.GetFileLineNumber (), "GetFileLineNumber");
			Assert.AreEqual (0, sf.GetFileColumnNumber (), "GetFileColumnNumber");
			Assert.IsTrue (sf.GetILOffset () >= 0, "GetILOffset");
			Assert.IsTrue (sf.GetNativeOffset () >= 0, "GetNativeOffset");
			Assert.AreEqual ("Default", sf.GetMethod ().Name, "GetMethod");
		}
 public override void Write(string message)
 {
     StackFrame sf = new StackFrame (5, true);
     string fileName = sf.GetFileName();
     int lineNumber = sf.GetFileLineNumber();
     string methodName = sf.GetMethod ().Name;
     string prefix = "["+ fileName + ":" + lineNumber +" (" + methodName + ")]";
     base.Write ( prefix + message);
 }
Beispiel #26
0
		public void FileName_LineNumber_ColumnNumber ()
		{
			StackFrame sf = new StackFrame (String.Empty, Int32.MinValue, Int32.MaxValue);
			Assert.AreEqual (Int32.MinValue, sf.GetFileLineNumber (), "GetFileLineNumber");
			Assert.AreEqual (Int32.MaxValue, sf.GetFileColumnNumber (), "GetFileColumnNumber");
			Assert.IsTrue (sf.GetILOffset () >= 0, "GetILOffset");
			Assert.IsTrue (sf.GetNativeOffset () > 0, "GetNativeOffset");
			Assert.AreEqual ("FileName_LineNumber_ColumnNumber", sf.GetMethod ().Name, "GetMethod");
		}
Beispiel #27
0
		static string GetExtraInfo (StackFrame sf = null)
		{
			string threadid = String.Format ("thread_id: {0}", Thread.CurrentThread.ManagedThreadId.ToString ("x"));
			string domainid = String.Format ("appdomain_id: {0}", AppDomain.CurrentDomain.Id.ToString ("x"));			
			string filepath = sf == null ? null : sf.GetFileName ();
			int lineNumber = sf == null ? -1 : sf.GetFileLineNumber ();
			string format = String.IsNullOrEmpty (filepath) ? " [{0}, {1}]" : " [{0}, {1}, in {2}:{3}]";
			return String.Format (format, domainid, threadid, filepath, lineNumber);
		}
Beispiel #28
0
    private static void log(string sInfo, int logLevel)
    {
#if DEBUG
        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(2, true);
        System.Diagnostics.StackFrame sf = st.GetFrame(0);
        Unity_Log(logLevel, sInfo, sf.GetFileName(), sf.GetFileLineNumber());
#else
        Unity_Log(logLevel, sInfo, "MojingLog.cs", 38);
#endif
    }
 /// <summary>
 /// Creates a new instance of the <see cref="WcfRawJson.ErrorHandling.FaultStackFrame"/> 
 /// class from an existing <see cref="System.Diagnostics.StackFrame"/>.
 /// </summary>
 /// <param name="frame">
 /// The <see cref="System.Diagnostics.StackFrame"/> object from which to derive this
 /// <see cref="WcfRawJson.ErrorHandling.StackFrame"/>
 /// </param>
 public FaultStackFrame(StackFrame frame)
 {
     this.FileColumnNumber = frame.GetFileColumnNumber();
     this.FileLineNumber = frame.GetFileLineNumber();
     this.FileName = frame.GetFileName();
     this.ILOffset = frame.GetILOffset();
     this.Method = frame.GetMethod().ToString();
     this.NativeOffset = frame.GetNativeOffset();
     this.Description = frame.ToString();
 }
Beispiel #30
0
        public static void PrintCodePosition(LogColor logColor)
        {
            StackFrame stackFrame = new System.Diagnostics.StackFrame(1, true);
            string     message    = "-> { " + stackFrame.GetMethod().ToString() + " }";

            string[] filePath = stackFrame.GetFileName().Split('/');
            message += " in " + filePath[filePath.Length - 1]; // Append the file name
            message += "::" + stackFrame.GetFileLineNumber().ToString();
            DebugLog.LogColor(message, logColor);
            return;
        }
Beispiel #31
0
        public static void Log(object o)
        {
            var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture);

            using (var fs = new FileStream("hnooo.log", FileMode.Append, FileAccess.Write)) {
                using(var sw = new StreamWriter(fs)) {
                    var frame = new StackFrame(1);
                    sw.WriteLine($"[{time}][{frame.GetFileName()}.{frame.GetMethod().Name} L{frame.GetFileLineNumber()}] {o}");
                }
            }
        }
    public static void LogCurrentStackTrace()
    {
        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();

        Debug.Log("LogCurrentStackTrace(): ");
        for (int i = 1; i < st.FrameCount; i++)
        {
            System.Diagnostics.StackFrame sf = st.GetFrame(i);
            Debug.Log(string.Format("Method: {0} (Line: {1})", sf.GetMethod(), sf.GetFileLineNumber()));
        }
    }
Beispiel #33
0
        public CallSite(StackFrame frame)
        {
            Line = frame.GetFileLineNumber();
            File = frame.GetFileName();
            ILOffset = frame.GetILOffset();

            var method = frame.GetMethod();

            if (method != null)
                Method = new MethodInfo(method);
        }
    private void WriteToFile(Exception ex)
    {
        System.Diagnostics.StackTrace st    = new System.Diagnostics.StackTrace(ex, true);
        System.Diagnostics.StackFrame frame = st.GetFrame(0);
        string        methodName            = frame.GetMethod().Name;
        int           line = frame.GetFileLineNumber();
        StringBuilder sb   = new StringBuilder();

        sb.Append("Error: " + ex.Message.ToString() + " Method name: " + methodName + " LineNo: " + Convert.ToInt16(line));

        CommonClass.WriteErrorErrFile(Request.RawUrl.ToString(), ex.StackTrace.ToString() + "-->" + sb.ToString());
    }
Beispiel #35
0
 public static void isNull(object pObject)
 {
     if (pObject == null)
     {
         StackFrame frame = new StackFrame(1, true);
         var message = string.Format("Line: {0}\r\nColumn: {1}\r\nWhere:{2}",
                             frame.GetFileLineNumber(),
                             frame.GetFileColumnNumber(),
                             frame.GetMethod().Name);
         throw new NullReferenceException(message);
     }
 }
Beispiel #36
0
 public static void assert(bool pCondition)
 {
     if (!pCondition)
     {
         StackFrame frame = new StackFrame(1, true);
         var message = string.Format("Line: {0}\r\nColumn: {1}\r\nWhere:{2}",
                             frame.GetFileLineNumber(),
                             frame.GetFileColumnNumber(),
                             frame.GetMethod().Name);
         throw new Exception(message);
     }
 }
Beispiel #37
0
		// 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 (StackFrame sf, bool checkFile)
		{
			int cn = sf.GetFileColumnNumber ();
			int ln = sf.GetFileLineNumber ();
			int il = sf.GetILOffset ();
			int no = sf.GetNativeOffset ();

			Assert.IsNotNull (sf.GetMethod (), "GetMethod");

			if (checkFile) {
				string fn = sf.GetFileName ();
			}
		}
Beispiel #38
0
        public static void CreateErrorLog(string LogMsg)
        {
            //    Dim frame As StackFrame = New StackFrame(1, True)
            //Dim ClassName As String = frame.GetMethod.ReflectedType.Name
            //Dim FunctionName As String = frame.GetMethod.Name
            //Dim LineNo As Integer = frame.GetFileLineNumber
            StackFrame frame = new StackFrame(1, true);
            string ClassName = frame.GetMethod().ReflectedType.Name;
            string FuntionName = frame.GetMethod().Name;
            int LineNo = frame.GetFileLineNumber();

            CreateErrorLog(LogMsg, ClassName + "." + FuntionName, GetLocalIPAddress());
        }
Beispiel #39
0
        public LogEventArgs(String message, Int32 stackDepth = 2)
        {
            var stackFrame = new StackFrame(stackDepth, true /* Get the file name, line number, and column number of the stack frame. */);
              var methodBase = stackFrame.GetMethod();
              var lineNumber = stackFrame.GetFileLineNumber();

              this._message = String.Format("{0}.{1}{2} - {3}",
            methodBase.DeclaringType.FullName,
            methodBase.Name,
            /* In JIT optimized builds, lineNumber will either be 0 or wildly inaccurate.
               In non-optimized builds, lineNumber will be non-zero and accurate. */
            this._isJitOptimized ? "" : " - Line " + lineNumber.ToString(),
            message);
        }
 /// <summary>
 /// Gets the trace string.
 /// </summary>
 /// <returns>The trace string.</returns>
 /// <param name="frame">Frame.</param>
 /// <param name="callerClassName">Caller class name.</param>
 public static string GetTraceString(StackFrame frame, out string callerClassName)
 {
     var fileName = frame.GetFileName();
     //			if(!string.IsNullOrEmpty(fileName))
     //			{
     //				var indexToTrim = fileName.IndexOf("/Assets"); // hardcode for Unity folder layout
     //				fileName = fileName.Remove(0, indexToTrim + 7);
     //			}
     var line = frame.GetFileLineNumber();
     var method = frame.GetMethod();
     var methodName = method.Name;
     callerClassName = method.ReflectedType.Name;
     return "      at " + callerClassName + "." + methodName + "() (in " + fileName + ":" + line + ")";
 }
 public CallerLocation(StackFrame f)
 {
     if (f == null)
     {
         FileName = "";
         LineNumber = 0;
         Method = null;
     }
     else
     {
         FileName = f.GetFileName();
         LineNumber = f.GetFileLineNumber();
         Method = f.GetMethod();
     }
 }
Beispiel #42
0
 public static void Report(
         ReportType type,
         string reportContext,
         string fileName,
         DDS.ErrorCode reportCode,
         string description)
 {
     StackFrame callStack = new StackFrame(1, true);
     Report( type,
             reportContext,
             fileName,
             callStack.GetFileLineNumber(),
             reportCode,
             description);
 }
Beispiel #43
0
    /// <summary>
    /// Logs an exception into the ErrorLog table
    /// </summary>
    /// <param name="ex"></param>
    /// <returns>Returns the ErrorID of the logged exception, 
    ///         if any error occurs a 0 is returned</returns>
    /// Alex Marcum - 11/20/2012
    public static DataSet logError(Exception ex, String additionalInformation = "")
    {
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1, true);

        //Class Name is the Whole path to the Filename
        string fileName = stackFrame.GetFileName();
        System.IO.FileInfo temp = new System.IO.FileInfo(fileName);
        fileName = temp.Name;
        string functionName = stackFrame.GetMethod().Name.ToString();
        int line = stackFrame.GetFileLineNumber();

        String connStr = Connections.connErrorLogStr();
        OleDbConnection conn = new OleDbConnection(connStr);
        DataSet ds = new DataSet();

        try
        {
            int code = 0; //default error code for now until we establish a list of exceptions and related numbers
            DateTime errorTime = DateTime.Now;  //date time stored in order to be used later in getErrorID method

            String sql = @"INSERT INTO ErrorLog([timeStamp], [fileName], [functionName], [lineNumber],
                        [errorText], [errorCode], [extraData])
                        Values(@now, @file, @function, @line, @eText, @eCode, @extraData);";

            OleDbCommand cmd = new OleDbCommand(sql, conn);
            cmd.Parameters.AddWithValue("@now", errorTime.ToString());
            cmd.Parameters.AddWithValue("@file", fileName);
            cmd.Parameters.AddWithValue("@function", functionName);
            cmd.Parameters.AddWithValue("@line", line);
            cmd.Parameters.AddWithValue("@eText", ex.Message);
            cmd.Parameters.AddWithValue("@eCode", code);
            cmd.Parameters.AddWithValue("@extraData", additionalInformation);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
            ds = getErrorID(errorTime);  //helper method used to get ErrorID based on the timestamp of the error
            return ds;
        }
        catch (Exception /*ex*/)
        {
        }
        finally
        {
            conn.Close();
        }
        return ds;
    }
Beispiel #44
0
        public static StackFrame Create(System.Diagnostics.StackFrame frame)
        {
            if (frame == null)
            {
                return(null);
            }

            string      fileName      = null;
            bool        isTaskAwaiter = false;
            ITypeMember member        = null;

            try {
                fileName = frame.GetFileName();
            } catch (SecurityException) {
                // CAS check failure
            }

            var method = frame.GetMethod();

            if (method != null)
            {
                isTaskAwaiter = method.DeclaringType.IsTaskAwaiter() ||
                                method.DeclaringType.DeclaringType.IsTaskAwaiter();

                var property = GetPropertyForMethodAccessor(method);
                if (property != null)
                {
                    member = Property.Create(property);
                }
                else
                {
                    member = Method.Create(method);
                }
            }

            return(new StackFrame(
                       fileName,
                       frame.GetFileLineNumber(),
                       frame.GetFileColumnNumber(),
                       frame.GetILOffset(),
                       frame.GetNativeOffset(),
                       frame.GetMethodAddress(),
                       frame.GetMethodIndex(),
                       isTaskAwaiter,
                       ParseInternalMethodName(frame.GetInternalMethodName()),
                       member));
        }
 public static string StackFrameToString(StackFrame stackFrame)
 {
     StringBuilder sb = new StringBuilder();
     int intParam; MemberInfo mi = stackFrame.GetMethod();
     sb.Append("   ");
     sb.Append(mi.DeclaringType.Namespace);
     sb.Append(".");
     sb.Append(mi.DeclaringType.Name);
     sb.Append(".");
     sb.Append(mi.Name);
     // -- build method params           
     sb.Append("(");
     intParam = 0;
     foreach (ParameterInfo param in stackFrame.GetMethod().GetParameters())
     {
         intParam += 1;
         sb.Append(param.Name);
         sb.Append(" As ");
         sb.Append(param.ParameterType.Name);
     }
     sb.Append(")");
     sb.Append(Environment.NewLine);
     // -- if source code is available, append location info           
     sb.Append("       ");
     if (string.IsNullOrEmpty(stackFrame.GetFileName()))
     {
         sb.Append("(unknown file)");
         //-- native code offset is always available               
         sb.Append(": N ");
         sb.Append(string.Format("{0:#00000}", stackFrame.GetNativeOffset()));
     }
     else
     {
         sb.Append(Path.GetFileName(stackFrame.GetFileName()));
         sb.Append(": line ");
         sb.Append(string.Format("{0:#0000}", stackFrame.GetFileLineNumber()));
         sb.Append(", col ");
         sb.Append(string.Format("{0:#00}", stackFrame.GetFileColumnNumber()));
         if (stackFrame.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
         {
             sb.Append(", IL ");
             sb.Append(string.Format("{0:#0000}", stackFrame.GetILOffset()));
         }
     }
     sb.Append(Environment.NewLine);
     return sb.ToString();
 }
Beispiel #46
0
        public void Add(string message)
        {
            // Taken from http://heifner.blogspot.com/2006/12/logging-method-name-in-c.html
            // Start one up so that we don't get the current method but the one that called this one
            StackFrame sf = new StackFrame(1, true);
            System.Reflection.MethodBase mb = sf.GetMethod();
            string methodName = mb != null ? mb.Name : "ERROR DETERMINING CALLING METHOD NAME";
            // note to self: not sure if i need the data captured below this point
            // filename can be null, if unable to determine
            string filename = sf.GetFileName();
            // we only want the filename, not the complete path
            if (filename != null)
                filename = filename.Substring(filename.LastIndexOf('\\') + 1);
            int lineNumber = sf.GetFileLineNumber();

            _log.Add(DateTime.Now.ToString() + "  :  " + filename + "  :  " + methodName + "  :  " + message);
        }
 public static void LogException(this ILogProvider provider,
                                 Exception exception)
 {
     var stackFrame = new StackFrame(1, true);
     var method = stackFrame.GetMethod();
     string memberName = null;
     if (method.IsNotNull())
     {
         memberName = method.Name;
     }
     var sourceFilePath = stackFrame.GetFileName();
     var sourceLineNumber = stackFrame.GetFileLineNumber();
     if (exception.IsNull())
     {
         throw new ArgumentNullException("exception");
     }
     InternalLogMessage(provider, exception.ToString(), Severity.Error, Verbosity.Normal, memberName, sourceFilePath, sourceLineNumber);
 }
Beispiel #48
0
    private static string GetLogSourceInfo(int skipFrames)
    {
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(skipFrames, true);
        if (stackFrame == null)
        {
            return("");
        }

        string fileName = stackFrame.GetFileName();

        fileName = (fileName == null) ? "UnknownFile" : fileName.Substring(fileName.LastIndexOf('/') + 1);
        int lineNumber = stackFrame.GetFileLineNumber();

        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        string methodName = (methodBase == null) ? "UnknownMethod" : methodBase.ToString();

        return(fileName + "(" + lineNumber + "): " + methodName);
    }
Beispiel #49
0
        /// <summary>
        /// Converts a System.Diagnostics.StackFrame to a Coding4Fun.VisualStudio.ApplicationInsights.Extensibility.Implementation.TelemetryTypes.StackFrame.
        /// </summary>
        /// <returns></returns>
        private static Coding4Fun.VisualStudio.ApplicationInsights.Extensibility.Implementation.External.StackFrame GetStackFrame(System.Diagnostics.StackFrame stackFrame, int frameId)
        {
            Coding4Fun.VisualStudio.ApplicationInsights.Extensibility.Implementation.External.StackFrame stackFrame2 = new Coding4Fun.VisualStudio.ApplicationInsights.Extensibility.Implementation.External.StackFrame
            {
                level = frameId
            };
            MethodBase method = stackFrame.GetMethod();
            string     text2  = stackFrame2.method = ((!(method.DeclaringType != null)) ? method.Name : (method.DeclaringType.FullName + "." + method.Name));

            stackFrame2.assembly = method.Module.Assembly.FullName;
            stackFrame2.fileName = stackFrame.GetFileName();
            int fileLineNumber = stackFrame.GetFileLineNumber();

            if (fileLineNumber != 0)
            {
                stackFrame2.line = fileLineNumber;
            }
            return(stackFrame2);
        }
Beispiel #50
0
        /// <summary>
        ///     Get next actions to perform in order to reach the player objective of the Petri net.
        /// </summary>
        /// <param name="pnName">The Petri net name to process.</param>
        /// <param name="maxActions">Maximum number of actions returned.</param>
        /// <returns>List of Pairs including a ComponentMonitoring and its associated game action useful to reach the player objective, the number of actions returned is less or equal to maxActions parameters.</returns>
        public static List <KeyValuePair <ComponentMonitoring, string> > getNextActionsToReachPlayerObjective(string pnName, int maxActions)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1, true);                                                      // get caller stackFrame with informations
            string exceptionStackTrace = "(at " + stackFrame.GetFileName() + ":" + stackFrame.GetFileLineNumber().ToString() + ")";                     // to point where this function was called

            if (MonitoringManager.Instance == null)
            {
                throw new TraceAborted("No MonitoringManager found. You must add MonitoringManager component to one of your GameObject first (the Main_Loop for instance).", null);
            }

            if (!MonitoringManager.Instance.PetriNetsName.Contains(pnName))
            {
                throw new TraceAborted("No Petri net with name \"" + pnName + "\" found", null);
            }

            string internalName = "##playerObjectives##";

            return(MonitoringManager.getNextActionsToReach(pnName, internalName, maxActions));
        }
Beispiel #51
0
        /// <summary>
        /// Converts a System.Diagnostics.StackFrame to a Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryTypes.StackFrame.
        /// </summary>
        internal static StackFrame GetStackFrame(System.Diagnostics.StackFrame stackFrame, int frameId)
        {
            var    methodInfo = stackFrame.GetMethod();
            string fullName;
            string assemblyName;

            if (methodInfo == null)
            {
                fullName     = "unknown";
                assemblyName = "unknown";
            }
            else
            {
                assemblyName = methodInfo.Module.Assembly.FullName;
                if (methodInfo.DeclaringType != null)
                {
                    fullName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name;
                }
                else
                {
                    fullName = methodInfo.Name;
                }
            }

            var convertedStackFrame = new StackFrame(frameId, fullName);

            convertedStackFrame.Assembly = assemblyName;
            convertedStackFrame.FileName = stackFrame.GetFileName();

            // 0 means it is unavailable
            int line = stackFrame.GetFileLineNumber();

            if (line != 0)
            {
                convertedStackFrame.Line = line;
            }

            return(convertedStackFrame);
        }
Beispiel #52
0
        /// <summary>
        /// Check if Q# stack frame and C# stack frame match (refer to the same location in the code)
        /// </summary>
        private static bool IsMatch(System.Diagnostics.StackFrame csharpFrame, StackFrame qsharpFrame)
        {
            string fileName = csharpFrame.GetFileName();

            if (string.IsNullOrEmpty(fileName))
            {
                return(false);
            }
            string fullPath = System.IO.Path.GetFullPath(fileName);

            if (fullPath != qsharpFrame.SourceFile)
            {
                return(false);
            }
            int failedLineNumber = csharpFrame.GetFileLineNumber();

            if (failedLineNumber < qsharpFrame.DeclarationStartLineNumber)
            {
                return(false);
            }
            return
                ((failedLineNumber < qsharpFrame.DeclarationEndLineNumber) ||
                 (qsharpFrame.DeclarationEndLineNumber == -1));
        }
Beispiel #53
0
        public override bool GetCurrentStackTrace(int n, System.Collections.Generic.List <string> procs,
                                                  System.Collections.Generic.List <string> files, System.Collections.Generic.List <int> lineNos)
        {
            StackTrace st = new StackTrace(true);

            for (int i = 0; i < st.FrameCount; i++)
            {
                System.Diagnostics.StackFrame sf = st.GetFrame(i);
                string assembly_name             = sf.GetMethod().Module.Assembly.GetName().ToString();

                // this is fragile
                if (assembly_name.Contains(".ManagedChess") || assembly_name.Contains(".ExtendedReflection"))
                {
                    continue;
                }

                string file = sf.GetFileName();

                if (file == null || file == "")
                {
                    file = "NONE";
                }

                string method = sf.GetMethod().Name;
                int    lineno = sf.GetFileLineNumber();
                procs.Add(method);
                files.Add(file);
                lineNos.Add(lineno);

                if (lineNos.Count >= n)
                {
                    break;
                }
            }
            return(true);
        }
    public void Push(ICommand command)
    {
#if DEBUG_METHOD_CALL
        System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
        System.Diagnostics.StackFrame frame      = stackTrace.GetFrame(1);
        Debug.LogFormat("Command Stack Push: {0} in file {1} at line {2}", frame.GetMethod().Name, System.IO.Path.GetFileName(frame.GetFileName()), frame.GetFileLineNumber());
#endif
        ResetTail();
        ++currentStackIndex;
        command.Invoke();
        commands.Add(command);
    }
Beispiel #55
0
        public override string ToString()
        {
            string        newline   = String.Format("{0}   {1} ", Environment.NewLine, Locale.GetText("at"));
            string        unknown   = Locale.GetText("<unknown method>");
            string        debuginfo = Locale.GetText(" in {0}:line {1}");
            StringBuilder sb        = new StringBuilder();

            for (int i = 0; i < FrameCount; i++)
            {
                StackFrame frame = GetFrame(i);
                if (i > 0)
                {
                    sb.Append(newline);
                }
                else
                {
                    sb.AppendFormat("   {0} ", Locale.GetText("at"));
                }
                MethodBase method = frame.GetMethod();
                if (method != null)
                {
                    // Method information available
                    sb.AppendFormat("{0}.{1}", method.DeclaringType.FullName, method.Name);
                    /* Append parameter information */
                    sb.Append("(");
                    ParameterInfo[] p = method.GetParameters();
                    for (int j = 0; j < p.Length; ++j)
                    {
                        if (j > 0)
                        {
                            sb.Append(", ");
                        }
                        Type pt    = p[j].ParameterType;
                        bool byref = pt.IsByRef;
                        if (byref)
                        {
                            pt = pt.GetElementType();
                        }
                        if (pt.IsClass && pt.Namespace != String.Empty)
                        {
                            sb.Append(pt.Namespace);
                            sb.Append(".");
                        }
                        sb.Append(pt.Name);
                        if (byref)
                        {
                            sb.Append(" ByRef");
                        }
                        sb.AppendFormat(" {0}", p [j].Name);
                    }
                    sb.Append(")");
                }
                else
                {
                    // Method information not available
                    sb.Append(unknown);
                }

                if (debug_info)
                {
                    // we were asked for debugging informations
                    // but that doesn't mean we have the debug information available
                    string fname = frame.GetSecureFileName();
                    if (fname != "<filename unknown>")
                    {
                        sb.AppendFormat(debuginfo, fname, frame.GetFileLineNumber());
                    }
                }
            }
            return(sb.ToString());
        }
 public static bool ErrorLog(string message)
 {
     System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(1, true);
     Debug.Log("file name :: " + sf.GetFileName() + "\nmethod name :: " + sf.GetMethod().ToString() + "\nline :: " + sf.GetFileLineNumber() + " >>> \n\n" + message + "\n");
     return(false);
 }
Beispiel #57
0
 string getFileMsg(System.Diagnostics.StackFrame SourceFile)
 {
     return(string.Format("FILE: [{0}] LINE:[{1}] Method:[{2}]", SourceFile.GetFileName(), SourceFile.GetFileLineNumber(), SourceFile.GetMethod()));
 }
Beispiel #58
0
        /// <summary> 事件传送信息打印 </summary>
        void EventsMsg(object sender, object e, System.Diagnostics.StackFrame SourceFile)
        {
            string msg = string.Format("[FILE:{0} ],LINE:{1},{2}] sender:{3},e:{4}", SourceFile.GetFileName(), SourceFile.GetFileLineNumber(), SourceFile.GetMethod(), sender.GetType(), e.GetType());

            //Trace.WriteLine(msg);
            if (Logger != null)
            {
                Logger.Info(msg);
            }
        }
Beispiel #59
0
        bool AddFrames(StringBuilder sb, bool separator, out bool isAsync)
        {
            isAsync = false;
            bool any_frame = false;

            for (int i = 0; i < FrameCount; i++)
            {
                StackFrame frame = GetFrame(i);

                if (frame.GetMethod() == null)
                {
                    if (any_frame || separator)
                    {
                        sb.Append(Environment.NewLine);
                    }
                    sb.Append(prefix);

                    string internal_name = frame.GetInternalMethodName();
                    if (internal_name != null)
                    {
                        sb.Append(internal_name);
                    }
                    else
                    {
                        sb.AppendFormat("<0x{0:x5} + 0x{1:x5}> <unknown method>", frame.GetMethodAddress(), frame.GetNativeOffset());
                    }
                }
                else
                {
                    GetFullNameForStackTrace(sb, frame.GetMethod(), any_frame || separator, out var skipped, out isAsync);
                    if (skipped)
                    {
                        continue;
                    }

                    if (frame.GetILOffset() == -1)
                    {
                        sb.AppendFormat(" <0x{0:x5} + 0x{1:x5}>", frame.GetMethodAddress(), frame.GetNativeOffset());
                        if (frame.GetMethodIndex() != 0xffffff)
                        {
                            sb.AppendFormat(" {0}", frame.GetMethodIndex());
                        }
                    }
                    else
                    {
                        sb.AppendFormat(" [0x{0:x5}]", frame.GetILOffset());
                    }

                    var filename = frame.GetSecureFileName();
                    if (filename[0] == '<')
                    {
                        var mvid  = frame.GetMethod().Module.ModuleVersionId.ToString("N");
                        var aotid = GetAotId();
                        if (frame.GetILOffset() != -1 || aotid == null)
                        {
                            filename = string.Format("<{0}>", mvid);
                        }
                        else
                        {
                            filename = string.Format("<{0}#{1}>", mvid, aotid);
                        }
                    }

                    sb.AppendFormat(" in {0}:{1} ", filename, frame.GetFileLineNumber());
                }

                any_frame = true;
            }

            return(any_frame);
        }
    public void Pop()
    {
#if DEBUG_METHOD_CALL
        System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
        System.Diagnostics.StackFrame frame      = stackTrace.GetFrame(1);
        Debug.LogFormat("Command Stack Pop: {0} in file {1} at line {2}", frame.GetMethod().Name, System.IO.Path.GetFileName(frame.GetFileName()), frame.GetFileLineNumber());
#endif
        if (!isAtStart)
        {
            commands[currentStackIndex--].Revoke();
        }
    }