GetFileName() public method

public GetFileName ( ) : string
return string
Beispiel #1
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());
    }
        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 #3
0
 public ConeStackFrame(StackFrame frame)
 {
     Method = frame.GetMethod();
     File = frame.GetFileName();
     Line = frame.GetFileLineNumber();
     Column = frame.GetFileColumnNumber();
 }
Beispiel #4
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 #5
0
 public TestMethodInfo(StackFrame callingFrame)
 {
     SourceFileDirectory = Path.GetDirectoryName(callingFrame.GetFileName());
     var realMethod = GetRealMethod(callingFrame.GetMethod());
     MethodName = realMethod.Name;
     DeclaringTypeName = realMethod.DeclaringType?.Name;
 }
        /// <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 #7
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 #8
0
 public static string GetWebRootFileSystemDirectory(string debugPath = null)
 {
     string fileSystemWebRoot = null;
     try
     {
         if (!string.IsNullOrEmpty(debugPath))
         {
             var sf = new StackFrame(0, true);
             var fileName = sf.GetFileName();
             var sourceWebRootDirectory = string.IsNullOrEmpty(fileName)
                                              ? ""
                                              : Path.GetFullPath(Path.Combine(fileName, @"..\..\..", debugPath));
             fileSystemWebRoot = Directory.Exists(sourceWebRootDirectory)
                                     ? sourceWebRootDirectory
                                     : AppDomain.CurrentDomain.BaseDirectory;
         }
         else
         {
             fileSystemWebRoot = AppDomain.CurrentDomain.BaseDirectory;
         }
     }
     catch (Exception)
     {
         fileSystemWebRoot = AppDomain.CurrentDomain.BaseDirectory;
     }
     return fileSystemWebRoot;
 }
Beispiel #9
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());
    }
Beispiel #10
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*/)
        {
        }
    }
Beispiel #11
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 #12
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 #13
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 #14
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
    }
        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 #16
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));
        }
Beispiel #17
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
    }
        /// <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 #19
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 #20
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));
        }
 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 #22
0
        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);
        }
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
        /// <summary> 事件传送信息打印 </summary>
        public static 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());

            if (Logger != null)
            {
                Logger.Info(msg);
            }
        }
        // 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 #26
0
 public void log(string strLevel, object objEvent)
 {
     StackFrame sf = new StackFrame(1, true);
     string strMethodName = sf.GetMethod().Name;
     string strFname = sf.GetFileName();
     string strFileName = System.IO.Path.GetFileName(strFname);
     string strEvent = JsonConvert.SerializeObject(objEvent);
     this.log(strFileName, strMethodName, strLevel, strEvent);
 }
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 string ExtractInfo(string message)
        {
            StackFrame frame1 = new StackFrame(2, true);
            string methodName = frame1.GetMethod().ToString();
            string fileName = Path.GetFileName(frame1.GetFileName());
            string[] textArray1 = new[] { "File:", fileName, " - Method:", methodName, " - ", message } ;

            return string.Concat(textArray1);
        }
 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);
 }
 /// <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 #31
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
    }
Beispiel #32
0
    private static void LogWarningFormat(LogLevel level, object message, UnityEngine.Object sender)
    {
        System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
        System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(2);
        string        stackMessageFormat         = Path.GetFileName(stackFrame.GetFileName()) + ":" + stackFrame.GetMethod().Name + "():at line " + stackFrame.GetFileLineNumber();
        StringBuilder msg = new StringBuilder();

        msg.AppendFormat("<color={0}>[{1}] [Msg: {2} ] [{3}]</color>", mWarningColor, level.ToString().ToUpper(), message, stackMessageFormat);
        Debug.LogWarning(msg);
    }
        public static string GetIntegrationTestRootDirectory()
        {
            // XXX: This is an evil hack, but it's okay for a unit test
            // We can't use Assembly.Location because unit test runners love
            // to move stuff to temp directories
            var st = new StackFrame(true);
            var di = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(st.GetFileName()), ".."));

            return di.FullName;
        }
Beispiel #34
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 #35
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);
        }
Beispiel #36
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}");
                }
            }
        }
 private string GetFileName(StackFrame sf)
 {
     string fileName = null;
     try
     {
         fileName = sf.GetFileName();
     }
     catch (SecurityException)
     {
     }
     return fileName;
 }
Beispiel #38
0
 public void log(string strLevel, object req ,object res)
 {
     StackFrame sf = new StackFrame(1, true);
     string strMethodName = sf.GetMethod().Name;
     string strFname = sf.GetFileName();
     string strFileName = System.IO.Path.GetFileName(strFname);
     Dictionary<string, object> dict = new Dictionary<string, object>();
     dict["request"] = req;
     dict["response"] = res;
     string strEvent = JsonConvert.SerializeObject(dict);
     this.log(strFileName, strMethodName, strLevel, strEvent);
 }
Beispiel #39
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 #40
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 #41
0
        /// <summary>
        /// 性能计数结束
        /// <remarks>性能计数本身会消耗性能,在想统计性能的方法段的开始调用该方法,在末尾调用PerformanceStop()方法可输出日志,两者必须匹配</remarks>
        /// </summary>
        public static void PerformanceStop()
        {
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            var stackFrame = new StackFrame(1, true);
            var fileName = stackFrame.GetFileName();
            var methodName = stackFrame.GetMethod().Name;

            stopWatch.Stop();

            PerformanceHelper.StopPerformance(fileName, methodName, stopWatch.ElapsedTicks);
        }
 /// <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 + ")";
 }
Beispiel #43
0
        private static string jFUNC(int iSkipFuncLevel = 1)
        {
            nSD.StackTrace st        = new nSD.StackTrace();
            nSD.StackFrame sf        = st.GetFrame(iSkipFuncLevel);
            nSD.StackFrame sf_prev   = st.GetFrame(iSkipFuncLevel + 1);
            string         prev_func = "";

            if (sf_prev != null)
            {
                prev_func = sf_prev.GetMethod().ToString();
            }

            return(prev_func + ">" + sf.GetMethod().ToString() + ":" + sf.GetFileName() + ":" + sf.GetFileLineNumber());
        }
    void ListStackTrace(int selected, int height)
    {
        for (int i = Util.Debug.DebugLines[selected].stackTrace.FrameCount - 1; i >= 0; i--)
        //foreach (System.Diagnostics.StackFrame frame in Util.Debug.DebugLines[selected].stackTrace.GetFrames())
        {
            System.Diagnostics.StackFrame frame = Util.Debug.DebugLines[selected].stackTrace.GetFrames()[i];
            if (frame.GetFileName() == null || frame.GetFileName() == "")
            {
                continue;
            }
            string[] names = frame.GetFileName().Split('\\');
            Rect     r     = EditorGUILayout.BeginHorizontal();
            //
            string s = names[names.Length - 1] + ":" + frame.GetMethod().Name + " - " + frame.GetFileLineNumber();
            EditorGUILayout.SelectableLabel(s, GUILayout.Height(16));
            if (GUILayout.Button(" ", GUILayout.Width(16)))
            {
                OpenStackTrace(frame);
            }
            EditorGUILayout.EndHorizontal();


            /*if (r.Contains(Event.current.mousePosition))
             * {
             *  if (GUI.Button(new Rect(r.x + r.width - 50, r.y + r.height - 16, 50, 16), "Open"))
             *      OpenStackTrace(frame);
             *
             * }
             * else
             * {
             *  EditorGUI.SelectableLabel(r, s);
             * }*/


            //EditorGUILayout.SelectableLabel(names[names.Length - 1] + ":" + frame.GetMethod().Name + " - " + frame.GetFileLineNumber(), GUILayout.Height(16));
        }
    }
Beispiel #45
0
    public static void LogError(object message, Exception e = null)
    {
        string stackTrace    = StackTraceUtility.ExtractStackTrace();
        string ErrorLocation = string.Empty;

#if UNITY_EDITOR
        if (e != null)
        {
            System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);
            System.Diagnostics.StackFrame frame = trace.GetFrame(0);
            ErrorLocation = "\n" + frame.GetFileName() + "." + frame.GetMethod() + ": " + frame.GetFileLineNumber();
        }
#endif
        Loom.QueueMessage(Loom.messageType.Error, message.ToString() + ErrorLocation + "\n" + stackTrace);
    }
 public CallerLocation(StackFrame f)
 {
     if (f == null)
     {
         FileName = "";
         LineNumber = 0;
         Method = null;
     }
     else
     {
         FileName = f.GetFileName();
         LineNumber = f.GetFileLineNumber();
         Method = f.GetMethod();
     }
 }
Beispiel #47
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 #48
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));
        }
Beispiel #49
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 #51
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 #52
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 #53
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 #54
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 #55
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);
        }
Beispiel #56
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));
        }
    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 #58
0
        [System.Security.SecurityCritical] // auto-generated
#endif
        internal String ToString(TraceFormat traceFormat)
        {
            bool   displayFilenames = true; // we'll try, but demand may fail
            String word_At          = "at";
            String inFileLineNum    = "in {0}:line {1}";

            if (traceFormat != TraceFormat.NoResourceLookup)
            {
                word_At       = Environment.GetResourceString("Word_At");
                inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber");
            }

            bool          fFirstFrame = true;
            StringBuilder sb          = new StringBuilder(255);

            for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
            {
                StackFrame sf = GetFrame(iFrameIndex);
                MethodBase mb = sf.GetMethod();
                if (mb != null)
                {
                    // We want a newline at the end of every line except for the last
                    if (fFirstFrame)
                    {
                        fFirstFrame = false;
                    }
                    else
                    {
                        sb.Append(Environment.NewLine);
                    }

                    sb.AppendFormat(CultureInfo.InvariantCulture, "   {0} ", word_At);

                    Type t = mb.DeclaringType;
                    // if there is a type (non global method) print it
                    if (t != null)
                    {
                        // Append t.FullName, replacing '+' with '.'
                        string fullName = t.FullName;
                        for (int i = 0; i < fullName.Length; i++)
                        {
                            char ch = fullName[i];
                            sb.Append(ch == '+' ? '.' : ch);
                        }
                        sb.Append('.');
                    }
                    sb.Append(mb.Name);

                    // deal with the generic portion of the method
                    if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
                    {
                        Type[] typars = ((MethodInfo)mb).GetGenericArguments();
                        sb.Append('[');
                        int  k             = 0;
                        bool fFirstTyParam = true;
                        while (k < typars.Length)
                        {
                            if (fFirstTyParam == false)
                            {
                                sb.Append(',');
                            }
                            else
                            {
                                fFirstTyParam = false;
                            }

                            sb.Append(typars[k].Name);
                            k++;
                        }
                        sb.Append(']');
                    }

                    ParameterInfo[] pi = null;
#if FEATURE_CORECLR
                    try
                    {
#endif
                    pi = mb.GetParameters();
#if FEATURE_CORECLR
                }
                catch
                {
                    // The parameter info cannot be loaded, so we don't
                    // append the parameter list.
                }
#endif
                    if (pi != null)
                    {
                        // arguments printing
                        sb.Append('(');
                        bool fFirstParam = true;
                        for (int j = 0; j < pi.Length; j++)
                        {
                            if (fFirstParam == false)
                            {
                                sb.Append(", ");
                            }
                            else
                            {
                                fFirstParam = false;
                            }

                            String typeName = "<UnknownType>";
                            if (pi[j].ParameterType != null)
                            {
                                typeName = pi[j].ParameterType.Name;
                            }
                            sb.Append(typeName);
                            sb.Append(' ');
                            sb.Append(pi[j].Name);
                        }
                        sb.Append(')');
                    }

                    // source location printing
                    if (displayFilenames && (sf.GetILOffset() != -1))
                    {
                        // If we don't have a PDB or PDB-reading is disabled for the module,
                        // then the file name will be null.
                        String fileName = null;

                        // Getting the filename from a StackFrame is a privileged operation - we won't want
                        // to disclose full path names to arbitrarily untrusted code.  Rather than just omit
                        // this we could probably trim to just the filename so it's still mostly usefull.
                        try
                        {
                            fileName = sf.GetFileName();
                        }
                        catch (SecurityException)
                        {
                            // If the demand for displaying filenames fails, then it won't
                            // succeed later in the loop.  Avoid repeated exceptions by not trying again.
                            displayFilenames = false;
                        }

                        if (fileName != null)
                        {
                            // tack on " in c:\tmp\MyFile.cs:line 5"
                            sb.Append(' ');
                            sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
                        }
                    }

#if FEATURE_EXCEPTIONDISPATCHINFO
                    if (sf.GetIsLastFrameFromForeignExceptionStackTrace())
                    {
                        sb.Append(Environment.NewLine);
                        sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
                    }
#endif // FEATURE_EXCEPTIONDISPATCHINFO
                }
            }

            if (traceFormat == TraceFormat.TrailingNewLine)
            {
                sb.Append(Environment.NewLine);
            }

            return(sb.ToString());
        }
Beispiel #59
0
 string getFileMsg(System.Diagnostics.StackFrame SourceFile)
 {
     return(string.Format("FILE: [{0}] LINE:[{1}] Method:[{2}]", SourceFile.GetFileName(), SourceFile.GetFileLineNumber(), SourceFile.GetMethod()));
 }
    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();
        }
    }